diff --git a/build/asset-manifest.json b/build/asset-manifest.json new file mode 100644 index 00000000..331c8e84 --- /dev/null +++ b/build/asset-manifest.json @@ -0,0 +1,14 @@ +{ + "main.css": "/static/css/main.992c251c.chunk.css", + "main.js": "/static/js/main.40d8c8fe.chunk.js", + "main.js.map": "/static/js/main.40d8c8fe.chunk.js.map", + "runtime~main.js": "/static/js/runtime~main.a8a9905a.js", + "runtime~main.js.map": "/static/js/runtime~main.a8a9905a.js.map", + "static/js/2.26935990.chunk.js": "/static/js/2.26935990.chunk.js", + "static/js/2.26935990.chunk.js.map": "/static/js/2.26935990.chunk.js.map", + "index.html": "/index.html", + "precache-manifest.f8b9d5a236b10808557b12f1b4230f3f.js": "/precache-manifest.f8b9d5a236b10808557b12f1b4230f3f.js", + "service-worker.js": "/service-worker.js", + "static/css/main.992c251c.chunk.css.map": "/static/css/main.992c251c.chunk.css.map", + "static/media/style.css": "/static/media/haymaker-webfont.e9535f20.ttf" +} \ No newline at end of file diff --git a/build/favicon.ico b/build/favicon.ico new file mode 100644 index 00000000..5c125de5 Binary files /dev/null and b/build/favicon.ico differ diff --git a/build/images/crab.jpg b/build/images/crab.jpg new file mode 100644 index 00000000..8f76d64f Binary files /dev/null and b/build/images/crab.jpg differ diff --git a/build/images/hali.jpg b/build/images/hali.jpg new file mode 100644 index 00000000..6b7ba49f Binary files /dev/null and b/build/images/hali.jpg differ diff --git a/build/images/lobster.jpg b/build/images/lobster.jpg new file mode 100644 index 00000000..e229750a Binary files /dev/null and b/build/images/lobster.jpg differ diff --git a/build/images/mahi.jpg b/build/images/mahi.jpg new file mode 100644 index 00000000..6cbe507b Binary files /dev/null and b/build/images/mahi.jpg differ diff --git a/build/images/mussels.jpg b/build/images/mussels.jpg new file mode 100644 index 00000000..e88143d6 Binary files /dev/null and b/build/images/mussels.jpg differ diff --git a/build/images/oysters.jpg b/build/images/oysters.jpg new file mode 100644 index 00000000..90cac68f Binary files /dev/null and b/build/images/oysters.jpg differ diff --git a/build/images/prawns.jpg b/build/images/prawns.jpg new file mode 100644 index 00000000..4a00408b Binary files /dev/null and b/build/images/prawns.jpg differ diff --git a/build/images/salmon.jpg b/build/images/salmon.jpg new file mode 100644 index 00000000..8ef6dcdc Binary files /dev/null and b/build/images/salmon.jpg differ diff --git a/build/images/scallops.jpg b/build/images/scallops.jpg new file mode 100644 index 00000000..0fa86aa3 Binary files /dev/null and b/build/images/scallops.jpg differ diff --git a/build/index.html b/build/index.html new file mode 100644 index 00000000..bd1af643 --- /dev/null +++ b/build/index.html @@ -0,0 +1 @@ +Catch of the Day
\ No newline at end of file diff --git a/build/precache-manifest.f8b9d5a236b10808557b12f1b4230f3f.js b/build/precache-manifest.f8b9d5a236b10808557b12f1b4230f3f.js new file mode 100644 index 00000000..bc078f5e --- /dev/null +++ b/build/precache-manifest.f8b9d5a236b10808557b12f1b4230f3f.js @@ -0,0 +1,58 @@ +self.__precacheManifest = [ + { + "revision": "e9535f20ca175cc3fdfe2816f7c47168", + "url": "/static/media/haymaker-webfont.e9535f20.ttf" + }, + { + "revision": "b8c2a3cda2b9dfb92b8f", + "url": "/static/css/main.992c251c.chunk.css" + }, + { + "revision": "42ac5946195a7306e2a5", + "url": "/static/js/runtime~main.a8a9905a.js" + }, + { + "revision": "e4fcd4b0627985d6b01d", + "url": "/static/js/2.26935990.chunk.js" + }, + { + "revision": "751e56274d3ea1c651ea824f902bb987", + "url": "/static/media/haymaker-webfont.751e5627.woff" + }, + { + "revision": "d2f8799a13e6db2022d9a7de22776705", + "url": "/static/media/anchor.d2f8799a.svg" + }, + { + "revision": "4c3fb584d3f63821357c8a9cff97f360", + "url": "/static/media/haymaker-webfont.4c3fb584.eot" + }, + { + "revision": "b8c2a3cda2b9dfb92b8f", + "url": "/static/js/main.40d8c8fe.chunk.js" + }, + { + "revision": "cf798e30eda73d84b25c4ae233fe5e21", + "url": "/static/media/haymaker-webfont.cf798e30.svg" + }, + { + "revision": "73a576a8254aeafebcdc66fe9fd41ac8", + "url": "/static/media/blanch_caps_inline-webfont.73a576a8.eot" + }, + { + "revision": "1461f8e9d2084c70c00830348efe1766", + "url": "/static/media/blanch_caps_inline-webfont.1461f8e9.woff" + }, + { + "revision": "8345e1b3362c1d640f0f11b5aae1d5bc", + "url": "/static/media/blanch_caps_inline-webfont.8345e1b3.ttf" + }, + { + "revision": "7bbffda6bcacac8360f0ee00bb03dc04", + "url": "/static/media/blanch_caps_inline-webfont.7bbffda6.svg" + }, + { + "revision": "3872195733d49d40078df5a85a1632c1", + "url": "/index.html" + } +]; \ No newline at end of file diff --git a/build/service-worker.js b/build/service-worker.js new file mode 100644 index 00000000..0731899e --- /dev/null +++ b/build/service-worker.js @@ -0,0 +1,34 @@ +/** + * Welcome to your Workbox-powered service worker! + * + * You'll need to register this file in your web app and you should + * disable HTTP caching for this file too. + * See https://goo.gl/nhQhGp + * + * The rest of the code is auto-generated. Please don't update this file + * directly; instead, make changes to your Workbox build configuration + * and re-run your build process. + * See https://goo.gl/2aRDsh + */ + +importScripts("https://storage.googleapis.com/workbox-cdn/releases/3.6.3/workbox-sw.js"); + +importScripts( + "/precache-manifest.f8b9d5a236b10808557b12f1b4230f3f.js" +); + +workbox.clientsClaim(); + +/** + * The workboxSW.precacheAndRoute() method efficiently caches and responds to + * requests for URLs in the manifest. + * See https://goo.gl/S9QRab + */ +self.__precacheManifest = [].concat(self.__precacheManifest || []); +workbox.precaching.suppressWarnings(); +workbox.precaching.precacheAndRoute(self.__precacheManifest, {}); + +workbox.routing.registerNavigationRoute("/index.html", { + + blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/], +}); diff --git a/build/static/css/main.992c251c.chunk.css b/build/static/css/main.992c251c.chunk.css new file mode 100644 index 00000000..4988cfa3 --- /dev/null +++ b/build/static/css/main.992c251c.chunk.css @@ -0,0 +1,2 @@ +.order-enter{-webkit-transform:translateX(-120%);transform:translateX(-120%);-webkit-transition:.5s;transition:.5s;max-height:0;padding:0!important}.order-enter.order-enter-active{max-height:60px;padding:2rem 0!important}.order-enter.order-enter-active,.order-exit{-webkit-transform:translateX(0);transform:translateX(0)}.order-exit{-webkit-transition:.5s;transition:.5s}.order-exit.order-exit-active{-webkit-transform:translateX(120%);transform:translateX(120%);padding:0}.count-enter{-webkit-transition:.5s;transition:.5s;-webkit-transform:translateY(100%);transform:translateY(100%)}.count-enter.count-enter-active,.count-exit{-webkit-transform:translateY(0);transform:translateY(0)}.count-exit{-webkit-transition:.5s;transition:.5s;position:absolute;left:0;bottom:0}.count-exit.count-exit-active{-webkit-transform:translateY(-100%);transform:translateY(-100%)}@font-face{font-family:haymakerregular;src:url(/static/media/haymaker-webfont.4c3fb584.eot);src:url(/static/media/haymaker-webfont.4c3fb584.eot?#iefix) format("embedded-opentype"),url(/static/media/haymaker-webfont.751e5627.woff) format("woff"),url(/static/media/haymaker-webfont.e9535f20.ttf) format("truetype"),url(/static/media/haymaker-webfont.cf798e30.svg#haymakerregular) format("svg");font-weight:400;font-style:normal}@font-face{font-family:blanchcaps_inline;src:url(/static/media/blanch_caps_inline-webfont.73a576a8.eot);src:url(/static/media/blanch_caps_inline-webfont.73a576a8.eot?#iefix) format("embedded-opentype"),url(/static/media/blanch_caps_inline-webfont.1461f8e9.woff) format("woff"),url(/static/media/blanch_caps_inline-webfont.8345e1b3.ttf) format("truetype"),url(/static/media/blanch_caps_inline-webfont.7bbffda6.svg#blanchcaps_inline) format("svg");font-weight:400;font-style:normal}article,aside,details,figcaption,figure,footer,header,hgroup,nav,section,summary{display:block}audio,canvas,video{display:inline-block}audio:not([controls]){display:none;height:0}[hidden]{display:none}html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}a:focus{outline:thin dotted}a:active,a:hover{outline:0}h1{font-size:2em}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}mark{background:#ff0;color:#000}code,kbd,pre,samp{font-family:monospace,serif;font-size:1em}pre{white-space:pre-wrap;word-wrap:break-word}q{quotes:2 1c 2 1d 2 18 2 19}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}button,input,select,textarea{font-family:inherit;font-size:100%;margin:0}button,input{line-height:normal}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],input[disabled]{cursor:default}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=search]{-webkit-appearance:textfield;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}textarea{overflow:auto;vertical-align:top}table{border-collapse:collapse;border-spacing:0}body,figure{margin:0}button::-moz-focus-inner,input::-moz-focus-inner,legend{border:0;padding:0}.clearfix:after{visibility:hidden;display:block;font-size:0;content:" ";clear:both;height:0}*{box-sizing:border-box}html{font-size:62.5%}body{background:#d4d4d4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;font-family:Open Sans,sans-serif;font-size:2rem}h1{font-family:blanchcaps_inline,sans-serif;text-align:center;font-weight:400;margin:0}h2,h3,h4,h5,h6{font-weight:400;font-family:haymakerregular,sans-serif}h2{text-align:center;margin-top:0;margin-bottom:2rem}h3{font-size:3rem}header.top{text-align:center}header.top h1{font-size:14.4rem;line-height:.7}header.top h1,header.top h1 .ofThe{display:flex;justify-content:center}header.top h1 .ofThe{font-size:3rem;color:#f5a623;align-items:center;background:url(/static/media/anchor.d2f8799a.svg) 50% no-repeat;background-size:cover;padding:0 1rem}header.top h1 .ofThe .of{padding-right:2rem;position:relative;right:-.5rem}header.top h3{margin:0;font-size:2rem;color:#f5a623;position:relative;display:inline-block}header.top h3 span{background:#fff;position:relative;z-index:2;padding-left:1rem;padding-right:1rem}header.top h3:after,header.top h3:before{display:block;z-index:1;background:#000;position:absolute;width:130%;height:1px;content:"";top:5px;margin-left:-15%}header.top h3:after{top:auto;bottom:7px}.catch-of-the-day{display:flex;height:90vh;max-width:1500px;margin:5vh auto 0;-webkit-perspective:1000px;perspective:1000px;-webkit-transform-style:preserve-3d;transform-style:preserve-3d}.catch-of-the-day>*{flex:1 4 auto;padding:2rem;border:1rem double #1a1a1a;position:relative;background:#fff;-webkit-transition:all .3s;transition:all .3s;box-shadow:0 5px 5px rgba(0,0,0,.1);overflow:scroll}.catch-of-the-day>:first-child{flex-shrink:1;flex-basis:50%;-webkit-transform:translateX(50%) rotateY(6deg) translateX(-50%);transform:translateX(50%) rotateY(6deg) translateX(-50%)}.catch-of-the-day>:nth-child(2){-webkit-transform:translateX(-50%) rotateY(-14deg) translateX(50%);transform:translateX(-50%) rotateY(-14deg) translateX(50%);border-left:0;border-right:0;min-width:300px}.catch-of-the-day>:last-child{flex-shrink:1;flex-basis:50%;-webkit-transform:translateX(-50%) rotateY(10deg) translateX(50%) scale(1.08) translateX(24px);transform:translateX(-50%) rotateY(10deg) translateX(50%) scale(1.08) translateX(24px)}input#fold:not(:checked)~#main .catch-of-the-day>*{-webkit-transform:none;transform:none}label[for=fold]{position:absolute;top:1rem;left:1rem;text-transform:uppercase;font-size:1.3rem;background:#000;color:#fff;border:2px solid #000;cursor:pointer;padding:.5rem 1rem}input#fold{display:none}input#fold:checked+label{background:#fff;color:#000}ul{list-style:none;margin:0;padding:0}ul.order li{border-bottom:1px solid #000;padding:2rem 0;display:flex;font-size:1.4rem;justify-content:space-between;align-items:center}ul.order li:hover button{display:inline}ul.order li button{border:0;display:none;line-height:1;padding:0}ul.order li.total{font-weight:600;border-bottom:3px solid #000;border-top:3px double #000}ul.order li.unavailable{text-decoration:line-through;background:#f8d0d2}ul.order li .price{font-size:1.2rem}ul.order li span.count{position:relative;overflow:hidden;float:left}ul.order li span.count span{display:inline-block}.order-title{text-align:center}.fish-edit{margin-bottom:20px;border:2px solid #000;overflow:hidden;display:flex;flex-wrap:wrap}.fish-edit input,.fish-edit select,.fish-edit textarea{width:33.33%;padding:10px;line-height:1;font-size:1.2rem;border:0;border-bottom:1px solid #000;border-right:1px solid #000;-webkit-appearance:none;-moz-appearance:none;appearance:none;border-radius:0;background:#fff}.fish-edit input:focus,.fish-edit select:focus,.fish-edit textarea:focus{outline:0;background:#fef2de}.fish-edit textarea{width:100%}.fish-edit input:last-of-type{width:100%}.fish-edit button{width:100%;border:0}.list-of-fish{border-top:2px solid #000;border-bottom:1px solid #000;padding-top:5px;margin-top:2rem;-webkit-transform:translateZ(0);transform:translateZ(0)}.menu-fish{border-bottom:2px solid #000;border-top:1px solid #000;padding-bottom:2rem;padding-top:2rem;margin-bottom:5px;clear:both;overflow:hidden}.menu-fish p{margin:0;font-size:1.8rem}.menu-fish .fish-name{margin:0;display:flex;justify-content:space-between;align-items:center}.menu-fish .price{font-size:1.4rem;justify-content:flex-end}.menu-fish img{float:left;width:150px;margin-right:1rem}button,input[type=submit]{text-transform:uppercase;background:none;border:1px solid #000;font-weight:600;font-size:1.5rem;font-family:Open Sans;-webkit-transition:all .2s;transition:all .2s;position:relative;z-index:2}button[disabled],input[type=submit][disabled]{color:#d12028;background:#fff;border-color:#d12028;-webkit-transform:rotate(-10deg) scale(2) translateX(50%) translateY(-50%);transform:rotate(-10deg) scale(2) translateX(50%) translateY(-50%)}button[disabled]:hover,input[type=submit][disabled]:hover{color:#d12028;cursor:not-allowed}button[disabled]:after,input[type=submit][disabled]:after{display:none}button:after,input[type=submit]:after{content:"";z-index:-1;display:block;background:#000;position:absolute;width:100%;height:0;left:0;top:0;-webkit-transition:all .2s;transition:all .2s}button:focus,button:hover,input[type=submit]:focus,input[type=submit]:hover{color:#fff;outline:0}button:focus:after,button:hover:after,input[type=submit]:focus:after,input[type=submit]:hover:after{height:100%}button.warning:after,input[type=submit].warning:after{background:#d12028}button.success:after,input[type=submit].success:after{background:#2dc22d}button.facebook,button.github,button.twitter,input[type=submit].facebook,input[type=submit].github,input[type=submit].twitter{border:0;display:block;margin-bottom:2rem;width:100%;color:#fff;padding:2rem}button.github,input[type=submit].github{background:#676d65}button.github:after,input[type=submit].github:after{background:#212b1d}button.facebook,input[type=submit].facebook{background:#3864a3}button.facebook:after,input[type=submit].facebook:after{background:#2d5082}button.twitter,input[type=submit].twitter{background:#5ea9dd}button.twitter:after,input[type=submit].twitter:after{background:#2c8dd0}.store-selector{background:#fff;max-width:500px;margin:50px auto;padding:2rem;border:2px solid #000}.store-selector button,.store-selector input{width:100%}.store-selector button[type=text],.store-selector input[type=text]{text-align:center;font-size:3rem} +/*# sourceMappingURL=main.992c251c.chunk.css.map */ \ No newline at end of file diff --git a/build/static/css/main.992c251c.chunk.css.map b/build/static/css/main.992c251c.chunk.css.map new file mode 100644 index 00000000..8ba1d1ce --- /dev/null +++ b/build/static/css/main.992c251c.chunk.css.map @@ -0,0 +1 @@ +{"version":3,"sources":["/home/jenipha/Desktop/Practise/catch-of-the-day/src/css/style.css","main.992c251c.chunk.css"],"names":[],"mappings":"AAAA,aACE,mCAAA,CACA,2BAAA,CACA,sBAAA,CACA,cAAA,CACA,YAAA,CACA,mBCCF,CDCA,gCAGE,eAAA,CACA,wBCCF,CDCA,4CALE,+BAAA,CACA,uBCSF,CDLA,YACE,sBAAA,CACA,cCGF,CDCA,8BACE,kCAAA,CACA,0BAAA,CACA,SCCF,CDCA,aACE,sBAAA,CACA,cAAA,CACA,kCAAA,CACA,0BCCF,CDKA,4CAHE,+BAAA,CACA,uBCUF,CDRA,YAGE,sBAAA,CACA,cAAA,CACA,iBAAA,CACA,MAAA,CACA,QCCF,CDCA,8BACE,mCAAA,CACA,2BCCF,CDCA,WACE,2BAAA,CACA,oDAAwC,CACxC,2SAGmE,CACnE,eAAA,CACA,iBCCF,CDCA,WACE,6BAAA,CACA,8DAAkD,CAClD,qVCKiB,CDCjB,eAAA,CACA,iBCCF,CDCA,iFAWE,aCCF,CDCA,mBAGE,oBCCF,CDCA,sBACE,YAAA,CACA,QCCF,CDCA,SACE,YCCF,CDCA,KACE,sBAAA,CACA,6BAAA,CACA,yBCCF,CDCA,QACE,mBCCF,CDCA,iBAEE,SCCF,CDCA,GACE,aCCF,CDCA,YACE,wBCCF,CDCA,SAEE,eCCF,CDCA,IACE,iBCCF,CDCA,KACE,eAAA,CACA,UCCF,CDCA,kBAIE,2BAAA,CACA,aCCF,CDCA,IACE,oBAAA,CACA,oBCCF,CDCA,EACE,0BCCF,CDCA,MACE,aCCF,CDCA,QAEE,aAAA,CACA,aAAA,CACA,iBAAA,CACA,uBCCF,CDCA,IACE,SCCF,CDCA,IACE,aCCF,CDCA,IACE,QCCF,CDCA,eACE,eCCF,CDCA,SACE,uBAAA,CACA,YAAA,CACA,0BCCF,CDCA,6BAIE,mBAAA,CACA,cAAA,CACA,QCCF,CDCA,aAEE,kBCCF,CDCA,oEAIE,yBAAA,CACA,cCCF,CDCA,iCAEE,cCCF,CDCA,uCAEE,qBAAA,CACA,SCCF,CDCA,mBACE,4BAAA,CACA,sBCCF,CDCA,+FAEE,uBCCF,CDCA,SACE,aAAA,CACA,kBCCF,CDCA,MACE,wBAAA,CACA,gBCCF,CDCA,YAEE,QCCF,CDCA,wDAGE,QAAA,CACA,SCCF,CDCA,gBACE,iBAAA,CACA,aAAA,CACA,WAAA,CACA,WAAA,CACA,UAAA,CACA,QCCF,CDCA,EACE,qBCCF,CDCA,KACE,eCCF,CDCA,KACE,kBAAA,CACA,kCAAA,CACA,iCAAA,CACA,gCAAA,CACA,cCCF,CDCA,GACE,wCAAA,CACA,iBAAA,CACA,eAAA,CACA,QCCF,CDCA,eAKE,eAAA,CACA,sCCCF,CDCA,GACE,iBAAA,CACA,YAAA,CACA,kBCCF,CDCA,GACE,cCCF,CDCA,WACE,iBCCF,CDCA,cACE,iBAAA,CACA,cCGF,CDGA,mCAJE,YAAA,CAEA,sBCSF,CDPA,qBAGE,cAAA,CACA,aAAA,CAIA,kBAAA,CACA,+DAAqD,CACrD,qBAAA,CACA,cCJF,CDMA,yBACE,kBAAA,CACA,iBAAA,CACA,YCJF,CDMA,cACE,QAAA,CACA,cAAA,CACA,aAAA,CACA,iBAAA,CACA,oBCJF,CDMA,mBACE,eAAA,CACA,iBAAA,CACA,SAAA,CACA,iBAAA,CACA,kBCJF,CDMA,yCAEE,aAAA,CACA,SAAA,CACA,eAAA,CACA,iBAAA,CACA,UAAA,CACA,UAAA,CACA,UAAA,CACA,OAAA,CACA,gBCJF,CDMA,oBACE,QAAA,CACA,UCJF,CDMA,kBAEE,YAAA,CACA,WAAA,CACA,gBAAA,CAEA,iBAAA,CACA,0BAAA,CACA,kBAAA,CACA,mCAAA,CACA,2BCLF,CDOA,oBAEE,aAAA,CACA,YAAA,CACA,0BAAA,CACA,iBAAA,CACA,eAAA,CACA,0BAAA,CACA,kBAAA,CACA,mCAAA,CACA,eCNF,CDQA,+BACE,aAAA,CACA,cAAA,CACA,gEAAA,CACA,wDCNF,CDQA,gCACE,kEAAA,CACA,0DAAA,CACA,aAAA,CACA,cAAA,CACA,eCNF,CDQA,8BACE,aAAA,CACA,cAAA,CACA,8FCNkB,CDQlB,sFCLF,CDQA,mDACE,sBAAA,CACA,cCNF,CDQA,gBACE,iBAAA,CACA,QAAA,CACA,SAAA,CACA,wBAAA,CACA,gBAAA,CACA,eAAA,CACA,UAAA,CACA,qBAAA,CACA,cAAA,CACA,kBCNF,CDQA,WACE,YCNF,CDQA,yBACE,eAAA,CACA,UCNF,CDQA,GACE,eAAA,CACA,QAAA,CACA,SCNF,CDQA,YACE,4BAAA,CACA,cAAA,CAEA,YAAA,CACA,gBAAA,CAEA,6BAAA,CAEA,kBCTF,CDWA,yBACE,cCTF,CDWA,mBACE,QAAA,CACA,YAAA,CACA,aAAA,CACA,SCTF,CDWA,kBACE,eAAA,CACA,4BAAA,CACA,0BCTF,CDWA,wBACE,4BAAA,CACA,kBCTF,CDWA,mBACE,gBCTF,CDWA,uBACE,iBAAA,CACA,eAAA,CACA,UCTF,CDWA,4BACE,oBCTF,CDWA,aACE,iBCTF,CDWA,WACE,kBAAA,CACA,qBAAA,CACA,eAAA,CAEA,YAAA,CACA,cCVF,CDYA,uDAGE,YAAA,CACA,YAAA,CACA,aAAA,CACA,gBAAA,CACA,QAAA,CACA,4BAAA,CACA,2BAAA,CACA,uBAAA,CACA,oBAAA,CACA,eAAA,CACA,eAAA,CACA,eCVF,CDYA,yEAGE,SAAA,CACA,kBCVF,CDYA,oBACE,UCVF,CDYA,8BACE,UCVF,CDYA,kBACE,UAAA,CACA,QCVF,CDYA,cACE,yBAAA,CACA,4BAAA,CACA,eAAA,CACA,eAAA,CACA,+BAAA,CACA,uBCVF,CDYA,WACE,4BAAA,CACA,yBAAA,CACA,mBAAA,CACA,gBAAA,CACA,iBAAA,CACA,UAAA,CACA,eCVF,CDYA,aACE,QAAA,CACA,gBCVF,CDYA,sBACE,QAAA,CAEA,YAAA,CAEA,6BAAA,CAEA,kBCbF,CDeA,kBACE,gBAAA,CAEA,wBCdF,CDgBA,eACE,UAAA,CACA,WAAA,CACA,iBCdF,CDgBA,0BAEE,wBAAA,CACA,eAAA,CACA,qBAAA,CACA,eAAA,CACA,gBAAA,CACA,qBAAA,CACA,0BAAA,CACA,kBAAA,CACA,iBAAA,CACA,SCdF,CDgBA,8CAEE,aAAA,CACA,eAAA,CACA,oBAAA,CACA,0EAAA,CACA,kECdF,CDgBA,0DAEE,aAAA,CACA,kBCdF,CDgBA,0DAEE,YCdF,CDgBA,sCAEE,UAAA,CACA,UAAA,CACA,aAAA,CACA,eAAA,CACA,iBAAA,CACA,UAAA,CACA,QAAA,CACA,MAAA,CACA,KAAA,CACA,0BAAA,CACA,kBCdF,CDgBA,4EAIE,UAAA,CACA,SCdF,CDgBA,oGAIE,WCdF,CDgBA,sDAEE,kBCdF,CDgBA,sDAEE,kBCdF,CDgBA,8HAME,QAAA,CACA,aAAA,CACA,kBAAA,CACA,UAAA,CACA,UAAA,CACA,YCdF,CDgBA,wCAEE,kBCdF,CDgBA,oDAEE,kBCdF,CDgBA,4CAEE,kBCdF,CDgBA,wDAEE,kBCdF,CDgBA,0CAEE,kBCdF,CDgBA,sDAEE,kBCdF,CDgBA,gBACE,eAAA,CACA,eAAA,CACA,gBAAA,CACA,YAAA,CACA,qBCdF,CDgBA,6CAEE,UCdF,CDgBA,mEAEE,iBAAA,CACA,cCdF","file":"main.992c251c.chunk.css","sourcesContent":[".order-enter {\n -webkit-transform: translateX(-120%);\n transform: translateX(-120%);\n -webkit-transition: 0.5s;\n transition: 0.5s;\n max-height: 0;\n padding: 0 !important;\n}\n.order-enter.order-enter-active {\n -webkit-transform: translateX(0);\n transform: translateX(0);\n max-height: 60px;\n padding: 2rem 0 !important;\n}\n.order-exit {\n -webkit-transition: 0.5s;\n transition: 0.5s;\n -webkit-transform: translateX(0);\n transform: translateX(0);\n}\n.order-exit.order-exit-active {\n -webkit-transform: translateX(120%);\n transform: translateX(120%);\n padding: 0;\n}\n.count-enter {\n -webkit-transition: 0.5s;\n transition: 0.5s;\n -webkit-transform: translateY(100%);\n transform: translateY(100%);\n}\n.count-enter.count-enter-active {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n}\n.count-exit {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n -webkit-transition: 0.5s;\n transition: 0.5s;\n position: absolute;\n left: 0;\n bottom: 0;\n}\n.count-exit.count-exit-active {\n -webkit-transform: translateY(-100%);\n transform: translateY(-100%);\n}\n@font-face {\n font-family: \"haymakerregular\";\n src: url(\"./fonts/haymaker-webfont.eot\");\n src: url(\"./fonts/haymaker-webfont.eot?#iefix\") format(\"embedded-opentype\"),\n url(\"./fonts/haymaker-webfont.woff\") format(\"woff\"),\n url(\"./fonts/haymaker-webfont.ttf\") format(\"truetype\"),\n url(\"./fonts/haymaker-webfont.svg#haymakerregular\") format(\"svg\");\n font-weight: normal;\n font-style: normal;\n}\n@font-face {\n font-family: \"blanchcaps_inline\";\n src: url(\"./fonts/blanch_caps_inline-webfont.eot\");\n src: url(\"./fonts/blanch_caps_inline-webfont.eot?#iefix\")\n format(\"embedded-opentype\"),\n url(\"./fonts/blanch_caps_inline-webfont.woff\") format(\"woff\"),\n url(\"./fonts/blanch_caps_inline-webfont.ttf\") format(\"truetype\"),\n url(\"./fonts/blanch_caps_inline-webfont.svg#blanchcaps_inline\")\n format(\"svg\");\n font-weight: normal;\n font-style: normal;\n}\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nnav,\nsection,\nsummary {\n display: block;\n}\naudio,\ncanvas,\nvideo {\n display: inline-block;\n}\naudio:not([controls]) {\n display: none;\n height: 0;\n}\n[hidden] {\n display: none;\n}\nhtml {\n font-family: sans-serif;\n -webkit-text-size-adjust: 100%;\n -ms-text-size-adjust: 100%;\n}\na:focus {\n outline: thin dotted;\n}\na:active,\na:hover {\n outline: 0;\n}\nh1 {\n font-size: 2em;\n}\nabbr[title] {\n border-bottom: 1px dotted;\n}\nb,\nstrong {\n font-weight: 700;\n}\ndfn {\n font-style: italic;\n}\nmark {\n background: #ff0;\n color: #000;\n}\ncode,\nkbd,\npre,\nsamp {\n font-family: monospace, serif;\n font-size: 1em;\n}\npre {\n white-space: pre-wrap;\n word-wrap: break-word;\n}\nq {\n quotes: 2 1c 2 1d 2 18 2 19;\n}\nsmall {\n font-size: 80%;\n}\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsup {\n top: -0.5em;\n}\nsub {\n bottom: -0.25em;\n}\nimg {\n border: 0;\n}\nsvg:not(:root) {\n overflow: hidden;\n}\nfieldset {\n border: 1px solid #c0c0c0;\n margin: 0 2px;\n padding: 0.35em 0.625em 0.75em;\n}\nbutton,\ninput,\nselect,\ntextarea {\n font-family: inherit;\n font-size: 100%;\n margin: 0;\n}\nbutton,\ninput {\n line-height: normal;\n}\nbutton,\nhtml input[type=\"button\"],\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n -webkit-appearance: button;\n cursor: pointer;\n}\nbutton[disabled],\ninput[disabled] {\n cursor: default;\n}\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n box-sizing: border-box;\n padding: 0;\n}\ninput[type=\"search\"] {\n -webkit-appearance: textfield;\n box-sizing: content-box;\n}\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n -webkit-appearance: none;\n}\ntextarea {\n overflow: auto;\n vertical-align: top;\n}\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\nbody,\nfigure {\n margin: 0;\n}\nlegend,\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n border: 0;\n padding: 0;\n}\n.clearfix:after {\n visibility: hidden;\n display: block;\n font-size: 0;\n content: \" \";\n clear: both;\n height: 0;\n}\n* {\n box-sizing: border-box;\n}\nhtml {\n font-size: 62.5%;\n}\nbody {\n background: #d4d4d4;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-family: \"Open Sans\", sans-serif;\n font-size: 2rem;\n}\nh1 {\n font-family: \"blanchcaps_inline\", sans-serif;\n text-align: center;\n font-weight: normal;\n margin: 0;\n}\nh2,\nh3,\nh4,\nh5,\nh6 {\n font-weight: normal;\n font-family: \"haymakerregular\", sans-serif;\n}\nh2 {\n text-align: center;\n margin-top: 0;\n margin-bottom: 2rem;\n}\nh3 {\n font-size: 3rem;\n}\nheader.top {\n text-align: center;\n}\nheader.top h1 {\n font-size: 14.4rem;\n line-height: 0.7;\n display: -webkit-box;\n display: flex;\n -webkit-box-pack: center;\n justify-content: center;\n}\nheader.top h1 .ofThe {\n display: -webkit-box;\n display: flex;\n font-size: 3rem;\n color: #f5a623;\n -webkit-box-pack: center;\n justify-content: center;\n -webkit-box-align: center;\n align-items: center;\n background: url(\"images/anchor.svg\") center no-repeat;\n background-size: cover;\n padding: 0 1rem;\n}\nheader.top h1 .ofThe .of {\n padding-right: 2rem;\n position: relative;\n right: -0.5rem;\n}\nheader.top h3 {\n margin: 0;\n font-size: 2rem;\n color: #f5a623;\n position: relative;\n display: inline-block;\n}\nheader.top h3 span {\n background: #fff;\n position: relative;\n z-index: 2;\n padding-left: 1rem;\n padding-right: 1rem;\n}\nheader.top h3:before,\nheader.top h3:after {\n display: block;\n z-index: 1;\n background: #000;\n position: absolute;\n width: 130%;\n height: 1px;\n content: \"\";\n top: 5px;\n margin-left: -15%;\n}\nheader.top h3:after {\n top: auto;\n bottom: 7px;\n}\n.catch-of-the-day {\n display: -webkit-box;\n display: flex;\n height: 90vh;\n max-width: 1500px;\n margin: 0 auto;\n margin-top: 5vh;\n -webkit-perspective: 1000px;\n perspective: 1000px;\n -webkit-transform-style: preserve-3d;\n transform-style: preserve-3d;\n}\n.catch-of-the-day > * {\n -webkit-box-flex: 1;\n flex: 1 4 auto;\n padding: 2rem;\n border: 1rem double #1a1a1a;\n position: relative;\n background: #fff;\n -webkit-transition: all 0.3s;\n transition: all 0.3s;\n box-shadow: 0 5px 5px rgba(0, 0, 0, 0.1);\n overflow: scroll;\n}\n.catch-of-the-day > *:first-child {\n flex-shrink: 1;\n flex-basis: 50%;\n -webkit-transform: translateX(50%) rotateY(6deg) translateX(-50%);\n transform: translateX(50%) rotateY(6deg) translateX(-50%);\n}\n.catch-of-the-day > *:nth-child(2) {\n -webkit-transform: translateX(-50%) rotateY(-14deg) translateX(50%);\n transform: translateX(-50%) rotateY(-14deg) translateX(50%);\n border-left: 0;\n border-right: 0;\n min-width: 300px;\n}\n.catch-of-the-day > *:last-child {\n flex-shrink: 1;\n flex-basis: 50%;\n -webkit-transform: translateX(-50%) rotateY(10deg) translateX(50%) scale(1.08)\n translateX(24px);\n transform: translateX(-50%) rotateY(10deg) translateX(50%) scale(1.08)\n translateX(24px);\n}\ninput#fold:not(:checked) ~ #main .catch-of-the-day > * {\n -webkit-transform: none;\n transform: none;\n}\nlabel[for=\"fold\"] {\n position: absolute;\n top: 1rem;\n left: 1rem;\n text-transform: uppercase;\n font-size: 1.3rem;\n background: #000;\n color: #fff;\n border: 2px solid #000;\n cursor: pointer;\n padding: 0.5rem 1rem;\n}\ninput#fold {\n display: none;\n}\ninput#fold:checked + label {\n background: #fff;\n color: #000;\n}\nul {\n list-style: none;\n margin: 0;\n padding: 0;\n}\nul.order li {\n border-bottom: 1px solid #000;\n padding: 2rem 0;\n display: -webkit-box;\n display: flex;\n font-size: 1.4rem;\n -webkit-box-pack: justify;\n justify-content: space-between;\n -webkit-box-align: center;\n align-items: center;\n}\nul.order li:hover button {\n display: inline;\n}\nul.order li button {\n border: 0;\n display: none;\n line-height: 1;\n padding: 0;\n}\nul.order li.total {\n font-weight: 600;\n border-bottom: 3px solid #000;\n border-top: 3px double #000;\n}\nul.order li.unavailable {\n text-decoration: line-through;\n background: #f8d0d2;\n}\nul.order li .price {\n font-size: 1.2rem;\n}\nul.order li span.count {\n position: relative;\n overflow: hidden;\n float: left;\n}\nul.order li span.count span {\n display: inline-block;\n}\n.order-title {\n text-align: center;\n}\n.fish-edit {\n margin-bottom: 20px;\n border: 2px solid #000;\n overflow: hidden;\n display: -webkit-box;\n display: flex;\n flex-wrap: wrap;\n}\n.fish-edit input,\n.fish-edit textarea,\n.fish-edit select {\n width: 33.33%;\n padding: 10px;\n line-height: 1;\n font-size: 1.2rem;\n border: 0;\n border-bottom: 1px solid #000;\n border-right: 1px solid #000;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n border-radius: 0;\n background: #fff;\n}\n.fish-edit input:focus,\n.fish-edit textarea:focus,\n.fish-edit select:focus {\n outline: 0;\n background: #fef2de;\n}\n.fish-edit textarea {\n width: 100%;\n}\n.fish-edit input:last-of-type {\n width: 100%;\n}\n.fish-edit button {\n width: 100%;\n border: 0;\n}\n.list-of-fish {\n border-top: 2px solid #000;\n border-bottom: 1px solid #000;\n padding-top: 5px;\n margin-top: 2rem;\n -webkit-transform: translateZ(0);\n transform: translateZ(0);\n}\n.menu-fish {\n border-bottom: 2px solid #000;\n border-top: 1px solid #000;\n padding-bottom: 2rem;\n padding-top: 2rem;\n margin-bottom: 5px;\n clear: both;\n overflow: hidden;\n}\n.menu-fish p {\n margin: 0;\n font-size: 1.8rem;\n}\n.menu-fish .fish-name {\n margin: 0;\n display: -webkit-box;\n display: flex;\n -webkit-box-pack: justify;\n justify-content: space-between;\n -webkit-box-align: center;\n align-items: center;\n}\n.menu-fish .price {\n font-size: 1.4rem;\n -webkit-box-pack: end;\n justify-content: flex-end;\n}\n.menu-fish img {\n float: left;\n width: 150px;\n margin-right: 1rem;\n}\nbutton,\ninput[type=\"submit\"] {\n text-transform: uppercase;\n background: none;\n border: 1px solid #000;\n font-weight: 600;\n font-size: 1.5rem;\n font-family: \"Open Sans\";\n -webkit-transition: all 0.2s;\n transition: all 0.2s;\n position: relative;\n z-index: 2;\n}\nbutton[disabled],\ninput[type=\"submit\"][disabled] {\n color: #d12028;\n background: #fff;\n border-color: #d12028;\n -webkit-transform: rotate(-10deg) scale(2) translateX(50%) translateY(-50%);\n transform: rotate(-10deg) scale(2) translateX(50%) translateY(-50%);\n}\nbutton[disabled]:hover,\ninput[type=\"submit\"][disabled]:hover {\n color: #d12028;\n cursor: not-allowed;\n}\nbutton[disabled]:after,\ninput[type=\"submit\"][disabled]:after {\n display: none;\n}\nbutton:after,\ninput[type=\"submit\"]:after {\n content: \"\";\n z-index: -1;\n display: block;\n background: #000;\n position: absolute;\n width: 100%;\n height: 0;\n left: 0;\n top: 0;\n -webkit-transition: all 0.2s;\n transition: all 0.2s;\n}\nbutton:hover,\ninput[type=\"submit\"]:hover,\nbutton:focus,\ninput[type=\"submit\"]:focus {\n color: #fff;\n outline: 0;\n}\nbutton:hover:after,\ninput[type=\"submit\"]:hover:after,\nbutton:focus:after,\ninput[type=\"submit\"]:focus:after {\n height: 100%;\n}\nbutton.warning:after,\ninput[type=\"submit\"].warning:after {\n background: #d12028;\n}\nbutton.success:after,\ninput[type=\"submit\"].success:after {\n background: #2dc22d;\n}\nbutton.github,\ninput[type=\"submit\"].github,\nbutton.facebook,\ninput[type=\"submit\"].facebook,\nbutton.twitter,\ninput[type=\"submit\"].twitter {\n border: 0;\n display: block;\n margin-bottom: 2rem;\n width: 100%;\n color: #fff;\n padding: 2rem;\n}\nbutton.github,\ninput[type=\"submit\"].github {\n background: #676d65;\n}\nbutton.github:after,\ninput[type=\"submit\"].github:after {\n background: #212b1d;\n}\nbutton.facebook,\ninput[type=\"submit\"].facebook {\n background: #3864a3;\n}\nbutton.facebook:after,\ninput[type=\"submit\"].facebook:after {\n background: #2d5082;\n}\nbutton.twitter,\ninput[type=\"submit\"].twitter {\n background: #5ea9dd;\n}\nbutton.twitter:after,\ninput[type=\"submit\"].twitter:after {\n background: #2c8dd0;\n}\n.store-selector {\n background: #fff;\n max-width: 500px;\n margin: 50px auto;\n padding: 2rem;\n border: 2px solid #000;\n}\n.store-selector input,\n.store-selector button {\n width: 100%;\n}\n.store-selector input[type=\"text\"],\n.store-selector button[type=\"text\"] {\n text-align: center;\n font-size: 3rem;\n}\n",".order-enter {\n -webkit-transform: translateX(-120%);\n transform: translateX(-120%);\n -webkit-transition: 0.5s;\n transition: 0.5s;\n max-height: 0;\n padding: 0 !important;\n}\n.order-enter.order-enter-active {\n -webkit-transform: translateX(0);\n transform: translateX(0);\n max-height: 60px;\n padding: 2rem 0 !important;\n}\n.order-exit {\n -webkit-transition: 0.5s;\n transition: 0.5s;\n -webkit-transform: translateX(0);\n transform: translateX(0);\n}\n.order-exit.order-exit-active {\n -webkit-transform: translateX(120%);\n transform: translateX(120%);\n padding: 0;\n}\n.count-enter {\n -webkit-transition: 0.5s;\n transition: 0.5s;\n -webkit-transform: translateY(100%);\n transform: translateY(100%);\n}\n.count-enter.count-enter-active {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n}\n.count-exit {\n -webkit-transform: translateY(0);\n transform: translateY(0);\n -webkit-transition: 0.5s;\n transition: 0.5s;\n position: absolute;\n left: 0;\n bottom: 0;\n}\n.count-exit.count-exit-active {\n -webkit-transform: translateY(-100%);\n transform: translateY(-100%);\n}\n@font-face {\n font-family: \"haymakerregular\";\n src: url(/static/media/haymaker-webfont.4c3fb584.eot);\n src: url(/static/media/haymaker-webfont.4c3fb584.eot?#iefix) format(\"embedded-opentype\"),\n url(/static/media/haymaker-webfont.751e5627.woff) format(\"woff\"),\n url(/static/media/haymaker-webfont.e9535f20.ttf) format(\"truetype\"),\n url(/static/media/haymaker-webfont.cf798e30.svg#haymakerregular) format(\"svg\");\n font-weight: normal;\n font-style: normal;\n}\n@font-face {\n font-family: \"blanchcaps_inline\";\n src: url(/static/media/blanch_caps_inline-webfont.73a576a8.eot);\n src: url(/static/media/blanch_caps_inline-webfont.73a576a8.eot?#iefix)\n format(\"embedded-opentype\"),\n url(/static/media/blanch_caps_inline-webfont.1461f8e9.woff) format(\"woff\"),\n url(/static/media/blanch_caps_inline-webfont.8345e1b3.ttf) format(\"truetype\"),\n url(/static/media/blanch_caps_inline-webfont.7bbffda6.svg#blanchcaps_inline)\n format(\"svg\");\n font-weight: normal;\n font-style: normal;\n}\narticle,\naside,\ndetails,\nfigcaption,\nfigure,\nfooter,\nheader,\nhgroup,\nnav,\nsection,\nsummary {\n display: block;\n}\naudio,\ncanvas,\nvideo {\n display: inline-block;\n}\naudio:not([controls]) {\n display: none;\n height: 0;\n}\n[hidden] {\n display: none;\n}\nhtml {\n font-family: sans-serif;\n -webkit-text-size-adjust: 100%;\n -ms-text-size-adjust: 100%;\n}\na:focus {\n outline: thin dotted;\n}\na:active,\na:hover {\n outline: 0;\n}\nh1 {\n font-size: 2em;\n}\nabbr[title] {\n border-bottom: 1px dotted;\n}\nb,\nstrong {\n font-weight: 700;\n}\ndfn {\n font-style: italic;\n}\nmark {\n background: #ff0;\n color: #000;\n}\ncode,\nkbd,\npre,\nsamp {\n font-family: monospace, serif;\n font-size: 1em;\n}\npre {\n white-space: pre-wrap;\n word-wrap: break-word;\n}\nq {\n quotes: 2 1c 2 1d 2 18 2 19;\n}\nsmall {\n font-size: 80%;\n}\nsub,\nsup {\n font-size: 75%;\n line-height: 0;\n position: relative;\n vertical-align: baseline;\n}\nsup {\n top: -0.5em;\n}\nsub {\n bottom: -0.25em;\n}\nimg {\n border: 0;\n}\nsvg:not(:root) {\n overflow: hidden;\n}\nfieldset {\n border: 1px solid #c0c0c0;\n margin: 0 2px;\n padding: 0.35em 0.625em 0.75em;\n}\nbutton,\ninput,\nselect,\ntextarea {\n font-family: inherit;\n font-size: 100%;\n margin: 0;\n}\nbutton,\ninput {\n line-height: normal;\n}\nbutton,\nhtml input[type=\"button\"],\ninput[type=\"reset\"],\ninput[type=\"submit\"] {\n -webkit-appearance: button;\n cursor: pointer;\n}\nbutton[disabled],\ninput[disabled] {\n cursor: default;\n}\ninput[type=\"checkbox\"],\ninput[type=\"radio\"] {\n box-sizing: border-box;\n padding: 0;\n}\ninput[type=\"search\"] {\n -webkit-appearance: textfield;\n box-sizing: content-box;\n}\ninput[type=\"search\"]::-webkit-search-cancel-button,\ninput[type=\"search\"]::-webkit-search-decoration {\n -webkit-appearance: none;\n}\ntextarea {\n overflow: auto;\n vertical-align: top;\n}\ntable {\n border-collapse: collapse;\n border-spacing: 0;\n}\nbody,\nfigure {\n margin: 0;\n}\nlegend,\nbutton::-moz-focus-inner,\ninput::-moz-focus-inner {\n border: 0;\n padding: 0;\n}\n.clearfix:after {\n visibility: hidden;\n display: block;\n font-size: 0;\n content: \" \";\n clear: both;\n height: 0;\n}\n* {\n box-sizing: border-box;\n}\nhtml {\n font-size: 62.5%;\n}\nbody {\n background: #d4d4d4;\n -webkit-font-smoothing: antialiased;\n -moz-osx-font-smoothing: grayscale;\n font-family: \"Open Sans\", sans-serif;\n font-size: 2rem;\n}\nh1 {\n font-family: \"blanchcaps_inline\", sans-serif;\n text-align: center;\n font-weight: normal;\n margin: 0;\n}\nh2,\nh3,\nh4,\nh5,\nh6 {\n font-weight: normal;\n font-family: \"haymakerregular\", sans-serif;\n}\nh2 {\n text-align: center;\n margin-top: 0;\n margin-bottom: 2rem;\n}\nh3 {\n font-size: 3rem;\n}\nheader.top {\n text-align: center;\n}\nheader.top h1 {\n font-size: 14.4rem;\n line-height: 0.7;\n display: flex;\n justify-content: center;\n}\nheader.top h1 .ofThe {\n display: flex;\n font-size: 3rem;\n color: #f5a623;\n justify-content: center;\n align-items: center;\n background: url(/static/media/anchor.d2f8799a.svg) center no-repeat;\n background-size: cover;\n padding: 0 1rem;\n}\nheader.top h1 .ofThe .of {\n padding-right: 2rem;\n position: relative;\n right: -0.5rem;\n}\nheader.top h3 {\n margin: 0;\n font-size: 2rem;\n color: #f5a623;\n position: relative;\n display: inline-block;\n}\nheader.top h3 span {\n background: #fff;\n position: relative;\n z-index: 2;\n padding-left: 1rem;\n padding-right: 1rem;\n}\nheader.top h3:before,\nheader.top h3:after {\n display: block;\n z-index: 1;\n background: #000;\n position: absolute;\n width: 130%;\n height: 1px;\n content: \"\";\n top: 5px;\n margin-left: -15%;\n}\nheader.top h3:after {\n top: auto;\n bottom: 7px;\n}\n.catch-of-the-day {\n display: flex;\n height: 90vh;\n max-width: 1500px;\n margin: 0 auto;\n margin-top: 5vh;\n -webkit-perspective: 1000px;\n perspective: 1000px;\n -webkit-transform-style: preserve-3d;\n transform-style: preserve-3d;\n}\n.catch-of-the-day > * {\n flex: 1 4 auto;\n padding: 2rem;\n border: 1rem double #1a1a1a;\n position: relative;\n background: #fff;\n -webkit-transition: all 0.3s;\n transition: all 0.3s;\n box-shadow: 0 5px 5px rgba(0, 0, 0, 0.1);\n overflow: scroll;\n}\n.catch-of-the-day > *:first-child {\n flex-shrink: 1;\n flex-basis: 50%;\n -webkit-transform: translateX(50%) rotateY(6deg) translateX(-50%);\n transform: translateX(50%) rotateY(6deg) translateX(-50%);\n}\n.catch-of-the-day > *:nth-child(2) {\n -webkit-transform: translateX(-50%) rotateY(-14deg) translateX(50%);\n transform: translateX(-50%) rotateY(-14deg) translateX(50%);\n border-left: 0;\n border-right: 0;\n min-width: 300px;\n}\n.catch-of-the-day > *:last-child {\n flex-shrink: 1;\n flex-basis: 50%;\n -webkit-transform: translateX(-50%) rotateY(10deg) translateX(50%) scale(1.08)\n translateX(24px);\n transform: translateX(-50%) rotateY(10deg) translateX(50%) scale(1.08)\n translateX(24px);\n}\ninput#fold:not(:checked) ~ #main .catch-of-the-day > * {\n -webkit-transform: none;\n transform: none;\n}\nlabel[for=\"fold\"] {\n position: absolute;\n top: 1rem;\n left: 1rem;\n text-transform: uppercase;\n font-size: 1.3rem;\n background: #000;\n color: #fff;\n border: 2px solid #000;\n cursor: pointer;\n padding: 0.5rem 1rem;\n}\ninput#fold {\n display: none;\n}\ninput#fold:checked + label {\n background: #fff;\n color: #000;\n}\nul {\n list-style: none;\n margin: 0;\n padding: 0;\n}\nul.order li {\n border-bottom: 1px solid #000;\n padding: 2rem 0;\n display: flex;\n font-size: 1.4rem;\n justify-content: space-between;\n align-items: center;\n}\nul.order li:hover button {\n display: inline;\n}\nul.order li button {\n border: 0;\n display: none;\n line-height: 1;\n padding: 0;\n}\nul.order li.total {\n font-weight: 600;\n border-bottom: 3px solid #000;\n border-top: 3px double #000;\n}\nul.order li.unavailable {\n text-decoration: line-through;\n background: #f8d0d2;\n}\nul.order li .price {\n font-size: 1.2rem;\n}\nul.order li span.count {\n position: relative;\n overflow: hidden;\n float: left;\n}\nul.order li span.count span {\n display: inline-block;\n}\n.order-title {\n text-align: center;\n}\n.fish-edit {\n margin-bottom: 20px;\n border: 2px solid #000;\n overflow: hidden;\n display: flex;\n flex-wrap: wrap;\n}\n.fish-edit input,\n.fish-edit textarea,\n.fish-edit select {\n width: 33.33%;\n padding: 10px;\n line-height: 1;\n font-size: 1.2rem;\n border: 0;\n border-bottom: 1px solid #000;\n border-right: 1px solid #000;\n -webkit-appearance: none;\n -moz-appearance: none;\n appearance: none;\n border-radius: 0;\n background: #fff;\n}\n.fish-edit input:focus,\n.fish-edit textarea:focus,\n.fish-edit select:focus {\n outline: 0;\n background: #fef2de;\n}\n.fish-edit textarea {\n width: 100%;\n}\n.fish-edit input:last-of-type {\n width: 100%;\n}\n.fish-edit button {\n width: 100%;\n border: 0;\n}\n.list-of-fish {\n border-top: 2px solid #000;\n border-bottom: 1px solid #000;\n padding-top: 5px;\n margin-top: 2rem;\n -webkit-transform: translateZ(0);\n transform: translateZ(0);\n}\n.menu-fish {\n border-bottom: 2px solid #000;\n border-top: 1px solid #000;\n padding-bottom: 2rem;\n padding-top: 2rem;\n margin-bottom: 5px;\n clear: both;\n overflow: hidden;\n}\n.menu-fish p {\n margin: 0;\n font-size: 1.8rem;\n}\n.menu-fish .fish-name {\n margin: 0;\n display: flex;\n justify-content: space-between;\n align-items: center;\n}\n.menu-fish .price {\n font-size: 1.4rem;\n justify-content: flex-end;\n}\n.menu-fish img {\n float: left;\n width: 150px;\n margin-right: 1rem;\n}\nbutton,\ninput[type=\"submit\"] {\n text-transform: uppercase;\n background: none;\n border: 1px solid #000;\n font-weight: 600;\n font-size: 1.5rem;\n font-family: \"Open Sans\";\n -webkit-transition: all 0.2s;\n transition: all 0.2s;\n position: relative;\n z-index: 2;\n}\nbutton[disabled],\ninput[type=\"submit\"][disabled] {\n color: #d12028;\n background: #fff;\n border-color: #d12028;\n -webkit-transform: rotate(-10deg) scale(2) translateX(50%) translateY(-50%);\n transform: rotate(-10deg) scale(2) translateX(50%) translateY(-50%);\n}\nbutton[disabled]:hover,\ninput[type=\"submit\"][disabled]:hover {\n color: #d12028;\n cursor: not-allowed;\n}\nbutton[disabled]:after,\ninput[type=\"submit\"][disabled]:after {\n display: none;\n}\nbutton:after,\ninput[type=\"submit\"]:after {\n content: \"\";\n z-index: -1;\n display: block;\n background: #000;\n position: absolute;\n width: 100%;\n height: 0;\n left: 0;\n top: 0;\n -webkit-transition: all 0.2s;\n transition: all 0.2s;\n}\nbutton:hover,\ninput[type=\"submit\"]:hover,\nbutton:focus,\ninput[type=\"submit\"]:focus {\n color: #fff;\n outline: 0;\n}\nbutton:hover:after,\ninput[type=\"submit\"]:hover:after,\nbutton:focus:after,\ninput[type=\"submit\"]:focus:after {\n height: 100%;\n}\nbutton.warning:after,\ninput[type=\"submit\"].warning:after {\n background: #d12028;\n}\nbutton.success:after,\ninput[type=\"submit\"].success:after {\n background: #2dc22d;\n}\nbutton.github,\ninput[type=\"submit\"].github,\nbutton.facebook,\ninput[type=\"submit\"].facebook,\nbutton.twitter,\ninput[type=\"submit\"].twitter {\n border: 0;\n display: block;\n margin-bottom: 2rem;\n width: 100%;\n color: #fff;\n padding: 2rem;\n}\nbutton.github,\ninput[type=\"submit\"].github {\n background: #676d65;\n}\nbutton.github:after,\ninput[type=\"submit\"].github:after {\n background: #212b1d;\n}\nbutton.facebook,\ninput[type=\"submit\"].facebook {\n background: #3864a3;\n}\nbutton.facebook:after,\ninput[type=\"submit\"].facebook:after {\n background: #2d5082;\n}\nbutton.twitter,\ninput[type=\"submit\"].twitter {\n background: #5ea9dd;\n}\nbutton.twitter:after,\ninput[type=\"submit\"].twitter:after {\n background: #2c8dd0;\n}\n.store-selector {\n background: #fff;\n max-width: 500px;\n margin: 50px auto;\n padding: 2rem;\n border: 2px solid #000;\n}\n.store-selector input,\n.store-selector button {\n width: 100%;\n}\n.store-selector input[type=\"text\"],\n.store-selector button[type=\"text\"] {\n text-align: center;\n font-size: 3rem;\n}\n\n"]} \ No newline at end of file diff --git a/build/static/js/2.26935990.chunk.js b/build/static/js/2.26935990.chunk.js new file mode 100644 index 00000000..8e54a4ca --- /dev/null +++ b/build/static/js/2.26935990.chunk.js @@ -0,0 +1,2 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[2],[function(t,e,n){"use strict";t.exports=n(34)},function(t,e,n){"use strict";n.r(e),n.d(e,"__extends",function(){return i}),n.d(e,"__assign",function(){return o}),n.d(e,"__rest",function(){return a}),n.d(e,"__decorate",function(){return s}),n.d(e,"__param",function(){return u}),n.d(e,"__metadata",function(){return c}),n.d(e,"__awaiter",function(){return l}),n.d(e,"__generator",function(){return h}),n.d(e,"__exportStar",function(){return f}),n.d(e,"__values",function(){return p}),n.d(e,"__read",function(){return d}),n.d(e,"__spread",function(){return y}),n.d(e,"__await",function(){return m}),n.d(e,"__asyncGenerator",function(){return g}),n.d(e,"__asyncDelegator",function(){return v}),n.d(e,"__asyncValues",function(){return b}),n.d(e,"__makeTemplateObject",function(){return _}),n.d(e,"__importStar",function(){return w}),n.d(e,"__importDefault",function(){return E});var r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};function i(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var o=Object.assign||function(t){for(var e,n=1,r=arguments.length;n=0;s--)(i=t[s])&&(a=(o<3?i(a):o>3?i(e,n,a):i(e,n))||a);return o>3&&a&&Object.defineProperty(e,n,a),a}function u(t,e){return function(n,r){e(n,r,t)}}function c(t,e){if("object"===typeof Reflect&&"function"===typeof Reflect.metadata)return Reflect.metadata(t,e)}function l(t,e,n,r){return new(n||(n=Promise))(function(i,o){function a(t){try{u(r.next(t))}catch(e){o(e)}}function s(t){try{u(r.throw(t))}catch(e){o(e)}}function u(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(a,s)}u((r=r.apply(t,e||[])).next())})}function h(t,e){var n,r,i,o,a={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:s(0),throw:s(1),return:s(2)},"function"===typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function s(o){return function(s){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(i=r[2&o[0]?"return":o[0]?"throw":"next"])&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[0,i.value]),o[0]){case 0:case 1:i=o;break;case 4:return a.label++,{value:o[1],done:!1};case 5:a.label++,r=o[1],o=[0];continue;case 7:o=a.ops.pop(),a.trys.pop();continue;default:if(!(i=(i=a.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){a=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}}}function d(t,e){var n="function"===typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,i,o=n.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=o.next()).done;)a.push(r.value)}catch(s){i={error:s}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(i)throw i.error}}return a}function y(){for(var t=[],e=0;e1||s(t,e)})})}function s(t,e){try{(n=i[t](e)).value instanceof m?Promise.resolve(n.value.v).then(u,c):l(o[0][2],n)}catch(r){l(o[0][3],r)}var n}function u(t){s("next",t)}function c(t){s("throw",t)}function l(t,e){t(e),o.shift(),o.length&&s(o[0][0],o[0][1])}}function v(t){var e,n;return e={},r("next"),r("throw",function(t){throw t}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(r,i){t[r]&&(e[r]=function(e){return(n=!n)?{value:m(t[r](e)),done:"return"===r}:i?i(e):e})}}function b(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator];return e?e.call(t):p(t)}function _(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function w(t){if(t&&t.__esModule)return t;var e={};if(null!=t)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function E(t){return t&&t.__esModule?t:{default:t}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(14),i=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},o="[DEFAULT]",a=[],s=function(){function t(t,e,n){this.firebase_=n,this.isDeleted_=!1,this.services_={},this.name_=e.name,this._automaticDataCollectionEnabled=e.automaticDataCollectionEnabled||!1,this.options_=r.deepCopy(t),this.INTERNAL={getUid:function(){return null},getToken:function(){return Promise.resolve(null)},addAuthTokenListener:function(t){a.push(t),setTimeout(function(){return t(null)},0)},removeAuthTokenListener:function(t){a=a.filter(function(e){return e!==t})}}}return Object.defineProperty(t.prototype,"automaticDataCollectionEnabled",{get:function(){return this.checkDestroyed_(),this._automaticDataCollectionEnabled},set:function(t){this.checkDestroyed_(),this._automaticDataCollectionEnabled=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"name",{get:function(){return this.checkDestroyed_(),this.name_},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"options",{get:function(){return this.checkDestroyed_(),this.options_},enumerable:!0,configurable:!0}),t.prototype.delete=function(){var t=this;return new Promise(function(e){t.checkDestroyed_(),e()}).then(function(){t.firebase_.INTERNAL.removeApp(t.name_);var e=[];return Object.keys(t.services_).forEach(function(n){Object.keys(t.services_[n]).forEach(function(r){e.push(t.services_[n][r])})}),Promise.all(e.map(function(t){return t.INTERNAL.delete()}))}).then(function(){t.isDeleted_=!0,t.services_={}})},t.prototype._getService=function(t,e){if(void 0===e&&(e=o),this.checkDestroyed_(),this.services_[t]||(this.services_[t]={}),!this.services_[t][e]){var n=e!==o?e:void 0,r=this.firebase_.INTERNAL.factories[t](this,this.extendApp.bind(this),n);this.services_[t][e]=r}return this.services_[t][e]},t.prototype.extendApp=function(t){var e=this;r.deepExtend(this,t),t.INTERNAL&&t.INTERNAL.addAuthTokenListener&&(a.forEach(function(t){e.INTERNAL.addAuthTokenListener(t)}),a=[])},t.prototype.checkDestroyed_=function(){this.isDeleted_&&u("app-deleted",{name:this.name_})},t}();function u(t,e){throw c.create(t,e)}s.prototype.name&&s.prototype.options||s.prototype.delete||console.log("dc");var c=new r.ErrorFactory("app","Firebase",{"no-app":"No Firebase App '{$name}' has been created - call Firebase App.initializeApp()","bad-app-name":"Illegal App name: '{$name}","duplicate-app":"Firebase App named '{$name}' already exists","app-deleted":"Firebase App named '{$name}' already deleted","duplicate-service":"Firebase service named '{$name}' already registered","sa-not-supported":"Initializing the Firebase SDK with a service account is only allowed in a Node.js environment. On client devices, you should instead initialize the SDK with an api key and auth domain","invalid-app-argument":"firebase.{$name}() takes either no argument or a Firebase App instance."}),l=function t(){var e={},n={},a={},c={__esModule:!0,initializeApp:function(t,n){if(void 0===n&&(n={}),"object"!==typeof n||null===n){var r=n;n={name:r}}var a=n;void 0===a.name&&(a.name=o);var l=a.name;"string"===typeof l&&l||u("bad-app-name",{name:l+""}),i(e,l)&&u("duplicate-app",{name:l});var h=new s(t,a,c);return e[l]=h,f(h,"create"),h},app:l,apps:null,Promise:Promise,SDK_VERSION:"5.5.9",INTERNAL:{registerService:function(t,e,i,o,f){n[t]&&u("duplicate-service",{name:t}),n[t]=e,o&&(a[t]=o,h().forEach(function(t){o("create",t)}));var p=function(e){return void 0===e&&(e=l()),"function"!==typeof e[t]&&u("invalid-app-argument",{name:t}),e[t]()};return void 0!==i&&r.deepExtend(p,i),c[t]=p,s.prototype[t]=function(){for(var e=[],n=0;n>6|192,e[n++]=63&i|128):55296==(64512&i)&&r+1>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128)}return e},u={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:function(t,e){if(!Array.isArray(t))throw Error("encodeByteArray takes an array as a parameter");this.init_();for(var n=e?this.byteToCharMapWebSafe_:this.byteToCharMap_,r=[],i=0;i>2,h=(3&o)<<4|s>>4,f=(15&s)<<2|c>>6,p=63&c;u||(p=64,a||(f=64)),r.push(n[l],n[h],n[f],n[p])}return r.join("")},encodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?btoa(t):this.encodeByteArray(s(t),e)},decodeString:function(t,e){return this.HAS_NATIVE_SUPPORT&&!e?atob(t):function(t){for(var e=[],n=0,r=0;n191&&i<224){var o=t[n++];e[r++]=String.fromCharCode((31&i)<<6|63&o)}else if(i>239&&i<365){var a=((7&i)<<18|(63&(o=t[n++]))<<12|(63&(s=t[n++]))<<6|63&t[n++])-65536;e[r++]=String.fromCharCode(55296+(a>>10)),e[r++]=String.fromCharCode(56320+(1023&a))}else{o=t[n++];var s=t[n++];e[r++]=String.fromCharCode((15&i)<<12|(63&o)<<6|63&s)}}return e.join("")}(this.decodeStringToByteArray(t,e))},decodeStringToByteArray:function(t,e){this.init_();for(var n=e?this.charToByteMapWebSafe_:this.charToByteMap_,r=[],i=0;i>4;if(r.push(c),64!=s){var l=a<<4&240|s>>2;if(r.push(l),64!=u){var h=s<<6&192|u;r.push(h)}}}return r},init_:function(){if(!this.byteToCharMap_){this.byteToCharMap_={},this.charToByteMap_={},this.byteToCharMapWebSafe_={},this.charToByteMapWebSafe_={};for(var t=0;t=this.ENCODED_VALS_BASE.length&&(this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(t)]=t,this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(t)]=t)}}},c=function(t){try{return u.decodeString(t,!0)}catch(e){console.error("base64Decode failed: ",e)}return null};function l(t,e){if(!(e instanceof Object))return e;switch(e.constructor){case Date:return new Date(e.getTime());case Object:void 0===t&&(t={});break;case Array:t=[];break;default:return e}for(var n in e)e.hasOwnProperty(n)&&(t[n]=l(t[n],e[n]));return t}var h=function(){function t(){var t=this;this.promise=new Promise(function(e,n){t.resolve=e,t.reject=n})}return t.prototype.wrapCallback=function(t){var e=this;return function(n,r){n?e.reject(n):e.resolve(r),"function"===typeof t&&(e.promise.catch(function(){}),1===t.length?t(n):t(n,r))}},t}(),f=function(){return"undefined"!==typeof navigator&&"string"===typeof navigator.userAgent?navigator.userAgent:""},p="FirebaseError",d=Error.captureStackTrace;var y=function(){return function(t,e){if(this.code=t,this.message=e,d)d(this,m.prototype.create);else try{throw Error.apply(this,arguments)}catch(n){this.name=p,Object.defineProperty(this,"stack",{get:function(){return n.stack}})}}}();y.prototype=Object.create(Error.prototype),y.prototype.constructor=y,y.prototype.name=p;var m=function(){function t(t,e,n){this.service=t,this.serviceName=e,this.errors=n,this.pattern=/\{\$([^}]+)}/g}return t.prototype.create=function(t,e){void 0===e&&(e={});var n,r=this.errors[t],i=this.service+"/"+t;n=void 0===r?"Error":r.replace(this.pattern,function(t,n){var r=e[n];return void 0!==r?r.toString():"<"+n+"?>"}),n=this.serviceName+": "+n+" ("+i+").";var o=new y(i,n);for(var a in e)e.hasOwnProperty(a)&&"_"!==a.slice(-1)&&(o[a]=e[a]);return o},t}();function g(t){return JSON.parse(t)}var v=function(t){var e={},n={},r={},i="";try{var o=t.split(".");e=g(c(o[0])||""),n=g(c(o[1])||""),i=o[2],r=n.d||{},delete n.d}catch(a){}return{header:e,claims:n,data:r,signature:i}},b=function(t,e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e(n,t[n])},_=function(t,e){return b(e,function(e,n){t[e]=n}),t},w=function(t,e,n){for(var r in t)if(e.call(n,t[r],r,t))return r},E=function(t){function e(){var e=t.call(this)||this;e.chain_=[],e.buf_=[],e.W_=[],e.pad_=[],e.inbuf_=0,e.total_=0,e.blockSize=64,e.pad_[0]=128;for(var n=1;n>>31)}var o,a,s=this.chain_[0],u=this.chain_[1],c=this.chain_[2],l=this.chain_[3],h=this.chain_[4];for(r=0;r<80;r++){r<40?r<20?(o=l^u&(c^l),a=1518500249):(o=u^c^l,a=1859775393):r<60?(o=u&c|l&(u|c),a=2400959708):(o=u^c^l,a=3395469782);i=(s<<5|s>>>27)+o+h+a+n[r]&4294967295;h=l,l=c,c=4294967295&(u<<30|u>>>2),u=s,s=i}this.chain_[0]=this.chain_[0]+s&4294967295,this.chain_[1]=this.chain_[1]+u&4294967295,this.chain_[2]=this.chain_[2]+c&4294967295,this.chain_[3]=this.chain_[3]+l&4294967295,this.chain_[4]=this.chain_[4]+h&4294967295},e.prototype.update=function(t,e){if(null!=t){void 0===e&&(e=t.length);for(var n=e-this.blockSize,r=0,i=this.buf_,o=this.inbuf_;r=56;n--)this.buf_[n]=255&e,e/=256;this.compress_(this.buf_);var r=0;for(n=0;n<5;n++)for(var i=24;i>=0;i-=8)t[r]=this.chain_[n]>>i&255,++r;return t},e}(function(){return function(){this.blockSize=-1}}());var T=function(){function t(t,e){var n=this;this.observers=[],this.unsubscribes=[],this.observerCount=0,this.task=Promise.resolve(),this.finalized=!1,this.onNoObservers=e,this.task.then(function(){t(n)}).catch(function(t){n.error(t)})}return t.prototype.next=function(t){this.forEachObserver(function(e){e.next(t)})},t.prototype.error=function(t){this.forEachObserver(function(e){e.error(t)}),this.close(t)},t.prototype.complete=function(){this.forEachObserver(function(t){t.complete()}),this.close()},t.prototype.subscribe=function(t,e,n){var r,i=this;if(void 0===t&&void 0===e&&void 0===n)throw new Error("Missing Observer.");void 0===(r=function(t,e){if("object"!==typeof t||null===t)return!1;for(var n=0,r=e;n 4. Need to update it?")}var i=t+" failed: ";return i+=r+" argument "}e.assert=o,e.assertionError=a,e.base64=u,e.base64Decode=c,e.base64Encode=function(t){var e=s(t);return u.encodeByteArray(e,!0)},e.CONSTANTS=i,e.deepCopy=function(t){return l(void 0,t)},e.deepExtend=l,e.patchProperty=function(t,e,n){t[e]=n},e.Deferred=h,e.getUA=f,e.isMobileCordova=function(){return"undefined"!==typeof window&&!!(window.cordova||window.phonegap||window.PhoneGap)&&/ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(f())},e.isNodeSdk=function(){return!0===i.NODE_CLIENT||!0===i.NODE_ADMIN},e.isReactNative=function(){return"object"===typeof navigator&&"ReactNative"===navigator.product},e.ErrorFactory=m,e.FirebaseError=y,e.patchCapture=function(t){var e=d;return d=t,e},e.jsonEval=g,e.stringify=function(t){return JSON.stringify(t)},e.decode=v,e.isAdmin=function(t){var e=v(t).claims;return"object"===typeof e&&!0===e.admin},e.issuedAtTime=function(t){var e=v(t).claims;return"object"===typeof e&&e.hasOwnProperty("iat")?e.iat:null},e.isValidFormat=function(t){var e=v(t).claims;return!!e&&"object"===typeof e&&e.hasOwnProperty("iat")},e.isValidTimestamp=function(t){var e,n,r=v(t).claims,i=Math.floor((new Date).getTime()/1e3);return"object"===typeof r&&(r.hasOwnProperty("nbf")?e=r.nbf:r.hasOwnProperty("iat")&&(e=r.iat),n=r.hasOwnProperty("exp")?r.exp:e+86400),i&&e&&n&&i>=e&&i<=n},e.clone=function(t){return _({},t)},e.contains=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.every=function(t,e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&!e(n,t[n]))return!1;return!0},e.extend=_,e.findKey=w,e.findValue=function(t,e,n){var r=w(t,e,n);return r&&t[r]},e.forEach=b,e.getAnyKey=function(t){for(var e in t)return e},e.getCount=function(t){var e=0;for(var n in t)e++;return e},e.getValues=function(t){var e=[],n=0;for(var r in t)e[n++]=t[r];return e},e.isEmpty=function(t){for(var e in t)return!1;return!0},e.isNonNullObject=function(t){return"object"===typeof t&&null!==t},e.map=function(t,e,n){var r={};for(var i in t)r[i]=e.call(n,t[i],i,t);return r},e.safeGet=function(t,e){if(Object.prototype.hasOwnProperty.call(t,e))return t[e]},e.querystring=function(t){var e=[];return b(t,function(t,n){Array.isArray(n)?n.forEach(function(n){e.push(encodeURIComponent(t)+"="+encodeURIComponent(n))}):e.push(encodeURIComponent(t)+"="+encodeURIComponent(n))}),e.length?"&"+e.join("&"):""},e.querystringDecode=function(t){var e={};return t.replace(/^\?/,"").split("&").forEach(function(t){if(t){var n=t.split("=");e[n[0]]=n[1]}}),e},e.Sha1=E,e.async=function(t,e){return function(){for(var n=[],r=0;rn&&(i=0===n?"none":"no more than "+n),i)throw new Error(t+" failed: Was called with "+r+(1===r?" argument.":" arguments.")+" Expects "+i+".")},e.validateCallback=function(t,e,n,r){if((!r||n)&&"function"!==typeof n)throw new Error(C(t,e,r)+"must be a valid function.")},e.validateContextObject=function(t,e,n,r){if((!r||n)&&("object"!==typeof n||null===n))throw new Error(C(t,e,r)+"must be a valid context object.")},e.validateNamespace=function(t,e,n,r){if((!r||n)&&"string"!==typeof n)throw new Error(C(t,e,r)+"must be a valid firebase namespace.")},e.stringLength=function(t){for(var e=0,n=0;n=55296&&r<=56319?(e+=4,n++):e+=3}return e},e.stringToByteArray=function(t){for(var e=[],n=0,r=0;r=55296&&i<=56319){var a=i-55296;o(++r>6|192,e[n++]=63&i|128):i<65536?(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128)}return e}},function(t,e,n){"use strict";n(28);var r,i=(r=n(2))&&"object"===typeof r&&"default"in r?r.default:r;n(52),n(53),n(54),n(56),n(57),n(58),console.warn("\nIt looks like you're using the development build of the Firebase JS SDK.\nWhen deploying Firebase apps to production, it is advisable to only import\nthe individual SDK components you intend to use.\n\nFor the module builds, these are available in the following manner\n(replace with the name of a component - i.e. auth, database, etc):\n\nCommonJS Modules:\nconst firebase = require('firebase/app');\nrequire('firebase/');\n\nES Modules:\nimport firebase from 'firebase/app';\nimport 'firebase/';\n\nTypescript:\nimport * as firebase from 'firebase/app';\nimport 'firebase/';\n"),t.exports=i},function(t,e,n){"use strict";var r=s(n(38)),i=s(n(45)),o=s(n(27)),a=s(n(24));function s(t){return t&&t.__esModule?t:{default:t}}t.exports={Transition:a.default,TransitionGroup:o.default,ReplaceTransition:i.default,CSSTransition:r.default}},function(t,e,n){"use strict";function r(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}n.d(e,"a",function(){return r})},function(t,e,n){t.exports=n(47)},function(t,e,n){"use strict";!function t(){if("undefined"!==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE)try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(t)}catch(e){console.error(e)}}(),t.exports=n(35)},function(t,e,n){"use strict";function r(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}n.d(e,"a",function(){return r})},function(t,e,n){"use strict";var r=n(32),i=n.n(r),o={},a=0;e.a=function(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];"string"===typeof e&&(e={path:e});var r=e,s=r.path,u=r.exact,c=void 0!==u&&u,l=r.strict,h=void 0!==l&&l,f=r.sensitive;if(null==s)return n;var p=function(t,e){var n=""+e.end+e.strict+e.sensitive,r=o[n]||(o[n]={});if(r[t])return r[t];var s=[],u={re:i()(t,s,e),keys:s};return a<1e4&&(r[t]=u,a++),u}(s,{end:c,strict:h,sensitive:void 0!==f&&f}),d=p.re,y=p.keys,m=d.exec(t);if(!m)return null;var g=m[0],v=m.slice(1),b=t===g;return c&&!b?null:{path:s,url:"/"===s&&""===g?"/":g,isExact:b,params:y.reduce(function(t,e,n){return t[e.name]=v[n],t},{})}}},function(t,e,n){"use strict";function r(t,e,n,r,i,o,a){try{var s=t[o](a),u=s.value}catch(c){return void n(c)}s.done?e(u):Promise.resolve(u).then(r,i)}function i(t){return function(){var e=this,n=arguments;return new Promise(function(i,o){var a=t.apply(e,n);function s(t){r(a,i,o,s,u,"next",t)}function u(t){r(a,i,o,s,u,"throw",t)}s(void 0)})}}n.d(e,"a",function(){return i})},function(t,e,n){"use strict";var r=Object.getOwnPropertySymbols,i=Object.prototype.hasOwnProperty,o=Object.prototype.propertyIsEnumerable;t.exports=function(){try{if(!Object.assign)return!1;var t=new String("abc");if(t[5]="de","5"===Object.getOwnPropertyNames(t)[0])return!1;for(var e={},n=0;n<10;n++)e["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(e).map(function(t){return e[t]}).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach(function(t){r[t]=t}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(i){return!1}}()?Object.assign:function(t,e){for(var n,a,s=function(t){if(null===t||void 0===t)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(t)}(t),u=1;u=0||(i[n]=t[n]);return i}(e,["children"]);if(delete r.in,delete r.mountOnEnter,delete r.unmountOnExit,delete r.appear,delete r.enter,delete r.exit,delete r.timeout,delete r.addEndListener,delete r.onEnter,delete r.onEntering,delete r.onEntered,delete r.onExit,delete r.onExiting,delete r.onExited,"function"===typeof n)return n(t,r);var o=i.default.Children.only(n);return i.default.cloneElement(o,r)},r}(i.default.Component);function p(){}f.contextTypes={transitionGroup:r.object},f.childContextTypes={transitionGroup:function(){}},f.propTypes={},f.defaultProps={in:!1,mountOnEnter:!1,unmountOnExit:!1,appear:!1,enter:!0,exit:!0,onEnter:p,onEntering:p,onEntered:p,onExit:p,onExiting:p,onExited:p},f.UNMOUNTED=0,f.EXITED=1,f.ENTERING=2,f.ENTERED=3,f.EXITING=4;var d=(0,a.polyfill)(f);e.default=d},function(t,e,n){"use strict";function r(){var t=this.constructor.getDerivedStateFromProps(this.props,this.state);null!==t&&void 0!==t&&this.setState(t)}function i(t){this.setState(function(e){var n=this.constructor.getDerivedStateFromProps(t,e);return null!==n&&void 0!==n?n:null}.bind(this))}function o(t,e){try{var n=this.props,r=this.state;this.props=t,this.state=e,this.__reactInternalSnapshotFlag=!0,this.__reactInternalSnapshot=this.getSnapshotBeforeUpdate(n,r)}finally{this.props=n,this.state=r}}function a(t){var e=t.prototype;if(!e||!e.isReactComponent)throw new Error("Can only polyfill class components");if("function"!==typeof t.getDerivedStateFromProps&&"function"!==typeof e.getSnapshotBeforeUpdate)return t;var n=null,a=null,s=null;if("function"===typeof e.componentWillMount?n="componentWillMount":"function"===typeof e.UNSAFE_componentWillMount&&(n="UNSAFE_componentWillMount"),"function"===typeof e.componentWillReceiveProps?a="componentWillReceiveProps":"function"===typeof e.UNSAFE_componentWillReceiveProps&&(a="UNSAFE_componentWillReceiveProps"),"function"===typeof e.componentWillUpdate?s="componentWillUpdate":"function"===typeof e.UNSAFE_componentWillUpdate&&(s="UNSAFE_componentWillUpdate"),null!==n||null!==a||null!==s){var u=t.displayName||t.name,c="function"===typeof t.getDerivedStateFromProps?"getDerivedStateFromProps()":"getSnapshotBeforeUpdate()";throw Error("Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n"+u+" uses "+c+" but also contains the following legacy lifecycles:"+(null!==n?"\n "+n:"")+(null!==a?"\n "+a:"")+(null!==s?"\n "+s:"")+"\n\nThe above lifecycles should be removed. Learn more about this warning here:\nhttps://fb.me/react-async-component-lifecycle-hooks")}if("function"===typeof t.getDerivedStateFromProps&&(e.componentWillMount=r,e.componentWillReceiveProps=i),"function"===typeof e.getSnapshotBeforeUpdate){if("function"!==typeof e.componentDidUpdate)throw new Error("Cannot polyfill getSnapshotBeforeUpdate() for components that do not define componentDidUpdate() on the prototype");e.componentWillUpdate=o;var l=e.componentDidUpdate;e.componentDidUpdate=function(t,e,n){var r=this.__reactInternalSnapshotFlag?this.__reactInternalSnapshot:n;l.call(this,t,e,r)}}return t}n.r(e),n.d(e,"polyfill",function(){return a}),r.__suppressDeprecationWarning=!0,i.__suppressDeprecationWarning=!0,o.__suppressDeprecationWarning=!0},function(t,e,n){"use strict";e.__esModule=!0,e.transitionTimeout=function(t){var e="transition"+t+"Timeout",n="transition"+t;return function(t){if(t[n]){if(null==t[e])return new Error(e+" wasn't supplied to CSSTransitionGroup: this can cause unreliable animations and won't be supported in a future version of React. See https://fb.me/react-animation-transition-group-timeout for more information.");if("number"!==typeof t[e])return new Error(e+" must be a number (in milliseconds)")}return null}},e.classNamesShape=e.timeoutsShape=void 0;var r,i=(r=n(3))&&r.__esModule?r:{default:r};var o=i.default.oneOfType([i.default.number,i.default.shape({enter:i.default.number,exit:i.default.number}).isRequired]);e.timeoutsShape=o;var a=i.default.oneOfType([i.default.string,i.default.shape({enter:i.default.string,exit:i.default.string,active:i.default.string}),i.default.shape({enter:i.default.string,enterDone:i.default.string,enterActive:i.default.string,exit:i.default.string,exitDone:i.default.string,exitActive:i.default.string})]);e.classNamesShape=a},function(t,e,n){"use strict";e.__esModule=!0,e.default=void 0;var r=s(n(3)),i=s(n(0)),o=n(25),a=n(46);function s(t){return t&&t.__esModule?t:{default:t}}function u(){return(u=Object.assign||function(t){for(var e=1;e=0||(i[n]=t[n]);return i}(t,["component","childFactory"]),o=l(this.state.children).map(n);return delete r.appear,delete r.enter,delete r.exit,null===e?o:i.default.createElement(e,r,o)},r}(i.default.Component);h.childContextTypes={transitionGroup:r.default.object.isRequired},h.propTypes={},h.defaultProps={component:"div",childFactory:function(t){return t}};var f=(0,o.polyfill)(h);e.default=f,t.exports=e.default},function(t,e,n){"use strict";n.r(e),function(t,e){n(51);var r=setTimeout;function i(){}function o(t){if(!(this instanceof o))throw new TypeError("Promises must be constructed via new");if("function"!==typeof t)throw new TypeError("not a function");this._state=0,this._handled=!1,this._value=void 0,this._deferreds=[],h(t,this)}function a(t,e){for(;3===t._state;)t=t._value;0!==t._state?(t._handled=!0,o._immediateFn(function(){var n=1===t._state?e.onFulfilled:e.onRejected;if(null!==n){var r;try{r=n(t._value)}catch(i){return void u(e.promise,i)}s(e.promise,r)}else(1===t._state?s:u)(e.promise,t._value)})):t._deferreds.push(e)}function s(t,e){try{if(e===t)throw new TypeError("A promise cannot be resolved with itself.");if(e&&("object"===typeof e||"function"===typeof e)){var n=e.then;if(e instanceof o)return t._state=3,t._value=e,void c(t);if("function"===typeof n)return void h((r=n,i=e,function(){r.apply(i,arguments)}),t)}t._state=1,t._value=e,c(t)}catch(a){u(t,a)}var r,i}function u(t,e){t._state=2,t._value=e,c(t)}function c(t){2===t._state&&0===t._deferreds.length&&o._immediateFn(function(){t._handled||o._unhandledRejectionFn(t._value)});for(var e=0,n=t._deferreds.length;e0?K:W)(t)},H=Math.min,z=function(t){return t>0?H(Q(t),9007199254740991):0},G=Array.isArray||function(t){return"Array"==j(t)},Y=d["__core-js_shared__"]||(d["__core-js_shared__"]={}),X=function(t){return Y[t]||(Y[t]={})},J=p(function(t){var e=X("wks"),n=d.Symbol,r="function"==typeof n;(t.exports=function(t){return e[t]||(e[t]=r&&n[t]||(r?n:P)("Symbol."+t))}).store=e}),$=J("species"),Z=function(t,e){return new(function(t){var e;return G(t)&&("function"!=typeof(e=t.constructor)||e!==Array&&!G(e.prototype)||(e=void 0),m(e)&&null===(e=e[$])&&(e=void 0)),void 0===e?Array:e}(t))(e)},tt=function(t,e){var n=1==t,r=2==t,i=3==t,o=4==t,a=6==t,s=5==t||a,u=e||Z;return function(e,c,l){for(var h,f,p=q(e),d=V(p),y=L(c,l,3),m=z(d.length),g=0,v=n?u(e,m):r?u(e,0):void 0;m>g;g++)if((s||g in d)&&(f=y(h=d[g],g,p),t))if(n)v[g]=f;else if(f)switch(t){case 3:return!0;case 5:return h;case 6:return g;case 2:v.push(h)}else if(o)return!1;return a?-1:i||o?o:v}},et=J("unscopables"),nt=Array.prototype;void 0==nt[et]&&k(nt,et,{});var rt=function(t){nt[et][t]=!0},it=tt(5),ot=!0;"find"in[]&&Array(1).find(function(){ot=!1}),F(F.P+F.F*ot,"Array",{find:function(t){return it(this,t,arguments.length>1?arguments[1]:void 0)}}),rt("find");y.Array.find;var at=tt(6),st=!0;"findIndex"in[]&&Array(1).findIndex(function(){st=!1}),F(F.P+F.F*st,"Array",{findIndex:function(t){return at(this,t,arguments.length>1?arguments[1]:void 0)}}),rt("findIndex");y.Array.findIndex;var ut,ct=function(t){return V(B(t))},lt=Math.max,ht=Math.min,ft=X("keys"),pt=function(t){return ft[t]||(ft[t]=P(t))},dt=(ut=!1,function(t,e,n){var r,i=ct(t),o=z(i.length),a=function(t,e){return(t=Q(t))<0?lt(t+e,0):ht(t,e)}(n,o);if(ut&&e!=e){for(;o>a;)if((r=i[a++])!=r)return!0}else for(;o>a;a++)if((ut||a in i)&&i[a]===e)return ut||a||0;return!ut&&-1}),yt=pt("IE_PROTO"),mt=function(t,e){var n,r=ct(t),i=0,o=[];for(n in r)n!=yt&&A(r,n)&&o.push(n);for(;e.length>i;)A(r,n=e[i++])&&(~dt(o,n)||o.push(n));return o},gt="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(","),vt=Object.keys||function(t){return mt(t,gt)},bt={f:Object.getOwnPropertySymbols},_t={f:{}.propertyIsEnumerable},wt=Object.assign,Et=!wt||v(function(){var t={},e={},n=Symbol(),r="abcdefghijklmnopqrst";return t[n]=7,r.split("").forEach(function(t){e[t]=t}),7!=wt({},t)[n]||Object.keys(wt({},e)).join("")!=r})?function(t,e){for(var n=q(t),r=arguments.length,i=1,o=bt.f,a=_t.f;r>i;)for(var s,u=V(arguments[i++]),c=o?vt(u).concat(o(u)):vt(u),l=c.length,h=0;l>h;)a.call(u,s=c[h++])&&(n[s]=u[s]);return n}:wt;F(F.S+F.F,"Object",{assign:Et});y.Object.assign;var Tt=J("match"),St=function(t,e,n){if(function(t){var e;return m(t)&&(void 0!==(e=t[Tt])?!!e:"RegExp"==j(t))}(e))throw TypeError("String#"+n+" doesn't accept regex!");return String(B(t))},Ct=J("match"),It="".startsWith;F(F.P+F.F*function(t){var e=/./;try{"/./"[t](e)}catch(n){try{return e[Ct]=!1,!"/./"[t](e)}catch(r){}}return!0}("startsWith"),"String",{startsWith:function(t){var e=St(this,t,"startsWith"),n=z(Math.min(arguments.length>1?arguments[1]:void 0,e.length)),r=String(t);return It?It.call(e,r,n):e.slice(n,n+r.length)===r}});y.String.startsWith;F(F.P,"String",{repeat:function(t){var e=String(B(this)),n="",r=Q(t);if(r<0||r==1/0)throw RangeError("Count can't be negative");for(;r>0;(r>>>=1)&&(e+=e))1&r&&(n+=e);return n}});y.String.repeat;var Nt=p(function(t){var e=P("meta"),n=I.f,r=0,i=Object.isExtensible||function(){return!0},o=!v(function(){return i(Object.preventExtensions({}))}),a=function(t){n(t,e,{value:{i:"O"+ ++r,w:{}}})},s=t.exports={KEY:e,NEED:!1,fastKey:function(t,n){if(!m(t))return"symbol"==typeof t?t:("string"==typeof t?"S":"P")+t;if(!A(t,e)){if(!i(t))return"F";if(!n)return"E";a(t)}return t[e].i},getWeak:function(t,n){if(!A(t,e)){if(!i(t))return!0;if(!n)return!1;a(t)}return t[e].w},onFreeze:function(t){return o&&s.NEED&&i(t)&&!A(t,e)&&a(t),t}}}),kt=(Nt.KEY,Nt.NEED,Nt.fastKey,Nt.getWeak,Nt.onFreeze,I.f),Dt=J("toStringTag"),At=function(t,e,n){t&&!A(t=n?t:t.prototype,Dt)&&kt(t,Dt,{configurable:!0,value:e})},Ot={f:J},Rt=I.f,Pt=function(t){var e=y.Symbol||(y.Symbol=d.Symbol||{});"_"==t.charAt(0)||t in e||Rt(e,t,{value:Ot.f(t)})},xt=b?Object.defineProperties:function(t,e){g(t);for(var n,r=vt(e),i=r.length,o=0;i>o;)I.f(t,n=r[o++],e[n]);return t},Lt=d.document,Mt=Lt&&Lt.documentElement,Ft=pt("IE_PROTO"),Ut=function(){},jt=function(){var t,e=E("iframe"),n=gt.length;for(e.style.display="none",Mt.appendChild(e),e.src="javascript:",(t=e.contentWindow.document).open(),t.write("';\n }\n\n var iframeContents = '' + script + '';\n\n try {\n this.myIFrame.doc.open();\n this.myIFrame.doc.write(iframeContents);\n this.myIFrame.doc.close();\n } catch (e) {\n log('frame writing exception');\n\n if (e.stack) {\n log(e.stack);\n }\n\n log(e);\n }\n } else {\n this.commandCB = commandCB;\n this.onMessageCB = onMessageCB;\n }\n }\n /**\r\n * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can\r\n * actually use.\r\n * @private\r\n * @return {Element}\r\n */\n\n\n FirebaseIFrameScriptHolder.createIFrame_ = function () {\n var iframe = document.createElement('iframe');\n iframe.style.display = 'none'; // This is necessary in order to initialize the document inside the iframe\n\n if (document.body) {\n document.body.appendChild(iframe);\n\n try {\n // If document.domain has been modified in IE, this will throw an error, and we need to set the\n // domain of the iframe's document manually. We can do this via a javascript: url as the src attribute\n // Also note that we must do this *after* the iframe has been appended to the page. Otherwise it doesn't work.\n var a = iframe.contentWindow.document;\n\n if (!a) {\n // Apologies for the log-spam, I need to do something to keep closure from optimizing out the assignment above.\n log('No IE domain setting required');\n }\n } catch (e) {\n var domain = document.domain;\n iframe.src = \"javascript:void((function(){document.open();document.domain='\" + domain + \"';document.close();})())\";\n }\n } else {\n // LongPollConnection attempts to delay initialization until the document is ready, so hopefully this\n // never gets hit.\n throw 'Document body has not initialized. Wait to initialize Firebase until after the document is ready.';\n } // Get the document of the iframe in a browser-specific way.\n\n\n if (iframe.contentDocument) {\n iframe.doc = iframe.contentDocument; // Firefox, Opera, Safari\n } else if (iframe.contentWindow) {\n iframe.doc = iframe.contentWindow.document; // Internet Explorer\n } else if (iframe.document) {\n iframe.doc = iframe.document; //others?\n }\n\n return iframe;\n };\n /**\r\n * Cancel all outstanding queries and remove the frame.\r\n */\n\n\n FirebaseIFrameScriptHolder.prototype.close = function () {\n var _this = this; //Mark this iframe as dead, so no new requests are sent.\n\n\n this.alive = false;\n\n if (this.myIFrame) {\n //We have to actually remove all of the html inside this iframe before removing it from the\n //window, or IE will continue loading and executing the script tags we've already added, which\n //can lead to some errors being thrown. Setting innerHTML seems to be the easiest way to do this.\n this.myIFrame.doc.body.innerHTML = '';\n setTimeout(function () {\n if (_this.myIFrame !== null) {\n document.body.removeChild(_this.myIFrame);\n _this.myIFrame = null;\n }\n }, Math.floor(0));\n }\n\n if (util.isNodeSdk() && this.myID) {\n var urlParams = {};\n urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_PARAM] = 't';\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n var theURL = this.urlFn(urlParams);\n FirebaseIFrameScriptHolder.nodeRestRequest(theURL);\n } // Protect from being called recursively.\n\n\n var onDisconnect = this.onDisconnect;\n\n if (onDisconnect) {\n this.onDisconnect = null;\n onDisconnect();\n }\n };\n /**\r\n * Actually start the long-polling session by adding the first script tag(s) to the iframe.\r\n * @param {!string} id - The ID of this connection\r\n * @param {!string} pw - The password for this connection\r\n */\n\n\n FirebaseIFrameScriptHolder.prototype.startLongPoll = function (id, pw) {\n this.myID = id;\n this.myPW = pw;\n this.alive = true; //send the initial request. If there are requests queued, make sure that we transmit as many as we are currently able to.\n\n while (this.newRequest_()) {}\n };\n /**\r\n * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't\r\n * too many outstanding requests and we are still alive.\r\n *\r\n * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if\r\n * needed.\r\n */\n\n\n FirebaseIFrameScriptHolder.prototype.newRequest_ = function () {\n // We keep one outstanding request open all the time to receive data, but if we need to send data\n // (pendingSegs.length > 0) then we create a new request to send the data. The server will automatically\n // close the old request.\n if (this.alive && this.sendNewPolls && this.outstandingRequests.count() < (this.pendingSegs.length > 0 ? 2 : 1)) {\n //construct our url\n this.currentSerial++;\n var urlParams = {};\n urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;\n urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;\n urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;\n var theURL = this.urlFn(urlParams); //Now add as much data as we can.\n\n var curDataString = '';\n var i = 0;\n\n while (this.pendingSegs.length > 0) {\n //first, lets see if the next segment will fit.\n var nextSeg = this.pendingSegs[0];\n\n if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <= MAX_URL_DATA_SIZE) {\n //great, the segment will fit. Lets append it.\n var theSeg = this.pendingSegs.shift();\n curDataString = curDataString + '&' + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + i + '=' + theSeg.seg + '&' + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + i + '=' + theSeg.ts + '&' + FIREBASE_LONGPOLL_DATA_PARAM + i + '=' + theSeg.d;\n i++;\n } else {\n break;\n }\n }\n\n theURL = theURL + curDataString;\n this.addLongPollTag_(theURL, this.currentSerial);\n return true;\n } else {\n return false;\n }\n };\n /**\r\n * Queue a packet for transmission to the server.\r\n * @param segnum - A sequential id for this packet segment used for reassembly\r\n * @param totalsegs - The total number of segments in this packet\r\n * @param data - The data for this segment.\r\n */\n\n\n FirebaseIFrameScriptHolder.prototype.enqueueSegment = function (segnum, totalsegs, data) {\n //add this to the queue of segments to send.\n this.pendingSegs.push({\n seg: segnum,\n ts: totalsegs,\n d: data\n }); //send the data immediately if there isn't already data being transmitted, unless\n //startLongPoll hasn't been called yet.\n\n if (this.alive) {\n this.newRequest_();\n }\n };\n /**\r\n * Add a script tag for a regular long-poll request.\r\n * @param {!string} url - The URL of the script tag.\r\n * @param {!number} serial - The serial number of the request.\r\n * @private\r\n */\n\n\n FirebaseIFrameScriptHolder.prototype.addLongPollTag_ = function (url, serial) {\n var _this = this; //remember that we sent this request.\n\n\n this.outstandingRequests.add(serial, 1);\n\n var doNewRequest = function doNewRequest() {\n _this.outstandingRequests.remove(serial);\n\n _this.newRequest_();\n }; // If this request doesn't return on its own accord (by the server sending us some data), we'll\n // create a new one after the KEEPALIVE interval to make sure we always keep a fresh request open.\n\n\n var keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));\n\n var readyStateCB = function readyStateCB() {\n // Request completed. Cancel the keepalive.\n clearTimeout(keepaliveTimeout); // Trigger a new request so we can continue receiving data.\n\n doNewRequest();\n };\n\n this.addTag(url, readyStateCB);\n };\n /**\r\n * Add an arbitrary script tag to the iframe.\r\n * @param {!string} url - The URL for the script tag source.\r\n * @param {!function()} loadCB - A callback to be triggered once the script has loaded.\r\n */\n\n\n FirebaseIFrameScriptHolder.prototype.addTag = function (url, loadCB) {\n var _this = this;\n\n if (util.isNodeSdk()) {\n this.doNodeLongPoll(url, loadCB);\n } else {\n setTimeout(function () {\n try {\n // if we're already closed, don't add this poll\n if (!_this.sendNewPolls) return;\n\n var newScript_1 = _this.myIFrame.doc.createElement('script');\n\n newScript_1.type = 'text/javascript';\n newScript_1.async = true;\n newScript_1.src = url;\n\n newScript_1.onload = newScript_1.onreadystatechange = function () {\n var rstate = newScript_1.readyState;\n\n if (!rstate || rstate === 'loaded' || rstate === 'complete') {\n newScript_1.onload = newScript_1.onreadystatechange = null;\n\n if (newScript_1.parentNode) {\n newScript_1.parentNode.removeChild(newScript_1);\n }\n\n loadCB();\n }\n };\n\n newScript_1.onerror = function () {\n log('Long-poll script failed to load: ' + url);\n _this.sendNewPolls = false;\n\n _this.close();\n };\n\n _this.myIFrame.doc.body.appendChild(newScript_1);\n } catch (e) {// TODO: we should make this error visible somehow\n }\n }, Math.floor(1));\n }\n };\n\n return FirebaseIFrameScriptHolder;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar WEBSOCKET_MAX_FRAME_SIZE = 16384;\nvar WEBSOCKET_KEEPALIVE_INTERVAL = 45000;\nvar WebSocketImpl = null;\n\nif (typeof MozWebSocket !== 'undefined') {\n WebSocketImpl = MozWebSocket;\n} else if (typeof WebSocket !== 'undefined') {\n WebSocketImpl = WebSocket;\n}\n/**\r\n * Create a new websocket connection with the given callbacks.\r\n * @constructor\r\n * @implements {Transport}\r\n */\n\n\nvar WebSocketConnection =\n/** @class */\nfunction () {\n /**\r\n * @param {string} connId identifier for this transport\r\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\r\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\r\n */\n function WebSocketConnection(connId, repoInfo, transportSessionId, lastSessionId) {\n this.connId = connId;\n this.keepaliveTimer = null;\n this.frames = null;\n this.totalFrames = 0;\n this.bytesSent = 0;\n this.bytesReceived = 0;\n this.log_ = logWrapper(this.connId);\n this.stats_ = StatsManager.getCollection(repoInfo);\n this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId);\n }\n /**\r\n * @param {RepoInfo} repoInfo The info for the websocket endpoint.\r\n * @param {string=} transportSessionId Optional transportSessionId if this is connecting to an existing transport\r\n * session\r\n * @param {string=} lastSessionId Optional lastSessionId if there was a previous connection\r\n * @return {string} connection url\r\n * @private\r\n */\n\n\n WebSocketConnection.connectionURL_ = function (repoInfo, transportSessionId, lastSessionId) {\n var urlParams = {};\n urlParams[VERSION_PARAM] = PROTOCOL_VERSION;\n\n if (!util.isNodeSdk() && typeof location !== 'undefined' && location.href && location.href.indexOf(FORGE_DOMAIN) !== -1) {\n urlParams[REFERER_PARAM] = FORGE_REF;\n }\n\n if (transportSessionId) {\n urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;\n }\n\n if (lastSessionId) {\n urlParams[LAST_SESSION_PARAM] = lastSessionId;\n }\n\n return repoInfo.connectionURL(WEBSOCKET, urlParams);\n };\n /**\r\n *\r\n * @param onMessage Callback when messages arrive\r\n * @param onDisconnect Callback with connection lost.\r\n */\n\n\n WebSocketConnection.prototype.open = function (onMessage, onDisconnect) {\n var _this = this;\n\n this.onDisconnect = onDisconnect;\n this.onMessage = onMessage;\n this.log_('Websocket connecting to ' + this.connURL);\n this.everConnected_ = false; // Assume failure until proven otherwise.\n\n PersistentStorage.set('previous_websocket_failure', true);\n\n try {\n if (util.isNodeSdk()) {\n var device = util.CONSTANTS.NODE_ADMIN ? 'AdminNode' : 'Node'; // UA Format: Firebase////\n\n var options = {\n headers: {\n 'User-Agent': \"Firebase/\" + PROTOCOL_VERSION + \"/\" + firebase.SDK_VERSION + \"/\" + process.platform + \"/\" + device\n }\n }; // Plumb appropriate http_proxy environment variable into faye-websocket if it exists.\n\n var env = process['env'];\n var proxy = this.connURL.indexOf('wss://') == 0 ? env['HTTPS_PROXY'] || env['https_proxy'] : env['HTTP_PROXY'] || env['http_proxy'];\n\n if (proxy) {\n options['proxy'] = {\n origin: proxy\n };\n }\n\n this.mySock = new WebSocketImpl(this.connURL, [], options);\n } else {\n this.mySock = new WebSocketImpl(this.connURL);\n }\n } catch (e) {\n this.log_('Error instantiating WebSocket.');\n var error$$1 = e.message || e.data;\n\n if (error$$1) {\n this.log_(error$$1);\n }\n\n this.onClosed_();\n return;\n }\n\n this.mySock.onopen = function () {\n _this.log_('Websocket connected.');\n\n _this.everConnected_ = true;\n };\n\n this.mySock.onclose = function () {\n _this.log_('Websocket connection was disconnected.');\n\n _this.mySock = null;\n\n _this.onClosed_();\n };\n\n this.mySock.onmessage = function (m) {\n _this.handleIncomingFrame(m);\n };\n\n this.mySock.onerror = function (e) {\n _this.log_('WebSocket error. Closing connection.');\n\n var error$$1 = e.message || e.data;\n\n if (error$$1) {\n _this.log_(error$$1);\n }\n\n _this.onClosed_();\n };\n };\n /**\r\n * No-op for websockets, we don't need to do anything once the connection is confirmed as open\r\n */\n\n\n WebSocketConnection.prototype.start = function () {};\n\n WebSocketConnection.forceDisallow = function () {\n WebSocketConnection.forceDisallow_ = true;\n };\n\n WebSocketConnection.isAvailable = function () {\n var isOldAndroid = false;\n\n if (typeof navigator !== 'undefined' && navigator.userAgent) {\n var oldAndroidRegex = /Android ([0-9]{0,}\\.[0-9]{0,})/;\n var oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);\n\n if (oldAndroidMatch && oldAndroidMatch.length > 1) {\n if (parseFloat(oldAndroidMatch[1]) < 4.4) {\n isOldAndroid = true;\n }\n }\n }\n\n return !isOldAndroid && WebSocketImpl !== null && !WebSocketConnection.forceDisallow_;\n };\n /**\r\n * Returns true if we previously failed to connect with this transport.\r\n * @return {boolean}\r\n */\n\n\n WebSocketConnection.previouslyFailed = function () {\n // If our persistent storage is actually only in-memory storage,\n // we default to assuming that it previously failed to be safe.\n return PersistentStorage.isInMemoryStorage || PersistentStorage.get('previous_websocket_failure') === true;\n };\n\n WebSocketConnection.prototype.markConnectionHealthy = function () {\n PersistentStorage.remove('previous_websocket_failure');\n };\n\n WebSocketConnection.prototype.appendFrame_ = function (data) {\n this.frames.push(data);\n\n if (this.frames.length == this.totalFrames) {\n var fullMess = this.frames.join('');\n this.frames = null;\n var jsonMess = util.jsonEval(fullMess); //handle the message\n\n this.onMessage(jsonMess);\n }\n };\n /**\r\n * @param {number} frameCount The number of frames we are expecting from the server\r\n * @private\r\n */\n\n\n WebSocketConnection.prototype.handleNewFrameCount_ = function (frameCount) {\n this.totalFrames = frameCount;\n this.frames = [];\n };\n /**\r\n * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1\r\n * @param {!String} data\r\n * @return {?String} Any remaining data to be process, or null if there is none\r\n * @private\r\n */\n\n\n WebSocketConnection.prototype.extractFrameCount_ = function (data) {\n util.assert(this.frames === null, 'We already have a frame buffer'); // TODO: The server is only supposed to send up to 9999 frames (i.e. length <= 4), but that isn't being enforced\n // currently. So allowing larger frame counts (length <= 6). See https://app.asana.com/0/search/8688598998380/8237608042508\n\n if (data.length <= 6) {\n var frameCount = Number(data);\n\n if (!isNaN(frameCount)) {\n this.handleNewFrameCount_(frameCount);\n return null;\n }\n }\n\n this.handleNewFrameCount_(1);\n return data;\n };\n /**\r\n * Process a websocket frame that has arrived from the server.\r\n * @param mess The frame data\r\n */\n\n\n WebSocketConnection.prototype.handleIncomingFrame = function (mess) {\n if (this.mySock === null) return; // Chrome apparently delivers incoming packets even after we .close() the connection sometimes.\n\n var data = mess['data'];\n this.bytesReceived += data.length;\n this.stats_.incrementCounter('bytes_received', data.length);\n this.resetKeepAlive();\n\n if (this.frames !== null) {\n // we're buffering\n this.appendFrame_(data);\n } else {\n // try to parse out a frame count, otherwise, assume 1 and process it\n var remainingData = this.extractFrameCount_(data);\n\n if (remainingData !== null) {\n this.appendFrame_(remainingData);\n }\n }\n };\n /**\r\n * Send a message to the server\r\n * @param {Object} data The JSON object to transmit\r\n */\n\n\n WebSocketConnection.prototype.send = function (data) {\n this.resetKeepAlive();\n var dataStr = util.stringify(data);\n this.bytesSent += dataStr.length;\n this.stats_.incrementCounter('bytes_sent', dataStr.length); //We can only fit a certain amount in each websocket frame, so we need to split this request\n //up into multiple pieces if it doesn't fit in one request.\n\n var dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE); //Send the length header\n\n if (dataSegs.length > 1) {\n this.sendString_(String(dataSegs.length));\n } //Send the actual data in segments.\n\n\n for (var i = 0; i < dataSegs.length; i++) {\n this.sendString_(dataSegs[i]);\n }\n };\n\n WebSocketConnection.prototype.shutdown_ = function () {\n this.isClosed_ = true;\n\n if (this.keepaliveTimer) {\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = null;\n }\n\n if (this.mySock) {\n this.mySock.close();\n this.mySock = null;\n }\n };\n\n WebSocketConnection.prototype.onClosed_ = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is closing itself');\n this.shutdown_(); // since this is an internal close, trigger the close listener\n\n if (this.onDisconnect) {\n this.onDisconnect(this.everConnected_);\n this.onDisconnect = null;\n }\n }\n };\n /**\r\n * External-facing close handler.\r\n * Close the websocket and kill the connection.\r\n */\n\n\n WebSocketConnection.prototype.close = function () {\n if (!this.isClosed_) {\n this.log_('WebSocket is being closed');\n this.shutdown_();\n }\n };\n /**\r\n * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after\r\n * the last activity.\r\n */\n\n\n WebSocketConnection.prototype.resetKeepAlive = function () {\n var _this = this;\n\n clearInterval(this.keepaliveTimer);\n this.keepaliveTimer = setInterval(function () {\n //If there has been no websocket activity for a while, send a no-op\n if (_this.mySock) {\n _this.sendString_('0');\n }\n\n _this.resetKeepAlive();\n }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));\n };\n /**\r\n * Send a string over the websocket.\r\n *\r\n * @param {string} str String to send.\r\n * @private\r\n */\n\n\n WebSocketConnection.prototype.sendString_ = function (str) {\n // Firefox seems to sometimes throw exceptions (NS_ERROR_UNEXPECTED) from websocket .send()\n // calls for some unknown reason. We treat these as an error and disconnect.\n // See https://app.asana.com/0/58926111402292/68021340250410\n try {\n this.mySock.send(str);\n } catch (e) {\n this.log_('Exception thrown from WebSocket.send():', e.message || e.data, 'Closing connection.');\n setTimeout(this.onClosed_.bind(this), 0);\n }\n };\n /**\r\n * Number of response before we consider the connection \"healthy.\"\r\n * @type {number}\r\n */\n\n\n WebSocketConnection.responsesRequiredToBeHealthy = 2;\n /**\r\n * Time to wait for the connection te become healthy before giving up.\r\n * @type {number}\r\n */\n\n WebSocketConnection.healthyTimeout = 30000;\n return WebSocketConnection;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Currently simplistic, this class manages what transport a Connection should use at various stages of its\r\n * lifecycle.\r\n *\r\n * It starts with longpolling in a browser, and httppolling on node. It then upgrades to websockets if\r\n * they are available.\r\n * @constructor\r\n */\n\n\nvar TransportManager =\n/** @class */\nfunction () {\n /**\r\n * @param {!RepoInfo} repoInfo Metadata around the namespace we're connecting to\r\n */\n function TransportManager(repoInfo) {\n this.initTransports_(repoInfo);\n }\n\n Object.defineProperty(TransportManager, \"ALL_TRANSPORTS\", {\n /**\r\n * @const\r\n * @type {!Array.}\r\n */\n get: function get() {\n return [BrowserPollConnection, WebSocketConnection];\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * @param {!RepoInfo} repoInfo\r\n * @private\r\n */\n\n TransportManager.prototype.initTransports_ = function (repoInfo) {\n var isWebSocketsAvailable = WebSocketConnection && WebSocketConnection['isAvailable']();\n var isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();\n\n if (repoInfo.webSocketOnly) {\n if (!isWebSocketsAvailable) warn(\"wss:// URL used, but browser isn't known to support websockets. Trying anyway.\");\n isSkipPollConnection = true;\n }\n\n if (isSkipPollConnection) {\n this.transports_ = [WebSocketConnection];\n } else {\n var transports_1 = this.transports_ = [];\n each(TransportManager.ALL_TRANSPORTS, function (i, transport) {\n if (transport && transport['isAvailable']()) {\n transports_1.push(transport);\n }\n });\n }\n };\n /**\r\n * @return {function(new:Transport, !string, !RepoInfo, string=, string=)} The constructor for the\r\n * initial transport to use\r\n */\n\n\n TransportManager.prototype.initialTransport = function () {\n if (this.transports_.length > 0) {\n return this.transports_[0];\n } else {\n throw new Error('No transports available');\n }\n };\n /**\r\n * @return {?function(new:Transport, function(),function(), string=)} The constructor for the next\r\n * transport, or null\r\n */\n\n\n TransportManager.prototype.upgradeTransport = function () {\n if (this.transports_.length > 1) {\n return this.transports_[1];\n } else {\n return null;\n }\n };\n\n return TransportManager;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// Abort upgrade attempt if it takes longer than 60s.\n\n\nvar UPGRADE_TIMEOUT = 60000; // For some transports (WebSockets), we need to \"validate\" the transport by exchanging a few requests and responses.\n// If we haven't sent enough requests within 5s, we'll start sending noop ping requests.\n\nvar DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5000; // If the initial data sent triggers a lot of bandwidth (i.e. it's a large put or a listen for a large amount of data)\n// then we may not be able to exchange our ping/pong requests within the healthy timeout. So if we reach the timeout\n// but we've sent/received enough bytes, we don't cancel the connection.\n\nvar BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;\nvar BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;\nvar MESSAGE_TYPE = 't';\nvar MESSAGE_DATA = 'd';\nvar CONTROL_SHUTDOWN = 's';\nvar CONTROL_RESET = 'r';\nvar CONTROL_ERROR = 'e';\nvar CONTROL_PONG = 'o';\nvar SWITCH_ACK = 'a';\nvar END_TRANSMISSION = 'n';\nvar PING = 'p';\nvar SERVER_HELLO = 'h';\n/**\r\n * Creates a new real-time connection to the server using whichever method works\r\n * best in the current browser.\r\n *\r\n * @constructor\r\n */\n\nvar Connection =\n/** @class */\nfunction () {\n /**\r\n * @param {!string} id - an id for this connection\r\n * @param {!RepoInfo} repoInfo_ - the info for the endpoint to connect to\r\n * @param {function(Object)} onMessage_ - the callback to be triggered when a server-push message arrives\r\n * @param {function(number, string)} onReady_ - the callback to be triggered when this connection is ready to send messages.\r\n * @param {function()} onDisconnect_ - the callback to be triggered when a connection was lost\r\n * @param {function(string)} onKill_ - the callback to be triggered when this connection has permanently shut down.\r\n * @param {string=} lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server\r\n */\n function Connection(id, repoInfo_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {\n this.id = id;\n this.repoInfo_ = repoInfo_;\n this.onMessage_ = onMessage_;\n this.onReady_ = onReady_;\n this.onDisconnect_ = onDisconnect_;\n this.onKill_ = onKill_;\n this.lastSessionId = lastSessionId;\n this.connectionCount = 0;\n this.pendingDataMessages = [];\n this.state_ = 0\n /* CONNECTING */\n ;\n this.log_ = logWrapper('c:' + this.id + ':');\n this.transportManager_ = new TransportManager(repoInfo_);\n this.log_('Connection created');\n this.start_();\n }\n /**\r\n * Starts a connection attempt\r\n * @private\r\n */\n\n\n Connection.prototype.start_ = function () {\n var _this = this;\n\n var conn = this.transportManager_.initialTransport();\n this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, undefined, this.lastSessionId); // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n\n this.primaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessageReceived = this.connReceiver_(this.conn_);\n var onConnectionLost = this.disconnReceiver_(this.conn_);\n this.tx_ = this.conn_;\n this.rx_ = this.conn_;\n this.secondaryConn_ = null;\n this.isHealthy_ = false;\n /*\r\n * Firefox doesn't like when code from one iframe tries to create another iframe by way of the parent frame.\r\n * This can occur in the case of a redirect, i.e. we guessed wrong on what server to connect to and received a reset.\r\n * Somehow, setTimeout seems to make this ok. That doesn't make sense from a security perspective, since you should\r\n * still have the context of your originating frame.\r\n */\n\n setTimeout(function () {\n // this.conn_ gets set to null in some of the tests. Check to make sure it still exists before using it\n _this.conn_ && _this.conn_.open(onMessageReceived, onConnectionLost);\n }, Math.floor(0));\n var healthyTimeout_ms = conn['healthyTimeout'] || 0;\n\n if (healthyTimeout_ms > 0) {\n this.healthyTimeout_ = setTimeoutNonBlocking(function () {\n _this.healthyTimeout_ = null;\n\n if (!_this.isHealthy_) {\n if (_this.conn_ && _this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has received ' + _this.conn_.bytesReceived + ' bytes. Marking connection healthy.');\n\n _this.isHealthy_ = true;\n\n _this.conn_.markConnectionHealthy();\n } else if (_this.conn_ && _this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {\n _this.log_('Connection exceeded healthy timeout but has sent ' + _this.conn_.bytesSent + ' bytes. Leaving connection alive.'); // NOTE: We don't want to mark it healthy, since we have no guarantee that the bytes have made it to\n // the server.\n\n } else {\n _this.log_('Closing unhealthy connection after timeout.');\n\n _this.close();\n }\n }\n }, Math.floor(healthyTimeout_ms));\n }\n };\n /**\r\n * @return {!string}\r\n * @private\r\n */\n\n\n Connection.prototype.nextTransportId_ = function () {\n return 'c:' + this.id + ':' + this.connectionCount++;\n };\n\n Connection.prototype.disconnReceiver_ = function (conn) {\n var _this = this;\n\n return function (everConnected) {\n if (conn === _this.conn_) {\n _this.onConnectionLost_(everConnected);\n } else if (conn === _this.secondaryConn_) {\n _this.log_('Secondary connection lost.');\n\n _this.onSecondaryConnectionLost_();\n } else {\n _this.log_('closing an old connection');\n }\n };\n };\n\n Connection.prototype.connReceiver_ = function (conn) {\n var _this = this;\n\n return function (message) {\n if (_this.state_ != 2\n /* DISCONNECTED */\n ) {\n if (conn === _this.rx_) {\n _this.onPrimaryMessageReceived_(message);\n } else if (conn === _this.secondaryConn_) {\n _this.onSecondaryMessageReceived_(message);\n } else {\n _this.log_('message on old connection');\n }\n }\n };\n };\n /**\r\n *\r\n * @param {Object} dataMsg An arbitrary data message to be sent to the server\r\n */\n\n\n Connection.prototype.sendRequest = function (dataMsg) {\n // wrap in a data message envelope and send it on\n var msg = {\n t: 'd',\n d: dataMsg\n };\n this.sendData_(msg);\n };\n\n Connection.prototype.tryCleanupConnection = function () {\n if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {\n this.log_('cleaning up and promoting a connection: ' + this.secondaryConn_.connId);\n this.conn_ = this.secondaryConn_;\n this.secondaryConn_ = null; // the server will shutdown the old connection\n }\n };\n\n Connection.prototype.onSecondaryControl_ = function (controlData) {\n if (MESSAGE_TYPE in controlData) {\n var cmd = controlData[MESSAGE_TYPE];\n\n if (cmd === SWITCH_ACK) {\n this.upgradeIfSecondaryHealthy_();\n } else if (cmd === CONTROL_RESET) {\n // Most likely the session wasn't valid. Abandon the switch attempt\n this.log_('Got a reset on secondary, closing it');\n this.secondaryConn_.close(); // If we were already using this connection for something, than we need to fully close\n\n if (this.tx_ === this.secondaryConn_ || this.rx_ === this.secondaryConn_) {\n this.close();\n }\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on secondary.');\n this.secondaryResponsesRequired_--;\n this.upgradeIfSecondaryHealthy_();\n }\n }\n };\n\n Connection.prototype.onSecondaryMessageReceived_ = function (parsedData) {\n var layer = requireKey('t', parsedData);\n var data = requireKey('d', parsedData);\n\n if (layer == 'c') {\n this.onSecondaryControl_(data);\n } else if (layer == 'd') {\n // got a data message, but we're still second connection. Need to buffer it up\n this.pendingDataMessages.push(data);\n } else {\n throw new Error('Unknown protocol layer: ' + layer);\n }\n };\n\n Connection.prototype.upgradeIfSecondaryHealthy_ = function () {\n if (this.secondaryResponsesRequired_ <= 0) {\n this.log_('Secondary connection is healthy.');\n this.isHealthy_ = true;\n this.secondaryConn_.markConnectionHealthy();\n this.proceedWithUpgrade_();\n } else {\n // Send a ping to make sure the connection is healthy.\n this.log_('sending ping on secondary.');\n this.secondaryConn_.send({\n t: 'c',\n d: {\n t: PING,\n d: {}\n }\n });\n }\n };\n\n Connection.prototype.proceedWithUpgrade_ = function () {\n // tell this connection to consider itself open\n this.secondaryConn_.start(); // send ack\n\n this.log_('sending client ack on secondary');\n this.secondaryConn_.send({\n t: 'c',\n d: {\n t: SWITCH_ACK,\n d: {}\n }\n }); // send end packet on primary transport, switch to sending on this one\n // can receive on this one, buffer responses until end received on primary transport\n\n this.log_('Ending transmission on primary');\n this.conn_.send({\n t: 'c',\n d: {\n t: END_TRANSMISSION,\n d: {}\n }\n });\n this.tx_ = this.secondaryConn_;\n this.tryCleanupConnection();\n };\n\n Connection.prototype.onPrimaryMessageReceived_ = function (parsedData) {\n // Must refer to parsedData properties in quotes, so closure doesn't touch them.\n var layer = requireKey('t', parsedData);\n var data = requireKey('d', parsedData);\n\n if (layer == 'c') {\n this.onControl_(data);\n } else if (layer == 'd') {\n this.onDataMessage_(data);\n }\n };\n\n Connection.prototype.onDataMessage_ = function (message) {\n this.onPrimaryResponse_(); // We don't do anything with data messages, just kick them up a level\n\n this.onMessage_(message);\n };\n\n Connection.prototype.onPrimaryResponse_ = function () {\n if (!this.isHealthy_) {\n this.primaryResponsesRequired_--;\n\n if (this.primaryResponsesRequired_ <= 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n this.conn_.markConnectionHealthy();\n }\n }\n };\n\n Connection.prototype.onControl_ = function (controlData) {\n var cmd = requireKey(MESSAGE_TYPE, controlData);\n\n if (MESSAGE_DATA in controlData) {\n var payload = controlData[MESSAGE_DATA];\n\n if (cmd === SERVER_HELLO) {\n this.onHandshake_(payload);\n } else if (cmd === END_TRANSMISSION) {\n this.log_('recvd end transmission on primary');\n this.rx_ = this.secondaryConn_;\n\n for (var i = 0; i < this.pendingDataMessages.length; ++i) {\n this.onDataMessage_(this.pendingDataMessages[i]);\n }\n\n this.pendingDataMessages = [];\n this.tryCleanupConnection();\n } else if (cmd === CONTROL_SHUTDOWN) {\n // This was previously the 'onKill' callback passed to the lower-level connection\n // payload in this case is the reason for the shutdown. Generally a human-readable error\n this.onConnectionShutdown_(payload);\n } else if (cmd === CONTROL_RESET) {\n // payload in this case is the host we should contact\n this.onReset_(payload);\n } else if (cmd === CONTROL_ERROR) {\n error('Server Error: ' + payload);\n } else if (cmd === CONTROL_PONG) {\n this.log_('got pong on primary.');\n this.onPrimaryResponse_();\n this.sendPingOnPrimaryIfNecessary_();\n } else {\n error('Unknown control packet command: ' + cmd);\n }\n }\n };\n /**\r\n *\r\n * @param {Object} handshake The handshake data returned from the server\r\n * @private\r\n */\n\n\n Connection.prototype.onHandshake_ = function (handshake) {\n var timestamp = handshake.ts;\n var version = handshake.v;\n var host = handshake.h;\n this.sessionId = handshake.s;\n this.repoInfo_.updateHost(host); // if we've already closed the connection, then don't bother trying to progress further\n\n if (this.state_ == 0\n /* CONNECTING */\n ) {\n this.conn_.start();\n this.onConnectionEstablished_(this.conn_, timestamp);\n\n if (PROTOCOL_VERSION !== version) {\n warn('Protocol version mismatch detected');\n } // TODO: do we want to upgrade? when? maybe a delay?\n\n\n this.tryStartUpgrade_();\n }\n };\n\n Connection.prototype.tryStartUpgrade_ = function () {\n var conn = this.transportManager_.upgradeTransport();\n\n if (conn) {\n this.startUpgrade_(conn);\n }\n };\n\n Connection.prototype.startUpgrade_ = function (conn) {\n var _this = this;\n\n this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.sessionId); // For certain transports (WebSockets), we need to send and receive several messages back and forth before we\n // can consider the transport healthy.\n\n this.secondaryResponsesRequired_ = conn['responsesRequiredToBeHealthy'] || 0;\n var onMessage = this.connReceiver_(this.secondaryConn_);\n var onDisconnect = this.disconnReceiver_(this.secondaryConn_);\n this.secondaryConn_.open(onMessage, onDisconnect); // If we haven't successfully upgraded after UPGRADE_TIMEOUT, give up and kill the secondary.\n\n setTimeoutNonBlocking(function () {\n if (_this.secondaryConn_) {\n _this.log_('Timed out trying to upgrade.');\n\n _this.secondaryConn_.close();\n }\n }, Math.floor(UPGRADE_TIMEOUT));\n };\n\n Connection.prototype.onReset_ = function (host) {\n this.log_('Reset packet received. New host: ' + host);\n this.repoInfo_.updateHost(host); // TODO: if we're already \"connected\", we need to trigger a disconnect at the next layer up.\n // We don't currently support resets after the connection has already been established\n\n if (this.state_ === 1\n /* CONNECTED */\n ) {\n this.close();\n } else {\n // Close whatever connections we have open and start again.\n this.closeConnections_();\n this.start_();\n }\n };\n\n Connection.prototype.onConnectionEstablished_ = function (conn, timestamp) {\n var _this = this;\n\n this.log_('Realtime connection established.');\n this.conn_ = conn;\n this.state_ = 1\n /* CONNECTED */\n ;\n\n if (this.onReady_) {\n this.onReady_(timestamp, this.sessionId);\n this.onReady_ = null;\n } // If after 5 seconds we haven't sent enough requests to the server to get the connection healthy,\n // send some pings.\n\n\n if (this.primaryResponsesRequired_ === 0) {\n this.log_('Primary connection is healthy.');\n this.isHealthy_ = true;\n } else {\n setTimeoutNonBlocking(function () {\n _this.sendPingOnPrimaryIfNecessary_();\n }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));\n }\n };\n\n Connection.prototype.sendPingOnPrimaryIfNecessary_ = function () {\n // If the connection isn't considered healthy yet, we'll send a noop ping packet request.\n if (!this.isHealthy_ && this.state_ === 1\n /* CONNECTED */\n ) {\n this.log_('sending ping on primary.');\n this.sendData_({\n t: 'c',\n d: {\n t: PING,\n d: {}\n }\n });\n }\n };\n\n Connection.prototype.onSecondaryConnectionLost_ = function () {\n var conn = this.secondaryConn_;\n this.secondaryConn_ = null;\n\n if (this.tx_ === conn || this.rx_ === conn) {\n // we are relying on this connection already in some capacity. Therefore, a failure is real\n this.close();\n }\n };\n /**\r\n *\r\n * @param {boolean} everConnected Whether or not the connection ever reached a server. Used to determine if\r\n * we should flush the host cache\r\n * @private\r\n */\n\n\n Connection.prototype.onConnectionLost_ = function (everConnected) {\n this.conn_ = null; // NOTE: IF you're seeing a Firefox error for this line, I think it might be because it's getting\n // called on window close and RealtimeState.CONNECTING is no longer defined. Just a guess.\n\n if (!everConnected && this.state_ === 0\n /* CONNECTING */\n ) {\n this.log_('Realtime connection failed.'); // Since we failed to connect at all, clear any cached entry for this namespace in case the machine went away\n\n if (this.repoInfo_.isCacheableHost()) {\n PersistentStorage.remove('host:' + this.repoInfo_.host); // reset the internal host to what we would show the user, i.e. .firebaseio.com\n\n this.repoInfo_.internalHost = this.repoInfo_.host;\n }\n } else if (this.state_ === 1\n /* CONNECTED */\n ) {\n this.log_('Realtime connection lost.');\n }\n\n this.close();\n };\n /**\r\n *\r\n * @param {string} reason\r\n * @private\r\n */\n\n\n Connection.prototype.onConnectionShutdown_ = function (reason) {\n this.log_('Connection shutdown command received. Shutting down...');\n\n if (this.onKill_) {\n this.onKill_(reason);\n this.onKill_ = null;\n } // We intentionally don't want to fire onDisconnect (kill is a different case),\n // so clear the callback.\n\n\n this.onDisconnect_ = null;\n this.close();\n };\n\n Connection.prototype.sendData_ = function (data) {\n if (this.state_ !== 1\n /* CONNECTED */\n ) {\n throw 'Connection is not connected';\n } else {\n this.tx_.send(data);\n }\n };\n /**\r\n * Cleans up this connection, calling the appropriate callbacks\r\n */\n\n\n Connection.prototype.close = function () {\n if (this.state_ !== 2\n /* DISCONNECTED */\n ) {\n this.log_('Closing realtime connection.');\n this.state_ = 2\n /* DISCONNECTED */\n ;\n this.closeConnections_();\n\n if (this.onDisconnect_) {\n this.onDisconnect_();\n this.onDisconnect_ = null;\n }\n }\n };\n /**\r\n *\r\n * @private\r\n */\n\n\n Connection.prototype.closeConnections_ = function () {\n this.log_('Shutting down all connections');\n\n if (this.conn_) {\n this.conn_.close();\n this.conn_ = null;\n }\n\n if (this.secondaryConn_) {\n this.secondaryConn_.close();\n this.secondaryConn_ = null;\n }\n\n if (this.healthyTimeout_) {\n clearTimeout(this.healthyTimeout_);\n this.healthyTimeout_ = null;\n }\n };\n\n return Connection;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Interface defining the set of actions that can be performed against the Firebase server\r\n * (basically corresponds to our wire protocol).\r\n *\r\n * @interface\r\n */\n\n\nvar ServerActions =\n/** @class */\nfunction () {\n function ServerActions() {}\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n * @param {string=} hash\r\n */\n\n\n ServerActions.prototype.put = function (pathString, data, onComplete, hash) {};\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, ?string)} onComplete\r\n * @param {string=} hash\r\n */\n\n\n ServerActions.prototype.merge = function (pathString, data, onComplete, hash) {};\n /**\r\n * Refreshes the auth token for the current connection.\r\n * @param {string} token The authentication token\r\n */\n\n\n ServerActions.prototype.refreshAuthToken = function (token) {};\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n */\n\n\n ServerActions.prototype.onDisconnectPut = function (pathString, data, onComplete) {};\n /**\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {function(string, string)=} onComplete\r\n */\n\n\n ServerActions.prototype.onDisconnectMerge = function (pathString, data, onComplete) {};\n /**\r\n * @param {string} pathString\r\n * @param {function(string, string)=} onComplete\r\n */\n\n\n ServerActions.prototype.onDisconnectCancel = function (pathString, onComplete) {};\n /**\r\n * @param {Object.} stats\r\n */\n\n\n ServerActions.prototype.reportStats = function (stats) {};\n\n return ServerActions;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar RECONNECT_MIN_DELAY = 1000;\nvar RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1000; // 5 minutes in milliseconds (Case: 1858)\n\nvar RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1000; // 30 seconds for admin clients (likely to be a backend server)\n\nvar RECONNECT_DELAY_MULTIPLIER = 1.3;\nvar RECONNECT_DELAY_RESET_TIMEOUT = 30000; // Reset delay back to MIN_DELAY after being connected for 30sec.\n\nvar SERVER_KILL_INTERRUPT_REASON = 'server_kill'; // If auth fails repeatedly, we'll assume something is wrong and log a warning / back off.\n\nvar INVALID_AUTH_TOKEN_THRESHOLD = 3;\n/**\r\n * Firebase connection. Abstracts wire protocol and handles reconnecting.\r\n *\r\n * NOTE: All JSON objects sent to the realtime connection must have property names enclosed\r\n * in quotes to make sure the closure compiler does not minify them.\r\n */\n\nvar PersistentConnection =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(PersistentConnection, _super);\n /**\r\n * @implements {ServerActions}\r\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\r\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\r\n * @param onConnectStatus_\r\n * @param onServerInfoUpdate_\r\n * @param authTokenProvider_\r\n * @param authOverride_\r\n */\n\n\n function PersistentConnection(repoInfo_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, authOverride_) {\n var _this = _super.call(this) || this;\n\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.onConnectStatus_ = onConnectStatus_;\n _this.onServerInfoUpdate_ = onServerInfoUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n _this.authOverride_ = authOverride_; // Used for diagnostic logging.\n\n _this.id = PersistentConnection.nextPersistentConnectionId_++;\n _this.log_ = logWrapper('p:' + _this.id + ':');\n /** @private {Object} */\n\n _this.interruptReasons_ = {};\n _this.listens_ = {};\n _this.outstandingPuts_ = [];\n _this.outstandingPutCount_ = 0;\n _this.onDisconnectRequestQueue_ = [];\n _this.connected_ = false;\n _this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n _this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;\n _this.securityDebugCallback_ = null;\n _this.lastSessionId = null;\n /** @private {number|null} */\n\n _this.establishConnectionTimer_ = null;\n /** @private {boolean} */\n\n _this.visible_ = false; // Before we get connected, we keep a queue of pending messages to send.\n\n _this.requestCBHash_ = {};\n _this.requestNumber_ = 0;\n /** @private {?{\r\n * sendRequest(Object),\r\n * close()\r\n * }} */\n\n _this.realtime_ = null;\n /** @private {string|null} */\n\n _this.authToken_ = null;\n _this.forceTokenRefresh_ = false;\n _this.invalidAuthTokenCount_ = 0;\n _this.firstConnection_ = true;\n _this.lastConnectionAttemptTime_ = null;\n _this.lastConnectionEstablishedTime_ = null;\n\n if (authOverride_ && !util.isNodeSdk()) {\n throw new Error('Auth override specified in options, but not supported on non Node.js platforms');\n }\n\n _this.scheduleConnect_(0);\n\n VisibilityMonitor.getInstance().on('visible', _this.onVisible_, _this);\n\n if (repoInfo_.host.indexOf('fblocal') === -1) {\n OnlineMonitor.getInstance().on('online', _this.onOnline_, _this);\n }\n\n return _this;\n }\n /**\r\n * @param {!string} action\r\n * @param {*} body\r\n * @param {function(*)=} onResponse\r\n * @protected\r\n */\n\n\n PersistentConnection.prototype.sendRequest = function (action, body, onResponse) {\n var curReqNum = ++this.requestNumber_;\n var msg = {\n r: curReqNum,\n a: action,\n b: body\n };\n this.log_(util.stringify(msg));\n util.assert(this.connected_, \"sendRequest call when we're not connected not allowed.\");\n this.realtime_.sendRequest(msg);\n\n if (onResponse) {\n this.requestCBHash_[curReqNum] = onResponse;\n }\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var queryId = query.queryIdentifier();\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + queryId);\n this.listens_[pathString] = this.listens_[pathString] || {};\n util.assert(query.getQueryParams().isDefault() || !query.getQueryParams().loadsAllData(), 'listen() called for non-default but complete query');\n util.assert(!this.listens_[pathString][queryId], 'listen() called twice for same path/queryId.');\n var listenSpec = {\n onComplete: onComplete,\n hashFn: currentHashFn,\n query: query,\n tag: tag\n };\n this.listens_[pathString][queryId] = listenSpec;\n\n if (this.connected_) {\n this.sendListen_(listenSpec);\n }\n };\n /**\r\n * @param {!{onComplete(),\r\n * hashFn():!string,\r\n * query: !Query,\r\n * tag: ?number}} listenSpec\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.sendListen_ = function (listenSpec) {\n var _this = this;\n\n var query = listenSpec.query;\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Listen on ' + pathString + ' for ' + queryId);\n var req = {\n /*path*/\n p: pathString\n };\n var action = 'q'; // Only bother to send query if it's non-default.\n\n if (listenSpec.tag) {\n req['q'] = query.queryObject();\n req['t'] = listenSpec.tag;\n }\n\n req[\n /*hash*/\n 'h'] = listenSpec.hashFn();\n this.sendRequest(action, req, function (message) {\n var payload = message[\n /*data*/\n 'd'];\n var status = message[\n /*status*/\n 's']; // print warnings in any case...\n\n PersistentConnection.warnOnListenWarnings_(payload, query);\n var currentListenSpec = _this.listens_[pathString] && _this.listens_[pathString][queryId]; // only trigger actions if the listen hasn't been removed and readded\n\n if (currentListenSpec === listenSpec) {\n _this.log_('listen response', message);\n\n if (status !== 'ok') {\n _this.removeListen_(pathString, queryId);\n }\n\n if (listenSpec.onComplete) {\n listenSpec.onComplete(status, payload);\n }\n }\n });\n };\n /**\r\n * @param {*} payload\r\n * @param {!Query} query\r\n * @private\r\n */\n\n\n PersistentConnection.warnOnListenWarnings_ = function (payload, query) {\n if (payload && typeof payload === 'object' && util.contains(payload, 'w')) {\n var warnings = util.safeGet(payload, 'w');\n\n if (Array.isArray(warnings) && ~warnings.indexOf('no_index')) {\n var indexSpec = '\".indexOn\": \"' + query.getQueryParams().getIndex().toString() + '\"';\n var indexPath = query.path.toString();\n warn(\"Using an unspecified index. Your data will be downloaded and \" + (\"filtered on the client. Consider adding \" + indexSpec + \" at \") + (indexPath + \" to your security rules for better performance.\"));\n }\n }\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.refreshAuthToken = function (token) {\n this.authToken_ = token;\n this.log_('Auth token refreshed');\n\n if (this.authToken_) {\n this.tryAuth();\n } else {\n //If we're connected we want to let the server know to unauthenticate us. If we're not connected, simply delete\n //the credential so we dont become authenticated next time we connect.\n if (this.connected_) {\n this.sendRequest('unauth', {}, function () {});\n }\n }\n\n this.reduceReconnectDelayIfAdminCredential_(token);\n };\n /**\r\n * @param {!string} credential\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.reduceReconnectDelayIfAdminCredential_ = function (credential) {\n // NOTE: This isn't intended to be bulletproof (a malicious developer can always just modify the client).\n // Additionally, we don't bother resetting the max delay back to the default if auth fails / expires.\n var isFirebaseSecret = credential && credential.length === 40;\n\n if (isFirebaseSecret || util.isAdmin(credential)) {\n this.log_('Admin auth credential detected. Reducing max reconnect time.');\n this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;\n }\n };\n /**\r\n * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like\r\n * a auth revoked (the connection is closed).\r\n */\n\n\n PersistentConnection.prototype.tryAuth = function () {\n var _this = this;\n\n if (this.connected_ && this.authToken_) {\n var token_1 = this.authToken_;\n var authMethod = util.isValidFormat(token_1) ? 'auth' : 'gauth';\n var requestData = {\n cred: token_1\n };\n\n if (this.authOverride_ === null) {\n requestData['noauth'] = true;\n } else if (typeof this.authOverride_ === 'object') {\n requestData['authvar'] = this.authOverride_;\n }\n\n this.sendRequest(authMethod, requestData, function (res) {\n var status = res[\n /*status*/\n 's'];\n var data = res[\n /*data*/\n 'd'] || 'error';\n\n if (_this.authToken_ === token_1) {\n if (status === 'ok') {\n _this.invalidAuthTokenCount_ = 0;\n } else {\n // Triggers reconnect and force refresh for auth token\n _this.onAuthRevoked_(status, data);\n }\n }\n });\n }\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.unlisten = function (query, tag) {\n var pathString = query.path.toString();\n var queryId = query.queryIdentifier();\n this.log_('Unlisten called for ' + pathString + ' ' + queryId);\n util.assert(query.getQueryParams().isDefault() || !query.getQueryParams().loadsAllData(), 'unlisten() called for non-default but complete query');\n var listen = this.removeListen_(pathString, queryId);\n\n if (listen && this.connected_) {\n this.sendUnlisten_(pathString, queryId, query.queryObject(), tag);\n }\n };\n\n PersistentConnection.prototype.sendUnlisten_ = function (pathString, queryId, queryObj, tag) {\n this.log_('Unlisten on ' + pathString + ' for ' + queryId);\n var req = {\n /*path*/\n p: pathString\n };\n var action = 'n'; // Only bother sending queryId if it's non-default.\n\n if (tag) {\n req['q'] = queryObj;\n req['t'] = tag;\n }\n\n this.sendRequest(action, req);\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.onDisconnectPut = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('o', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'o',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.onDisconnectMerge = function (pathString, data, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('om', pathString, data, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'om',\n data: data,\n onComplete: onComplete\n });\n }\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.onDisconnectCancel = function (pathString, onComplete) {\n if (this.connected_) {\n this.sendOnDisconnect_('oc', pathString, null, onComplete);\n } else {\n this.onDisconnectRequestQueue_.push({\n pathString: pathString,\n action: 'oc',\n data: null,\n onComplete: onComplete\n });\n }\n };\n\n PersistentConnection.prototype.sendOnDisconnect_ = function (action, pathString, data, onComplete) {\n var request = {\n /*path*/\n p: pathString,\n\n /*data*/\n d: data\n };\n this.log_('onDisconnect ' + action, request);\n this.sendRequest(action, request, function (response) {\n if (onComplete) {\n setTimeout(function () {\n onComplete(response[\n /*status*/\n 's'], response[\n /* data */\n 'd']);\n }, Math.floor(0));\n }\n });\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.put = function (pathString, data, onComplete, hash) {\n this.putInternal('p', pathString, data, onComplete, hash);\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.merge = function (pathString, data, onComplete, hash) {\n this.putInternal('m', pathString, data, onComplete, hash);\n };\n\n PersistentConnection.prototype.putInternal = function (action, pathString, data, onComplete, hash) {\n var request = {\n /*path*/\n p: pathString,\n\n /*data*/\n d: data\n };\n if (hash !== undefined) request[\n /*hash*/\n 'h'] = hash; // TODO: Only keep track of the most recent put for a given path?\n\n this.outstandingPuts_.push({\n action: action,\n request: request,\n onComplete: onComplete\n });\n this.outstandingPutCount_++;\n var index = this.outstandingPuts_.length - 1;\n\n if (this.connected_) {\n this.sendPut_(index);\n } else {\n this.log_('Buffering put: ' + pathString);\n }\n };\n\n PersistentConnection.prototype.sendPut_ = function (index) {\n var _this = this;\n\n var action = this.outstandingPuts_[index].action;\n var request = this.outstandingPuts_[index].request;\n var onComplete = this.outstandingPuts_[index].onComplete;\n this.outstandingPuts_[index].queued = this.connected_;\n this.sendRequest(action, request, function (message) {\n _this.log_(action + ' response', message);\n\n delete _this.outstandingPuts_[index];\n _this.outstandingPutCount_--; // Clean up array occasionally.\n\n if (_this.outstandingPutCount_ === 0) {\n _this.outstandingPuts_ = [];\n }\n\n if (onComplete) onComplete(message[\n /*status*/\n 's'], message[\n /* data */\n 'd']);\n });\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n PersistentConnection.prototype.reportStats = function (stats) {\n var _this = this; // If we're not connected, we just drop the stats.\n\n\n if (this.connected_) {\n var request = {\n /*counters*/\n c: stats\n };\n this.log_('reportStats', request);\n this.sendRequest(\n /*stats*/\n 's', request, function (result) {\n var status = result[\n /*status*/\n 's'];\n\n if (status !== 'ok') {\n var errorReason = result[\n /* data */\n 'd'];\n\n _this.log_('reportStats', 'Error sending stats: ' + errorReason);\n }\n });\n }\n };\n /**\r\n * @param {*} message\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.onDataMessage_ = function (message) {\n if ('r' in message) {\n // this is a response\n this.log_('from server: ' + util.stringify(message));\n var reqNum = message['r'];\n var onResponse = this.requestCBHash_[reqNum];\n\n if (onResponse) {\n delete this.requestCBHash_[reqNum];\n onResponse(message[\n /*body*/\n 'b']);\n }\n } else if ('error' in message) {\n throw 'A server-side error has occurred: ' + message['error'];\n } else if ('a' in message) {\n // a and b are action and body, respectively\n this.onDataPush_(message['a'], message['b']);\n }\n };\n\n PersistentConnection.prototype.onDataPush_ = function (action, body) {\n this.log_('handleServerMessage', action, body);\n if (action === 'd') this.onDataUpdate_(body[\n /*path*/\n 'p'], body[\n /*data*/\n 'd'],\n /*isMerge*/\n false, body['t']);else if (action === 'm') this.onDataUpdate_(body[\n /*path*/\n 'p'], body[\n /*data*/\n 'd'],\n /*isMerge=*/\n true, body['t']);else if (action === 'c') this.onListenRevoked_(body[\n /*path*/\n 'p'], body[\n /*query*/\n 'q']);else if (action === 'ac') this.onAuthRevoked_(body[\n /*status code*/\n 's'], body[\n /* explanation */\n 'd']);else if (action === 'sd') this.onSecurityDebugPacket_(body);else error('Unrecognized action received from server: ' + util.stringify(action) + '\\nAre you using the latest client?');\n };\n\n PersistentConnection.prototype.onReady_ = function (timestamp, sessionId) {\n this.log_('connection ready');\n this.connected_ = true;\n this.lastConnectionEstablishedTime_ = new Date().getTime();\n this.handleTimestamp_(timestamp);\n this.lastSessionId = sessionId;\n\n if (this.firstConnection_) {\n this.sendConnectStats_();\n }\n\n this.restoreState_();\n this.firstConnection_ = false;\n this.onConnectStatus_(true);\n };\n\n PersistentConnection.prototype.scheduleConnect_ = function (timeout) {\n var _this = this;\n\n util.assert(!this.realtime_, \"Scheduling a connect when we're already connected/ing?\");\n\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n } // NOTE: Even when timeout is 0, it's important to do a setTimeout to work around an infuriating \"Security Error\" in\n // Firefox when trying to write to our long-polling iframe in some scenarios (e.g. Forge or our unit tests).\n\n\n this.establishConnectionTimer_ = setTimeout(function () {\n _this.establishConnectionTimer_ = null;\n\n _this.establishConnection_();\n }, Math.floor(timeout));\n };\n /**\r\n * @param {boolean} visible\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.onVisible_ = function (visible) {\n // NOTE: Tabbing away and back to a window will defeat our reconnect backoff, but I think that's fine.\n if (visible && !this.visible_ && this.reconnectDelay_ === this.maxReconnectDelay_) {\n this.log_('Window became visible. Reducing delay.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n\n this.visible_ = visible;\n };\n\n PersistentConnection.prototype.onOnline_ = function (online) {\n if (online) {\n this.log_('Browser went online.');\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n } else {\n this.log_('Browser went offline. Killing connection.');\n\n if (this.realtime_) {\n this.realtime_.close();\n }\n }\n };\n\n PersistentConnection.prototype.onRealtimeDisconnect_ = function () {\n this.log_('data client disconnected');\n this.connected_ = false;\n this.realtime_ = null; // Since we don't know if our sent transactions succeeded or not, we need to cancel them.\n\n this.cancelSentTransactions_(); // Clear out the pending requests.\n\n this.requestCBHash_ = {};\n\n if (this.shouldReconnect_()) {\n if (!this.visible_) {\n this.log_(\"Window isn't visible. Delaying reconnect.\");\n this.reconnectDelay_ = this.maxReconnectDelay_;\n this.lastConnectionAttemptTime_ = new Date().getTime();\n } else if (this.lastConnectionEstablishedTime_) {\n // If we've been connected long enough, reset reconnect delay to minimum.\n var timeSinceLastConnectSucceeded = new Date().getTime() - this.lastConnectionEstablishedTime_;\n if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n this.lastConnectionEstablishedTime_ = null;\n }\n\n var timeSinceLastConnectAttempt = new Date().getTime() - this.lastConnectionAttemptTime_;\n var reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);\n reconnectDelay = Math.random() * reconnectDelay;\n this.log_('Trying to reconnect in ' + reconnectDelay + 'ms');\n this.scheduleConnect_(reconnectDelay); // Adjust reconnect delay for next time.\n\n this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);\n }\n\n this.onConnectStatus_(false);\n };\n\n PersistentConnection.prototype.establishConnection_ = function () {\n if (this.shouldReconnect_()) {\n this.log_('Making a connection attempt');\n this.lastConnectionAttemptTime_ = new Date().getTime();\n this.lastConnectionEstablishedTime_ = null;\n var onDataMessage_1 = this.onDataMessage_.bind(this);\n var onReady_1 = this.onReady_.bind(this);\n var onDisconnect_1 = this.onRealtimeDisconnect_.bind(this);\n var connId_1 = this.id + ':' + PersistentConnection.nextConnectionId_++;\n var self_1 = this;\n var lastSessionId_1 = this.lastSessionId;\n var canceled_1 = false;\n var connection_1 = null;\n\n var closeFn_1 = function closeFn_1() {\n if (connection_1) {\n connection_1.close();\n } else {\n canceled_1 = true;\n onDisconnect_1();\n }\n };\n\n var sendRequestFn = function sendRequestFn(msg) {\n util.assert(connection_1, \"sendRequest call when we're not connected not allowed.\");\n connection_1.sendRequest(msg);\n };\n\n this.realtime_ = {\n close: closeFn_1,\n sendRequest: sendRequestFn\n };\n var forceRefresh = this.forceTokenRefresh_;\n this.forceTokenRefresh_ = false; // First fetch auth token, and establish connection after fetching the token was successful\n\n this.authTokenProvider_.getToken(forceRefresh).then(function (result) {\n if (!canceled_1) {\n log('getToken() completed. Creating connection.');\n self_1.authToken_ = result && result.accessToken;\n connection_1 = new Connection(connId_1, self_1.repoInfo_, onDataMessage_1, onReady_1, onDisconnect_1,\n /* onKill= */\n function (reason) {\n warn(reason + ' (' + self_1.repoInfo_.toString() + ')');\n self_1.interrupt(SERVER_KILL_INTERRUPT_REASON);\n }, lastSessionId_1);\n } else {\n log('getToken() completed but was canceled');\n }\n }).then(null, function (error$$1) {\n self_1.log_('Failed to get token: ' + error$$1);\n\n if (!canceled_1) {\n if (util.CONSTANTS.NODE_ADMIN) {\n // This may be a critical error for the Admin Node.js SDK, so log a warning.\n // But getToken() may also just have temporarily failed, so we still want to\n // continue retrying.\n warn(error$$1);\n }\n\n closeFn_1();\n }\n });\n }\n };\n /**\r\n * @param {string} reason\r\n */\n\n\n PersistentConnection.prototype.interrupt = function (reason) {\n log('Interrupting connection for reason: ' + reason);\n this.interruptReasons_[reason] = true;\n\n if (this.realtime_) {\n this.realtime_.close();\n } else {\n if (this.establishConnectionTimer_) {\n clearTimeout(this.establishConnectionTimer_);\n this.establishConnectionTimer_ = null;\n }\n\n if (this.connected_) {\n this.onRealtimeDisconnect_();\n }\n }\n };\n /**\r\n * @param {string} reason\r\n */\n\n\n PersistentConnection.prototype.resume = function (reason) {\n log('Resuming connection for reason: ' + reason);\n delete this.interruptReasons_[reason];\n\n if (util.isEmpty(this.interruptReasons_)) {\n this.reconnectDelay_ = RECONNECT_MIN_DELAY;\n\n if (!this.realtime_) {\n this.scheduleConnect_(0);\n }\n }\n };\n\n PersistentConnection.prototype.handleTimestamp_ = function (timestamp) {\n var delta = timestamp - new Date().getTime();\n this.onServerInfoUpdate_({\n serverTimeOffset: delta\n });\n };\n\n PersistentConnection.prototype.cancelSentTransactions_ = function () {\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n var put = this.outstandingPuts_[i];\n\n if (put &&\n /*hash*/\n 'h' in put.request && put.queued) {\n if (put.onComplete) put.onComplete('disconnect');\n delete this.outstandingPuts_[i];\n this.outstandingPutCount_--;\n }\n } // Clean up array occasionally.\n\n\n if (this.outstandingPutCount_ === 0) this.outstandingPuts_ = [];\n };\n /**\r\n * @param {!string} pathString\r\n * @param {Array.<*>=} query\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.onListenRevoked_ = function (pathString, query) {\n // Remove the listen and manufacture a \"permission_denied\" error for the failed listen.\n var queryId;\n\n if (!query) {\n queryId = 'default';\n } else {\n queryId = query.map(function (q) {\n return ObjectToUniqueKey(q);\n }).join('$');\n }\n\n var listen = this.removeListen_(pathString, queryId);\n if (listen && listen.onComplete) listen.onComplete('permission_denied');\n };\n /**\r\n * @param {!string} pathString\r\n * @param {!string} queryId\r\n * @return {{queries:Array., onComplete:function(string)}}\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.removeListen_ = function (pathString, queryId) {\n var normalizedPathString = new Path(pathString).toString(); // normalize path.\n\n var listen;\n\n if (this.listens_[normalizedPathString] !== undefined) {\n listen = this.listens_[normalizedPathString][queryId];\n delete this.listens_[normalizedPathString][queryId];\n\n if (util.getCount(this.listens_[normalizedPathString]) === 0) {\n delete this.listens_[normalizedPathString];\n }\n } else {\n // all listens for this path has already been removed\n listen = undefined;\n }\n\n return listen;\n };\n\n PersistentConnection.prototype.onAuthRevoked_ = function (statusCode, explanation) {\n log('Auth token revoked: ' + statusCode + '/' + explanation);\n this.authToken_ = null;\n this.forceTokenRefresh_ = true;\n this.realtime_.close();\n\n if (statusCode === 'invalid_token' || statusCode === 'permission_denied') {\n // We'll wait a couple times before logging the warning / increasing the\n // retry period since oauth tokens will report as \"invalid\" if they're\n // just expired. Plus there may be transient issues that resolve themselves.\n this.invalidAuthTokenCount_++;\n\n if (this.invalidAuthTokenCount_ >= INVALID_AUTH_TOKEN_THRESHOLD) {\n // Set a long reconnect delay because recovery is unlikely\n this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS; // Notify the auth token provider that the token is invalid, which will log\n // a warning\n\n this.authTokenProvider_.notifyForInvalidToken();\n }\n }\n };\n\n PersistentConnection.prototype.onSecurityDebugPacket_ = function (body) {\n if (this.securityDebugCallback_) {\n this.securityDebugCallback_(body);\n } else {\n if ('msg' in body) {\n console.log('FIREBASE: ' + body['msg'].replace('\\n', '\\nFIREBASE: '));\n }\n }\n };\n\n PersistentConnection.prototype.restoreState_ = function () {\n var _this = this; //Re-authenticate ourselves if we have a credential stored.\n\n\n this.tryAuth(); // Puts depend on having received the corresponding data update from the server before they complete, so we must\n // make sure to send listens before puts.\n\n util.forEach(this.listens_, function (pathString, queries) {\n util.forEach(queries, function (key, listenSpec) {\n _this.sendListen_(listenSpec);\n });\n });\n\n for (var i = 0; i < this.outstandingPuts_.length; i++) {\n if (this.outstandingPuts_[i]) this.sendPut_(i);\n }\n\n while (this.onDisconnectRequestQueue_.length) {\n var request = this.onDisconnectRequestQueue_.shift();\n this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);\n }\n };\n /**\r\n * Sends client stats for first connection\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.sendConnectStats_ = function () {\n var stats = {};\n var clientName = 'js';\n\n if (util.CONSTANTS.NODE_ADMIN) {\n clientName = 'admin_node';\n } else if (util.CONSTANTS.NODE_CLIENT) {\n clientName = 'node';\n }\n\n stats['sdk.' + clientName + '.' + firebase.SDK_VERSION.replace(/\\./g, '-')] = 1;\n\n if (util.isMobileCordova()) {\n stats['framework.cordova'] = 1;\n } else if (util.isReactNative()) {\n stats['framework.reactnative'] = 1;\n }\n\n this.reportStats(stats);\n };\n /**\r\n * @return {boolean}\r\n * @private\r\n */\n\n\n PersistentConnection.prototype.shouldReconnect_ = function () {\n var online = OnlineMonitor.getInstance().currentlyOnline();\n return util.isEmpty(this.interruptReasons_) && online;\n };\n /**\r\n * @private\r\n */\n\n\n PersistentConnection.nextPersistentConnectionId_ = 0;\n /**\r\n * Counter for number of connections created. Mainly used for tagging in the logs\r\n * @type {number}\r\n * @private\r\n */\n\n PersistentConnection.nextConnectionId_ = 0;\n return PersistentConnection;\n}(ServerActions);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * An implementation of ServerActions that communicates with the server via REST requests.\r\n * This is mostly useful for compatibility with crawlers, where we don't want to spin up a full\r\n * persistent connection (using WebSockets or long-polling)\r\n */\n\n\nvar ReadonlyRestClient =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ReadonlyRestClient, _super);\n /**\r\n * @param {!RepoInfo} repoInfo_ Data about the namespace we are connecting to\r\n * @param {function(string, *, boolean, ?number)} onDataUpdate_ A callback for new data from the server\r\n * @param {AuthTokenProvider} authTokenProvider_\r\n * @implements {ServerActions}\r\n */\n\n\n function ReadonlyRestClient(repoInfo_, onDataUpdate_, authTokenProvider_) {\n var _this = _super.call(this) || this;\n\n _this.repoInfo_ = repoInfo_;\n _this.onDataUpdate_ = onDataUpdate_;\n _this.authTokenProvider_ = authTokenProvider_;\n /** @private {function(...[*])} */\n\n _this.log_ = logWrapper('p:rest:');\n /**\r\n * We don't actually need to track listens, except to prevent us calling an onComplete for a listen\r\n * that's been removed. :-/\r\n *\r\n * @private {!Object.}\r\n */\n\n _this.listens_ = {};\n return _this;\n }\n\n ReadonlyRestClient.prototype.reportStats = function (stats) {\n throw new Error('Method not implemented.');\n };\n /**\r\n * @param {!Query} query\r\n * @param {?number=} tag\r\n * @return {string}\r\n * @private\r\n */\n\n\n ReadonlyRestClient.getListenId_ = function (query, tag) {\n if (tag !== undefined) {\n return 'tag$' + tag;\n } else {\n util.assert(query.getQueryParams().isDefault(), \"should have a tag if it's not a default query.\");\n return query.path.toString();\n }\n };\n /** @inheritDoc */\n\n\n ReadonlyRestClient.prototype.listen = function (query, currentHashFn, tag, onComplete) {\n var _this = this;\n\n var pathString = query.path.toString();\n this.log_('Listen called for ' + pathString + ' ' + query.queryIdentifier()); // Mark this listener so we can tell if it's removed.\n\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n var thisListen = {};\n this.listens_[listenId] = thisListen;\n var queryStringParamaters = query.getQueryParams().toRestQueryStringParameters();\n this.restRequest_(pathString + '.json', queryStringParamaters, function (error$$1, result) {\n var data = result;\n\n if (error$$1 === 404) {\n data = null;\n error$$1 = null;\n }\n\n if (error$$1 === null) {\n _this.onDataUpdate_(pathString, data,\n /*isMerge=*/\n false, tag);\n }\n\n if (util.safeGet(_this.listens_, listenId) === thisListen) {\n var status_1;\n\n if (!error$$1) {\n status_1 = 'ok';\n } else if (error$$1 == 401) {\n status_1 = 'permission_denied';\n } else {\n status_1 = 'rest_error:' + error$$1;\n }\n\n onComplete(status_1, null);\n }\n });\n };\n /** @inheritDoc */\n\n\n ReadonlyRestClient.prototype.unlisten = function (query, tag) {\n var listenId = ReadonlyRestClient.getListenId_(query, tag);\n delete this.listens_[listenId];\n };\n /** @inheritDoc */\n\n\n ReadonlyRestClient.prototype.refreshAuthToken = function (token) {// no-op since we just always call getToken.\n };\n /**\r\n * Performs a REST request to the given path, with the provided query string parameters,\r\n * and any auth credentials we have.\r\n *\r\n * @param {!string} pathString\r\n * @param {!Object.} queryStringParameters\r\n * @param {?function(?number, *=)} callback\r\n * @private\r\n */\n\n\n ReadonlyRestClient.prototype.restRequest_ = function (pathString, queryStringParameters, callback) {\n var _this = this;\n\n if (queryStringParameters === void 0) {\n queryStringParameters = {};\n }\n\n queryStringParameters['format'] = 'export';\n this.authTokenProvider_.getToken(\n /*forceRefresh=*/\n false).then(function (authTokenData) {\n var authToken = authTokenData && authTokenData.accessToken;\n\n if (authToken) {\n queryStringParameters['auth'] = authToken;\n }\n\n var url = (_this.repoInfo_.secure ? 'https://' : 'http://') + _this.repoInfo_.host + pathString + '?' + util.querystring(queryStringParameters);\n\n _this.log_('Sending REST request for ' + url);\n\n var xhr = new XMLHttpRequest();\n\n xhr.onreadystatechange = function () {\n if (callback && xhr.readyState === 4) {\n _this.log_('REST Response for ' + url + ' received. status:', xhr.status, 'response:', xhr.responseText);\n\n var res = null;\n\n if (xhr.status >= 200 && xhr.status < 300) {\n try {\n res = util.jsonEval(xhr.responseText);\n } catch (e) {\n warn('Failed to parse JSON response for ' + url + ': ' + xhr.responseText);\n }\n\n callback(null, res);\n } else {\n // 401 and 404 are expected.\n if (xhr.status !== 401 && xhr.status !== 404) {\n warn('Got unsuccessful REST response for ' + url + ' Status: ' + xhr.status);\n }\n\n callback(xhr.status);\n }\n\n callback = null;\n }\n };\n\n xhr.open('GET', url,\n /*asynchronous=*/\n true);\n xhr.send();\n });\n };\n\n return ReadonlyRestClient;\n}(ServerActions);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar INTERRUPT_REASON = 'repo_interrupt';\n/**\r\n * A connection to a single data repository.\r\n */\n\nvar Repo =\n/** @class */\nfunction () {\n /**\r\n * @param {!RepoInfo} repoInfo_\r\n * @param {boolean} forceRestClient\r\n * @param {!FirebaseApp} app\r\n */\n function Repo(repoInfo_, forceRestClient, app) {\n var _this = this;\n\n this.repoInfo_ = repoInfo_;\n this.app = app;\n this.dataUpdateCount = 0;\n this.statsListener_ = null;\n this.eventQueue_ = new EventQueue();\n this.nextWriteId_ = 1;\n this.interceptServerDataCallback_ = null; // A list of data pieces and paths to be set when this client disconnects.\n\n this.onDisconnect_ = new SparseSnapshotTree();\n /**\r\n * TODO: This should be @private but it's used by test_access.js and internal.js\r\n * @type {?PersistentConnection}\r\n */\n\n this.persistentConnection_ = null;\n /** @type {!AuthTokenProvider} */\n\n var authTokenProvider = new AuthTokenProvider(app);\n this.stats_ = StatsManager.getCollection(repoInfo_);\n\n if (forceRestClient || beingCrawled()) {\n this.server_ = new ReadonlyRestClient(this.repoInfo_, this.onDataUpdate_.bind(this), authTokenProvider); // Minor hack: Fire onConnect immediately, since there's no actual connection.\n\n setTimeout(this.onConnectStatus_.bind(this, true), 0);\n } else {\n var authOverride = app.options['databaseAuthVariableOverride']; // Validate authOverride\n\n if (typeof authOverride !== 'undefined' && authOverride !== null) {\n if (typeof authOverride !== 'object') {\n throw new Error('Only objects are supported for option databaseAuthVariableOverride');\n }\n\n try {\n util.stringify(authOverride);\n } catch (e) {\n throw new Error('Invalid authOverride provided: ' + e);\n }\n }\n\n this.persistentConnection_ = new PersistentConnection(this.repoInfo_, this.onDataUpdate_.bind(this), this.onConnectStatus_.bind(this), this.onServerInfoUpdate_.bind(this), authTokenProvider, authOverride);\n this.server_ = this.persistentConnection_;\n }\n\n authTokenProvider.addTokenChangeListener(function (token) {\n _this.server_.refreshAuthToken(token);\n }); // In the case of multiple Repos for the same repoInfo (i.e. there are multiple Firebase.Contexts being used),\n // we only want to create one StatsReporter. As such, we'll report stats over the first Repo created.\n\n this.statsReporter_ = StatsManager.getOrCreateReporter(repoInfo_, function () {\n return new StatsReporter(_this.stats_, _this.server_);\n });\n this.transactions_init_(); // Used for .info.\n\n this.infoData_ = new SnapshotHolder();\n this.infoSyncTree_ = new SyncTree({\n startListening: function startListening(query, tag, currentHashFn, onComplete) {\n var infoEvents = [];\n\n var node = _this.infoData_.getNode(query.path); // This is possibly a hack, but we have different semantics for .info endpoints. We don't raise null events\n // on initial data...\n\n\n if (!node.isEmpty()) {\n infoEvents = _this.infoSyncTree_.applyServerOverwrite(query.path, node);\n setTimeout(function () {\n onComplete('ok');\n }, 0);\n }\n\n return infoEvents;\n },\n stopListening: function stopListening() {}\n });\n this.updateInfo_('connected', false);\n this.serverSyncTree_ = new SyncTree({\n startListening: function startListening(query, tag, currentHashFn, onComplete) {\n _this.server_.listen(query, currentHashFn, tag, function (status, data) {\n var events = onComplete(status, data);\n\n _this.eventQueue_.raiseEventsForChangedPath(query.path, events);\n }); // No synchronous events for network-backed sync trees\n\n\n return [];\n },\n stopListening: function stopListening(query, tag) {\n _this.server_.unlisten(query, tag);\n }\n });\n }\n /**\r\n * @return {string} The URL corresponding to the root of this Firebase.\r\n */\n\n\n Repo.prototype.toString = function () {\n return (this.repoInfo_.secure ? 'https://' : 'http://') + this.repoInfo_.host;\n };\n /**\r\n * @return {!string} The namespace represented by the repo.\r\n */\n\n\n Repo.prototype.name = function () {\n return this.repoInfo_.namespace;\n };\n /**\r\n * @return {!number} The time in milliseconds, taking the server offset into account if we have one.\r\n */\n\n\n Repo.prototype.serverTime = function () {\n var offsetNode = this.infoData_.getNode(new Path('.info/serverTimeOffset'));\n var offset = offsetNode.val() || 0;\n return new Date().getTime() + offset;\n };\n /**\r\n * Generate ServerValues using some variables from the repo object.\r\n * @return {!Object}\r\n */\n\n\n Repo.prototype.generateServerValues = function () {\n return generateWithValues({\n timestamp: this.serverTime()\n });\n };\n /**\r\n * Called by realtime when we get new messages from the server.\r\n *\r\n * @private\r\n * @param {string} pathString\r\n * @param {*} data\r\n * @param {boolean} isMerge\r\n * @param {?number} tag\r\n */\n\n\n Repo.prototype.onDataUpdate_ = function (pathString, data, isMerge, tag) {\n // For testing.\n this.dataUpdateCount++;\n var path = new Path(pathString);\n data = this.interceptServerDataCallback_ ? this.interceptServerDataCallback_(pathString, data) : data;\n var events = [];\n\n if (tag) {\n if (isMerge) {\n var taggedChildren = util.map(data, function (raw) {\n return nodeFromJSON$1(raw);\n });\n events = this.serverSyncTree_.applyTaggedQueryMerge(path, taggedChildren, tag);\n } else {\n var taggedSnap = nodeFromJSON$1(data);\n events = this.serverSyncTree_.applyTaggedQueryOverwrite(path, taggedSnap, tag);\n }\n } else if (isMerge) {\n var changedChildren = util.map(data, function (raw) {\n return nodeFromJSON$1(raw);\n });\n events = this.serverSyncTree_.applyServerMerge(path, changedChildren);\n } else {\n var snap = nodeFromJSON$1(data);\n events = this.serverSyncTree_.applyServerOverwrite(path, snap);\n }\n\n var affectedPath = path;\n\n if (events.length > 0) {\n // Since we have a listener outstanding for each transaction, receiving any events\n // is a proxy for some change having occurred.\n affectedPath = this.rerunTransactions_(path);\n }\n\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, events);\n };\n /**\r\n * TODO: This should be @private but it's used by test_access.js and internal.js\r\n * @param {?function(!string, *):*} callback\r\n * @private\r\n */\n\n\n Repo.prototype.interceptServerData_ = function (callback) {\n this.interceptServerDataCallback_ = callback;\n };\n /**\r\n * @param {!boolean} connectStatus\r\n * @private\r\n */\n\n\n Repo.prototype.onConnectStatus_ = function (connectStatus) {\n this.updateInfo_('connected', connectStatus);\n\n if (connectStatus === false) {\n this.runOnDisconnectEvents_();\n }\n };\n /**\r\n * @param {!Object} updates\r\n * @private\r\n */\n\n\n Repo.prototype.onServerInfoUpdate_ = function (updates) {\n var _this = this;\n\n each(updates, function (value, key) {\n _this.updateInfo_(key, value);\n });\n };\n /**\r\n *\r\n * @param {!string} pathString\r\n * @param {*} value\r\n * @private\r\n */\n\n\n Repo.prototype.updateInfo_ = function (pathString, value) {\n var path = new Path('/.info/' + pathString);\n var newNode = nodeFromJSON$1(value);\n this.infoData_.updateSnapshot(path, newNode);\n var events = this.infoSyncTree_.applyServerOverwrite(path, newNode);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n };\n /**\r\n * @return {!number}\r\n * @private\r\n */\n\n\n Repo.prototype.getNextWriteId_ = function () {\n return this.nextWriteId_++;\n };\n /**\r\n * @param {!Path} path\r\n * @param {*} newVal\r\n * @param {number|string|null} newPriority\r\n * @param {?function(?Error, *=)} onComplete\r\n */\n\n\n Repo.prototype.setWithPriority = function (path, newVal, newPriority, onComplete) {\n var _this = this;\n\n this.log_('set', {\n path: path.toString(),\n value: newVal,\n priority: newPriority\n }); // TODO: Optimize this behavior to either (a) store flag to skip resolving where possible and / or\n // (b) store unresolved paths on JSON parse\n\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON$1(newVal, newPriority);\n var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n var writeId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, writeId, true);\n this.eventQueue_.queueEvents(events);\n this.server_.put(path.toString(), newNodeUnresolved.val(\n /*export=*/\n true), function (status, errorReason) {\n var success = status === 'ok';\n\n if (!success) {\n warn('set at ' + path + ' failed: ' + status);\n }\n\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId, !success);\n\n _this.eventQueue_.raiseEventsForChangedPath(path, clearEvents);\n\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n var affectedPath = this.abortTransactions_(path);\n this.rerunTransactions_(affectedPath); // We queued the events above, so just flush the queue here\n\n this.eventQueue_.raiseEventsForChangedPath(affectedPath, []);\n };\n /**\r\n * @param {!Path} path\r\n * @param {!Object} childrenToMerge\r\n * @param {?function(?Error, *=)} onComplete\r\n */\n\n\n Repo.prototype.update = function (path, childrenToMerge, onComplete) {\n var _this = this;\n\n this.log_('update', {\n path: path.toString(),\n value: childrenToMerge\n }); // Start with our existing data and merge each child into it.\n\n var empty = true;\n var serverValues = this.generateServerValues();\n var changedChildren = {};\n util.forEach(childrenToMerge, function (changedKey, changedValue) {\n empty = false;\n var newNodeUnresolved = nodeFromJSON$1(changedValue);\n changedChildren[changedKey] = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n });\n\n if (!empty) {\n var writeId_1 = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserMerge(path, changedChildren, writeId_1);\n this.eventQueue_.queueEvents(events);\n this.server_.merge(path.toString(), childrenToMerge, function (status, errorReason) {\n var success = status === 'ok';\n\n if (!success) {\n warn('update at ' + path + ' failed: ' + status);\n }\n\n var clearEvents = _this.serverSyncTree_.ackUserWrite(writeId_1, !success);\n\n var affectedPath = clearEvents.length > 0 ? _this.rerunTransactions_(path) : path;\n\n _this.eventQueue_.raiseEventsForChangedPath(affectedPath, clearEvents);\n\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n util.forEach(childrenToMerge, function (changedPath) {\n var affectedPath = _this.abortTransactions_(path.child(changedPath));\n\n _this.rerunTransactions_(affectedPath);\n }); // We queued the events above, so just flush the queue here\n\n this.eventQueue_.raiseEventsForChangedPath(path, []);\n } else {\n log(\"update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n }\n };\n /**\r\n * Applies all of the changes stored up in the onDisconnect_ tree.\r\n * @private\r\n */\n\n\n Repo.prototype.runOnDisconnectEvents_ = function () {\n var _this = this;\n\n this.log_('onDisconnectEvents');\n var serverValues = this.generateServerValues();\n var resolvedOnDisconnectTree = resolveDeferredValueTree(this.onDisconnect_, serverValues);\n var events = [];\n resolvedOnDisconnectTree.forEachTree(Path.Empty, function (path, snap) {\n events = events.concat(_this.serverSyncTree_.applyServerOverwrite(path, snap));\n\n var affectedPath = _this.abortTransactions_(path);\n\n _this.rerunTransactions_(affectedPath);\n });\n this.onDisconnect_ = new SparseSnapshotTree();\n this.eventQueue_.raiseEventsForChangedPath(Path.Empty, events);\n };\n /**\r\n * @param {!Path} path\r\n * @param {?function(?Error, *=)} onComplete\r\n */\n\n\n Repo.prototype.onDisconnectCancel = function (path, onComplete) {\n var _this = this;\n\n this.server_.onDisconnectCancel(path.toString(), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.forget(path);\n }\n\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\r\n * @param {!Path} path\r\n * @param {*} value\r\n * @param {?function(?Error, *=)} onComplete\r\n */\n\n\n Repo.prototype.onDisconnectSet = function (path, value, onComplete) {\n var _this = this;\n\n var newNode = nodeFromJSON$1(value);\n this.server_.onDisconnectPut(path.toString(), newNode.val(\n /*export=*/\n true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\r\n * @param {!Path} path\r\n * @param {*} value\r\n * @param {*} priority\r\n * @param {?function(?Error, *=)} onComplete\r\n */\n\n\n Repo.prototype.onDisconnectSetWithPriority = function (path, value, priority, onComplete) {\n var _this = this;\n\n var newNode = nodeFromJSON$1(value, priority);\n this.server_.onDisconnectPut(path.toString(), newNode.val(\n /*export=*/\n true), function (status, errorReason) {\n if (status === 'ok') {\n _this.onDisconnect_.remember(path, newNode);\n }\n\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\r\n * @param {!Path} path\r\n * @param {*} childrenToMerge\r\n * @param {?function(?Error, *=)} onComplete\r\n */\n\n\n Repo.prototype.onDisconnectUpdate = function (path, childrenToMerge, onComplete) {\n var _this = this;\n\n if (util.isEmpty(childrenToMerge)) {\n log(\"onDisconnect().update() called with empty data. Don't do anything.\");\n this.callOnCompleteCallback(onComplete, 'ok');\n return;\n }\n\n this.server_.onDisconnectMerge(path.toString(), childrenToMerge, function (status, errorReason) {\n if (status === 'ok') {\n util.forEach(childrenToMerge, function (childName, childNode) {\n var newChildNode = nodeFromJSON$1(childNode);\n\n _this.onDisconnect_.remember(path.child(childName), newChildNode);\n });\n }\n\n _this.callOnCompleteCallback(onComplete, status, errorReason);\n });\n };\n /**\r\n * @param {!Query} query\r\n * @param {!EventRegistration} eventRegistration\r\n */\n\n\n Repo.prototype.addEventCallbackForQuery = function (query, eventRegistration) {\n var events;\n\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.addEventRegistration(query, eventRegistration);\n } else {\n events = this.serverSyncTree_.addEventRegistration(query, eventRegistration);\n }\n\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n /**\r\n * @param {!Query} query\r\n * @param {?EventRegistration} eventRegistration\r\n */\n\n\n Repo.prototype.removeEventCallbackForQuery = function (query, eventRegistration) {\n // These are guaranteed not to raise events, since we're not passing in a cancelError. However, we can future-proof\n // a little bit by handling the return values anyways.\n var events;\n\n if (query.path.getFront() === '.info') {\n events = this.infoSyncTree_.removeEventRegistration(query, eventRegistration);\n } else {\n events = this.serverSyncTree_.removeEventRegistration(query, eventRegistration);\n }\n\n this.eventQueue_.raiseEventsAtPath(query.path, events);\n };\n\n Repo.prototype.interrupt = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.interrupt(INTERRUPT_REASON);\n }\n };\n\n Repo.prototype.resume = function () {\n if (this.persistentConnection_) {\n this.persistentConnection_.resume(INTERRUPT_REASON);\n }\n };\n\n Repo.prototype.stats = function (showDelta) {\n if (showDelta === void 0) {\n showDelta = false;\n }\n\n if (typeof console === 'undefined') return;\n var stats;\n\n if (showDelta) {\n if (!this.statsListener_) this.statsListener_ = new StatsListener(this.stats_);\n stats = this.statsListener_.get();\n } else {\n stats = this.stats_.get();\n }\n\n var longestName = Object.keys(stats).reduce(function (previousValue, currentValue) {\n return Math.max(currentValue.length, previousValue);\n }, 0);\n util.forEach(stats, function (stat, value) {\n // pad stat names to be the same length (plus 2 extra spaces).\n for (var i = stat.length; i < longestName + 2; i++) {\n stat += ' ';\n }\n\n console.log(stat + value);\n });\n };\n\n Repo.prototype.statsIncrementCounter = function (metric) {\n this.stats_.incrementCounter(metric);\n this.statsReporter_.includeStat(metric);\n };\n /**\r\n * @param {...*} var_args\r\n * @private\r\n */\n\n\n Repo.prototype.log_ = function () {\n var var_args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n\n var prefix = '';\n\n if (this.persistentConnection_) {\n prefix = this.persistentConnection_.id + ':';\n }\n\n log.apply(void 0, [prefix].concat(var_args));\n };\n /**\r\n * @param {?function(?Error, *=)} callback\r\n * @param {!string} status\r\n * @param {?string=} errorReason\r\n */\n\n\n Repo.prototype.callOnCompleteCallback = function (callback, status, errorReason) {\n if (callback) {\n exceptionGuard(function () {\n if (status == 'ok') {\n callback(null);\n } else {\n var code = (status || 'error').toUpperCase();\n var message = code;\n if (errorReason) message += ': ' + errorReason;\n var error$$1 = new Error(message);\n error$$1.code = code;\n callback(error$$1);\n }\n });\n }\n };\n\n Object.defineProperty(Repo.prototype, \"database\", {\n get: function get() {\n return this.__database || (this.__database = new Database(this));\n },\n enumerable: true,\n configurable: true\n });\n return Repo;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Filters nodes by range and uses an IndexFilter to track any changes after filtering the node\r\n *\r\n * @constructor\r\n * @implements {NodeFilter}\r\n */\n\n\nvar RangedFilter =\n/** @class */\nfunction () {\n /**\r\n * @param {!QueryParams} params\r\n */\n function RangedFilter(params) {\n this.indexedFilter_ = new IndexedFilter(params.getIndex());\n this.index_ = params.getIndex();\n this.startPost_ = RangedFilter.getStartPost_(params);\n this.endPost_ = RangedFilter.getEndPost_(params);\n }\n /**\r\n * @return {!NamedNode}\r\n */\n\n\n RangedFilter.prototype.getStartPost = function () {\n return this.startPost_;\n };\n /**\r\n * @return {!NamedNode}\r\n */\n\n\n RangedFilter.prototype.getEndPost = function () {\n return this.endPost_;\n };\n /**\r\n * @param {!NamedNode} node\r\n * @return {boolean}\r\n */\n\n\n RangedFilter.prototype.matches = function (node) {\n return this.index_.compare(this.getStartPost(), node) <= 0 && this.index_.compare(node, this.getEndPost()) <= 0;\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n RangedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n\n return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n RangedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n if (newSnap.isLeafNode()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n newSnap = ChildrenNode.EMPTY_NODE;\n }\n\n var filtered = newSnap.withIndex(this.index_); // Don't support priorities on queries\n\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n var self = this;\n newSnap.forEachChild(PRIORITY_INDEX, function (key, childNode) {\n if (!self.matches(new NamedNode(key, childNode))) {\n filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);\n }\n });\n return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n RangedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n RangedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n RangedFilter.prototype.getIndexedFilter = function () {\n return this.indexedFilter_;\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n RangedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\r\n * @param {!QueryParams} params\r\n * @return {!NamedNode}\r\n * @private\r\n */\n\n\n RangedFilter.getStartPost_ = function (params) {\n if (params.hasStart()) {\n var startName = params.getIndexStartName();\n return params.getIndex().makePost(params.getIndexStartValue(), startName);\n } else {\n return params.getIndex().minPost();\n }\n };\n /**\r\n * @param {!QueryParams} params\r\n * @return {!NamedNode}\r\n * @private\r\n */\n\n\n RangedFilter.getEndPost_ = function (params) {\n if (params.hasEnd()) {\n var endName = params.getIndexEndName();\n return params.getIndex().makePost(params.getIndexEndValue(), endName);\n } else {\n return params.getIndex().maxPost();\n }\n };\n\n return RangedFilter;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Applies a limit and a range to a node and uses RangedFilter to do the heavy lifting where possible\r\n *\r\n * @constructor\r\n * @implements {NodeFilter}\r\n */\n\n\nvar LimitedFilter =\n/** @class */\nfunction () {\n /**\r\n * @param {!QueryParams} params\r\n */\n function LimitedFilter(params) {\n this.rangedFilter_ = new RangedFilter(params);\n this.index_ = params.getIndex();\n this.limit_ = params.getLimit();\n this.reverse_ = !params.isViewFromLeft();\n }\n /**\r\n * @inheritDoc\r\n */\n\n\n LimitedFilter.prototype.updateChild = function (snap, key, newChild, affectedPath, source, optChangeAccumulator) {\n if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {\n newChild = ChildrenNode.EMPTY_NODE;\n }\n\n if (snap.getImmediateChild(key).equals(newChild)) {\n // No change\n return snap;\n } else if (snap.numChildren() < this.limit_) {\n return this.rangedFilter_.getIndexedFilter().updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);\n } else {\n return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);\n }\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n LimitedFilter.prototype.updateFullNode = function (oldSnap, newSnap, optChangeAccumulator) {\n var filtered;\n\n if (newSnap.isLeafNode() || newSnap.isEmpty()) {\n // Make sure we have a children node with the correct index, not a leaf node;\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);\n } else {\n if (this.limit_ * 2 < newSnap.numChildren() && newSnap.isIndexed(this.index_)) {\n // Easier to build up a snapshot, since what we're given has more than twice the elements we want\n filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_); // anchor to the startPost, endPost, or last element as appropriate\n\n var iterator = void 0;\n\n if (this.reverse_) {\n iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);\n } else {\n iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);\n }\n\n var count = 0;\n\n while (iterator.hasNext() && count < this.limit_) {\n var next = iterator.getNext();\n var inRange = void 0;\n\n if (this.reverse_) {\n inRange = this.index_.compare(this.rangedFilter_.getStartPost(), next) <= 0;\n } else {\n inRange = this.index_.compare(next, this.rangedFilter_.getEndPost()) <= 0;\n }\n\n if (inRange) {\n filtered = filtered.updateImmediateChild(next.name, next.node);\n count++;\n } else {\n // if we have reached the end post, we cannot keep adding elemments\n break;\n }\n }\n } else {\n // The snap contains less than twice the limit. Faster to delete from the snap than build up a new one\n filtered = newSnap.withIndex(this.index_); // Don't support priorities on queries\n\n filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);\n var startPost = void 0;\n var endPost = void 0;\n var cmp = void 0;\n var iterator = void 0;\n\n if (this.reverse_) {\n iterator = filtered.getReverseIterator(this.index_);\n startPost = this.rangedFilter_.getEndPost();\n endPost = this.rangedFilter_.getStartPost();\n var indexCompare_1 = this.index_.getCompare();\n\n cmp = function cmp(a, b) {\n return indexCompare_1(b, a);\n };\n } else {\n iterator = filtered.getIterator(this.index_);\n startPost = this.rangedFilter_.getStartPost();\n endPost = this.rangedFilter_.getEndPost();\n cmp = this.index_.getCompare();\n }\n\n var count = 0;\n var foundStartPost = false;\n\n while (iterator.hasNext()) {\n var next = iterator.getNext();\n\n if (!foundStartPost && cmp(startPost, next) <= 0) {\n // start adding\n foundStartPost = true;\n }\n\n var inRange = foundStartPost && count < this.limit_ && cmp(next, endPost) <= 0;\n\n if (inRange) {\n count++;\n } else {\n filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);\n }\n }\n }\n }\n\n return this.rangedFilter_.getIndexedFilter().updateFullNode(oldSnap, filtered, optChangeAccumulator);\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n LimitedFilter.prototype.updatePriority = function (oldSnap, newPriority) {\n // Don't support priorities on queries\n return oldSnap;\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n LimitedFilter.prototype.filtersNodes = function () {\n return true;\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n LimitedFilter.prototype.getIndexedFilter = function () {\n return this.rangedFilter_.getIndexedFilter();\n };\n /**\r\n * @inheritDoc\r\n */\n\n\n LimitedFilter.prototype.getIndex = function () {\n return this.index_;\n };\n /**\r\n * @param {!Node} snap\r\n * @param {string} childKey\r\n * @param {!Node} childSnap\r\n * @param {!CompleteChildSource} source\r\n * @param {?ChildChangeAccumulator} changeAccumulator\r\n * @return {!Node}\r\n * @private\r\n */\n\n\n LimitedFilter.prototype.fullLimitUpdateChild_ = function (snap, childKey, childSnap, source, changeAccumulator) {\n // TODO: rename all cache stuff etc to general snap terminology\n var cmp;\n\n if (this.reverse_) {\n var indexCmp_1 = this.index_.getCompare();\n\n cmp = function cmp(a, b) {\n return indexCmp_1(b, a);\n };\n } else {\n cmp = this.index_.getCompare();\n }\n\n var oldEventCache = snap;\n util.assert(oldEventCache.numChildren() == this.limit_, '');\n var newChildNamedNode = new NamedNode(childKey, childSnap);\n var windowBoundary = this.reverse_ ? oldEventCache.getFirstChild(this.index_) : oldEventCache.getLastChild(this.index_);\n var inRange = this.rangedFilter_.matches(newChildNamedNode);\n\n if (oldEventCache.hasChild(childKey)) {\n var oldChildSnap = oldEventCache.getImmediateChild(childKey);\n var nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);\n\n while (nextChild != null && (nextChild.name == childKey || oldEventCache.hasChild(nextChild.name))) {\n // There is a weird edge case where a node is updated as part of a merge in the write tree, but hasn't\n // been applied to the limited filter yet. Ignore this next child which will be updated later in\n // the limited filter...\n nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);\n }\n\n var compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);\n var remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;\n\n if (remainsInWindow) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change.childChangedChange(childKey, childSnap, oldChildSnap));\n }\n\n return oldEventCache.updateImmediateChild(childKey, childSnap);\n } else {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change.childRemovedChange(childKey, oldChildSnap));\n }\n\n var newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);\n var nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);\n\n if (nextChildInRange) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change.childAddedChange(nextChild.name, nextChild.node));\n }\n\n return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);\n } else {\n return newEventCache;\n }\n }\n } else if (childSnap.isEmpty()) {\n // we're deleting a node, but it was not in the window, so ignore it\n return snap;\n } else if (inRange) {\n if (cmp(windowBoundary, newChildNamedNode) >= 0) {\n if (changeAccumulator != null) {\n changeAccumulator.trackChildChange(Change.childRemovedChange(windowBoundary.name, windowBoundary.node));\n changeAccumulator.trackChildChange(Change.childAddedChange(childKey, childSnap));\n }\n\n return oldEventCache.updateImmediateChild(childKey, childSnap).updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);\n } else {\n return snap;\n }\n } else {\n return snap;\n }\n };\n\n return LimitedFilter;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * This class is an immutable-from-the-public-api struct containing a set of query parameters defining a\r\n * range to be returned for a particular location. It is assumed that validation of parameters is done at the\r\n * user-facing API level, so it is not done here.\r\n * @constructor\r\n */\n\n\nvar QueryParams =\n/** @class */\nfunction () {\n function QueryParams() {\n this.limitSet_ = false;\n this.startSet_ = false;\n this.startNameSet_ = false;\n this.endSet_ = false;\n this.endNameSet_ = false;\n this.limit_ = 0;\n this.viewFrom_ = '';\n this.indexStartValue_ = null;\n this.indexStartName_ = '';\n this.indexEndValue_ = null;\n this.indexEndName_ = '';\n this.index_ = PRIORITY_INDEX;\n }\n /**\r\n * @return {boolean}\r\n */\n\n\n QueryParams.prototype.hasStart = function () {\n return this.startSet_;\n };\n /**\r\n * @return {boolean} True if it would return from left.\r\n */\n\n\n QueryParams.prototype.isViewFromLeft = function () {\n if (this.viewFrom_ === '') {\n // limit(), rather than limitToFirst or limitToLast was called.\n // This means that only one of startSet_ and endSet_ is true. Use them\n // to calculate which side of the view to anchor to. If neither is set,\n // anchor to the end.\n return this.startSet_;\n } else {\n return this.viewFrom_ === QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n }\n };\n /**\r\n * Only valid to call if hasStart() returns true\r\n * @return {*}\r\n */\n\n\n QueryParams.prototype.getIndexStartValue = function () {\n util.assert(this.startSet_, 'Only valid if start has been set');\n return this.indexStartValue_;\n };\n /**\r\n * Only valid to call if hasStart() returns true.\r\n * Returns the starting key name for the range defined by these query parameters\r\n * @return {!string}\r\n */\n\n\n QueryParams.prototype.getIndexStartName = function () {\n util.assert(this.startSet_, 'Only valid if start has been set');\n\n if (this.startNameSet_) {\n return this.indexStartName_;\n } else {\n return MIN_NAME;\n }\n };\n /**\r\n * @return {boolean}\r\n */\n\n\n QueryParams.prototype.hasEnd = function () {\n return this.endSet_;\n };\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * @return {*}\r\n */\n\n\n QueryParams.prototype.getIndexEndValue = function () {\n util.assert(this.endSet_, 'Only valid if end has been set');\n return this.indexEndValue_;\n };\n /**\r\n * Only valid to call if hasEnd() returns true.\r\n * Returns the end key name for the range defined by these query parameters\r\n * @return {!string}\r\n */\n\n\n QueryParams.prototype.getIndexEndName = function () {\n util.assert(this.endSet_, 'Only valid if end has been set');\n\n if (this.endNameSet_) {\n return this.indexEndName_;\n } else {\n return MAX_NAME;\n }\n };\n /**\r\n * @return {boolean}\r\n */\n\n\n QueryParams.prototype.hasLimit = function () {\n return this.limitSet_;\n };\n /**\r\n * @return {boolean} True if a limit has been set and it has been explicitly anchored\r\n */\n\n\n QueryParams.prototype.hasAnchoredLimit = function () {\n return this.limitSet_ && this.viewFrom_ !== '';\n };\n /**\r\n * Only valid to call if hasLimit() returns true\r\n * @return {!number}\r\n */\n\n\n QueryParams.prototype.getLimit = function () {\n util.assert(this.limitSet_, 'Only valid if limit has been set');\n return this.limit_;\n };\n /**\r\n * @return {!Index}\r\n */\n\n\n QueryParams.prototype.getIndex = function () {\n return this.index_;\n };\n /**\r\n * @return {!QueryParams}\r\n * @private\r\n */\n\n\n QueryParams.prototype.copy_ = function () {\n var copy = new QueryParams();\n copy.limitSet_ = this.limitSet_;\n copy.limit_ = this.limit_;\n copy.startSet_ = this.startSet_;\n copy.indexStartValue_ = this.indexStartValue_;\n copy.startNameSet_ = this.startNameSet_;\n copy.indexStartName_ = this.indexStartName_;\n copy.endSet_ = this.endSet_;\n copy.indexEndValue_ = this.indexEndValue_;\n copy.endNameSet_ = this.endNameSet_;\n copy.indexEndName_ = this.indexEndName_;\n copy.index_ = this.index_;\n copy.viewFrom_ = this.viewFrom_;\n return copy;\n };\n /**\r\n * @param {!number} newLimit\r\n * @return {!QueryParams}\r\n */\n\n\n QueryParams.prototype.limit = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = '';\n return newParams;\n };\n /**\r\n * @param {!number} newLimit\r\n * @return {!QueryParams}\r\n */\n\n\n QueryParams.prototype.limitToFirst = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_LEFT;\n return newParams;\n };\n /**\r\n * @param {!number} newLimit\r\n * @return {!QueryParams}\r\n */\n\n\n QueryParams.prototype.limitToLast = function (newLimit) {\n var newParams = this.copy_();\n newParams.limitSet_ = true;\n newParams.limit_ = newLimit;\n newParams.viewFrom_ = QueryParams.WIRE_PROTOCOL_CONSTANTS_.VIEW_FROM_RIGHT;\n return newParams;\n };\n /**\r\n * @param {*} indexValue\r\n * @param {?string=} key\r\n * @return {!QueryParams}\r\n */\n\n\n QueryParams.prototype.startAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.startSet_ = true;\n\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n\n newParams.indexStartValue_ = indexValue;\n\n if (key != null) {\n newParams.startNameSet_ = true;\n newParams.indexStartName_ = key;\n } else {\n newParams.startNameSet_ = false;\n newParams.indexStartName_ = '';\n }\n\n return newParams;\n };\n /**\r\n * @param {*} indexValue\r\n * @param {?string=} key\r\n * @return {!QueryParams}\r\n */\n\n\n QueryParams.prototype.endAt = function (indexValue, key) {\n var newParams = this.copy_();\n newParams.endSet_ = true;\n\n if (!(indexValue !== undefined)) {\n indexValue = null;\n }\n\n newParams.indexEndValue_ = indexValue;\n\n if (key !== undefined) {\n newParams.endNameSet_ = true;\n newParams.indexEndName_ = key;\n } else {\n newParams.endNameSet_ = false;\n newParams.indexEndName_ = '';\n }\n\n return newParams;\n };\n /**\r\n * @param {!Index} index\r\n * @return {!QueryParams}\r\n */\n\n\n QueryParams.prototype.orderBy = function (index) {\n var newParams = this.copy_();\n newParams.index_ = index;\n return newParams;\n };\n /**\r\n * @return {!Object}\r\n */\n\n\n QueryParams.prototype.getQueryObject = function () {\n var WIRE_PROTOCOL_CONSTANTS = QueryParams.WIRE_PROTOCOL_CONSTANTS_;\n var obj = {};\n\n if (this.startSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE] = this.indexStartValue_;\n\n if (this.startNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME] = this.indexStartName_;\n }\n }\n\n if (this.endSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE] = this.indexEndValue_;\n\n if (this.endNameSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME] = this.indexEndName_;\n }\n }\n\n if (this.limitSet_) {\n obj[WIRE_PROTOCOL_CONSTANTS.LIMIT] = this.limit_;\n var viewFrom = this.viewFrom_;\n\n if (viewFrom === '') {\n if (this.isViewFromLeft()) {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_LEFT;\n } else {\n viewFrom = WIRE_PROTOCOL_CONSTANTS.VIEW_FROM_RIGHT;\n }\n }\n\n obj[WIRE_PROTOCOL_CONSTANTS.VIEW_FROM] = viewFrom;\n } // For now, priority index is the default, so we only specify if it's some other index\n\n\n if (this.index_ !== PRIORITY_INDEX) {\n obj[WIRE_PROTOCOL_CONSTANTS.INDEX] = this.index_.toString();\n }\n\n return obj;\n };\n /**\r\n * @return {boolean}\r\n */\n\n\n QueryParams.prototype.loadsAllData = function () {\n return !(this.startSet_ || this.endSet_ || this.limitSet_);\n };\n /**\r\n * @return {boolean}\r\n */\n\n\n QueryParams.prototype.isDefault = function () {\n return this.loadsAllData() && this.index_ == PRIORITY_INDEX;\n };\n /**\r\n * @return {!NodeFilter}\r\n */\n\n\n QueryParams.prototype.getNodeFilter = function () {\n if (this.loadsAllData()) {\n return new IndexedFilter(this.getIndex());\n } else if (this.hasLimit()) {\n return new LimitedFilter(this);\n } else {\n return new RangedFilter(this);\n }\n };\n /**\r\n * Returns a set of REST query string parameters representing this query.\r\n *\r\n * @return {!Object.} query string parameters\r\n */\n\n\n QueryParams.prototype.toRestQueryStringParameters = function () {\n var REST_CONSTANTS = QueryParams.REST_QUERY_CONSTANTS_;\n var qs = {};\n\n if (this.isDefault()) {\n return qs;\n }\n\n var orderBy;\n\n if (this.index_ === PRIORITY_INDEX) {\n orderBy = REST_CONSTANTS.PRIORITY_INDEX;\n } else if (this.index_ === VALUE_INDEX) {\n orderBy = REST_CONSTANTS.VALUE_INDEX;\n } else if (this.index_ === KEY_INDEX) {\n orderBy = REST_CONSTANTS.KEY_INDEX;\n } else {\n util.assert(this.index_ instanceof PathIndex, 'Unrecognized index type!');\n orderBy = this.index_.toString();\n }\n\n qs[REST_CONSTANTS.ORDER_BY] = util.stringify(orderBy);\n\n if (this.startSet_) {\n qs[REST_CONSTANTS.START_AT] = util.stringify(this.indexStartValue_);\n\n if (this.startNameSet_) {\n qs[REST_CONSTANTS.START_AT] += ',' + util.stringify(this.indexStartName_);\n }\n }\n\n if (this.endSet_) {\n qs[REST_CONSTANTS.END_AT] = util.stringify(this.indexEndValue_);\n\n if (this.endNameSet_) {\n qs[REST_CONSTANTS.END_AT] += ',' + util.stringify(this.indexEndName_);\n }\n }\n\n if (this.limitSet_) {\n if (this.isViewFromLeft()) {\n qs[REST_CONSTANTS.LIMIT_TO_FIRST] = this.limit_;\n } else {\n qs[REST_CONSTANTS.LIMIT_TO_LAST] = this.limit_;\n }\n }\n\n return qs;\n };\n /**\r\n * Wire Protocol Constants\r\n * @const\r\n * @enum {string}\r\n * @private\r\n */\n\n\n QueryParams.WIRE_PROTOCOL_CONSTANTS_ = {\n INDEX_START_VALUE: 'sp',\n INDEX_START_NAME: 'sn',\n INDEX_END_VALUE: 'ep',\n INDEX_END_NAME: 'en',\n LIMIT: 'l',\n VIEW_FROM: 'vf',\n VIEW_FROM_LEFT: 'l',\n VIEW_FROM_RIGHT: 'r',\n INDEX: 'i'\n };\n /**\r\n * REST Query Constants\r\n * @const\r\n * @enum {string}\r\n * @private\r\n */\n\n QueryParams.REST_QUERY_CONSTANTS_ = {\n ORDER_BY: 'orderBy',\n PRIORITY_INDEX: '$priority',\n VALUE_INDEX: '$value',\n KEY_INDEX: '$key',\n START_AT: 'startAt',\n END_AT: 'endAt',\n LIMIT_TO_FIRST: 'limitToFirst',\n LIMIT_TO_LAST: 'limitToLast'\n };\n /**\r\n * Default, empty query parameters\r\n * @type {!QueryParams}\r\n * @const\r\n */\n\n QueryParams.DEFAULT = new QueryParams();\n return QueryParams;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar Reference =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(Reference, _super);\n /**\r\n * Call options:\r\n * new Reference(Repo, Path) or\r\n * new Reference(url: string, string|RepoManager)\r\n *\r\n * Externally - this is the firebase.database.Reference type.\r\n *\r\n * @param {!Repo} repo\r\n * @param {(!Path)} path\r\n * @extends {Query}\r\n */\n\n\n function Reference(repo, path) {\n var _this = this;\n\n if (!(repo instanceof Repo)) {\n throw new Error('new Reference() no longer supported - use app.database().');\n } // call Query's constructor, passing in the repo and path.\n\n\n _this = _super.call(this, repo, path, QueryParams.DEFAULT, false) || this;\n return _this;\n }\n /** @return {?string} */\n\n\n Reference.prototype.getKey = function () {\n util.validateArgCount('Reference.key', 0, 0, arguments.length);\n if (this.path.isEmpty()) return null;else return this.path.getBack();\n };\n /**\r\n * @param {!(string|Path)} pathString\r\n * @return {!Reference}\r\n */\n\n\n Reference.prototype.child = function (pathString) {\n util.validateArgCount('Reference.child', 1, 1, arguments.length);\n\n if (typeof pathString === 'number') {\n pathString = String(pathString);\n } else if (!(pathString instanceof Path)) {\n if (this.path.getFront() === null) validateRootPathString('Reference.child', 1, pathString, false);else validatePathString('Reference.child', 1, pathString, false);\n }\n\n return new Reference(this.repo, this.path.child(pathString));\n };\n /** @return {?Reference} */\n\n\n Reference.prototype.getParent = function () {\n util.validateArgCount('Reference.parent', 0, 0, arguments.length);\n var parentPath = this.path.parent();\n return parentPath === null ? null : new Reference(this.repo, parentPath);\n };\n /** @return {!Reference} */\n\n\n Reference.prototype.getRoot = function () {\n util.validateArgCount('Reference.root', 0, 0, arguments.length);\n var ref = this;\n\n while (ref.getParent() !== null) {\n ref = ref.getParent();\n }\n\n return ref;\n };\n /** @return {!Database} */\n\n\n Reference.prototype.databaseProp = function () {\n return this.repo.database;\n };\n /**\r\n * @param {*} newVal\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\n\n\n Reference.prototype.set = function (newVal, onComplete) {\n util.validateArgCount('Reference.set', 1, 2, arguments.length);\n validateWritablePath('Reference.set', this.path);\n validateFirebaseDataArg('Reference.set', 1, newVal, this.path, false);\n util.validateCallback('Reference.set', 2, onComplete, true);\n var deferred = new util.Deferred();\n this.repo.setWithPriority(this.path, newVal,\n /*priority=*/\n null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\r\n * @param {!Object} objectToMerge\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\n\n\n Reference.prototype.update = function (objectToMerge, onComplete) {\n util.validateArgCount('Reference.update', 1, 2, arguments.length);\n validateWritablePath('Reference.update', this.path);\n\n if (Array.isArray(objectToMerge)) {\n var newObjectToMerge = {};\n\n for (var i = 0; i < objectToMerge.length; ++i) {\n newObjectToMerge['' + i] = objectToMerge[i];\n }\n\n objectToMerge = newObjectToMerge;\n warn('Passing an Array to Firebase.update() is deprecated. ' + 'Use set() if you want to overwrite the existing data, or ' + 'an Object with integer keys if you really do want to ' + 'only update some of the children.');\n }\n\n validateFirebaseMergeDataArg('Reference.update', 1, objectToMerge, this.path, false);\n util.validateCallback('Reference.update', 2, onComplete, true);\n var deferred = new util.Deferred();\n this.repo.update(this.path, objectToMerge, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\r\n * @param {*} newVal\r\n * @param {string|number|null} newPriority\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\n\n\n Reference.prototype.setWithPriority = function (newVal, newPriority, onComplete) {\n util.validateArgCount('Reference.setWithPriority', 2, 3, arguments.length);\n validateWritablePath('Reference.setWithPriority', this.path);\n validateFirebaseDataArg('Reference.setWithPriority', 1, newVal, this.path, false);\n validatePriority('Reference.setWithPriority', 2, newPriority, false);\n util.validateCallback('Reference.setWithPriority', 3, onComplete, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys') throw 'Reference.setWithPriority failed: ' + this.getKey() + ' is a read-only object.';\n var deferred = new util.Deferred();\n this.repo.setWithPriority(this.path, newVal, newPriority, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\n\n\n Reference.prototype.remove = function (onComplete) {\n util.validateArgCount('Reference.remove', 0, 1, arguments.length);\n validateWritablePath('Reference.remove', this.path);\n util.validateCallback('Reference.remove', 1, onComplete, true);\n return this.set(null, onComplete);\n };\n /**\r\n * @param {function(*):*} transactionUpdate\r\n * @param {(function(?Error, boolean, ?DataSnapshot))=} onComplete\r\n * @param {boolean=} applyLocally\r\n * @return {!Promise}\r\n */\n\n\n Reference.prototype.transaction = function (transactionUpdate, onComplete, applyLocally) {\n util.validateArgCount('Reference.transaction', 1, 3, arguments.length);\n validateWritablePath('Reference.transaction', this.path);\n util.validateCallback('Reference.transaction', 1, transactionUpdate, false);\n util.validateCallback('Reference.transaction', 2, onComplete, true); // NOTE: applyLocally is an internal-only option for now. We need to decide if we want to keep it and how\n // to expose it.\n\n validateBoolean('Reference.transaction', 3, applyLocally, true);\n if (this.getKey() === '.length' || this.getKey() === '.keys') throw 'Reference.transaction failed: ' + this.getKey() + ' is a read-only object.';\n if (applyLocally === undefined) applyLocally = true;\n var deferred = new util.Deferred();\n\n if (typeof onComplete === 'function') {\n deferred.promise.catch(function () {});\n }\n\n var promiseComplete = function promiseComplete(error$$1, committed, snapshot) {\n if (error$$1) {\n deferred.reject(error$$1);\n } else {\n deferred.resolve(new TransactionResult(committed, snapshot));\n }\n\n if (typeof onComplete === 'function') {\n onComplete(error$$1, committed, snapshot);\n }\n };\n\n this.repo.startTransaction(this.path, transactionUpdate, promiseComplete, applyLocally);\n return deferred.promise;\n };\n /**\r\n * @param {string|number|null} priority\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Promise}\r\n */\n\n\n Reference.prototype.setPriority = function (priority, onComplete) {\n util.validateArgCount('Reference.setPriority', 1, 2, arguments.length);\n validateWritablePath('Reference.setPriority', this.path);\n validatePriority('Reference.setPriority', 1, priority, false);\n util.validateCallback('Reference.setPriority', 2, onComplete, true);\n var deferred = new util.Deferred();\n this.repo.setWithPriority(this.path.child('.priority'), priority, null, deferred.wrapCallback(onComplete));\n return deferred.promise;\n };\n /**\r\n * @param {*=} value\r\n * @param {function(?Error)=} onComplete\r\n * @return {!Reference}\r\n */\n\n\n Reference.prototype.push = function (value, onComplete) {\n util.validateArgCount('Reference.push', 0, 2, arguments.length);\n validateWritablePath('Reference.push', this.path);\n validateFirebaseDataArg('Reference.push', 1, value, this.path, true);\n util.validateCallback('Reference.push', 2, onComplete, true);\n var now = this.repo.serverTime();\n var name = nextPushId(now); // push() returns a ThennableReference whose promise is fulfilled with a regular Reference.\n // We use child() to create handles to two different references. The first is turned into a\n // ThennableReference below by adding then() and catch() methods and is used as the\n // return value of push(). The second remains a regular Reference and is used as the fulfilled\n // value of the first ThennableReference.\n\n var thennablePushRef = this.child(name);\n var pushRef = this.child(name);\n var promise;\n\n if (value != null) {\n promise = thennablePushRef.set(value, onComplete).then(function () {\n return pushRef;\n });\n } else {\n promise = Promise.resolve(pushRef);\n }\n\n thennablePushRef.then = promise.then.bind(promise);\n thennablePushRef.catch = promise.then.bind(promise, undefined);\n\n if (typeof onComplete === 'function') {\n promise.catch(function () {});\n }\n\n return thennablePushRef;\n };\n /**\r\n * @return {!OnDisconnect}\r\n */\n\n\n Reference.prototype.onDisconnect = function () {\n validateWritablePath('Reference.onDisconnect', this.path);\n return new OnDisconnect(this.repo, this.path);\n };\n\n Object.defineProperty(Reference.prototype, \"database\", {\n get: function get() {\n return this.databaseProp();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"key\", {\n get: function get() {\n return this.getKey();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"parent\", {\n get: function get() {\n return this.getParent();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n get: function get() {\n return this.getRoot();\n },\n enumerable: true,\n configurable: true\n });\n return Reference;\n}(Query);\n/**\r\n * Define reference constructor in various modules\r\n *\r\n * We are doing this here to avoid several circular\r\n * dependency issues\r\n */\n\n\nQuery.__referenceConstructor = Reference;\nSyncPoint.__referenceConstructor = Reference;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Node in a Tree.\r\n */\n\nvar TreeNode =\n/** @class */\nfunction () {\n function TreeNode() {\n // TODO: Consider making accessors that create children and value lazily or\n // separate Internal / Leaf 'types'.\n this.children = {};\n this.childCount = 0;\n this.value = null;\n }\n\n return TreeNode;\n}();\n/**\r\n * A light-weight tree, traversable by path. Nodes can have both values and children.\r\n * Nodes are not enumerated (by forEachChild) unless they have a value or non-empty\r\n * children.\r\n */\n\n\nvar Tree =\n/** @class */\nfunction () {\n /**\r\n * @template T\r\n * @param {string=} name_ Optional name of the node.\r\n * @param {Tree=} parent_ Optional parent node.\r\n * @param {TreeNode=} node_ Optional node to wrap.\r\n */\n function Tree(name_, parent_, node_) {\n if (name_ === void 0) {\n name_ = '';\n }\n\n if (parent_ === void 0) {\n parent_ = null;\n }\n\n if (node_ === void 0) {\n node_ = new TreeNode();\n }\n\n this.name_ = name_;\n this.parent_ = parent_;\n this.node_ = node_;\n }\n /**\r\n * Returns a sub-Tree for the given path.\r\n *\r\n * @param {!(string|Path)} pathObj Path to look up.\r\n * @return {!Tree.} Tree for path.\r\n */\n\n\n Tree.prototype.subTree = function (pathObj) {\n // TODO: Require pathObj to be Path?\n var path = pathObj instanceof Path ? pathObj : new Path(pathObj);\n var child = this,\n next;\n\n while ((next = path.getFront()) !== null) {\n var childNode = util.safeGet(child.node_.children, next) || new TreeNode();\n child = new Tree(next, child, childNode);\n path = path.popFront();\n }\n\n return child;\n };\n /**\r\n * Returns the data associated with this tree node.\r\n *\r\n * @return {?T} The data or null if no data exists.\r\n */\n\n\n Tree.prototype.getValue = function () {\n return this.node_.value;\n };\n /**\r\n * Sets data to this tree node.\r\n *\r\n * @param {!T} value Value to set.\r\n */\n\n\n Tree.prototype.setValue = function (value) {\n util.assert(typeof value !== 'undefined', 'Cannot set value to undefined');\n this.node_.value = value;\n this.updateParents_();\n };\n /**\r\n * Clears the contents of the tree node (its value and all children).\r\n */\n\n\n Tree.prototype.clear = function () {\n this.node_.value = null;\n this.node_.children = {};\n this.node_.childCount = 0;\n this.updateParents_();\n };\n /**\r\n * @return {boolean} Whether the tree has any children.\r\n */\n\n\n Tree.prototype.hasChildren = function () {\n return this.node_.childCount > 0;\n };\n /**\r\n * @return {boolean} Whether the tree is empty (no value or children).\r\n */\n\n\n Tree.prototype.isEmpty = function () {\n return this.getValue() === null && !this.hasChildren();\n };\n /**\r\n * Calls action for each child of this tree node.\r\n *\r\n * @param {function(!Tree.)} action Action to be called for each child.\r\n */\n\n\n Tree.prototype.forEachChild = function (action) {\n var _this = this;\n\n util.forEach(this.node_.children, function (child, childTree) {\n action(new Tree(child, _this, childTree));\n });\n };\n /**\r\n * Does a depth-first traversal of this node's descendants, calling action for each one.\r\n *\r\n * @param {function(!Tree.)} action Action to be called for each child.\r\n * @param {boolean=} includeSelf Whether to call action on this node as well. Defaults to\r\n * false.\r\n * @param {boolean=} childrenFirst Whether to call action on children before calling it on\r\n * parent.\r\n */\n\n\n Tree.prototype.forEachDescendant = function (action, includeSelf, childrenFirst) {\n if (includeSelf && !childrenFirst) action(this);\n this.forEachChild(function (child) {\n child.forEachDescendant(action,\n /*includeSelf=*/\n true, childrenFirst);\n });\n if (includeSelf && childrenFirst) action(this);\n };\n /**\r\n * Calls action on each ancestor node.\r\n *\r\n * @param {function(!Tree.)} action Action to be called on each parent; return\r\n * true to abort.\r\n * @param {boolean=} includeSelf Whether to call action on this node as well.\r\n * @return {boolean} true if the action callback returned true.\r\n */\n\n\n Tree.prototype.forEachAncestor = function (action, includeSelf) {\n var node = includeSelf ? this : this.parent();\n\n while (node !== null) {\n if (action(node)) {\n return true;\n }\n\n node = node.parent();\n }\n\n return false;\n };\n /**\r\n * Does a depth-first traversal of this node's descendants. When a descendant with a value\r\n * is found, action is called on it and traversal does not continue inside the node.\r\n * Action is *not* called on this node.\r\n *\r\n * @param {function(!Tree.)} action Action to be called for each child.\r\n */\n\n\n Tree.prototype.forEachImmediateDescendantWithValue = function (action) {\n this.forEachChild(function (child) {\n if (child.getValue() !== null) action(child);else child.forEachImmediateDescendantWithValue(action);\n });\n };\n /**\r\n * @return {!Path} The path of this tree node, as a Path.\r\n */\n\n\n Tree.prototype.path = function () {\n return new Path(this.parent_ === null ? this.name_ : this.parent_.path() + '/' + this.name_);\n };\n /**\r\n * @return {string} The name of the tree node.\r\n */\n\n\n Tree.prototype.name = function () {\n return this.name_;\n };\n /**\r\n * @return {?Tree} The parent tree node, or null if this is the root of the tree.\r\n */\n\n\n Tree.prototype.parent = function () {\n return this.parent_;\n };\n /**\r\n * Adds or removes this child from its parent based on whether it's empty or not.\r\n *\r\n * @private\r\n */\n\n\n Tree.prototype.updateParents_ = function () {\n if (this.parent_ !== null) this.parent_.updateChild_(this.name_, this);\n };\n /**\r\n * Adds or removes the passed child to this tree node, depending on whether it's empty.\r\n *\r\n * @param {string} childName The name of the child to update.\r\n * @param {!Tree.} child The child to update.\r\n * @private\r\n */\n\n\n Tree.prototype.updateChild_ = function (childName, child) {\n var childEmpty = child.isEmpty();\n var childExists = util.contains(this.node_.children, childName);\n\n if (childEmpty && childExists) {\n delete this.node_.children[childName];\n this.node_.childCount--;\n this.updateParents_();\n } else if (!childEmpty && !childExists) {\n this.node_.children[childName] = child.node_;\n this.node_.childCount++;\n this.updateParents_();\n }\n };\n\n return Tree;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// TODO: This is pretty messy. Ideally, a lot of this would move into FirebaseData, or a transaction-specific\n// component used by FirebaseData, but it has ties to user callbacks (transaction update and onComplete) as well\n// as the realtime connection (to send transactions to the server). So that all needs to be decoupled first.\n// For now it's part of Repo, but in its own file.\n\n/**\r\n * @enum {number}\r\n */\n\n\nvar TransactionStatus;\n\n(function (TransactionStatus) {\n // We've run the transaction and updated transactionResultData_ with the result, but it isn't currently sent to the\n // server. A transaction will go from RUN -> SENT -> RUN if it comes back from the server as rejected due to\n // mismatched hash.\n TransactionStatus[TransactionStatus[\"RUN\"] = 0] = \"RUN\"; // We've run the transaction and sent it to the server and it's currently outstanding (hasn't come back as accepted\n // or rejected yet).\n\n TransactionStatus[TransactionStatus[\"SENT\"] = 1] = \"SENT\"; // Temporary state used to mark completed transactions (whether successful or aborted). The transaction will be\n // removed when we get a chance to prune completed ones.\n\n TransactionStatus[TransactionStatus[\"COMPLETED\"] = 2] = \"COMPLETED\"; // Used when an already-sent transaction needs to be aborted (e.g. due to a conflicting set() call that was made).\n // If it comes back as unsuccessful, we'll abort it.\n\n TransactionStatus[TransactionStatus[\"SENT_NEEDS_ABORT\"] = 3] = \"SENT_NEEDS_ABORT\"; // Temporary state used to mark transactions that need to be aborted.\n\n TransactionStatus[TransactionStatus[\"NEEDS_ABORT\"] = 4] = \"NEEDS_ABORT\";\n})(TransactionStatus || (TransactionStatus = {}));\n/**\r\n * If a transaction does not succeed after 25 retries, we abort it. Among other things this ensure that if there's\r\n * ever a bug causing a mismatch between client / server hashes for some data, we won't retry indefinitely.\r\n * @type {number}\r\n * @const\r\n * @private\r\n */\n\n\nRepo.MAX_TRANSACTION_RETRIES_ = 25;\n/**\r\n * Setup the transaction data structures\r\n * @private\r\n */\n\nRepo.prototype.transactions_init_ = function () {\n /**\r\n * Stores queues of outstanding transactions for Firebase locations.\r\n *\r\n * @type {!Tree.>}\r\n * @private\r\n */\n this.transactionQueueTree_ = new Tree();\n};\n/**\r\n * Creates a new transaction, adds it to the transactions we're tracking, and sends it to the server if possible.\r\n *\r\n * @param {!Path} path Path at which to do transaction.\r\n * @param {function(*):*} transactionUpdate Update callback.\r\n * @param {?function(?Error, boolean, ?DataSnapshot)} onComplete Completion callback.\r\n * @param {boolean} applyLocally Whether or not to make intermediate results visible\r\n */\n\n\nRepo.prototype.startTransaction = function (path, transactionUpdate, onComplete, applyLocally) {\n this.log_('transaction on ' + path); // Add a watch to make sure we get server updates.\n\n var valueCallback = function valueCallback() {};\n\n var watchRef = new Reference(this, path);\n watchRef.on('value', valueCallback);\n\n var unwatcher = function unwatcher() {\n watchRef.off('value', valueCallback);\n }; // Initialize transaction.\n\n\n var transaction = {\n path: path,\n update: transactionUpdate,\n onComplete: onComplete,\n // One of TransactionStatus enums.\n status: null,\n // Used when combining transactions at different locations to figure out which one goes first.\n order: LUIDGenerator(),\n // Whether to raise local events for this transaction.\n applyLocally: applyLocally,\n // Count of how many times we've retried the transaction.\n retryCount: 0,\n // Function to call to clean up our .on() listener.\n unwatcher: unwatcher,\n // Stores why a transaction was aborted.\n abortReason: null,\n currentWriteId: null,\n currentInputSnapshot: null,\n currentOutputSnapshotRaw: null,\n currentOutputSnapshotResolved: null\n }; // Run transaction initially.\n\n var currentState = this.getLatestState_(path);\n transaction.currentInputSnapshot = currentState;\n var newVal = transaction.update(currentState.val());\n\n if (newVal === undefined) {\n // Abort transaction.\n transaction.unwatcher();\n transaction.currentOutputSnapshotRaw = null;\n transaction.currentOutputSnapshotResolved = null;\n\n if (transaction.onComplete) {\n // We just set the input snapshot, so this cast should be safe\n var snapshot = new DataSnapshot(transaction.currentInputSnapshot, new Reference(this, transaction.path), PRIORITY_INDEX);\n transaction.onComplete(null, false, snapshot);\n }\n } else {\n validateFirebaseData('transaction failed: Data returned ', newVal, transaction.path); // Mark as run and add to our queue.\n\n transaction.status = TransactionStatus.RUN;\n var queueNode = this.transactionQueueTree_.subTree(path);\n var nodeQueue = queueNode.getValue() || [];\n nodeQueue.push(transaction);\n queueNode.setValue(nodeQueue); // Update visibleData and raise events\n // Note: We intentionally raise events after updating all of our transaction state, since the user could\n // start new transactions from the event callbacks.\n\n var priorityForNode = void 0;\n\n if (typeof newVal === 'object' && newVal !== null && util.contains(newVal, '.priority')) {\n priorityForNode = util.safeGet(newVal, '.priority');\n util.assert(isValidPriority(priorityForNode), 'Invalid priority returned by transaction. ' + 'Priority must be a valid string, finite number, server value, or null.');\n } else {\n var currentNode = this.serverSyncTree_.calcCompleteEventCache(path) || ChildrenNode.EMPTY_NODE;\n priorityForNode = currentNode.getPriority().val();\n }\n\n priorityForNode\n /** @type {null|number|string} */\n = priorityForNode;\n var serverValues = this.generateServerValues();\n var newNodeUnresolved = nodeFromJSON$1(newVal, priorityForNode);\n var newNode = resolveDeferredValueSnapshot(newNodeUnresolved, serverValues);\n transaction.currentOutputSnapshotRaw = newNodeUnresolved;\n transaction.currentOutputSnapshotResolved = newNode;\n transaction.currentWriteId = this.getNextWriteId_();\n var events = this.serverSyncTree_.applyUserOverwrite(path, newNode, transaction.currentWriteId, transaction.applyLocally);\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n this.sendReadyTransactions_();\n }\n};\n/**\r\n * @param {!Path} path\r\n * @param {Array.=} excludeSets A specific set to exclude\r\n * @return {Node}\r\n * @private\r\n */\n\n\nRepo.prototype.getLatestState_ = function (path, excludeSets) {\n return this.serverSyncTree_.calcCompleteEventCache(path, excludeSets) || ChildrenNode.EMPTY_NODE;\n};\n/**\r\n * Sends any already-run transactions that aren't waiting for outstanding transactions to\r\n * complete.\r\n *\r\n * Externally it's called with no arguments, but it calls itself recursively with a particular\r\n * transactionQueueTree node to recurse through the tree.\r\n *\r\n * @param {Tree.>=} node transactionQueueTree node to start at.\r\n * @private\r\n */\n\n\nRepo.prototype.sendReadyTransactions_ = function (node) {\n var _this = this;\n\n if (node === void 0) {\n node = this.transactionQueueTree_;\n } // Before recursing, make sure any completed transactions are removed.\n\n\n if (!node) {\n this.pruneCompletedTransactionsBelowNode_(node);\n }\n\n if (node.getValue() !== null) {\n var queue = this.buildTransactionQueue_(node);\n util.assert(queue.length > 0, 'Sending zero length transaction queue');\n var allRun = queue.every(function (transaction) {\n return transaction.status === TransactionStatus.RUN;\n }); // If they're all run (and not sent), we can send them. Else, we must wait.\n\n if (allRun) {\n this.sendTransactionQueue_(node.path(), queue);\n }\n } else if (node.hasChildren()) {\n node.forEachChild(function (childNode) {\n _this.sendReadyTransactions_(childNode);\n });\n }\n};\n/**\r\n * Given a list of run transactions, send them to the server and then handle the result (success or failure).\r\n *\r\n * @param {!Path} path The location of the queue.\r\n * @param {!Array.} queue Queue of transactions under the specified location.\r\n * @private\r\n */\n\n\nRepo.prototype.sendTransactionQueue_ = function (path, queue) {\n var _this = this; // Mark transactions as sent and increment retry count!\n\n\n var setsToIgnore = queue.map(function (txn) {\n return txn.currentWriteId;\n });\n var latestState = this.getLatestState_(path, setsToIgnore);\n var snapToSend = latestState;\n var latestHash = latestState.hash();\n\n for (var i = 0; i < queue.length; i++) {\n var txn = queue[i];\n util.assert(txn.status === TransactionStatus.RUN, 'tryToSendTransactionQueue_: items in queue should all be run.');\n txn.status = TransactionStatus.SENT;\n txn.retryCount++;\n var relativePath = Path.relativePath(path, txn.path); // If we've gotten to this point, the output snapshot must be defined.\n\n snapToSend = snapToSend.updateChild(relativePath\n /**@type {!Node} */\n , txn.currentOutputSnapshotRaw);\n }\n\n var dataToSend = snapToSend.val(true);\n var pathToSend = path; // Send the put.\n\n this.server_.put(pathToSend.toString(), dataToSend, function (status) {\n _this.log_('transaction put response', {\n path: pathToSend.toString(),\n status: status\n });\n\n var events = [];\n\n if (status === 'ok') {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = [];\n\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.COMPLETED;\n events = events.concat(_this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId));\n\n if (queue[i].onComplete) {\n // We never unset the output snapshot, and given that this transaction is complete, it should be set\n var node = queue[i].currentOutputSnapshotResolved;\n var ref = new Reference(_this, queue[i].path);\n var snapshot = new DataSnapshot(node, ref, PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, true, snapshot));\n }\n\n queue[i].unwatcher();\n } // Now remove the completed transactions.\n\n\n _this.pruneCompletedTransactionsBelowNode_(_this.transactionQueueTree_.subTree(path)); // There may be pending transactions that we can now send.\n\n\n _this.sendReadyTransactions_();\n\n _this.eventQueue_.raiseEventsForChangedPath(path, events); // Finally, trigger onComplete callbacks.\n\n\n for (var i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n } else {\n // transactions are no longer sent. Update their status appropriately.\n if (status === 'datastale') {\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) queue[i].status = TransactionStatus.NEEDS_ABORT;else queue[i].status = TransactionStatus.RUN;\n }\n } else {\n warn('transaction at ' + pathToSend.toString() + ' failed: ' + status);\n\n for (var i = 0; i < queue.length; i++) {\n queue[i].status = TransactionStatus.NEEDS_ABORT;\n queue[i].abortReason = status;\n }\n }\n\n _this.rerunTransactions_(path);\n }\n }, latestHash);\n};\n/**\r\n * Finds all transactions dependent on the data at changedPath and reruns them.\r\n *\r\n * Should be called any time cached data changes.\r\n *\r\n * Return the highest path that was affected by rerunning transactions. This is the path at which events need to\r\n * be raised for.\r\n *\r\n * @param {!Path} changedPath The path in mergedData that changed.\r\n * @return {!Path} The rootmost path that was affected by rerunning transactions.\r\n * @private\r\n */\n\n\nRepo.prototype.rerunTransactions_ = function (changedPath) {\n var rootMostTransactionNode = this.getAncestorTransactionNode_(changedPath);\n var path = rootMostTransactionNode.path();\n var queue = this.buildTransactionQueue_(rootMostTransactionNode);\n this.rerunTransactionQueue_(queue, path);\n return path;\n};\n/**\r\n * Does all the work of rerunning transactions (as well as cleans up aborted transactions and whatnot).\r\n *\r\n * @param {Array.} queue The queue of transactions to run.\r\n * @param {!Path} path The path the queue is for.\r\n * @private\r\n */\n\n\nRepo.prototype.rerunTransactionQueue_ = function (queue, path) {\n if (queue.length === 0) {\n return; // Nothing to do!\n } // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n\n\n var callbacks = [];\n var events = []; // Ignore all of the sets we're going to re-run.\n\n var txnsToRerun = queue.filter(function (q) {\n return q.status === TransactionStatus.RUN;\n });\n var setsToIgnore = txnsToRerun.map(function (q) {\n return q.currentWriteId;\n });\n\n for (var i = 0; i < queue.length; i++) {\n var transaction = queue[i];\n var relativePath = Path.relativePath(path, transaction.path);\n var abortTransaction = false,\n abortReason = void 0;\n util.assert(relativePath !== null, 'rerunTransactionsUnderNode_: relativePath should not be null.');\n\n if (transaction.status === TransactionStatus.NEEDS_ABORT) {\n abortTransaction = true;\n abortReason = transaction.abortReason;\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n } else if (transaction.status === TransactionStatus.RUN) {\n if (transaction.retryCount >= Repo.MAX_TRANSACTION_RETRIES_) {\n abortTransaction = true;\n abortReason = 'maxretry';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n } else {\n // This code reruns a transaction\n var currentNode = this.getLatestState_(transaction.path, setsToIgnore);\n transaction.currentInputSnapshot = currentNode;\n var newData = queue[i].update(currentNode.val());\n\n if (newData !== undefined) {\n validateFirebaseData('transaction failed: Data returned ', newData, transaction.path);\n var newDataNode = nodeFromJSON$1(newData);\n var hasExplicitPriority = typeof newData === 'object' && newData != null && util.contains(newData, '.priority');\n\n if (!hasExplicitPriority) {\n // Keep the old priority if there wasn't a priority explicitly specified.\n newDataNode = newDataNode.updatePriority(currentNode.getPriority());\n }\n\n var oldWriteId = transaction.currentWriteId;\n var serverValues = this.generateServerValues();\n var newNodeResolved = resolveDeferredValueSnapshot(newDataNode, serverValues);\n transaction.currentOutputSnapshotRaw = newDataNode;\n transaction.currentOutputSnapshotResolved = newNodeResolved;\n transaction.currentWriteId = this.getNextWriteId_(); // Mutates setsToIgnore in place\n\n setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);\n events = events.concat(this.serverSyncTree_.applyUserOverwrite(transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));\n events = events.concat(this.serverSyncTree_.ackUserWrite(oldWriteId, true));\n } else {\n abortTransaction = true;\n abortReason = 'nodata';\n events = events.concat(this.serverSyncTree_.ackUserWrite(transaction.currentWriteId, true));\n }\n }\n }\n\n this.eventQueue_.raiseEventsForChangedPath(path, events);\n events = [];\n\n if (abortTransaction) {\n // Abort.\n queue[i].status = TransactionStatus.COMPLETED; // Removing a listener can trigger pruning which can muck with mergedData/visibleData (as it prunes data).\n // So defer the unwatcher until we're done.\n\n (function (unwatcher) {\n setTimeout(unwatcher, Math.floor(0));\n })(queue[i].unwatcher);\n\n if (queue[i].onComplete) {\n if (abortReason === 'nodata') {\n var ref = new Reference(this, queue[i].path); // We set this field immediately, so it's safe to cast to an actual snapshot\n\n var lastInput\n /** @type {!Node} */\n = queue[i].currentInputSnapshot;\n var snapshot = new DataSnapshot(lastInput, ref, PRIORITY_INDEX);\n callbacks.push(queue[i].onComplete.bind(null, null, false, snapshot));\n } else {\n callbacks.push(queue[i].onComplete.bind(null, new Error(abortReason), false, null));\n }\n }\n }\n } // Clean up completed transactions.\n\n\n this.pruneCompletedTransactionsBelowNode_(this.transactionQueueTree_); // Now fire callbacks, now that we're in a good, known state.\n\n for (var i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n } // Try to send the transaction result to the server.\n\n\n this.sendReadyTransactions_();\n};\n/**\r\n * Returns the rootmost ancestor node of the specified path that has a pending transaction on it, or just returns\r\n * the node for the given path if there are no pending transactions on any ancestor.\r\n *\r\n * @param {!Path} path The location to start at.\r\n * @return {!Tree.>} The rootmost node with a transaction.\r\n * @private\r\n */\n\n\nRepo.prototype.getAncestorTransactionNode_ = function (path) {\n var front; // Start at the root and walk deeper into the tree towards path until we find a node with pending transactions.\n\n var transactionNode = this.transactionQueueTree_;\n\n while ((front = path.getFront()) !== null && transactionNode.getValue() === null) {\n transactionNode = transactionNode.subTree(front);\n path = path.popFront();\n }\n\n return transactionNode;\n};\n/**\r\n * Builds the queue of all transactions at or below the specified transactionNode.\r\n *\r\n * @param {!Tree.>} transactionNode\r\n * @return {Array.} The generated queue.\r\n * @private\r\n */\n\n\nRepo.prototype.buildTransactionQueue_ = function (transactionNode) {\n // Walk any child transaction queues and aggregate them into a single queue.\n var transactionQueue = [];\n this.aggregateTransactionQueuesForNode_(transactionNode, transactionQueue); // Sort them by the order the transactions were created.\n\n transactionQueue.sort(function (a, b) {\n return a.order - b.order;\n });\n return transactionQueue;\n};\n/**\r\n * @param {!Tree.>} node\r\n * @param {Array.} queue\r\n * @private\r\n */\n\n\nRepo.prototype.aggregateTransactionQueuesForNode_ = function (node, queue) {\n var _this = this;\n\n var nodeQueue = node.getValue();\n\n if (nodeQueue !== null) {\n for (var i = 0; i < nodeQueue.length; i++) {\n queue.push(nodeQueue[i]);\n }\n }\n\n node.forEachChild(function (child) {\n _this.aggregateTransactionQueuesForNode_(child, queue);\n });\n};\n/**\r\n * Remove COMPLETED transactions at or below this node in the transactionQueueTree_.\r\n *\r\n * @param {!Tree.>} node\r\n * @private\r\n */\n\n\nRepo.prototype.pruneCompletedTransactionsBelowNode_ = function (node) {\n var _this = this;\n\n var queue = node.getValue();\n\n if (queue) {\n var to = 0;\n\n for (var from = 0; from < queue.length; from++) {\n if (queue[from].status !== TransactionStatus.COMPLETED) {\n queue[to] = queue[from];\n to++;\n }\n }\n\n queue.length = to;\n node.setValue(queue.length > 0 ? queue : null);\n }\n\n node.forEachChild(function (childNode) {\n _this.pruneCompletedTransactionsBelowNode_(childNode);\n });\n};\n/**\r\n * Aborts all transactions on ancestors or descendants of the specified path. Called when doing a set() or update()\r\n * since we consider them incompatible with transactions.\r\n *\r\n * @param {!Path} path Path for which we want to abort related transactions.\r\n * @return {!Path}\r\n * @private\r\n */\n\n\nRepo.prototype.abortTransactions_ = function (path) {\n var _this = this;\n\n var affectedPath = this.getAncestorTransactionNode_(path).path();\n var transactionNode = this.transactionQueueTree_.subTree(path);\n transactionNode.forEachAncestor(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n this.abortTransactionsOnNode_(transactionNode);\n transactionNode.forEachDescendant(function (node) {\n _this.abortTransactionsOnNode_(node);\n });\n return affectedPath;\n};\n/**\r\n * Abort transactions stored in this transaction queue node.\r\n *\r\n * @param {!Tree.>} node Node to abort transactions for.\r\n * @private\r\n */\n\n\nRepo.prototype.abortTransactionsOnNode_ = function (node) {\n var queue = node.getValue();\n\n if (queue !== null) {\n // Queue up the callbacks and fire them after cleaning up all of our transaction state, since\n // the callback could trigger more transactions or sets.\n var callbacks = []; // Go through queue. Any already-sent transactions must be marked for abort, while the unsent ones\n // can be immediately aborted and removed.\n\n var events = [];\n var lastSent = -1;\n\n for (var i = 0; i < queue.length; i++) {\n if (queue[i].status === TransactionStatus.SENT_NEEDS_ABORT) {// Already marked. No action needed.\n } else if (queue[i].status === TransactionStatus.SENT) {\n util.assert(lastSent === i - 1, 'All SENT items should be at beginning of queue.');\n lastSent = i; // Mark transaction for abort when it comes back.\n\n queue[i].status = TransactionStatus.SENT_NEEDS_ABORT;\n queue[i].abortReason = 'set';\n } else {\n util.assert(queue[i].status === TransactionStatus.RUN, 'Unexpected transaction status in abort'); // We can abort it immediately.\n\n queue[i].unwatcher();\n events = events.concat(this.serverSyncTree_.ackUserWrite(queue[i].currentWriteId, true));\n\n if (queue[i].onComplete) {\n var snapshot = null;\n callbacks.push(queue[i].onComplete.bind(null, new Error('set'), false, snapshot));\n }\n }\n }\n\n if (lastSent === -1) {\n // We're not waiting for any sent transactions. We can clear the queue.\n node.setValue(null);\n } else {\n // Remove the transactions we aborted.\n queue.length = lastSent + 1;\n } // Now fire the callbacks.\n\n\n this.eventQueue_.raiseEventsForChangedPath(node.path(), events);\n\n for (var i = 0; i < callbacks.length; i++) {\n exceptionGuard(callbacks[i]);\n }\n }\n};\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/** @const {string} */\n\n\nvar DATABASE_URL_OPTION = 'databaseURL';\n\nvar _staticInstance;\n/**\r\n * Creates and caches Repo instances.\r\n */\n\n\nvar RepoManager =\n/** @class */\nfunction () {\n function RepoManager() {\n /**\r\n * @private {!Object.>}\r\n */\n this.repos_ = {};\n /**\r\n * If true, new Repos will be created to use ReadonlyRestClient (for testing purposes).\r\n * @private {boolean}\r\n */\n\n this.useRestClient_ = false;\n }\n\n RepoManager.getInstance = function () {\n if (!_staticInstance) {\n _staticInstance = new RepoManager();\n }\n\n return _staticInstance;\n }; // TODO(koss): Remove these functions unless used in tests?\n\n\n RepoManager.prototype.interrupt = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].interrupt();\n }\n }\n };\n\n RepoManager.prototype.resume = function () {\n for (var appName in this.repos_) {\n for (var dbUrl in this.repos_[appName]) {\n this.repos_[appName][dbUrl].resume();\n }\n }\n };\n /**\r\n * This function should only ever be called to CREATE a new database instance.\r\n *\r\n * @param {!FirebaseApp} app\r\n * @return {!Database}\r\n */\n\n\n RepoManager.prototype.databaseFromApp = function (app, url) {\n var dbUrl = url || app.options[DATABASE_URL_OPTION];\n\n if (dbUrl === undefined) {\n fatal(\"Can't determine Firebase Database URL. Be sure to include \" + DATABASE_URL_OPTION + ' option when calling firebase.initializeApp().');\n }\n\n var parsedUrl = parseRepoInfo(dbUrl);\n var repoInfo = parsedUrl.repoInfo;\n validateUrl('Invalid Firebase Database URL', 1, parsedUrl);\n\n if (!parsedUrl.path.isEmpty()) {\n fatal('Database URL must point to the root of a Firebase Database ' + '(not including a child path).');\n }\n\n var repo = this.createRepo(repoInfo, app);\n return repo.database;\n };\n /**\r\n * Remove the repo and make sure it is disconnected.\r\n *\r\n * @param {!Repo} repo\r\n */\n\n\n RepoManager.prototype.deleteRepo = function (repo) {\n var appRepos = util.safeGet(this.repos_, repo.app.name); // This should never happen...\n\n if (!appRepos || util.safeGet(appRepos, repo.repoInfo_.toURLString()) !== repo) {\n fatal(\"Database \" + repo.app.name + \"(\" + repo.repoInfo_ + \") has already been deleted.\");\n }\n\n repo.interrupt();\n delete appRepos[repo.repoInfo_.toURLString()];\n };\n /**\r\n * Ensures a repo doesn't already exist and then creates one using the\r\n * provided app.\r\n *\r\n * @param {!RepoInfo} repoInfo The metadata about the Repo\r\n * @param {!FirebaseApp} app\r\n * @return {!Repo} The Repo object for the specified server / repoName.\r\n */\n\n\n RepoManager.prototype.createRepo = function (repoInfo, app) {\n var appRepos = util.safeGet(this.repos_, app.name);\n\n if (!appRepos) {\n appRepos = {};\n this.repos_[app.name] = appRepos;\n }\n\n var repo = util.safeGet(appRepos, repoInfo.toURLString());\n\n if (repo) {\n fatal('Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.');\n }\n\n repo = new Repo(repoInfo, this.useRestClient_, app);\n appRepos[repoInfo.toURLString()] = repo;\n return repo;\n };\n /**\r\n * Forces us to use ReadonlyRestClient instead of PersistentConnection for new Repos.\r\n * @param {boolean} forceRestClient\r\n */\n\n\n RepoManager.prototype.forceRestClient = function (forceRestClient) {\n this.useRestClient_ = forceRestClient;\n };\n\n return RepoManager;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Class representing a firebase database.\r\n * @implements {FirebaseService}\r\n */\n\n\nvar Database =\n/** @class */\nfunction () {\n /**\r\n * The constructor should not be called by users of our public API.\r\n * @param {!Repo} repo_\r\n */\n function Database(repo_) {\n this.repo_ = repo_;\n\n if (!(repo_ instanceof Repo)) {\n fatal(\"Don't call new Database() directly - please use firebase.database().\");\n }\n /** @type {Reference} */\n\n\n this.root_ = new Reference(repo_, Path.Empty);\n this.INTERNAL = new DatabaseInternals(this);\n }\n\n Object.defineProperty(Database.prototype, \"app\", {\n get: function get() {\n return this.repo_.app;\n },\n enumerable: true,\n configurable: true\n });\n\n Database.prototype.ref = function (path) {\n this.checkDeleted_('ref');\n util.validateArgCount('database.ref', 0, 1, arguments.length);\n\n if (path instanceof Reference) {\n return this.refFromURL(path.toString());\n }\n\n return path !== undefined ? this.root_.child(path) : this.root_;\n };\n /**\r\n * Returns a reference to the root or the path specified in url.\r\n * We throw a exception if the url is not in the same domain as the\r\n * current repo.\r\n * @param {string} url\r\n * @return {!Reference} Firebase reference.\r\n */\n\n\n Database.prototype.refFromURL = function (url) {\n /** @const {string} */\n var apiName = 'database.refFromURL';\n this.checkDeleted_(apiName);\n util.validateArgCount(apiName, 1, 1, arguments.length);\n var parsedURL = parseRepoInfo(url);\n validateUrl(apiName, 1, parsedURL);\n var repoInfo = parsedURL.repoInfo;\n\n if (repoInfo.host !== this.repo_.repoInfo_.host) {\n fatal(apiName + ': Host name does not match the current database: ' + '(found ' + repoInfo.host + ' but expected ' + this.repo_.repoInfo_.host + ')');\n }\n\n return this.ref(parsedURL.path.toString());\n };\n /**\r\n * @param {string} apiName\r\n */\n\n\n Database.prototype.checkDeleted_ = function (apiName) {\n if (this.repo_ === null) {\n fatal('Cannot call ' + apiName + ' on a deleted database.');\n }\n }; // Make individual repo go offline.\n\n\n Database.prototype.goOffline = function () {\n util.validateArgCount('database.goOffline', 0, 0, arguments.length);\n this.checkDeleted_('goOffline');\n this.repo_.interrupt();\n };\n\n Database.prototype.goOnline = function () {\n util.validateArgCount('database.goOnline', 0, 0, arguments.length);\n this.checkDeleted_('goOnline');\n this.repo_.resume();\n };\n\n Database.ServerValue = {\n TIMESTAMP: {\n '.sv': 'timestamp'\n }\n };\n return Database;\n}();\n\nvar DatabaseInternals =\n/** @class */\nfunction () {\n /** @param {!Database} database */\n function DatabaseInternals(database) {\n this.database = database;\n }\n /** @return {Promise} */\n\n\n DatabaseInternals.prototype.delete = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.database.checkDeleted_('delete');\n RepoManager.getInstance().deleteRepo(this.database.repo_);\n this.database.repo_ = null;\n this.database.root_ = null;\n this.database.INTERNAL = null;\n this.database = null;\n return [2\n /*return*/\n ];\n });\n });\n };\n\n return DatabaseInternals;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * INTERNAL methods for internal-use only (tests, etc.).\r\n *\r\n * Customers shouldn't use these or else should be aware that they could break at any time.\r\n *\r\n * @const\r\n */\n\n\nvar forceLongPolling = function forceLongPolling() {\n WebSocketConnection.forceDisallow();\n BrowserPollConnection.forceAllow();\n};\n\nvar forceWebSockets = function forceWebSockets() {\n BrowserPollConnection.forceDisallow();\n};\n/* Used by App Manager */\n\n\nvar isWebSocketsAvailable = function isWebSocketsAvailable() {\n return WebSocketConnection['isAvailable']();\n};\n\nvar setSecurityDebugCallback = function setSecurityDebugCallback(ref, callback) {\n ref.repo.persistentConnection_.securityDebugCallback_ = callback;\n};\n\nvar stats = function stats(ref, showDelta) {\n ref.repo.stats(showDelta);\n};\n\nvar statsIncrementCounter = function statsIncrementCounter(ref, metric) {\n ref.repo.statsIncrementCounter(metric);\n};\n\nvar dataUpdateCount = function dataUpdateCount(ref) {\n return ref.repo.dataUpdateCount;\n};\n\nvar interceptServerData = function interceptServerData(ref, callback) {\n return ref.repo.interceptServerData_(callback);\n};\n\nvar INTERNAL =\n/*#__PURE__*/\nObject.freeze({\n forceLongPolling: forceLongPolling,\n forceWebSockets: forceWebSockets,\n isWebSocketsAvailable: isWebSocketsAvailable,\n setSecurityDebugCallback: setSecurityDebugCallback,\n stats: stats,\n statsIncrementCounter: statsIncrementCounter,\n dataUpdateCount: dataUpdateCount,\n interceptServerData: interceptServerData\n});\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar DataConnection = PersistentConnection;\n/**\r\n * @param {!string} pathString\r\n * @param {function(*)} onComplete\r\n */\n\nPersistentConnection.prototype.simpleListen = function (pathString, onComplete) {\n this.sendRequest('q', {\n p: pathString\n }, onComplete);\n};\n/**\r\n * @param {*} data\r\n * @param {function(*)} onEcho\r\n */\n\n\nPersistentConnection.prototype.echo = function (data, onEcho) {\n this.sendRequest('echo', {\n d: data\n }, onEcho);\n}; // RealTimeConnection properties that we use in tests.\n\n\nvar RealTimeConnection = Connection;\n/**\r\n * @param {function(): string} newHash\r\n * @return {function()}\r\n */\n\nvar hijackHash = function hijackHash(newHash) {\n var oldPut = PersistentConnection.prototype.put;\n\n PersistentConnection.prototype.put = function (pathString, data, opt_onComplete, opt_hash) {\n if (opt_hash !== undefined) {\n opt_hash = newHash();\n }\n\n oldPut.call(this, pathString, data, opt_onComplete, opt_hash);\n };\n\n return function () {\n PersistentConnection.prototype.put = oldPut;\n };\n};\n/**\r\n * @type {function(new:RepoInfo, !string, boolean, !string, boolean): undefined}\r\n */\n\n\nvar ConnectionTarget = RepoInfo;\n/**\r\n * @param {!Query} query\r\n * @return {!string}\r\n */\n\nvar queryIdentifier = function queryIdentifier(query) {\n return query.queryIdentifier();\n};\n/**\r\n * @param {!Query} firebaseRef\r\n * @return {!Object}\r\n */\n\n\nvar listens = function listens(firebaseRef) {\n return firebaseRef.repo.persistentConnection_.listens_;\n};\n/**\r\n * Forces the RepoManager to create Repos that use ReadonlyRestClient instead of PersistentConnection.\r\n *\r\n * @param {boolean} forceRestClient\r\n */\n\n\nvar forceRestClient = function forceRestClient(_forceRestClient) {\n RepoManager.getInstance().forceRestClient(_forceRestClient);\n};\n\nvar TEST_ACCESS =\n/*#__PURE__*/\nObject.freeze({\n DataConnection: DataConnection,\n RealTimeConnection: RealTimeConnection,\n hijackHash: hijackHash,\n ConnectionTarget: ConnectionTarget,\n queryIdentifier: queryIdentifier,\n listens: listens,\n forceRestClient: forceRestClient\n});\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar ServerValue = Database.ServerValue;\n\nfunction registerDatabase(instance) {\n // Register the Database Service with the 'firebase' namespace.\n var namespace = instance.INTERNAL.registerService('database', function (app, unused, url) {\n return RepoManager.getInstance().databaseFromApp(app, url);\n }, // firebase.database namespace properties\n {\n Reference: Reference,\n Query: Query,\n Database: Database,\n enableLogging: enableLogging,\n INTERNAL: INTERNAL,\n ServerValue: ServerValue,\n TEST_ACCESS: TEST_ACCESS\n }, null, true);\n\n if (util.isNodeSdk()) {\n module.exports = namespace;\n }\n}\n\nregisterDatabase(firebase);\nexports.registerDatabase = registerDatabase;\nexports.Database = Database;\nexports.Query = Query;\nexports.Reference = Reference;\nexports.enableLogging = enableLogging;\nexports.ServerValue = ServerValue;\nexports.DataSnapshot = DataSnapshot;\nexports.OnDisconnect = OnDisconnect;","'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nfunction _interopDefault(ex) {\n return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex;\n}\n\nvar firebase = _interopDefault(require('@firebase/app'));\n\nvar logger = require('@firebase/logger');\n\nvar tslib_1 = require('tslib');\n\nvar webchannelWrapper = require('@firebase/webchannel-wrapper');\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/** The semver (www.semver.org) version of the SDK. */\n\n\nvar SDK_VERSION = firebase.SDK_VERSION;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar logClient = new logger.Logger('@firebase/firestore');\nvar LogLevel;\n\n(function (LogLevel) {\n LogLevel[LogLevel[\"DEBUG\"] = 0] = \"DEBUG\";\n LogLevel[LogLevel[\"ERROR\"] = 1] = \"ERROR\";\n LogLevel[LogLevel[\"SILENT\"] = 2] = \"SILENT\";\n})(LogLevel || (LogLevel = {})); // Helper methods are needed because variables can't be exported as read/write\n\n\nfunction getLogLevel() {\n if (logClient.logLevel === logger.LogLevel.DEBUG) {\n return LogLevel.DEBUG;\n } else if (logClient.logLevel === logger.LogLevel.SILENT) {\n return LogLevel.SILENT;\n } else {\n return LogLevel.ERROR;\n }\n}\n\nfunction setLogLevel(newLevel) {\n /**\r\n * Map the new log level to the associated Firebase Log Level\r\n */\n switch (newLevel) {\n case LogLevel.DEBUG:\n logClient.logLevel = logger.LogLevel.DEBUG;\n break;\n\n case LogLevel.ERROR:\n logClient.logLevel = logger.LogLevel.ERROR;\n break;\n\n case LogLevel.SILENT:\n logClient.logLevel = logger.LogLevel.SILENT;\n break;\n\n default:\n logClient.error(\"Firestore (\" + SDK_VERSION + \"): Invalid value passed to `setLogLevel`\");\n }\n}\n\nfunction debug(tag, msg) {\n var obj = [];\n\n for (var _i = 2; _i < arguments.length; _i++) {\n obj[_i - 2] = arguments[_i];\n }\n\n if (logClient.logLevel <= logger.LogLevel.DEBUG) {\n var args = obj.map(argToString);\n logClient.debug.apply(logClient, [\"Firestore (\" + SDK_VERSION + \") [\" + tag + \"]: \" + msg].concat(args));\n }\n}\n\nfunction error(msg) {\n var obj = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n obj[_i - 1] = arguments[_i];\n }\n\n if (logClient.logLevel <= logger.LogLevel.ERROR) {\n var args = obj.map(argToString);\n logClient.error.apply(logClient, [\"Firestore (\" + SDK_VERSION + \"): \" + msg].concat(args));\n }\n}\n/**\r\n * Converts an additional log parameter to a string representation.\r\n */\n\n\nfunction argToString(obj) {\n if (typeof obj === 'string') {\n return obj;\n } else {\n var platform = PlatformSupport.getPlatform();\n\n try {\n return platform.formatJSON(obj);\n } catch (e) {\n // Converting to JSON failed, just log the object directly\n return obj;\n }\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Unconditionally fails, throwing an Error with the given message.\r\n *\r\n * Returns any so it can be used in expressions:\r\n * @example\r\n * let futureVar = fail('not implemented yet');\r\n */\n\n\nfunction fail(failure) {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n var message = \"FIRESTORE (\" + SDK_VERSION + \") INTERNAL ASSERTION FAILED: \" + failure;\n error(message); // 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\n throw new Error(message);\n}\n/**\r\n * Fails if the given assertion condition is false, throwing an Error with the\r\n * given message if it did.\r\n */\n\n\nfunction assert(assertion, message) {\n if (!assertion) {\n fail(message);\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Provides singleton helpers where setup code can inject a platform at runtime.\r\n * setPlatform needs to be set before Firestore is used and must be set exactly\r\n * once.\r\n */\n\n\nvar PlatformSupport =\n/** @class */\nfunction () {\n function PlatformSupport() {}\n\n PlatformSupport.setPlatform = function (platform) {\n if (PlatformSupport.platform) {\n fail('Platform already defined');\n }\n\n PlatformSupport.platform = platform;\n };\n\n PlatformSupport.getPlatform = function () {\n if (!PlatformSupport.platform) {\n fail('Platform not set');\n }\n\n return PlatformSupport.platform;\n };\n\n return PlatformSupport;\n}();\n/**\r\n * Returns the representation of an empty \"proto\" byte string for the\r\n * platform.\r\n */\n\n\nfunction emptyByteString() {\n return PlatformSupport.getPlatform().emptyByteString;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// TODO(mcg): Change to a string enum once we've upgraded to typescript 2.4.\n// tslint:disable-next-line:variable-name Intended to look like a TS 2.4 enum\n\n\nvar 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\n /** Not an error; returned on success. */\n OK: 'ok',\n\n /** The operation was cancelled (typically by the caller). */\n CANCELLED: 'cancelled',\n\n /** Unknown error or an error from a different error domain. */\n UNKNOWN: 'unknown',\n\n /**\r\n * Client specified an invalid argument. Note that this differs from\r\n * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are\r\n * problematic regardless of the state of the system (e.g., a malformed file\r\n * name).\r\n */\n INVALID_ARGUMENT: 'invalid-argument',\n\n /**\r\n * Deadline expired before operation could complete. For operations that\r\n * change the state of the system, this error may be returned even if the\r\n * operation has completed successfully. For example, a successful response\r\n * from a server could have been delayed long enough for the deadline to\r\n * expire.\r\n */\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n\n /** Some requested entity (e.g., file or directory) was not found. */\n NOT_FOUND: 'not-found',\n\n /**\r\n * Some entity that we attempted to create (e.g., file or directory) already\r\n * exists.\r\n */\n ALREADY_EXISTS: 'already-exists',\n\n /**\r\n * The caller does not have permission to execute the specified operation.\r\n * PERMISSION_DENIED must not be used for rejections caused by exhausting\r\n * some resource (use RESOURCE_EXHAUSTED instead for those errors).\r\n * PERMISSION_DENIED must not be used if the caller can not be identified\r\n * (use UNAUTHENTICATED instead for those errors).\r\n */\n PERMISSION_DENIED: 'permission-denied',\n\n /**\r\n * The request does not have valid authentication credentials for the\r\n * operation.\r\n */\n UNAUTHENTICATED: 'unauthenticated',\n\n /**\r\n * Some resource has been exhausted, perhaps a per-user quota, or perhaps the\r\n * entire file system is out of space.\r\n */\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n\n /**\r\n * Operation was rejected because the system is not in a state required for\r\n * the operation's execution. For example, directory to be deleted may be\r\n * non-empty, an rmdir operation is applied to a non-directory, etc.\r\n *\r\n * A litmus test that may help a service implementor in deciding\r\n * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE:\r\n * (a) Use UNAVAILABLE if the client can retry just the failing call.\r\n * (b) Use ABORTED if the client should retry at a higher-level\r\n * (e.g., restarting a read-modify-write sequence).\r\n * (c) Use FAILED_PRECONDITION if the client should not retry until\r\n * the system state has been explicitly fixed. E.g., if an \"rmdir\"\r\n * fails because the directory is non-empty, FAILED_PRECONDITION\r\n * should be returned since the client should not retry unless\r\n * they have first fixed up the directory by deleting files from it.\r\n * (d) Use FAILED_PRECONDITION if the client performs conditional\r\n * REST Get/Update/Delete on a resource and the resource on the\r\n * server does not match the condition. E.g., conflicting\r\n * read-modify-write on the same resource.\r\n */\n FAILED_PRECONDITION: 'failed-precondition',\n\n /**\r\n * The operation was aborted, typically due to a concurrency issue like\r\n * sequencer check failures, transaction aborts, etc.\r\n *\r\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\r\n * and UNAVAILABLE.\r\n */\n ABORTED: 'aborted',\n\n /**\r\n * Operation was attempted past the valid range. E.g., seeking or reading\r\n * past end of file.\r\n *\r\n * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed\r\n * if the system state changes. For example, a 32-bit file system will\r\n * generate INVALID_ARGUMENT if asked to read at an offset that is not in the\r\n * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from\r\n * an offset past the current file size.\r\n *\r\n * There is a fair bit of overlap between FAILED_PRECONDITION and\r\n * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error)\r\n * when it applies so that callers who are iterating through a space can\r\n * easily look for an OUT_OF_RANGE error to detect when they are done.\r\n */\n OUT_OF_RANGE: 'out-of-range',\n\n /** Operation is not implemented or not supported/enabled in this service. */\n UNIMPLEMENTED: 'unimplemented',\n\n /**\r\n * Internal errors. Means some invariants expected by underlying System has\r\n * been broken. If you see one of these errors, Something is very broken.\r\n */\n INTERNAL: 'internal',\n\n /**\r\n * The service is currently unavailable. This is a most likely a transient\r\n * condition and may be corrected by retrying with a backoff.\r\n *\r\n * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED,\r\n * and UNAVAILABLE.\r\n */\n UNAVAILABLE: 'unavailable',\n\n /** Unrecoverable data loss or corruption. */\n DATA_LOSS: 'data-loss'\n};\n/**\r\n * An error class used for Firestore-generated errors. Ideally we should be\r\n * using FirebaseError, but integrating with it is overly arduous at the moment,\r\n * so we define our own compatible error class (with a `name` of 'FirebaseError'\r\n * and compatible `code` and `message` fields.)\r\n */\n\nvar FirestoreError =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(FirestoreError, _super);\n\n function FirestoreError(code, message) {\n var _this = _super.call(this, message) || this;\n\n _this.code = code;\n _this.message = message;\n _this.name = 'FirebaseError'; // 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\n _this.toString = function () {\n return _this.name + \": [code=\" + _this.code + \"]: \" + _this.message;\n };\n\n return _this;\n }\n\n return FirestoreError;\n}(Error);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Helper function to prevent instantiation through the constructor.\r\n *\r\n * This method creates a new constructor that throws when it's invoked.\r\n * The prototype of that constructor is then set to the prototype of the hidden\r\n * \"class\" to expose all the prototype methods and allow for instanceof\r\n * checks.\r\n *\r\n * To also make all the static methods available, all properties of the\r\n * original constructor are copied to the new constructor.\r\n */\n\n\nfunction makeConstructorPrivate(cls, optionalMessage) {\n function PublicConstructor() {\n var error = 'This constructor is private.';\n\n if (optionalMessage) {\n error += ' ';\n error += optionalMessage;\n }\n\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\n } // Make sure instanceof checks work and all methods are exposed on the public\n // constructor\n\n\n PublicConstructor.prototype = cls.prototype; // Copy any static methods/members\n\n for (var staticProperty in cls) {\n if (cls.hasOwnProperty(staticProperty)) {\n PublicConstructor[staticProperty] = cls[staticProperty];\n }\n }\n\n return PublicConstructor;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction contains(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n/** Returns the given value if it's defined or the defaultValue otherwise. */\n\n\nfunction defaulted(value, defaultValue) {\n return value !== undefined ? value : defaultValue;\n}\n\nfunction forEachNumber(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n var num = Number(key);\n\n if (!isNaN(num)) {\n fn(num, obj[key]);\n }\n }\n }\n}\n\nfunction values(obj) {\n var vs = [];\n forEach(obj, function (_, v) {\n return vs.push(v);\n });\n return vs;\n}\n\nfunction forEach(obj, fn) {\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n fn(key, obj[key]);\n }\n }\n}\n\nfunction isEmpty(obj) {\n assert(obj != null && typeof obj === 'object', 'isEmpty() expects object parameter.');\n\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction shallowCopy(obj) {\n assert(obj && typeof obj === 'object', 'shallowCopy() expects object parameter.');\n var result = {};\n\n for (var key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n result[key] = obj[key];\n }\n }\n\n return result;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Validates the invocation of functionName has the exact number of arguments.\r\n *\r\n * Forward the magic \"arguments\" variable as second parameter on which the\r\n * parameter validation is performed:\r\n * validateExactNumberOfArgs('myFunction', arguments, 2);\r\n */\n\n\nfunction validateExactNumberOfArgs(functionName, args, numberOfArgs) {\n if (args.length !== numberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires \" + formatPlural(numberOfArgs, 'argument') + ', but was called with ' + formatPlural(args.length, 'argument') + '.');\n }\n}\n/**\r\n * Validates the invocation of functionName has at least the provided number of\r\n * arguments (but can have many more).\r\n *\r\n * Forward the magic \"arguments\" variable as second parameter on which the\r\n * parameter validation is performed:\r\n * validateAtLeastNumberOfArgs('myFunction', arguments, 2);\r\n */\n\n\nfunction validateAtLeastNumberOfArgs(functionName, args, minNumberOfArgs) {\n if (args.length < minNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires at least \" + formatPlural(minNumberOfArgs, 'argument') + ', but was called with ' + formatPlural(args.length, 'argument') + '.');\n }\n}\n/**\r\n * Validates the invocation of functionName has number of arguments between\r\n * the values provided.\r\n *\r\n * Forward the magic \"arguments\" variable as second parameter on which the\r\n * parameter validation is performed:\r\n * validateBetweenNumberOfArgs('myFunction', arguments, 2, 3);\r\n */\n\n\nfunction validateBetweenNumberOfArgs(functionName, args, minNumberOfArgs, maxNumberOfArgs) {\n if (args.length < minNumberOfArgs || args.length > maxNumberOfArgs) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires between \" + minNumberOfArgs + \" and \" + (maxNumberOfArgs + \" arguments, but was called with \") + formatPlural(args.length, 'argument') + '.');\n }\n}\n/**\r\n * Validates the provided argument is an array and has as least the expected\r\n * number of elements.\r\n */\n\n\nfunction validateNamedArrayAtLeastNumberOfElements(functionName, value, name, minNumberOfElements) {\n if (!(value instanceof Array) || value.length < minNumberOfElements) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + name + \" argument to be an \" + 'array with at least ' + (formatPlural(minNumberOfElements, 'element') + \".\"));\n }\n}\n/**\r\n * Validates the provided positional argument has the native JavaScript type\r\n * using typeof checks.\r\n */\n\n\nfunction validateArgType(functionName, type, position, argument) {\n validateType(functionName, type, ordinal(position) + \" argument\", argument);\n}\n/**\r\n * Validates the provided argument has the native JavaScript type using\r\n * typeof checks or is undefined.\r\n */\n\n\nfunction validateOptionalArgType(functionName, type, position, argument) {\n if (argument !== undefined) {\n validateArgType(functionName, type, position, argument);\n }\n}\n/**\r\n * Validates the provided named option has the native JavaScript type using\r\n * typeof checks.\r\n */\n\n\nfunction validateNamedType(functionName, type, optionName, argument) {\n validateType(functionName, type, optionName + \" option\", argument);\n}\n/**\r\n * Validates the provided named option has the native JavaScript type using\r\n * typeof checks or is undefined.\r\n */\n\n\nfunction validateNamedOptionalType(functionName, type, optionName, argument) {\n if (argument !== undefined) {\n validateNamedType(functionName, type, optionName, argument);\n }\n}\n\nfunction validateArrayElements(functionName, optionName, typeDescription, argument, validator) {\n if (!(argument instanceof Array)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + optionName + \" \" + (\"option to be an array, but it was: \" + valueDescription(argument)));\n }\n\n for (var i = 0; i < argument.length; ++i) {\n if (!validator(argument[i])) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires all \" + optionName + \" \" + (\"elements to be \" + typeDescription + \", but the value at index \" + i + \" \") + (\"was: \" + valueDescription(argument[i])));\n }\n }\n}\n\nfunction validateOptionalArrayElements(functionName, optionName, typeDescription, argument, validator) {\n if (argument !== undefined) {\n validateArrayElements(functionName, optionName, typeDescription, argument, validator);\n }\n}\n/**\r\n * Validates that the provided named option equals one of the expected values.\r\n */\n\n\nfunction validateNamedPropertyEquals(functionName, inputName, optionName, input, expected) {\n var expectedDescription = [];\n\n for (var _i = 0, expected_1 = expected; _i < expected_1.length; _i++) {\n var val = expected_1[_i];\n\n if (val === input) {\n return;\n }\n\n expectedDescription.push(valueDescription(val));\n }\n\n var actualDescription = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid value \" + actualDescription + \" provided to function \" + functionName + \"() for option \" + (\"\\\"\" + optionName + \"\\\". Acceptable values: \" + expectedDescription.join(', ')));\n}\n/**\r\n * Validates that the provided named option equals one of the expected values or\r\n * is undefined.\r\n */\n\n\nfunction validateNamedOptionalPropertyEquals(functionName, inputName, optionName, input, expected) {\n if (input !== undefined) {\n validateNamedPropertyEquals(functionName, inputName, optionName, input, expected);\n }\n}\n/** Helper to validate the type of a provided input. */\n\n\nfunction validateType(functionName, type, inputName, input) {\n var valid = false;\n\n if (type === 'object') {\n valid = isPlainObject(input);\n } else if (type === 'non-empty string') {\n valid = typeof input === 'string' && input !== '';\n } else {\n valid = typeof input === type;\n }\n\n if (!valid) {\n var description = valueDescription(input);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + inputName + \" \" + (\"to be of type \" + type + \", but it was: \" + description));\n }\n}\n/**\r\n * Returns true if it's a non-null object without a custom prototype\r\n * (i.e. excludes Array, Date, etc.).\r\n */\n\n\nfunction isPlainObject(input) {\n return typeof input === 'object' && input !== null && (Object.getPrototypeOf(input) === Object.prototype || Object.getPrototypeOf(input) === null);\n}\n/** Returns a string describing the type / value of the provided input. */\n\n\nfunction valueDescription(input) {\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\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 var customObjectName = tryGetCustomObjectType(input);\n\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/** Hacky method to try to get the constructor name for an object. */\n\n\nfunction tryGetCustomObjectType(input) {\n if (input.constructor) {\n var funcNameRegex = /function\\s+([^\\s(]+)\\s*\\(/;\n var results = funcNameRegex.exec(input.constructor.toString());\n\n if (results && results.length > 1) {\n return results[1];\n }\n }\n\n return null;\n}\n/** Validates the provided argument is defined. */\n\n\nfunction validateDefined(functionName, position, argument) {\n if (argument === undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires a valid \" + ordinal(position) + \" \" + \"argument, but it was undefined.\");\n }\n}\n/**\r\n * Validates the provided positional argument is an object, and its keys and\r\n * values match the expected keys and types provided in optionTypes.\r\n */\n\n\nfunction validateOptionNames(functionName, options, optionNames) {\n forEach(options, function (key, _) {\n if (optionNames.indexOf(key) < 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Unknown option '\" + key + \"' passed to function \" + functionName + \"(). \" + 'Available options: ' + optionNames.join(', '));\n }\n });\n}\n/**\r\n * Helper method to throw an error that the provided argument did not pass\r\n * an instanceof check.\r\n */\n\n\nfunction invalidClassError(functionName, type, position, argument) {\n var description = valueDescription(argument);\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + functionName + \"() requires its \" + ordinal(position) + \" \" + (\"argument to be a \" + type + \", but it was: \" + description));\n}\n/** Converts a number to its english word representation */\n\n\nfunction ordinal(num) {\n switch (num) {\n case 1:\n return 'first';\n\n case 2:\n return 'second';\n\n case 3:\n return 'third';\n\n default:\n return num + 'th';\n }\n}\n/**\r\n * Formats the given word as plural conditionally given the preceding number.\r\n */\n\n\nfunction formatPlural(num, str) {\n return num + \" \" + str + (num === 1 ? '' : 's');\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// tslint:disable-next-line:class-as-namespace\n\n\nvar AutoId =\n/** @class */\nfunction () {\n function AutoId() {}\n\n AutoId.newId = function () {\n // Alphanumeric characters\n var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';\n var autoId = '';\n\n for (var i = 0; i < 20; i++) {\n autoId += chars.charAt(Math.floor(Math.random() * chars.length));\n }\n\n assert(autoId.length === 20, 'Invalid auto ID: ' + autoId);\n return autoId;\n };\n\n return AutoId;\n}();\n\nfunction primitiveComparator(left, right) {\n if (left < right) return -1;\n if (left > right) return 1;\n return 0;\n}\n/** Helper to compare nullable (or undefined-able) objects using isEqual(). */\n\n\nfunction equals(left, right) {\n if (left !== null && left !== undefined) {\n return !!(right && left.isEqual(right));\n } else {\n // HACK: Explicitly cast since TypeScript's type narrowing apparently isn't\n // smart enough.\n return left === right;\n }\n}\n/** Helper to compare arrays using isEqual(). */\n\n\nfunction arrayEquals(left, right) {\n if (left.length !== right.length) {\n return false;\n }\n\n for (var i = 0; i < left.length; i++) {\n if (!left[i].isEqual(right[i])) {\n return false;\n }\n }\n\n return true;\n}\n/**\r\n * Returns the immediate lexicographically-following string. This is useful to\r\n * construct an inclusive range for indexeddb iterators.\r\n */\n\n\nfunction immediateSuccessor(s) {\n // Return the input string, with an additional NUL byte appended.\n return s + '\\0';\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/** Helper function to assert Uint8Array is available at runtime. */\n\n\nfunction assertUint8ArrayAvailable() {\n if (typeof Uint8Array === 'undefined') {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Uint8Arrays are not available in this environment.');\n }\n}\n/** Helper function to assert Base64 functions are available at runtime. */\n\n\nfunction assertBase64Available() {\n if (!PlatformSupport.getPlatform().base64Available) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'Blobs are unavailable in Firestore in this environment.');\n }\n}\n/**\r\n * Immutable class holding a blob (binary data).\r\n * This class is directly exposed in the public API.\r\n *\r\n * Note that while you can't hide the constructor in JavaScript code, we are\r\n * using the hack above to make sure no-one outside this module can call it.\r\n */\n\n\nvar Blob =\n/** @class */\nfunction () {\n function Blob(binaryString) {\n assertBase64Available();\n this._binaryString = binaryString;\n }\n\n Blob.fromBase64String = function (base64) {\n validateExactNumberOfArgs('Blob.fromBase64String', arguments, 1);\n validateArgType('Blob.fromBase64String', 'string', 1, base64);\n assertBase64Available();\n\n try {\n var binaryString = PlatformSupport.getPlatform().atob(base64);\n return new Blob(binaryString);\n } catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct Blob from Base64 string: ' + e);\n }\n };\n\n Blob.fromUint8Array = function (array) {\n validateExactNumberOfArgs('Blob.fromUint8Array', arguments, 1);\n assertUint8ArrayAvailable();\n\n if (!(array instanceof Uint8Array)) {\n throw invalidClassError('Blob.fromUint8Array', 'Uint8Array', 1, array);\n } // We can't call array.map directly because it expects the return type to\n // be a Uint8Array, whereas we can convert it to a regular array by invoking\n // map on the Array prototype.\n\n\n var binaryString = Array.prototype.map.call(array, function (char) {\n return String.fromCharCode(char);\n }).join('');\n return new Blob(binaryString);\n };\n\n Blob.prototype.toBase64 = function () {\n validateExactNumberOfArgs('Blob.toBase64', arguments, 0);\n assertBase64Available();\n return PlatformSupport.getPlatform().btoa(this._binaryString);\n };\n\n Blob.prototype.toUint8Array = function () {\n validateExactNumberOfArgs('Blob.toUint8Array', arguments, 0);\n assertUint8ArrayAvailable();\n var buffer = new Uint8Array(this._binaryString.length);\n\n for (var i = 0; i < this._binaryString.length; i++) {\n buffer[i] = this._binaryString.charCodeAt(i);\n }\n\n return buffer;\n };\n\n Blob.prototype.toString = function () {\n return 'Blob(base64: ' + this.toBase64() + ')';\n };\n\n Blob.prototype.isEqual = function (other) {\n return this._binaryString === other._binaryString;\n };\n /**\r\n * Actually private to JS consumers of our API, so this function is prefixed\r\n * with an underscore.\r\n */\n\n\n Blob.prototype._compareTo = function (other) {\n return primitiveComparator(this._binaryString, other._binaryString);\n };\n\n return Blob;\n}(); // Public instance that disallows construction at runtime. This constructor is\n// used when exporting Blob on firebase.firestore.Blob and will be called Blob\n// publicly. Internally we still use Blob which has a type checked private\n// constructor. Note that Blob and PublicBlob can be used interchangeably in\n// instanceof checks.\n// For our internal TypeScript code PublicBlob doesn't exist as a type, and so\n// we need to use Blob as type and export it too.\n// tslint:disable-next-line:variable-name We're treating this as a class name.\n\n\nvar PublicBlob = makeConstructorPrivate(Blob, 'Use Blob.fromUint8Array() or Blob.fromBase64String() instead.');\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Immutable class representing a geo point as latitude-longitude pair.\r\n * This class is directly exposed in the public API, including its constructor.\r\n */\n\nvar GeoPoint =\n/** @class */\nfunction () {\n function GeoPoint(latitude, longitude) {\n validateExactNumberOfArgs('GeoPoint', arguments, 2);\n validateArgType('GeoPoint', 'number', 1, latitude);\n validateArgType('GeoPoint', 'number', 2, longitude);\n\n if (!isFinite(latitude) || latitude < -90 || latitude > 90) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '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(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude);\n }\n\n this._lat = latitude;\n this._long = longitude;\n }\n\n Object.defineProperty(GeoPoint.prototype, \"latitude\", {\n /**\r\n * Returns the latitude of this geo point, a number between -90 and 90.\r\n */\n get: function get() {\n return this._lat;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(GeoPoint.prototype, \"longitude\", {\n /**\r\n * Returns the longitude of this geo point, a number between -180 and 180.\r\n */\n get: function get() {\n return this._long;\n },\n enumerable: true,\n configurable: true\n });\n\n GeoPoint.prototype.isEqual = function (other) {\n return this._lat === other._lat && this._long === other._long;\n };\n /**\r\n * Actually private to JS consumers of our API, so this function is prefixed\r\n * with an underscore.\r\n */\n\n\n GeoPoint.prototype._compareTo = function (other) {\n return primitiveComparator(this._lat, other._lat) || primitiveComparator(this._long, other._long);\n };\n\n return GeoPoint;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar Timestamp =\n/** @class */\nfunction () {\n function Timestamp(seconds, nanoseconds) {\n this.seconds = seconds;\n this.nanoseconds = nanoseconds;\n\n if (nanoseconds < 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);\n }\n\n if (nanoseconds >= 1e9) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds);\n } // Midnight at the beginning of 1/1/1 is the earliest Firestore supports.\n\n\n if (seconds < -62135596800) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);\n } // This will break in the year 10,000.\n\n\n if (seconds >= 253402300800) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds);\n }\n }\n\n Timestamp.now = function () {\n return Timestamp.fromMillis(Date.now());\n };\n\n Timestamp.fromDate = function (date) {\n return Timestamp.fromMillis(date.getTime());\n };\n\n Timestamp.fromMillis = function (milliseconds) {\n var seconds = Math.floor(milliseconds / 1000);\n var nanos = (milliseconds - seconds * 1000) * 1e6;\n return new Timestamp(seconds, nanos);\n };\n\n Timestamp.prototype.toDate = function () {\n return new Date(this.toMillis());\n };\n\n Timestamp.prototype.toMillis = function () {\n return this.seconds * 1000 + this.nanoseconds / 1e6;\n };\n\n Timestamp.prototype._compareTo = function (other) {\n if (this.seconds === other.seconds) {\n return primitiveComparator(this.nanoseconds, other.nanoseconds);\n }\n\n return primitiveComparator(this.seconds, other.seconds);\n };\n\n Timestamp.prototype.isEqual = function (other) {\n return other.seconds === this.seconds && other.nanoseconds === this.nanoseconds;\n };\n\n Timestamp.prototype.toString = function () {\n return 'Timestamp(seconds=' + this.seconds + ', nanoseconds=' + this.nanoseconds + ')';\n };\n\n return Timestamp;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar DatabaseInfo =\n/** @class */\nfunction () {\n /**\r\n * Constructs a DatabaseInfo using the provided host, databaseId and\r\n * persistenceKey.\r\n *\r\n * @param databaseId The database to use.\r\n * @param persistenceKey A unique identifier for this Firestore's local\r\n * storage (used in conjunction with the databaseId).\r\n * @param host The Firestore backend host to connect to.\r\n * @param ssl Whether to use SSL when connecting.\r\n */\n function DatabaseInfo(databaseId, persistenceKey, host, ssl) {\n this.databaseId = databaseId;\n this.persistenceKey = persistenceKey;\n this.host = host;\n this.ssl = ssl;\n }\n\n return DatabaseInfo;\n}();\n/** The default database name for a project. */\n\n\nvar DEFAULT_DATABASE_NAME = '(default)';\n/** Represents the database ID a Firestore client is associated with. */\n\nvar DatabaseId =\n/** @class */\nfunction () {\n function DatabaseId(projectId, database) {\n this.projectId = projectId;\n this.database = database ? database : DEFAULT_DATABASE_NAME;\n }\n\n Object.defineProperty(DatabaseId.prototype, \"isDefaultDatabase\", {\n get: function get() {\n return this.database === DEFAULT_DATABASE_NAME;\n },\n enumerable: true,\n configurable: true\n });\n\n DatabaseId.prototype.isEqual = function (other) {\n return other instanceof DatabaseId && other.projectId === this.projectId && other.database === this.database;\n };\n\n DatabaseId.prototype.compareTo = function (other) {\n return primitiveComparator(this.projectId, other.projectId) || primitiveComparator(this.database, other.database);\n };\n\n return DatabaseId;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar DOCUMENT_KEY_NAME = '__name__';\n/**\r\n * Path represents an ordered sequence of string segments.\r\n */\n\nvar Path =\n/** @class */\nfunction () {\n function Path(segments, offset, length) {\n this.init(segments, offset, length);\n }\n /**\r\n * An initialization method that can be called from outside the constructor.\r\n * We need this so that we can have a non-static construct method that returns\r\n * the polymorphic `this` type.\r\n */\n\n\n Path.prototype.init = function (segments, offset, length) {\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\n this.segments = segments;\n this.offset = offset;\n this.len = length;\n };\n /**\r\n * Constructs a new instance of Path using the same concrete type as `this`.\r\n * We need this instead of using the normal constructor, because polymorphic\r\n * `this` doesn't work on static methods.\r\n */\n\n\n Path.prototype.construct = function (segments, offset, length) {\n var path = Object.create(Object.getPrototypeOf(this));\n path.init(segments, offset, length);\n return path;\n };\n\n Object.defineProperty(Path.prototype, \"length\", {\n get: function get() {\n return this.len;\n },\n enumerable: true,\n configurable: true\n });\n\n Path.prototype.isEqual = function (other) {\n return Path.comparator(this, other) === 0;\n };\n\n Path.prototype.child = function (nameOrPath) {\n var segments = this.segments.slice(this.offset, this.limit());\n\n if (nameOrPath instanceof Path) {\n nameOrPath.forEach(function (segment) {\n segments.push(segment);\n });\n } else if (typeof nameOrPath === 'string') {\n segments.push(nameOrPath);\n } else {\n fail('Unknown parameter type for Path.child(): ' + nameOrPath);\n }\n\n return this.construct(segments);\n };\n /** The index of one past the last segment of the path. */\n\n\n Path.prototype.limit = function () {\n return this.offset + this.length;\n };\n\n Path.prototype.popFirst = function (size) {\n size = size === undefined ? 1 : size;\n assert(this.length >= size, \"Can't call popFirst() with less segments\");\n return this.construct(this.segments, this.offset + size, this.length - size);\n };\n\n Path.prototype.popLast = function () {\n assert(!this.isEmpty(), \"Can't call popLast() on empty path\");\n return this.construct(this.segments, this.offset, this.length - 1);\n };\n\n Path.prototype.firstSegment = function () {\n assert(!this.isEmpty(), \"Can't call firstSegment() on empty path\");\n return this.segments[this.offset];\n };\n\n Path.prototype.lastSegment = function () {\n assert(!this.isEmpty(), \"Can't call lastSegment() on empty path\");\n return this.segments[this.limit() - 1];\n };\n\n Path.prototype.get = function (index) {\n assert(index < this.length, 'Index out of range');\n return this.segments[this.offset + index];\n };\n\n Path.prototype.isEmpty = function () {\n return this.length === 0;\n };\n\n Path.prototype.isPrefixOf = function (other) {\n if (other.length < this.length) {\n return false;\n }\n\n for (var 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 Path.prototype.isImmediateParentOf = function (potentialChild) {\n if (this.length + 1 !== potentialChild.length) {\n return false;\n }\n\n for (var 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 Path.prototype.forEach = function (fn) {\n for (var i = this.offset, end = this.limit(); i < end; i++) {\n fn(this.segments[i]);\n }\n };\n\n Path.prototype.toArray = function () {\n return this.segments.slice(this.offset, this.limit());\n };\n\n Path.comparator = function (p1, p2) {\n var len = Math.min(p1.length, p2.length);\n\n for (var i = 0; i < len; i++) {\n var left = p1.get(i);\n var right = p2.get(i);\n if (left < right) return -1;\n if (left > right) return 1;\n }\n\n if (p1.length < p2.length) return -1;\n if (p1.length > p2.length) return 1;\n return 0;\n };\n\n return Path;\n}();\n/**\r\n * A slash-separated path for navigating resources (documents and collections)\r\n * within Firestore.\r\n */\n\n\nvar ResourcePath =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ResourcePath, _super);\n\n function ResourcePath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n\n ResourcePath.prototype.canonicalString = function () {\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 return this.toArray().join('/');\n };\n\n ResourcePath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\r\n * Creates a resource path from the given slash-delimited string.\r\n */\n\n\n ResourcePath.fromString = function (path) {\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 if (path.indexOf('//') >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid path (\" + path + \"). Paths must not contain // in them.\");\n } // We may still have an empty segment at the beginning or end if they had a\n // leading or trailing slash (which we allow).\n\n\n var segments = path.split('/').filter(function (segment) {\n return segment.length > 0;\n });\n return new ResourcePath(segments);\n };\n\n ResourcePath.EMPTY_PATH = new ResourcePath([]);\n return ResourcePath;\n}(Path);\n\nvar identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/;\n/** A dot-separated path for navigating sub-objects within a document. */\n\nvar FieldPath =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(FieldPath, _super);\n\n function FieldPath() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n /**\r\n * Returns true if the string could be used as a segment in a field path\r\n * without escaping.\r\n */\n\n\n FieldPath.isValidIdentifier = function (segment) {\n return identifierRegExp.test(segment);\n };\n\n FieldPath.prototype.canonicalString = function () {\n return this.toArray().map(function (str) {\n str = str.replace('\\\\', '\\\\\\\\').replace('`', '\\\\`');\n\n if (!FieldPath.isValidIdentifier(str)) {\n str = '`' + str + '`';\n }\n\n return str;\n }).join('.');\n };\n\n FieldPath.prototype.toString = function () {\n return this.canonicalString();\n };\n /**\r\n * Returns true if this field references the key of a document.\r\n */\n\n\n FieldPath.prototype.isKeyField = function () {\n return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME;\n };\n /**\r\n * The field designating the key of a document.\r\n */\n\n\n FieldPath.keyField = function () {\n return new FieldPath([DOCUMENT_KEY_NAME]);\n };\n /**\r\n * Parses a field string from the given server-formatted string.\r\n *\r\n * - Splitting the empty string is not allowed (for now at least).\r\n * - Empty segments within the string (e.g. if there are two consecutive\r\n * separators) are not allowed.\r\n *\r\n * TODO(b/37244157): we should make this more strict. Right now, it allows\r\n * non-identifier path components, even if they aren't escaped.\r\n */\n\n\n FieldPath.fromServerFormat = function (path) {\n var segments = [];\n var current = '';\n var i = 0;\n\n var addCurrentSegment = function addCurrentSegment() {\n if (current.length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, begin \" + \"with '.', end with '.', or contain '..'\");\n }\n\n segments.push(current);\n current = '';\n };\n\n var inBackticks = false;\n\n while (i < path.length) {\n var c = path[i];\n\n if (c === '\\\\') {\n if (i + 1 === path.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path);\n }\n\n var next = path[i + 1];\n\n if (!(next === '\\\\' || next === '.' || next === '`')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '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\n addCurrentSegment();\n\n if (inBackticks) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path);\n }\n\n return new FieldPath(segments);\n };\n\n FieldPath.EMPTY_PATH = new FieldPath([]);\n return FieldPath;\n}(Path);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar DocumentKey =\n/** @class */\nfunction () {\n function DocumentKey(path) {\n this.path = path;\n assert(DocumentKey.isDocumentKey(path), 'Invalid DocumentKey with an odd number of segments: ' + path.toArray().join('/'));\n }\n\n DocumentKey.prototype.isEqual = function (other) {\n return other !== null && ResourcePath.comparator(this.path, other.path) === 0;\n };\n\n DocumentKey.prototype.toString = function () {\n return this.path.toString();\n };\n\n DocumentKey.comparator = function (k1, k2) {\n return ResourcePath.comparator(k1.path, k2.path);\n };\n\n DocumentKey.isDocumentKey = function (path) {\n return path.length % 2 === 0;\n };\n /**\r\n * Creates and returns a new document key with the given segments.\r\n *\r\n * @param path The segments of the path to the document\r\n * @return A new instance of DocumentKey\r\n */\n\n\n DocumentKey.fromSegments = function (segments) {\n return new DocumentKey(new ResourcePath(segments.slice()));\n };\n /**\r\n * Creates and returns a new document key using '/' to split the string into\r\n * segments.\r\n *\r\n * @param path The slash-separated path string to the document\r\n * @return A new instance of DocumentKey\r\n */\n\n\n DocumentKey.fromPathString = function (path) {\n return new DocumentKey(ResourcePath.fromString(path));\n };\n\n DocumentKey.EMPTY = new DocumentKey(new ResourcePath([]));\n return DocumentKey;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * The result of a lookup for a given path may be an existing document or a\r\n * marker that this document does not exist at a given version.\r\n */\n\n\nvar MaybeDocument =\n/** @class */\nfunction () {\n function MaybeDocument(key, version) {\n this.key = key;\n this.version = version;\n }\n\n MaybeDocument.compareByKey = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n\n return MaybeDocument;\n}();\n/**\r\n * Represents a document in Firestore with a key, version, data and whether the\r\n * data has local mutations applied to it.\r\n */\n\n\nvar Document =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(Document, _super);\n\n function Document(key, version, data, options) {\n var _this = _super.call(this, key, version) || this;\n\n _this.data = data;\n _this.hasLocalMutations = !!options.hasLocalMutations;\n _this.hasCommittedMutations = !!options.hasCommittedMutations;\n return _this;\n }\n\n Document.prototype.field = function (path) {\n return this.data.field(path);\n };\n\n Document.prototype.fieldValue = function (path) {\n var field = this.field(path);\n return field ? field.value() : undefined;\n };\n\n Document.prototype.value = function () {\n return this.data.value();\n };\n\n Document.prototype.isEqual = function (other) {\n return other instanceof Document && this.key.isEqual(other.key) && this.version.isEqual(other.version) && this.data.isEqual(other.data) && this.hasLocalMutations === other.hasLocalMutations && this.hasCommittedMutations === other.hasCommittedMutations;\n };\n\n Document.prototype.toString = function () {\n return \"Document(\" + this.key + \", \" + this.version + \", \" + this.data.toString() + \", \" + (\"{hasLocalMutations: \" + this.hasLocalMutations + \"}), \") + (\"{hasCommittedMutations: \" + this.hasCommittedMutations + \"})\");\n };\n\n Object.defineProperty(Document.prototype, \"hasPendingWrites\", {\n get: function get() {\n return this.hasLocalMutations || this.hasCommittedMutations;\n },\n enumerable: true,\n configurable: true\n });\n\n Document.compareByField = function (field, d1, d2) {\n var v1 = d1.field(field);\n var v2 = d2.field(field);\n\n if (v1 !== undefined && v2 !== undefined) {\n return v1.compareTo(v2);\n } else {\n return fail(\"Trying to compare documents on fields that don't exist\");\n }\n };\n\n return Document;\n}(MaybeDocument);\n/**\r\n * A class representing a deleted document.\r\n * Version is set to 0 if we don't point to any specific time, otherwise it\r\n * denotes time we know it didn't exist at.\r\n */\n\n\nvar NoDocument =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(NoDocument, _super);\n\n function NoDocument(key, version, options) {\n var _this = _super.call(this, key, version) || this;\n\n _this.hasCommittedMutations = !!(options && options.hasCommittedMutations);\n return _this;\n }\n\n NoDocument.prototype.toString = function () {\n return \"NoDocument(\" + this.key + \", \" + this.version + \")\";\n };\n\n Object.defineProperty(NoDocument.prototype, \"hasPendingWrites\", {\n get: function get() {\n return this.hasCommittedMutations;\n },\n enumerable: true,\n configurable: true\n });\n\n NoDocument.prototype.isEqual = function (other) {\n return other instanceof NoDocument && other.hasCommittedMutations === this.hasCommittedMutations && other.version.isEqual(this.version) && other.key.isEqual(this.key);\n };\n\n return NoDocument;\n}(MaybeDocument);\n/**\r\n * A class representing an existing document whose data is unknown (e.g. a\r\n * document that was updated without a known base document).\r\n */\n\n\nvar UnknownDocument =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(UnknownDocument, _super);\n\n function UnknownDocument(key, version) {\n return _super.call(this, key, version) || this;\n }\n\n UnknownDocument.prototype.toString = function () {\n return \"UnknownDocument(\" + this.key + \", \" + this.version + \")\";\n };\n\n Object.defineProperty(UnknownDocument.prototype, \"hasPendingWrites\", {\n get: function get() {\n return true;\n },\n enumerable: true,\n configurable: true\n });\n\n UnknownDocument.prototype.isEqual = function (other) {\n return other instanceof UnknownDocument && other.version.isEqual(this.version) && other.key.isEqual(this.key);\n };\n\n return UnknownDocument;\n}(MaybeDocument);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// An immutable sorted map implementation, based on a Left-leaning Red-Black\n// tree.\n\n\nvar SortedMap =\n/** @class */\nfunction () {\n function SortedMap(comparator, root) {\n this.comparator = comparator;\n this.root = root ? root : LLRBNode.EMPTY;\n } // Returns a copy of the map, with the specified key/value added or replaced.\n\n\n SortedMap.prototype.insert = function (key, value) {\n return new SortedMap(this.comparator, this.root.insert(key, value, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n }; // Returns a copy of the map, with the specified key removed.\n\n\n SortedMap.prototype.remove = function (key) {\n return new SortedMap(this.comparator, this.root.remove(key, this.comparator).copy(null, null, LLRBNode.BLACK, null, null));\n }; // Returns the value of the node with the given key, or null.\n\n\n SortedMap.prototype.get = function (key) {\n var node = this.root;\n\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n\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\n return null;\n }; // Returns the index of the element in this sorted map, or -1 if it doesn't\n // exist.\n\n\n SortedMap.prototype.indexOf = function (key) {\n // Number of nodes that were pruned when descending right\n var prunedNodes = 0;\n var node = this.root;\n\n while (!node.isEmpty()) {\n var cmp = this.comparator(key, node.key);\n\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 } // Node not found\n\n\n return -1;\n };\n\n SortedMap.prototype.isEmpty = function () {\n return this.root.isEmpty();\n };\n\n Object.defineProperty(SortedMap.prototype, \"size\", {\n // Returns the total number of nodes in the map.\n get: function get() {\n return this.root.size;\n },\n enumerable: true,\n configurable: true\n }); // Returns the minimum key in the map.\n\n SortedMap.prototype.minKey = function () {\n return this.root.minKey();\n }; // Returns the maximum key in the map.\n\n\n SortedMap.prototype.maxKey = function () {\n return this.root.maxKey();\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\n\n SortedMap.prototype.inorderTraversal = function (action) {\n return this.root.inorderTraversal(action);\n };\n\n SortedMap.prototype.forEach = function (fn) {\n this.inorderTraversal(function (k, v) {\n fn(k, v);\n return false;\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\n\n SortedMap.prototype.reverseTraversal = function (action) {\n return this.root.reverseTraversal(action);\n }; // Returns an iterator over the SortedMap.\n\n\n SortedMap.prototype.getIterator = function () {\n return new SortedMapIterator(this.root, null, this.comparator, false);\n };\n\n SortedMap.prototype.getIteratorFrom = function (key) {\n return new SortedMapIterator(this.root, key, this.comparator, false);\n };\n\n SortedMap.prototype.getReverseIterator = function () {\n return new SortedMapIterator(this.root, null, this.comparator, true);\n };\n\n SortedMap.prototype.getReverseIteratorFrom = function (key) {\n return new SortedMapIterator(this.root, key, this.comparator, true);\n };\n\n return SortedMap;\n}(); // end SortedMap\n// An iterator over an LLRBNode.\n\n\nvar SortedMapIterator =\n/** @class */\nfunction () {\n function SortedMapIterator(node, startKey, comparator, isReverse) {\n this.isReverse = isReverse;\n this.nodeStack = [];\n var cmp = 1;\n\n while (!node.isEmpty()) {\n cmp = startKey ? comparator(node.key, startKey) : 1; // flip the comparison if we're going in reverse\n\n if (isReverse) cmp *= -1;\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\n if (this.isReverse) {\n node = node.right;\n } else {\n node = node.left;\n }\n }\n }\n }\n\n SortedMapIterator.prototype.getNext = function () {\n assert(this.nodeStack.length > 0, 'getNext() called on iterator when hasNext() is false.');\n var node = this.nodeStack.pop();\n var result = {\n key: node.key,\n value: node.value\n };\n\n if (this.isReverse) {\n node = node.left;\n\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.right;\n }\n } else {\n node = node.right;\n\n while (!node.isEmpty()) {\n this.nodeStack.push(node);\n node = node.left;\n }\n }\n\n return result;\n };\n\n SortedMapIterator.prototype.hasNext = function () {\n return this.nodeStack.length > 0;\n };\n\n SortedMapIterator.prototype.peek = function () {\n if (this.nodeStack.length === 0) return null;\n var node = this.nodeStack[this.nodeStack.length - 1];\n return {\n key: node.key,\n value: node.value\n };\n };\n\n return SortedMapIterator;\n}(); // end SortedMapIterator\n// Represents a node in a Left-leaning Red-Black tree.\n\n\nvar LLRBNode =\n/** @class */\nfunction () {\n function LLRBNode(key, value, color, left, right) {\n this.key = key;\n this.value = value;\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 } // Returns a copy of the current node, optionally replacing pieces of it.\n\n\n LLRBNode.prototype.copy = function (key, value, color, left, right) {\n return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);\n };\n\n LLRBNode.prototype.isEmpty = function () {\n return false;\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\n\n LLRBNode.prototype.inorderTraversal = function (action) {\n return this.left.inorderTraversal(action) || action(this.key, this.value) || this.right.inorderTraversal(action);\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\n\n LLRBNode.prototype.reverseTraversal = function (action) {\n return this.right.reverseTraversal(action) || action(this.key, this.value) || this.left.reverseTraversal(action);\n }; // Returns the minimum node in the tree.\n\n\n LLRBNode.prototype.min = function () {\n if (this.left.isEmpty()) {\n return this;\n } else {\n return this.left.min();\n }\n }; // Returns the maximum key in the tree.\n\n\n LLRBNode.prototype.minKey = function () {\n return this.min().key;\n }; // Returns the maximum key in the tree.\n\n\n LLRBNode.prototype.maxKey = function () {\n if (this.right.isEmpty()) {\n return this.key;\n } else {\n return this.right.maxKey();\n }\n }; // Returns new tree, with the key/value added.\n\n\n LLRBNode.prototype.insert = function (key, value, comparator) {\n var n = this;\n var cmp = comparator(key, n.key);\n\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(null, null, null, null, n.right.insert(key, value, comparator));\n }\n\n return n.fixUp();\n };\n\n LLRBNode.prototype.removeMin = function () {\n if (this.left.isEmpty()) {\n return LLRBNode.EMPTY;\n }\n\n var n = this;\n if (!n.left.isRed() && !n.left.left.isRed()) n = n.moveRedLeft();\n n = n.copy(null, null, null, n.left.removeMin(), null);\n return n.fixUp();\n }; // Returns new tree, with the specified item removed.\n\n\n LLRBNode.prototype.remove = function (key, comparator) {\n var smallest;\n var n = this;\n\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 = n.copy(null, null, null, n.left.remove(key, comparator), null);\n } else {\n if (n.left.isRed()) n = n.rotateRight();\n\n if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) {\n n = n.moveRedRight();\n }\n\n if (comparator(key, n.key) === 0) {\n if (n.right.isEmpty()) {\n return LLRBNode.EMPTY;\n } else {\n smallest = n.right.min();\n n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin());\n }\n }\n\n n = n.copy(null, null, null, null, n.right.remove(key, comparator));\n }\n\n return n.fixUp();\n };\n\n LLRBNode.prototype.isRed = function () {\n return this.color;\n }; // Returns new tree after performing any needed rotations.\n\n\n LLRBNode.prototype.fixUp = function () {\n var n = this;\n if (n.right.isRed() && !n.left.isRed()) n = n.rotateLeft();\n if (n.left.isRed() && n.left.left.isRed()) n = n.rotateRight();\n if (n.left.isRed() && n.right.isRed()) n = n.colorFlip();\n return n;\n };\n\n LLRBNode.prototype.moveRedLeft = function () {\n var n = this.colorFlip();\n\n if (n.right.left.isRed()) {\n n = n.copy(null, null, null, null, n.right.rotateRight());\n n = n.rotateLeft();\n n = n.colorFlip();\n }\n\n return n;\n };\n\n LLRBNode.prototype.moveRedRight = function () {\n var n = this.colorFlip();\n\n if (n.left.left.isRed()) {\n n = n.rotateRight();\n n = n.colorFlip();\n }\n\n return n;\n };\n\n LLRBNode.prototype.rotateLeft = function () {\n var nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);\n return this.right.copy(null, null, this.color, nl, null);\n };\n\n LLRBNode.prototype.rotateRight = function () {\n var nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);\n return this.left.copy(null, null, this.color, null, nr);\n };\n\n LLRBNode.prototype.colorFlip = function () {\n var left = this.left.copy(null, null, !this.left.color, null, null);\n var right = this.right.copy(null, null, !this.right.color, null, null);\n return this.copy(null, null, !this.color, left, right);\n }; // For testing.\n\n\n LLRBNode.prototype.checkMaxDepth = function () {\n var blackDepth = this.check();\n\n if (Math.pow(2.0, blackDepth) <= this.size + 1) {\n return true;\n } else {\n return false;\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\n\n LLRBNode.prototype.check = function () {\n if (this.isRed() && this.left.isRed()) {\n throw fail('Red node has red child(' + this.key + ',' + this.value + ')');\n }\n\n if (this.right.isRed()) {\n throw fail('Right child of (' + this.key + ',' + this.value + ') is red');\n }\n\n var blackDepth = this.left.check();\n\n if (blackDepth !== this.right.check()) {\n throw fail('Black depths differ');\n } else {\n return blackDepth + (this.isRed() ? 0 : 1);\n }\n }; // tslint:disable-next-line:no-any Empty node is shared between all LLRB trees.\n\n\n LLRBNode.EMPTY = null;\n LLRBNode.RED = true;\n LLRBNode.BLACK = false;\n return LLRBNode;\n}(); // end LLRBNode\n// Represents an empty node (a leaf node in the Red-Black Tree).\n\n\nvar LLRBEmptyNode =\n/** @class */\nfunction () {\n function LLRBEmptyNode() {\n this.size = 0;\n } // Returns a copy of the current node.\n\n\n LLRBEmptyNode.prototype.copy = function (key, value, color, left, right) {\n return this;\n }; // Returns a copy of the tree, with the specified key/value added.\n\n\n LLRBEmptyNode.prototype.insert = function (key, value, comparator) {\n return new LLRBNode(key, value);\n }; // Returns a copy of the tree, with the specified key removed.\n\n\n LLRBEmptyNode.prototype.remove = function (key, comparator) {\n return this;\n };\n\n LLRBEmptyNode.prototype.isEmpty = function () {\n return true;\n };\n\n LLRBEmptyNode.prototype.inorderTraversal = function (action) {\n return false;\n };\n\n LLRBEmptyNode.prototype.reverseTraversal = function (action) {\n return false;\n };\n\n LLRBEmptyNode.prototype.minKey = function () {\n return null;\n };\n\n LLRBEmptyNode.prototype.maxKey = function () {\n return null;\n };\n\n LLRBEmptyNode.prototype.isRed = function () {\n return false;\n }; // For testing.\n\n\n LLRBEmptyNode.prototype.checkMaxDepth = function () {\n return true;\n };\n\n LLRBEmptyNode.prototype.check = function () {\n return 0;\n };\n\n return LLRBEmptyNode;\n}(); // end LLRBEmptyNode\n\n\nLLRBNode.EMPTY = new LLRBEmptyNode();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar TypeOrder;\n\n(function (TypeOrder) {\n // This order is defined by the backend.\n TypeOrder[TypeOrder[\"NullValue\"] = 0] = \"NullValue\";\n TypeOrder[TypeOrder[\"BooleanValue\"] = 1] = \"BooleanValue\";\n TypeOrder[TypeOrder[\"NumberValue\"] = 2] = \"NumberValue\";\n TypeOrder[TypeOrder[\"TimestampValue\"] = 3] = \"TimestampValue\";\n TypeOrder[TypeOrder[\"StringValue\"] = 4] = \"StringValue\";\n TypeOrder[TypeOrder[\"BlobValue\"] = 5] = \"BlobValue\";\n TypeOrder[TypeOrder[\"RefValue\"] = 6] = \"RefValue\";\n TypeOrder[TypeOrder[\"GeoPointValue\"] = 7] = \"GeoPointValue\";\n TypeOrder[TypeOrder[\"ArrayValue\"] = 8] = \"ArrayValue\";\n TypeOrder[TypeOrder[\"ObjectValue\"] = 9] = \"ObjectValue\";\n})(TypeOrder || (TypeOrder = {}));\n/** Defines the return value for pending server timestamps. */\n\n\nvar ServerTimestampBehavior;\n\n(function (ServerTimestampBehavior) {\n ServerTimestampBehavior[ServerTimestampBehavior[\"Default\"] = 0] = \"Default\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Estimate\"] = 1] = \"Estimate\";\n ServerTimestampBehavior[ServerTimestampBehavior[\"Previous\"] = 2] = \"Previous\";\n})(ServerTimestampBehavior || (ServerTimestampBehavior = {}));\n/** Holds properties that define field value deserialization options. */\n\n\nvar FieldValueOptions =\n/** @class */\nfunction () {\n function FieldValueOptions(serverTimestampBehavior, timestampsInSnapshots) {\n this.serverTimestampBehavior = serverTimestampBehavior;\n this.timestampsInSnapshots = timestampsInSnapshots;\n }\n\n FieldValueOptions.fromSnapshotOptions = function (options, timestampsInSnapshots) {\n switch (options.serverTimestamps) {\n case 'estimate':\n return new FieldValueOptions(ServerTimestampBehavior.Estimate, timestampsInSnapshots);\n\n case 'previous':\n return new FieldValueOptions(ServerTimestampBehavior.Previous, timestampsInSnapshots);\n\n case 'none': // Fall-through intended.\n\n case undefined:\n return new FieldValueOptions(ServerTimestampBehavior.Default, timestampsInSnapshots);\n\n default:\n return fail('fromSnapshotOptions() called with invalid options.');\n }\n };\n\n return FieldValueOptions;\n}();\n/**\r\n * A field value represents a datatype as stored by Firestore.\r\n */\n\n\nvar FieldValue =\n/** @class */\nfunction () {\n function FieldValue() {}\n\n FieldValue.prototype.toString = function () {\n var val = this.value();\n return val === null ? 'null' : val.toString();\n };\n\n FieldValue.prototype.defaultCompareTo = function (other) {\n assert(this.typeOrder !== other.typeOrder, 'Default compareTo should not be used for values of same type.');\n var cmp = primitiveComparator(this.typeOrder, other.typeOrder);\n return cmp;\n };\n\n return FieldValue;\n}();\n\nvar NullValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(NullValue, _super);\n\n function NullValue() {\n var _this = _super.call(this) || this;\n\n _this.typeOrder = TypeOrder.NullValue; // internalValue is unused but we add it to work around\n // https://github.com/Microsoft/TypeScript/issues/15585\n\n _this.internalValue = null;\n return _this;\n }\n\n NullValue.prototype.value = function (options) {\n return null;\n };\n\n NullValue.prototype.isEqual = function (other) {\n return other instanceof NullValue;\n };\n\n NullValue.prototype.compareTo = function (other) {\n if (other instanceof NullValue) {\n return 0;\n }\n\n return this.defaultCompareTo(other);\n };\n\n NullValue.INSTANCE = new NullValue();\n return NullValue;\n}(FieldValue);\n\nvar BooleanValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(BooleanValue, _super);\n\n function BooleanValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BooleanValue;\n return _this;\n }\n\n BooleanValue.prototype.value = function (options) {\n return this.internalValue;\n };\n\n BooleanValue.prototype.isEqual = function (other) {\n return other instanceof BooleanValue && this.internalValue === other.internalValue;\n };\n\n BooleanValue.prototype.compareTo = function (other) {\n if (other instanceof BooleanValue) {\n return primitiveComparator(this, other);\n }\n\n return this.defaultCompareTo(other);\n };\n\n BooleanValue.of = function (value) {\n return value ? BooleanValue.TRUE : BooleanValue.FALSE;\n };\n\n BooleanValue.TRUE = new BooleanValue(true);\n BooleanValue.FALSE = new BooleanValue(false);\n return BooleanValue;\n}(FieldValue);\n/** Base class for IntegerValue and DoubleValue. */\n\n\nvar NumberValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(NumberValue, _super);\n\n function NumberValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.NumberValue;\n return _this;\n }\n\n NumberValue.prototype.value = function (options) {\n return this.internalValue;\n };\n\n NumberValue.prototype.compareTo = function (other) {\n if (other instanceof NumberValue) {\n return numericComparator(this.internalValue, other.internalValue);\n }\n\n return this.defaultCompareTo(other);\n };\n\n return NumberValue;\n}(FieldValue);\n/** Utility function to compare doubles (using Firestore semantics for NaN). */\n\n\nfunction numericComparator(left, right) {\n if (left < right) {\n return -1;\n } else if (left > right) {\n return 1;\n } else if (left === right) {\n return 0;\n } else {\n // one or both are NaN.\n if (isNaN(left)) {\n return isNaN(right) ? 0 : -1;\n } else {\n return 1;\n }\n }\n}\n/**\r\n * Utility function to check numbers for equality using Firestore semantics\r\n * (NaN === NaN, -0.0 !== 0.0).\r\n */\n\n\nfunction numericEquals(left, right) {\n // Implemented based on Object.is() polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n if (left === right) {\n // +0 != -0\n return left !== 0 || 1 / left === 1 / right;\n } else {\n // NaN == NaN\n return left !== left && right !== right;\n }\n}\n\nvar IntegerValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(IntegerValue, _super);\n\n function IntegerValue(internalValue) {\n return _super.call(this, internalValue) || this;\n }\n\n IntegerValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof IntegerValue) {\n return numericEquals(this.internalValue, other.internalValue);\n } else {\n return false;\n }\n };\n\n return IntegerValue;\n}(NumberValue);\n\nvar DoubleValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(DoubleValue, _super);\n\n function DoubleValue(internalValue) {\n var _this = _super.call(this, internalValue) || this;\n\n _this.internalValue = internalValue;\n return _this;\n }\n\n DoubleValue.prototype.isEqual = function (other) {\n // NOTE: DoubleValue and IntegerValue instances may compareTo() the same,\n // but that doesn't make them equal via isEqual().\n if (other instanceof DoubleValue) {\n return numericEquals(this.internalValue, other.internalValue);\n } else {\n return false;\n }\n };\n\n DoubleValue.NAN = new DoubleValue(NaN);\n DoubleValue.POSITIVE_INFINITY = new DoubleValue(Infinity);\n DoubleValue.NEGATIVE_INFINITY = new DoubleValue(-Infinity);\n return DoubleValue;\n}(NumberValue); // TODO(b/37267885): Add truncation support\n\n\nvar StringValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(StringValue, _super);\n\n function StringValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.StringValue;\n return _this;\n }\n\n StringValue.prototype.value = function (options) {\n return this.internalValue;\n };\n\n StringValue.prototype.isEqual = function (other) {\n return other instanceof StringValue && this.internalValue === other.internalValue;\n };\n\n StringValue.prototype.compareTo = function (other) {\n if (other instanceof StringValue) {\n return primitiveComparator(this.internalValue, other.internalValue);\n }\n\n return this.defaultCompareTo(other);\n };\n\n return StringValue;\n}(FieldValue);\n\nvar TimestampValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(TimestampValue, _super);\n\n function TimestampValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n\n TimestampValue.prototype.value = function (options) {\n if (options && options.timestampsInSnapshots) {\n return this.internalValue;\n } else {\n return this.internalValue.toDate();\n }\n };\n\n TimestampValue.prototype.isEqual = function (other) {\n return other instanceof TimestampValue && this.internalValue.isEqual(other.internalValue);\n };\n\n TimestampValue.prototype.compareTo = function (other) {\n if (other instanceof TimestampValue) {\n return this.internalValue._compareTo(other.internalValue);\n } else if (other instanceof ServerTimestampValue) {\n // Concrete timestamps come before server timestamps.\n return -1;\n } else {\n return this.defaultCompareTo(other);\n }\n };\n\n return TimestampValue;\n}(FieldValue);\n/**\r\n * Represents a locally-applied ServerTimestamp.\r\n *\r\n * Notes:\r\n * - ServerTimestampValue instances are created as the result of applying a\r\n * TransformMutation (see TransformMutation.applyTo()). They can only exist in\r\n * the local view of a document. Therefore they do not need to be parsed or\r\n * serialized.\r\n * - When evaluated locally (e.g. for snapshot.data()), they by default\r\n * evaluate to `null`. This behavior can be configured by passing custom\r\n * FieldValueOptions to value().\r\n * - With respect to other ServerTimestampValues, they sort by their\r\n * localWriteTime.\r\n */\n\n\nvar ServerTimestampValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ServerTimestampValue, _super);\n\n function ServerTimestampValue(localWriteTime, previousValue) {\n var _this = _super.call(this) || this;\n\n _this.localWriteTime = localWriteTime;\n _this.previousValue = previousValue;\n _this.typeOrder = TypeOrder.TimestampValue;\n return _this;\n }\n\n ServerTimestampValue.prototype.value = function (options) {\n if (options && options.serverTimestampBehavior === ServerTimestampBehavior.Estimate) {\n return new TimestampValue(this.localWriteTime).value(options);\n } else if (options && options.serverTimestampBehavior === ServerTimestampBehavior.Previous) {\n return this.previousValue ? this.previousValue.value(options) : null;\n } else {\n return null;\n }\n };\n\n ServerTimestampValue.prototype.isEqual = function (other) {\n return other instanceof ServerTimestampValue && this.localWriteTime.isEqual(other.localWriteTime);\n };\n\n ServerTimestampValue.prototype.compareTo = function (other) {\n if (other instanceof ServerTimestampValue) {\n return this.localWriteTime._compareTo(other.localWriteTime);\n } else if (other instanceof TimestampValue) {\n // Server timestamps come after all concrete timestamps.\n return 1;\n } else {\n return this.defaultCompareTo(other);\n }\n };\n\n ServerTimestampValue.prototype.toString = function () {\n return '';\n };\n\n return ServerTimestampValue;\n}(FieldValue);\n\nvar BlobValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(BlobValue, _super);\n\n function BlobValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.BlobValue;\n return _this;\n }\n\n BlobValue.prototype.value = function (options) {\n return this.internalValue;\n };\n\n BlobValue.prototype.isEqual = function (other) {\n return other instanceof BlobValue && this.internalValue.isEqual(other.internalValue);\n };\n\n BlobValue.prototype.compareTo = function (other) {\n if (other instanceof BlobValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n\n return this.defaultCompareTo(other);\n };\n\n return BlobValue;\n}(FieldValue);\n\nvar RefValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(RefValue, _super);\n\n function RefValue(databaseId, key) {\n var _this = _super.call(this) || this;\n\n _this.databaseId = databaseId;\n _this.key = key;\n _this.typeOrder = TypeOrder.RefValue;\n return _this;\n }\n\n RefValue.prototype.value = function (options) {\n return this.key;\n };\n\n RefValue.prototype.isEqual = function (other) {\n if (other instanceof RefValue) {\n return this.key.isEqual(other.key) && this.databaseId.isEqual(other.databaseId);\n } else {\n return false;\n }\n };\n\n RefValue.prototype.compareTo = function (other) {\n if (other instanceof RefValue) {\n var cmp = this.databaseId.compareTo(other.databaseId);\n return cmp !== 0 ? cmp : DocumentKey.comparator(this.key, other.key);\n }\n\n return this.defaultCompareTo(other);\n };\n\n return RefValue;\n}(FieldValue);\n\nvar GeoPointValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(GeoPointValue, _super);\n\n function GeoPointValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.GeoPointValue;\n return _this;\n }\n\n GeoPointValue.prototype.value = function (options) {\n return this.internalValue;\n };\n\n GeoPointValue.prototype.isEqual = function (other) {\n return other instanceof GeoPointValue && this.internalValue.isEqual(other.internalValue);\n };\n\n GeoPointValue.prototype.compareTo = function (other) {\n if (other instanceof GeoPointValue) {\n return this.internalValue._compareTo(other.internalValue);\n }\n\n return this.defaultCompareTo(other);\n };\n\n return GeoPointValue;\n}(FieldValue);\n\nvar ObjectValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ObjectValue, _super);\n\n function ObjectValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ObjectValue;\n return _this;\n }\n\n ObjectValue.prototype.value = function (options) {\n var result = {};\n this.internalValue.inorderTraversal(function (key, val) {\n result[key] = val.value(options);\n });\n return result;\n };\n\n ObjectValue.prototype.forEach = function (action) {\n this.internalValue.inorderTraversal(action);\n };\n\n ObjectValue.prototype.isEqual = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n\n if (next1.key !== next2.key || !next1.value.isEqual(next2.value)) {\n return false;\n }\n }\n\n return !it1.hasNext() && !it2.hasNext();\n }\n\n return false;\n };\n\n ObjectValue.prototype.compareTo = function (other) {\n if (other instanceof ObjectValue) {\n var it1 = this.internalValue.getIterator();\n var it2 = other.internalValue.getIterator();\n\n while (it1.hasNext() && it2.hasNext()) {\n var next1 = it1.getNext();\n var next2 = it2.getNext();\n var cmp = primitiveComparator(next1.key, next2.key) || next1.value.compareTo(next2.value);\n\n if (cmp) {\n return cmp;\n }\n } // Only equal if both iterators are exhausted\n\n\n return primitiveComparator(it1.hasNext(), it2.hasNext());\n } else {\n return this.defaultCompareTo(other);\n }\n };\n\n ObjectValue.prototype.set = function (path, to) {\n assert(!path.isEmpty(), 'Cannot set field for empty path on ObjectValue');\n\n if (path.length === 1) {\n return this.setChild(path.firstSegment(), to);\n } else {\n var child = this.child(path.firstSegment());\n\n if (!(child instanceof ObjectValue)) {\n child = ObjectValue.EMPTY;\n }\n\n var newChild = child.set(path.popFirst(), to);\n return this.setChild(path.firstSegment(), newChild);\n }\n };\n\n ObjectValue.prototype.delete = function (path) {\n assert(!path.isEmpty(), 'Cannot delete field for empty path on ObjectValue');\n\n if (path.length === 1) {\n return new ObjectValue(this.internalValue.remove(path.firstSegment()));\n } else {\n // nested field\n var child = this.child(path.firstSegment());\n\n if (child instanceof ObjectValue) {\n var newChild = child.delete(path.popFirst());\n return new ObjectValue(this.internalValue.insert(path.firstSegment(), newChild));\n } else {\n // Don't actually change a primitive value to an object for a delete\n return this;\n }\n }\n };\n\n ObjectValue.prototype.contains = function (path) {\n return this.field(path) !== undefined;\n };\n\n ObjectValue.prototype.field = function (path) {\n assert(!path.isEmpty(), \"Can't get field of empty path\");\n var field = this;\n path.forEach(function (pathSegment) {\n if (field instanceof ObjectValue) {\n field = field.internalValue.get(pathSegment) || undefined;\n } else {\n field = undefined;\n }\n });\n return field;\n };\n\n ObjectValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n\n ObjectValue.prototype.child = function (childName) {\n return this.internalValue.get(childName) || undefined;\n };\n\n ObjectValue.prototype.setChild = function (childName, value) {\n return new ObjectValue(this.internalValue.insert(childName, value));\n };\n\n ObjectValue.EMPTY = new ObjectValue(new SortedMap(primitiveComparator));\n return ObjectValue;\n}(FieldValue);\n\nvar ArrayValue =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ArrayValue, _super);\n\n function ArrayValue(internalValue) {\n var _this = _super.call(this) || this;\n\n _this.internalValue = internalValue;\n _this.typeOrder = TypeOrder.ArrayValue;\n return _this;\n }\n\n ArrayValue.prototype.value = function (options) {\n return this.internalValue.map(function (v) {\n return v.value(options);\n });\n };\n\n ArrayValue.prototype.forEach = function (action) {\n this.internalValue.forEach(action);\n };\n\n ArrayValue.prototype.isEqual = function (other) {\n if (other instanceof ArrayValue) {\n if (this.internalValue.length !== other.internalValue.length) {\n return false;\n }\n\n for (var i = 0; i < this.internalValue.length; i++) {\n if (!this.internalValue[i].isEqual(other.internalValue[i])) {\n return false;\n }\n }\n\n return true;\n }\n\n return false;\n };\n\n ArrayValue.prototype.compareTo = function (other) {\n if (other instanceof ArrayValue) {\n var minLength = Math.min(this.internalValue.length, other.internalValue.length);\n\n for (var i = 0; i < minLength; i++) {\n var cmp = this.internalValue[i].compareTo(other.internalValue[i]);\n\n if (cmp) {\n return cmp;\n }\n }\n\n return primitiveComparator(this.internalValue.length, other.internalValue.length);\n } else {\n return this.defaultCompareTo(other);\n }\n };\n\n ArrayValue.prototype.toString = function () {\n return JSON.stringify(this.value());\n };\n\n return ArrayValue;\n}(FieldValue);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// Untyped Number alias we can use to check for ES6 methods / properties.\n// tslint:disable-next-line:no-any variable-name\n\n\nvar NumberAsAny = Number;\n/**\r\n * Minimum safe integer in Javascript because of floating point precision.\r\n * Added to not rely on ES6 features.\r\n */\n\nvar MIN_SAFE_INTEGER = NumberAsAny.MIN_SAFE_INTEGER || -(Math.pow(2, 53) - 1);\n/**\r\n * Maximum safe integer in Javascript because of floating point precision.\r\n * Added to not rely on ES6 features.\r\n */\n\nvar MAX_SAFE_INTEGER = NumberAsAny.MAX_SAFE_INTEGER || Math.pow(2, 53) - 1;\n/**\r\n * Returns whether an number is an integer, uses native implementation if\r\n * available.\r\n * Added to not rely on ES6 features.\r\n * @param value The value to test for being an integer\r\n */\n\nvar isInteger = NumberAsAny.isInteger || function (value) {\n return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;\n};\n/**\r\n * Returns whether a variable is either undefined or null.\r\n */\n\n\nfunction isNullOrUndefined(value) {\n return value === null || value === undefined;\n}\n/**\r\n * Returns whether a value is an integer and in the safe integer range\r\n * @param value The value to test for being an integer and in the safe range\r\n */\n\n\nfunction isSafeInteger(value) {\n return isInteger(value) && value <= MAX_SAFE_INTEGER && value >= MIN_SAFE_INTEGER;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar Query =\n/** @class */\nfunction () {\n function Query(path, explicitOrderBy, filters, limit, startAt, endAt) {\n if (explicitOrderBy === void 0) {\n explicitOrderBy = [];\n }\n\n if (filters === void 0) {\n filters = [];\n }\n\n if (limit === void 0) {\n limit = null;\n }\n\n if (startAt === void 0) {\n startAt = null;\n }\n\n if (endAt === void 0) {\n endAt = null;\n }\n\n this.path = path;\n this.explicitOrderBy = explicitOrderBy;\n this.filters = filters;\n this.limit = limit;\n this.startAt = startAt;\n this.endAt = endAt;\n this.memoizedCanonicalId = null;\n this.memoizedOrderBy = null;\n\n if (this.startAt) {\n this.assertValidBound(this.startAt);\n }\n\n if (this.endAt) {\n this.assertValidBound(this.endAt);\n }\n }\n\n Query.atPath = function (path) {\n return new Query(path);\n };\n\n Object.defineProperty(Query.prototype, \"orderBy\", {\n get: function get() {\n if (this.memoizedOrderBy === null) {\n var inequalityField = this.getInequalityFilterField();\n var firstOrderByField = this.getFirstOrderByField();\n\n if (inequalityField !== null && firstOrderByField === null) {\n // In order to implicitly add key ordering, we must also add the\n // inequality filter field for it to be a valid query.\n // Note that the default inequality field and key ordering is ascending.\n if (inequalityField.isKeyField()) {\n this.memoizedOrderBy = [KEY_ORDERING_ASC];\n } else {\n this.memoizedOrderBy = [new OrderBy(inequalityField), KEY_ORDERING_ASC];\n }\n } else {\n assert(inequalityField === null || firstOrderByField !== null && inequalityField.isEqual(firstOrderByField), 'First orderBy should match inequality field.');\n this.memoizedOrderBy = [];\n var foundKeyOrdering = false;\n\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n this.memoizedOrderBy.push(orderBy);\n\n if (orderBy.field.isKeyField()) {\n foundKeyOrdering = true;\n }\n }\n\n if (!foundKeyOrdering) {\n // The order of the implicit key ordering always matches the last\n // explicit order by\n var lastDirection = this.explicitOrderBy.length > 0 ? this.explicitOrderBy[this.explicitOrderBy.length - 1].dir : Direction.ASCENDING;\n this.memoizedOrderBy.push(lastDirection === Direction.ASCENDING ? KEY_ORDERING_ASC : KEY_ORDERING_DESC);\n }\n }\n }\n\n return this.memoizedOrderBy;\n },\n enumerable: true,\n configurable: true\n });\n\n Query.prototype.addFilter = function (filter) {\n assert(this.getInequalityFilterField() == null || !(filter instanceof RelationFilter) || !filter.isInequality() || filter.field.isEqual(this.getInequalityFilterField()), 'Query must only have one inequality field.');\n assert(!DocumentKey.isDocumentKey(this.path), 'No filtering allowed for document query');\n var newFilters = this.filters.concat([filter]);\n return new Query(this.path, this.explicitOrderBy.slice(), newFilters, this.limit, this.startAt, this.endAt);\n };\n\n Query.prototype.addOrderBy = function (orderBy) {\n assert(!DocumentKey.isDocumentKey(this.path), 'No ordering allowed for document query');\n assert(!this.startAt && !this.endAt, 'Bounds must be set after orderBy'); // TODO(dimond): validate that orderBy does not list the same key twice.\n\n var newOrderBy = this.explicitOrderBy.concat([orderBy]);\n return new Query(this.path, newOrderBy, this.filters.slice(), this.limit, this.startAt, this.endAt);\n };\n\n Query.prototype.withLimit = function (limit) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), limit, this.startAt, this.endAt);\n };\n\n Query.prototype.withStartAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, bound, this.endAt);\n };\n\n Query.prototype.withEndAt = function (bound) {\n return new Query(this.path, this.explicitOrderBy.slice(), this.filters.slice(), this.limit, this.startAt, bound);\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.\n\n\n Query.prototype.canonicalId = function () {\n if (this.memoizedCanonicalId === null) {\n var canonicalId = this.path.canonicalString();\n canonicalId += '|f:';\n\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n canonicalId += filter.canonicalId();\n canonicalId += ',';\n }\n\n canonicalId += '|ob:'; // TODO(dimond): make this collision resistant\n\n for (var _b = 0, _c = this.orderBy; _b < _c.length; _b++) {\n var orderBy = _c[_b];\n canonicalId += orderBy.canonicalId();\n canonicalId += ',';\n }\n\n if (!isNullOrUndefined(this.limit)) {\n canonicalId += '|l:';\n canonicalId += this.limit;\n }\n\n if (this.startAt) {\n canonicalId += '|lb:';\n canonicalId += this.startAt.canonicalId();\n }\n\n if (this.endAt) {\n canonicalId += '|ub:';\n canonicalId += this.endAt.canonicalId();\n }\n\n this.memoizedCanonicalId = canonicalId;\n }\n\n return this.memoizedCanonicalId;\n };\n\n Query.prototype.toString = function () {\n var str = 'Query(' + this.path.canonicalString();\n\n if (this.filters.length > 0) {\n str += \", filters: [\" + this.filters.join(', ') + \"]\";\n }\n\n if (!isNullOrUndefined(this.limit)) {\n str += ', limit: ' + this.limit;\n }\n\n if (this.explicitOrderBy.length > 0) {\n str += \", orderBy: [\" + this.explicitOrderBy.join(', ') + \"]\";\n }\n\n if (this.startAt) {\n str += ', startAt: ' + this.startAt.canonicalId();\n }\n\n if (this.endAt) {\n str += ', endAt: ' + this.endAt.canonicalId();\n }\n\n return str + ')';\n };\n\n Query.prototype.isEqual = function (other) {\n if (this.limit !== other.limit) {\n return false;\n }\n\n if (this.orderBy.length !== other.orderBy.length) {\n return false;\n }\n\n for (var i = 0; i < this.orderBy.length; i++) {\n if (!this.orderBy[i].isEqual(other.orderBy[i])) {\n return false;\n }\n }\n\n if (this.filters.length !== other.filters.length) {\n return false;\n }\n\n for (var i = 0; i < this.filters.length; i++) {\n if (!this.filters[i].isEqual(other.filters[i])) {\n return false;\n }\n }\n\n if (!this.path.isEqual(other.path)) {\n return false;\n }\n\n if (this.startAt !== null ? !this.startAt.isEqual(other.startAt) : other.startAt !== null) {\n return false;\n }\n\n return this.endAt !== null ? this.endAt.isEqual(other.endAt) : other.endAt === null;\n };\n\n Query.prototype.docComparator = function (d1, d2) {\n var comparedOnKeyField = false;\n\n for (var _i = 0, _a = this.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n var comp = orderBy.compare(d1, d2);\n if (comp !== 0) return comp;\n comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField();\n } // Assert that we actually compared by key\n\n\n assert(comparedOnKeyField, \"orderBy used that doesn't compare on key field\");\n return 0;\n };\n\n Query.prototype.matches = function (doc) {\n return this.matchesAncestor(doc) && this.matchesOrderBy(doc) && this.matchesFilters(doc) && this.matchesBounds(doc);\n };\n\n Query.prototype.hasLimit = function () {\n return !isNullOrUndefined(this.limit);\n };\n\n Query.prototype.getFirstOrderByField = function () {\n return this.explicitOrderBy.length > 0 ? this.explicitOrderBy[0].field : null;\n };\n\n Query.prototype.getInequalityFilterField = function () {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n\n if (filter instanceof RelationFilter && filter.isInequality()) {\n return filter.field;\n }\n }\n\n return null;\n };\n\n Query.prototype.hasArrayContainsFilter = function () {\n return this.filters.find(function (filter) {\n return filter instanceof RelationFilter && filter.op === RelationOp.ARRAY_CONTAINS;\n }) !== undefined;\n };\n\n Query.prototype.isDocumentQuery = function () {\n return DocumentKey.isDocumentKey(this.path) && this.filters.length === 0;\n };\n\n Query.prototype.matchesAncestor = function (doc) {\n var docPath = doc.key.path;\n\n if (DocumentKey.isDocumentKey(this.path)) {\n // exact match for document queries\n return this.path.isEqual(docPath);\n } else {\n // shallow ancestor queries by default\n return this.path.isPrefixOf(docPath) && this.path.length === docPath.length - 1;\n }\n };\n /**\r\n * A document must have a value for every ordering clause in order to show up\r\n * in the results.\r\n */\n\n\n Query.prototype.matchesOrderBy = function (doc) {\n for (var _i = 0, _a = this.explicitOrderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i]; // order by key always matches\n\n if (!orderBy.field.isKeyField() && doc.field(orderBy.field) === undefined) {\n return false;\n }\n }\n\n return true;\n };\n\n Query.prototype.matchesFilters = function (doc) {\n for (var _i = 0, _a = this.filters; _i < _a.length; _i++) {\n var filter = _a[_i];\n\n if (!filter.matches(doc)) {\n return false;\n }\n }\n\n return true;\n };\n /**\r\n * Makes sure a document is within the bounds, if provided.\r\n */\n\n\n Query.prototype.matchesBounds = function (doc) {\n if (this.startAt && !this.startAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n\n if (this.endAt && this.endAt.sortsBeforeDocument(this.orderBy, doc)) {\n return false;\n }\n\n return true;\n };\n\n Query.prototype.assertValidBound = function (bound) {\n assert(bound.position.length <= this.orderBy.length, 'Bound is longer than orderBy');\n };\n\n return Query;\n}();\n\nvar Filter =\n/** @class */\nfunction () {\n function Filter() {}\n /**\r\n * Creates a filter based on the provided arguments.\r\n */\n\n\n Filter.create = function (field, op, value) {\n if (value.isEqual(NullValue.INSTANCE)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals comparisons on null.');\n }\n\n return new NullFilter(field);\n } else if (value.isEqual(DoubleValue.NAN)) {\n if (op !== RelationOp.EQUAL) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You can only perform equals comparisons on NaN.');\n }\n\n return new NanFilter(field);\n } else {\n return new RelationFilter(field, op, value);\n }\n };\n\n return Filter;\n}();\n\nvar RelationOp =\n/** @class */\nfunction () {\n function RelationOp(name) {\n this.name = name;\n }\n\n RelationOp.fromString = function (op) {\n switch (op) {\n case '<':\n return RelationOp.LESS_THAN;\n\n case '<=':\n return RelationOp.LESS_THAN_OR_EQUAL;\n\n case '==':\n return RelationOp.EQUAL;\n\n case '>=':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n\n case '>':\n return RelationOp.GREATER_THAN;\n\n case 'array-contains':\n return RelationOp.ARRAY_CONTAINS;\n\n default:\n return fail('Unknown relation: ' + op);\n }\n };\n\n RelationOp.prototype.toString = function () {\n return this.name;\n };\n\n RelationOp.prototype.isEqual = function (other) {\n return this.name === other.name;\n };\n\n RelationOp.LESS_THAN = new RelationOp('<');\n RelationOp.LESS_THAN_OR_EQUAL = new RelationOp('<=');\n RelationOp.EQUAL = new RelationOp('==');\n RelationOp.GREATER_THAN = new RelationOp('>');\n RelationOp.GREATER_THAN_OR_EQUAL = new RelationOp('>=');\n RelationOp.ARRAY_CONTAINS = new RelationOp('array-contains');\n return RelationOp;\n}();\n\nvar RelationFilter =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(RelationFilter, _super);\n\n function RelationFilter(field, op, value) {\n var _this = _super.call(this) || this;\n\n _this.field = field;\n _this.op = op;\n _this.value = value;\n return _this;\n }\n\n RelationFilter.prototype.matches = function (doc) {\n if (this.field.isKeyField()) {\n assert(this.value instanceof RefValue, 'Comparing on key, but filter value not a RefValue');\n assert(this.op !== RelationOp.ARRAY_CONTAINS, \"array-contains queries don't make sense on document keys.\");\n var refValue = this.value;\n var comparison = DocumentKey.comparator(doc.key, refValue.key);\n return this.matchesComparison(comparison);\n } else {\n var val = doc.field(this.field);\n return val !== undefined && this.matchesValue(val);\n }\n };\n\n RelationFilter.prototype.matchesValue = function (value) {\n var _this = this;\n\n if (this.op === RelationOp.ARRAY_CONTAINS) {\n return value instanceof ArrayValue && value.internalValue.find(function (element) {\n return element.isEqual(_this.value);\n }) !== undefined;\n } else {\n // Only compare types with matching backend order (such as double and int).\n return this.value.typeOrder === value.typeOrder && this.matchesComparison(value.compareTo(this.value));\n }\n };\n\n RelationFilter.prototype.matchesComparison = function (comparison) {\n switch (this.op) {\n case RelationOp.LESS_THAN:\n return comparison < 0;\n\n case RelationOp.LESS_THAN_OR_EQUAL:\n return comparison <= 0;\n\n case RelationOp.EQUAL:\n return comparison === 0;\n\n case RelationOp.GREATER_THAN:\n return comparison > 0;\n\n case RelationOp.GREATER_THAN_OR_EQUAL:\n return comparison >= 0;\n\n default:\n return fail('Unknown relation op' + this.op);\n }\n };\n\n RelationFilter.prototype.isInequality = function () {\n return this.op !== RelationOp.EQUAL && this.op !== RelationOp.ARRAY_CONTAINS;\n };\n\n RelationFilter.prototype.canonicalId = function () {\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 this.field.canonicalString() + this.op.toString() + this.value.toString();\n };\n\n RelationFilter.prototype.isEqual = function (other) {\n if (other instanceof RelationFilter) {\n return this.op.isEqual(other.op) && this.field.isEqual(other.field) && this.value.isEqual(other.value);\n } else {\n return false;\n }\n };\n\n RelationFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" \" + this.op + \" \" + this.value.value();\n };\n\n return RelationFilter;\n}(Filter);\n/**\r\n * Filter that matches 'null' values.\r\n */\n\n\nvar NullFilter =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(NullFilter, _super);\n\n function NullFilter(field) {\n var _this = _super.call(this) || this;\n\n _this.field = field;\n return _this;\n }\n\n NullFilter.prototype.matches = function (doc) {\n var val = doc.field(this.field);\n return val !== undefined && val.value() === null;\n };\n\n NullFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS null';\n };\n\n NullFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS null\";\n };\n\n NullFilter.prototype.isEqual = function (other) {\n if (other instanceof NullFilter) {\n return this.field.isEqual(other.field);\n } else {\n return false;\n }\n };\n\n return NullFilter;\n}(Filter);\n/**\r\n * Filter that matches 'NaN' values.\r\n */\n\n\nvar NanFilter =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(NanFilter, _super);\n\n function NanFilter(field) {\n var _this = _super.call(this) || this;\n\n _this.field = field;\n return _this;\n }\n\n NanFilter.prototype.matches = function (doc) {\n var field = doc.field(this.field);\n var val = field && field.value();\n return typeof val === 'number' && isNaN(val);\n };\n\n NanFilter.prototype.canonicalId = function () {\n return this.field.canonicalString() + ' IS NaN';\n };\n\n NanFilter.prototype.toString = function () {\n return this.field.canonicalString() + \" IS NaN\";\n };\n\n NanFilter.prototype.isEqual = function (other) {\n if (other instanceof NanFilter) {\n return this.field.isEqual(other.field);\n } else {\n return false;\n }\n };\n\n return NanFilter;\n}(Filter);\n/**\r\n * The direction of sorting in an order by.\r\n */\n\n\nvar Direction =\n/** @class */\nfunction () {\n function Direction(name) {\n this.name = name;\n }\n\n Direction.prototype.toString = function () {\n return this.name;\n };\n\n Direction.ASCENDING = new Direction('asc');\n Direction.DESCENDING = new Direction('desc');\n return Direction;\n}();\n/**\r\n * Represents a bound of a query.\r\n *\r\n * The bound is specified with the given components representing a position and\r\n * whether it's just before or just after the position (relative to whatever the\r\n * query order is).\r\n *\r\n * The position represents a logical index position for a query. It's a prefix\r\n * of values for the (potentially implicit) order by clauses of a query.\r\n *\r\n * Bound provides a function to determine whether a document comes before or\r\n * after a bound. This is influenced by whether the position is just before or\r\n * just after the provided values.\r\n */\n\n\nvar Bound =\n/** @class */\nfunction () {\n function Bound(position, before) {\n this.position = position;\n this.before = before;\n }\n\n Bound.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n var canonicalId = this.before ? 'b:' : 'a:';\n\n for (var _i = 0, _a = this.position; _i < _a.length; _i++) {\n var component = _a[_i];\n canonicalId += component.toString();\n }\n\n return canonicalId;\n };\n /**\r\n * Returns true if a document sorts before a bound using the provided sort\r\n * order.\r\n */\n\n\n Bound.prototype.sortsBeforeDocument = function (orderBy, doc) {\n assert(this.position.length <= orderBy.length, \"Bound has more components than query's orderBy\");\n var comparison = 0;\n\n for (var i = 0; i < this.position.length; i++) {\n var orderByComponent = orderBy[i];\n var component = this.position[i];\n\n if (orderByComponent.field.isKeyField()) {\n assert(component instanceof RefValue, 'Bound has a non-key value where the key path is being used.');\n comparison = DocumentKey.comparator(component.key, doc.key);\n } else {\n var docValue = doc.field(orderByComponent.field);\n assert(docValue !== undefined, 'Field should exist since document matched the orderBy already.');\n comparison = component.compareTo(docValue);\n }\n\n if (orderByComponent.dir === Direction.DESCENDING) {\n comparison = comparison * -1;\n }\n\n if (comparison !== 0) {\n break;\n }\n }\n\n return this.before ? comparison <= 0 : comparison < 0;\n };\n\n Bound.prototype.isEqual = function (other) {\n if (other === null) {\n return false;\n }\n\n if (this.before !== other.before || this.position.length !== other.position.length) {\n return false;\n }\n\n for (var i = 0; i < this.position.length; i++) {\n var thisPosition = this.position[i];\n var otherPosition = other.position[i];\n return thisPosition.isEqual(otherPosition);\n }\n\n return true;\n };\n\n return Bound;\n}();\n/**\r\n * An ordering on a field, in some Direction. Direction defaults to ASCENDING.\r\n */\n\n\nvar OrderBy =\n/** @class */\nfunction () {\n function OrderBy(field, dir) {\n this.field = field;\n\n if (dir === undefined) {\n dir = Direction.ASCENDING;\n }\n\n this.dir = dir;\n this.isKeyOrderBy = field.isKeyField();\n }\n\n OrderBy.prototype.compare = function (d1, d2) {\n var comparison = this.isKeyOrderBy ? Document.compareByKey(d1, d2) : Document.compareByField(this.field, d1, d2);\n\n switch (this.dir) {\n case Direction.ASCENDING:\n return comparison;\n\n case Direction.DESCENDING:\n return -1 * comparison;\n\n default:\n return fail('Unknown direction: ' + this.dir);\n }\n };\n\n OrderBy.prototype.canonicalId = function () {\n // TODO(b/29183165): Make this collision robust.\n return this.field.canonicalString() + this.dir.toString();\n };\n\n OrderBy.prototype.toString = function () {\n return this.field.canonicalString() + \" (\" + this.dir + \")\";\n };\n\n OrderBy.prototype.isEqual = function (other) {\n return this.dir === other.dir && this.field.isEqual(other.field);\n };\n\n return OrderBy;\n}();\n\nvar KEY_ORDERING_ASC = new OrderBy(FieldPath.keyField(), Direction.ASCENDING);\nvar KEY_ORDERING_DESC = new OrderBy(FieldPath.keyField(), Direction.DESCENDING);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * A version of a document in Firestore. This corresponds to the version\r\n * timestamp, such as update_time or read_time.\r\n */\n\nvar SnapshotVersion =\n/** @class */\nfunction () {\n function SnapshotVersion(timestamp) {\n this.timestamp = timestamp;\n } // TODO(b/34176344): Once we no longer need to use the old alpha protos,\n // delete this constructor and use a timestamp-backed version everywhere.\n\n\n SnapshotVersion.fromMicroseconds = function (value) {\n var seconds = Math.floor(value / 1e6);\n var nanos = value % 1e6 * 1e3;\n return new SnapshotVersion(new Timestamp(seconds, nanos));\n };\n\n SnapshotVersion.fromTimestamp = function (value) {\n return new SnapshotVersion(value);\n };\n\n SnapshotVersion.forDeletedDoc = function () {\n return SnapshotVersion.MIN;\n };\n\n SnapshotVersion.prototype.compareTo = function (other) {\n return this.timestamp._compareTo(other.timestamp);\n };\n\n SnapshotVersion.prototype.isEqual = function (other) {\n return this.timestamp.isEqual(other.timestamp);\n };\n /** Returns a number representation of the version for use in spec tests. */\n\n\n SnapshotVersion.prototype.toMicroseconds = function () {\n // Convert to microseconds.\n return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000;\n };\n\n SnapshotVersion.prototype.toString = function () {\n return 'SnapshotVersion(' + this.timestamp.toString() + ')';\n };\n\n SnapshotVersion.prototype.toTimestamp = function () {\n return this.timestamp;\n };\n\n SnapshotVersion.MIN = new SnapshotVersion(new Timestamp(0, 0));\n return SnapshotVersion;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/** An enumeration of the different purposes we have for queries. */\n\n\nvar QueryPurpose;\n\n(function (QueryPurpose) {\n /** A regular, normal query. */\n QueryPurpose[QueryPurpose[\"Listen\"] = 0] = \"Listen\";\n /**\r\n * The query was used to refill a query after an existence filter mismatch.\r\n */\n\n QueryPurpose[QueryPurpose[\"ExistenceFilterMismatch\"] = 1] = \"ExistenceFilterMismatch\";\n /** The query was used to resolve a limbo document. */\n\n QueryPurpose[QueryPurpose[\"LimboResolution\"] = 2] = \"LimboResolution\";\n})(QueryPurpose || (QueryPurpose = {}));\n/**\r\n * An immutable set of metadata that the local store tracks for each query.\r\n */\n\n\nvar QueryData =\n/** @class */\nfunction () {\n function QueryData(\n /** The query being listened to. */\n query,\n /**\r\n * The target ID to which the query corresponds; Assigned by the\r\n * LocalStore for user listens and by the SyncEngine for limbo watches.\r\n */\n targetId,\n /** The purpose of the query. */\n purpose,\n /** The sequence number of the last transaction during which this query data was modified */\n sequenceNumber,\n /** The latest snapshot version seen for this target. */\n snapshotVersion,\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data that\r\n * matches the query. The resume token essentially identifies a point in\r\n * time from which the server should resume sending results.\r\n */\n resumeToken) {\n if (snapshotVersion === void 0) {\n snapshotVersion = SnapshotVersion.MIN;\n }\n\n if (resumeToken === void 0) {\n resumeToken = emptyByteString();\n }\n\n this.query = query;\n this.targetId = targetId;\n this.purpose = purpose;\n this.sequenceNumber = sequenceNumber;\n this.snapshotVersion = snapshotVersion;\n this.resumeToken = resumeToken;\n }\n /**\r\n * Creates a new query data instance with an updated snapshot version and\r\n * resume token.\r\n */\n\n\n QueryData.prototype.copy = function (overwrite) {\n return new QueryData(this.query, this.targetId, this.purpose, overwrite.sequenceNumber === undefined ? this.sequenceNumber : overwrite.sequenceNumber, overwrite.snapshotVersion === undefined ? this.snapshotVersion : overwrite.snapshotVersion, overwrite.resumeToken === undefined ? this.resumeToken : overwrite.resumeToken);\n };\n\n QueryData.prototype.isEqual = function (other) {\n return this.targetId === other.targetId && this.purpose === other.purpose && this.sequenceNumber === other.sequenceNumber && this.snapshotVersion.isEqual(other.snapshotVersion) && this.resumeToken === other.resumeToken && this.query.isEqual(other.query);\n };\n\n return QueryData;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * SortedSet is an immutable (copy-on-write) collection that holds elements\r\n * in order specified by the provided comparator.\r\n *\r\n * NOTE: if provided comparator returns 0 for two elements, we consider them to\r\n * be equal!\r\n */\n\n\nvar SortedSet =\n/** @class */\nfunction () {\n function SortedSet(comparator) {\n this.comparator = comparator;\n this.data = new SortedMap(this.comparator);\n }\n /**\r\n * Creates a SortedSet from the keys of the map.\r\n * This is currently implemented as an O(n) copy.\r\n */\n\n\n SortedSet.fromMapKeys = function (map) {\n var keys = new SortedSet(map.comparator);\n map.forEach(function (key) {\n keys = keys.add(key);\n });\n return keys;\n };\n\n SortedSet.prototype.has = function (elem) {\n return this.data.get(elem) !== null;\n };\n\n SortedSet.prototype.first = function () {\n return this.data.minKey();\n };\n\n SortedSet.prototype.last = function () {\n return this.data.maxKey();\n };\n\n Object.defineProperty(SortedSet.prototype, \"size\", {\n get: function get() {\n return this.data.size;\n },\n enumerable: true,\n configurable: true\n });\n\n SortedSet.prototype.indexOf = function (elem) {\n return this.data.indexOf(elem);\n };\n /** Iterates elements in order defined by \"comparator\" */\n\n\n SortedSet.prototype.forEach = function (cb) {\n this.data.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */\n\n\n SortedSet.prototype.forEachInRange = function (range, cb) {\n var iter = this.data.getIteratorFrom(range[0]);\n\n while (iter.hasNext()) {\n var elem = iter.getNext();\n if (this.comparator(elem.key, range[1]) >= 0) return;\n cb(elem.key);\n }\n };\n /**\r\n * Iterates over `elem`s such that: start <= elem until false is returned.\r\n */\n\n\n SortedSet.prototype.forEachWhile = function (cb, start) {\n var iter;\n\n if (start !== undefined) {\n iter = this.data.getIteratorFrom(start);\n } else {\n iter = this.data.getIterator();\n }\n\n while (iter.hasNext()) {\n var elem = iter.getNext();\n var result = cb(elem.key);\n if (!result) return;\n }\n };\n /** Finds the least element greater than or equal to `elem`. */\n\n\n SortedSet.prototype.firstAfterOrEqual = function (elem) {\n var iter = this.data.getIteratorFrom(elem);\n return iter.hasNext() ? iter.getNext().key : null;\n };\n /** Inserts or updates an element */\n\n\n SortedSet.prototype.add = function (elem) {\n return this.copy(this.data.remove(elem).insert(elem, true));\n };\n /** Deletes an element */\n\n\n SortedSet.prototype.delete = function (elem) {\n if (!this.has(elem)) return this;\n return this.copy(this.data.remove(elem));\n };\n\n SortedSet.prototype.isEmpty = function () {\n return this.data.isEmpty();\n };\n\n SortedSet.prototype.unionWith = function (other) {\n var result = this;\n other.forEach(function (elem) {\n result = result.add(elem);\n });\n return result;\n };\n\n SortedSet.prototype.isEqual = function (other) {\n if (!(other instanceof SortedSet)) return false;\n if (this.size !== other.size) return false;\n var thisIt = this.data.getIterator();\n var otherIt = other.data.getIterator();\n\n while (thisIt.hasNext()) {\n var thisElem = thisIt.getNext().key;\n var otherElem = otherIt.getNext().key;\n if (this.comparator(thisElem, otherElem) !== 0) return false;\n }\n\n return true;\n };\n\n SortedSet.prototype.toArray = function () {\n var res = [];\n this.forEach(function (targetId) {\n res.push(targetId);\n });\n return res;\n };\n\n SortedSet.prototype.toString = function () {\n var result = [];\n this.forEach(function (elem) {\n return result.push(elem);\n });\n return 'SortedSet(' + result.toString() + ')';\n };\n\n SortedSet.prototype.copy = function (data) {\n var result = new SortedSet(this.comparator);\n result.data = data;\n return result;\n };\n\n return SortedSet;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Provides a set of fields that can be used to partially patch a document.\r\n * FieldMask is used in conjunction with ObjectValue.\r\n * Examples:\r\n * foo - Overwrites foo entirely with the provided value. If foo is not\r\n * present in the companion ObjectValue, the field is deleted.\r\n * foo.bar - Overwrites only the field bar of the object foo.\r\n * If foo is not an object, foo is replaced with an object\r\n * containing foo\r\n */\n\n\nvar FieldMask =\n/** @class */\nfunction () {\n function FieldMask(fields) {\n this.fields = fields; // TODO(dimond): validation of FieldMask\n }\n\n FieldMask.fromArray = function (fields) {\n var fieldsAsSet = new SortedSet(FieldPath.comparator);\n fields.forEach(function (fieldPath) {\n return fieldsAsSet = fieldsAsSet.add(fieldPath);\n });\n return new FieldMask(fieldsAsSet);\n };\n /**\r\n * Verifies that `fieldPath` is included by at least one field in this field\r\n * mask.\r\n *\r\n * This is an O(n) operation, where `n` is the size of the field mask.\r\n */\n\n\n FieldMask.prototype.covers = function (fieldPath) {\n var found = false;\n this.fields.forEach(function (fieldMaskPath) {\n if (fieldMaskPath.isPrefixOf(fieldPath)) {\n found = true;\n }\n });\n return found;\n };\n\n FieldMask.prototype.isEqual = function (other) {\n return this.fields.isEqual(other.fields);\n };\n\n return FieldMask;\n}();\n/** A field path and the TransformOperation to perform upon it. */\n\n\nvar FieldTransform =\n/** @class */\nfunction () {\n function FieldTransform(field, transform) {\n this.field = field;\n this.transform = transform;\n }\n\n FieldTransform.prototype.isEqual = function (other) {\n return this.field.isEqual(other.field) && this.transform.isEqual(other.transform);\n };\n\n return FieldTransform;\n}();\n/** The result of successfully applying a mutation to the backend. */\n\n\nvar MutationResult =\n/** @class */\nfunction () {\n function MutationResult(\n /**\r\n * The version at which the mutation was committed:\r\n *\r\n * - For most operations, this is the updateTime in the WriteResult.\r\n * - For deletes, the commitTime of the WriteResponse (because deletes are\r\n * not stored and have no updateTime).\r\n *\r\n * Note that these versions can be different: No-op writes will not change\r\n * the updateTime even though the commitTime advances.\r\n */\n version,\n /**\r\n * The resulting fields returned from the backend after a\r\n * TransformMutation has been committed. Contains one FieldValue for each\r\n * FieldTransform that was in the mutation.\r\n *\r\n * Will be null if the mutation was not a TransformMutation.\r\n */\n transformResults) {\n this.version = version;\n this.transformResults = transformResults;\n }\n\n return MutationResult;\n}();\n\nvar MutationType;\n\n(function (MutationType) {\n MutationType[MutationType[\"Set\"] = 0] = \"Set\";\n MutationType[MutationType[\"Patch\"] = 1] = \"Patch\";\n MutationType[MutationType[\"Transform\"] = 2] = \"Transform\";\n MutationType[MutationType[\"Delete\"] = 3] = \"Delete\";\n})(MutationType || (MutationType = {}));\n/**\r\n * Encodes a precondition for a mutation. This follows the model that the\r\n * backend accepts with the special case of an explicit \"empty\" precondition\r\n * (meaning no precondition).\r\n */\n\n\nvar Precondition =\n/** @class */\nfunction () {\n function Precondition(updateTime, exists) {\n this.updateTime = updateTime;\n this.exists = exists;\n assert(updateTime === undefined || exists === undefined, 'Precondition can specify \"exists\" or \"updateTime\" but not both');\n }\n /** Creates a new Precondition with an exists flag. */\n\n\n Precondition.exists = function (exists) {\n return new Precondition(undefined, exists);\n };\n /** Creates a new Precondition based on a version a document exists at. */\n\n\n Precondition.updateTime = function (version) {\n return new Precondition(version);\n };\n\n Object.defineProperty(Precondition.prototype, \"isNone\", {\n /** Returns whether this Precondition is empty. */\n get: function get() {\n return this.updateTime === undefined && this.exists === undefined;\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Returns true if the preconditions is valid for the given document\r\n * (or null if no document is available).\r\n */\n\n Precondition.prototype.isValidFor = function (maybeDoc) {\n if (this.updateTime !== undefined) {\n return maybeDoc instanceof Document && maybeDoc.version.isEqual(this.updateTime);\n } else if (this.exists !== undefined) {\n return this.exists === maybeDoc instanceof Document;\n } else {\n assert(this.isNone, 'Precondition should be empty');\n return true;\n }\n };\n\n Precondition.prototype.isEqual = function (other) {\n return equals(this.updateTime, other.updateTime) && this.exists === other.exists;\n };\n\n Precondition.NONE = new Precondition();\n return Precondition;\n}();\n/**\r\n * A mutation describes a self-contained change to a document. Mutations can\r\n * create, replace, delete, and update subsets of documents.\r\n *\r\n * Mutations not only act on the value of the document but also it version.\r\n *\r\n * For local mutations (mutations that haven't been committed yet), we preserve\r\n * the existing version for Set, Patch, and Transform mutations. For Delete\r\n * mutations, we reset the version to 0.\r\n *\r\n * Here's the expected transition table.\r\n *\r\n * MUTATION APPLIED TO RESULTS IN\r\n *\r\n * SetMutation Document(v3) Document(v3)\r\n * SetMutation NoDocument(v3) Document(v0)\r\n * SetMutation null Document(v0)\r\n * PatchMutation Document(v3) Document(v3)\r\n * PatchMutation NoDocument(v3) NoDocument(v3)\r\n * PatchMutation null null\r\n * TransformMutation Document(v3) Document(v3)\r\n * TransformMutation NoDocument(v3) NoDocument(v3)\r\n * TransformMutation null null\r\n * DeleteMutation Document(v3) NoDocument(v0)\r\n * DeleteMutation NoDocument(v3) NoDocument(v0)\r\n * DeleteMutation null NoDocument(v0)\r\n *\r\n * For acknowledged mutations, we use the updateTime of the WriteResponse as\r\n * the resulting version for Set, Patch, and Transform mutations. As deletes\r\n * have no explicit update time, we use the commitTime of the WriteResponse for\r\n * Delete mutations.\r\n *\r\n * If a mutation is acknowledged by the backend but fails the precondition check\r\n * locally, we return an `UnknownDocument` and rely on Watch to send us the\r\n * updated version.\r\n *\r\n * Note that TransformMutations don't create Documents (in the case of being\r\n * applied to a NoDocument), even though they would on the backend. This is\r\n * because the client always combines the TransformMutation with a SetMutation\r\n * or PatchMutation and we only want to apply the transform if the prior\r\n * mutation resulted in a Document (always true for a SetMutation, but not\r\n * necessarily for a PatchMutation).\r\n *\r\n * ## Subclassing Notes\r\n *\r\n * Subclasses of Mutation need to implement applyToRemoteDocument() and\r\n * applyToLocalView() to implement the actual behavior of applying the mutation\r\n * to some source document.\r\n */\n\n\nvar Mutation =\n/** @class */\nfunction () {\n function Mutation() {}\n\n Mutation.prototype.verifyKeyMatches = function (maybeDoc) {\n if (maybeDoc != null) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply a mutation to a document with the same key');\n }\n };\n /**\r\n * Returns the version from the given document for use as the result of a\r\n * mutation. Mutations are defined to return the version of the base document\r\n * only if it is an existing document. Deleted and unknown documents have a\r\n * post-mutation version of SnapshotVersion.MIN.\r\n */\n\n\n Mutation.getPostMutationVersion = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n return maybeDoc.version;\n } else {\n return SnapshotVersion.MIN;\n }\n };\n\n return Mutation;\n}();\n/**\r\n * A mutation that creates or replaces the document at the given key with the\r\n * object value contents.\r\n */\n\n\nvar SetMutation =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(SetMutation, _super);\n\n function SetMutation(key, value, precondition) {\n var _this = _super.call(this) || this;\n\n _this.key = key;\n _this.value = value;\n _this.precondition = precondition;\n _this.type = MutationType.Set;\n return _this;\n }\n\n SetMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by SetMutation.'); // 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\n var version = mutationResult.version;\n return new Document(this.key, version, this.value, {\n hasCommittedMutations: true\n });\n };\n\n SetMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n var version = Mutation.getPostMutationVersion(maybeDoc);\n return new Document(this.key, version, this.value, {\n hasLocalMutations: true\n });\n };\n\n SetMutation.prototype.isEqual = function (other) {\n return other instanceof SetMutation && this.key.isEqual(other.key) && this.value.isEqual(other.value) && this.precondition.isEqual(other.precondition);\n };\n\n return SetMutation;\n}(Mutation);\n/**\r\n * A mutation that modifies fields of the document at the given key with the\r\n * given values. The values are applied through a field mask:\r\n *\r\n * * When a field is in both the mask and the values, the corresponding field\r\n * is updated.\r\n * * When a field is in neither the mask nor the values, the corresponding\r\n * field is unmodified.\r\n * * When a field is in the mask but not in the values, the corresponding field\r\n * is deleted.\r\n * * When a field is not in the mask but is in the values, the values map is\r\n * ignored.\r\n */\n\n\nvar PatchMutation =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(PatchMutation, _super);\n\n function PatchMutation(key, data, fieldMask, precondition) {\n var _this = _super.call(this) || this;\n\n _this.key = key;\n _this.data = data;\n _this.fieldMask = fieldMask;\n _this.precondition = precondition;\n _this.type = MutationType.Patch;\n return _this;\n }\n\n PatchMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by PatchMutation.');\n\n if (!this.precondition.isValidFor(maybeDoc)) {\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 return an UnknownDocument with the\n // known updateTime.\n return new UnknownDocument(this.key, mutationResult.version);\n }\n\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, mutationResult.version, newData, {\n hasCommittedMutations: true\n });\n };\n\n PatchMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n var version = Mutation.getPostMutationVersion(maybeDoc);\n var newData = this.patchDocument(maybeDoc);\n return new Document(this.key, version, newData, {\n hasLocalMutations: true\n });\n };\n\n PatchMutation.prototype.isEqual = function (other) {\n return other instanceof PatchMutation && this.key.isEqual(other.key) && this.fieldMask.isEqual(other.fieldMask) && this.precondition.isEqual(other.precondition);\n };\n /**\r\n * Patches the data of document if available or creates a new document. Note\r\n * that this does not check whether or not the precondition of this patch\r\n * holds.\r\n */\n\n\n PatchMutation.prototype.patchDocument = function (maybeDoc) {\n var data;\n\n if (maybeDoc instanceof Document) {\n data = maybeDoc.data;\n } else {\n data = ObjectValue.EMPTY;\n }\n\n return this.patchObject(data);\n };\n\n PatchMutation.prototype.patchObject = function (data) {\n var _this = this;\n\n this.fieldMask.fields.forEach(function (fieldPath) {\n if (!fieldPath.isEmpty()) {\n var newValue = _this.data.field(fieldPath);\n\n if (newValue !== undefined) {\n data = data.set(fieldPath, newValue);\n } else {\n data = data.delete(fieldPath);\n }\n }\n });\n return data;\n };\n\n return PatchMutation;\n}(Mutation);\n/**\r\n * A mutation that modifies specific fields of the document with transform\r\n * operations. Currently the only supported transform is a server timestamp, but\r\n * IP Address, increment(n), etc. could be supported in the future.\r\n *\r\n * It is somewhat similar to a PatchMutation in that it patches specific fields\r\n * and has no effect when applied to a null or NoDocument (see comment on\r\n * Mutation for rationale).\r\n */\n\n\nvar TransformMutation =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(TransformMutation, _super);\n\n function TransformMutation(key, fieldTransforms) {\n var _this = _super.call(this) || this;\n\n _this.key = key;\n _this.fieldTransforms = fieldTransforms;\n _this.type = MutationType.Transform; // NOTE: We set a precondition of exists: true as a safety-check, since we\n // always combine TransformMutations with a SetMutation or PatchMutation which\n // (if successful) should end up with an existing document.\n\n _this.precondition = Precondition.exists(true);\n return _this;\n }\n\n TransformMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults != null, 'Transform results missing for TransformMutation.');\n\n if (!this.precondition.isValidFor(maybeDoc)) {\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 return an UnknownDocument with the\n // known updateTime.\n return new UnknownDocument(this.key, mutationResult.version);\n }\n\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.serverTransformResults(maybeDoc, mutationResult.transformResults);\n var version = mutationResult.version;\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, version, newData, {\n hasCommittedMutations: true\n });\n };\n\n TransformMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n var doc = this.requireDocument(maybeDoc);\n var transformResults = this.localTransformResults(localWriteTime, baseDoc);\n var newData = this.transformObject(doc.data, transformResults);\n return new Document(this.key, doc.version, newData, {\n hasLocalMutations: true\n });\n };\n\n TransformMutation.prototype.isEqual = function (other) {\n return other instanceof TransformMutation && this.key.isEqual(other.key) && arrayEquals(this.fieldTransforms, other.fieldTransforms) && this.precondition.isEqual(other.precondition);\n };\n /**\r\n * Asserts that the given MaybeDocument is actually a Document and verifies\r\n * that it matches the key for this mutation. Since we only support\r\n * transformations with precondition exists this method is guaranteed to be\r\n * safe.\r\n */\n\n\n TransformMutation.prototype.requireDocument = function (maybeDoc) {\n assert(maybeDoc instanceof Document, 'Unknown MaybeDocument type ' + maybeDoc);\n var doc = maybeDoc;\n assert(doc.key.isEqual(this.key), 'Can only transform a document with the same key');\n return doc;\n };\n /**\r\n * Creates a list of \"transform results\" (a transform result is a field value\r\n * representing the result of applying a transform) for use after a\r\n * TransformMutation has been acknowledged by the server.\r\n *\r\n * @param baseDoc The document prior to applying this mutation batch.\r\n * @param serverTransformResults The transform results received by the server.\r\n * @return The transform results list.\r\n */\n\n\n TransformMutation.prototype.serverTransformResults = function (baseDoc, serverTransformResults) {\n var transformResults = [];\n assert(this.fieldTransforms.length === serverTransformResults.length, \"server transform result count (\" + serverTransformResults.length + \") \" + (\"should match field transform count (\" + this.fieldTransforms.length + \")\"));\n\n for (var i = 0; i < serverTransformResults.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var transform = fieldTransform.transform;\n var previousValue = null;\n\n if (baseDoc instanceof Document) {\n previousValue = baseDoc.field(fieldTransform.field) || null;\n }\n\n transformResults.push(transform.applyToRemoteDocument(previousValue, serverTransformResults[i]));\n }\n\n return transformResults;\n };\n /**\r\n * Creates a list of \"transform results\" (a transform result is a field value\r\n * representing the result of applying a transform) for use when applying a\r\n * TransformMutation locally.\r\n *\r\n * @param localWriteTime The local time of the transform mutation (used to\r\n * generate ServerTimestampValues).\r\n * @param baseDoc The document prior to applying this mutation batch.\r\n * @return The transform results list.\r\n */\n\n\n TransformMutation.prototype.localTransformResults = function (localWriteTime, baseDoc) {\n var transformResults = [];\n\n for (var _i = 0, _a = this.fieldTransforms; _i < _a.length; _i++) {\n var fieldTransform = _a[_i];\n var transform = fieldTransform.transform;\n var previousValue = null;\n\n if (baseDoc instanceof Document) {\n previousValue = baseDoc.field(fieldTransform.field) || null;\n }\n\n transformResults.push(transform.applyToLocalView(previousValue, localWriteTime));\n }\n\n return transformResults;\n };\n\n TransformMutation.prototype.transformObject = function (data, transformResults) {\n assert(transformResults.length === this.fieldTransforms.length, 'TransformResults length mismatch.');\n\n for (var i = 0; i < this.fieldTransforms.length; i++) {\n var fieldTransform = this.fieldTransforms[i];\n var fieldPath = fieldTransform.field;\n data = data.set(fieldPath, transformResults[i]);\n }\n\n return data;\n };\n\n return TransformMutation;\n}(Mutation);\n/** A mutation that deletes the document at the given key. */\n\n\nvar DeleteMutation =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(DeleteMutation, _super);\n\n function DeleteMutation(key, precondition) {\n var _this = _super.call(this) || this;\n\n _this.key = key;\n _this.precondition = precondition;\n _this.type = MutationType.Delete;\n return _this;\n }\n\n DeleteMutation.prototype.applyToRemoteDocument = function (maybeDoc, mutationResult) {\n this.verifyKeyMatches(maybeDoc);\n assert(mutationResult.transformResults == null, 'Transform results received by DeleteMutation.'); // 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\n return new NoDocument(this.key, mutationResult.version, {\n hasCommittedMutations: true\n });\n };\n\n DeleteMutation.prototype.applyToLocalView = function (maybeDoc, baseDoc, localWriteTime) {\n this.verifyKeyMatches(maybeDoc);\n\n if (!this.precondition.isValidFor(maybeDoc)) {\n return maybeDoc;\n }\n\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(this.key), 'Can only apply mutation to document with same key');\n }\n\n return new NoDocument(this.key, SnapshotVersion.forDeletedDoc());\n };\n\n DeleteMutation.prototype.isEqual = function (other) {\n return other instanceof DeleteMutation && this.key.isEqual(other.key) && this.precondition.isEqual(other.precondition);\n };\n\n return DeleteMutation;\n}(Mutation);\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/** Transforms a value into a server-generated timestamp. */\n\n\nvar ServerTimestampTransform =\n/** @class */\nfunction () {\n function ServerTimestampTransform() {}\n\n ServerTimestampTransform.prototype.applyToLocalView = function (previousValue, localWriteTime) {\n return new ServerTimestampValue(localWriteTime, previousValue);\n };\n\n ServerTimestampTransform.prototype.applyToRemoteDocument = function (previousValue, transformResult) {\n return transformResult;\n };\n\n ServerTimestampTransform.prototype.isEqual = function (other) {\n return other instanceof ServerTimestampTransform;\n };\n\n ServerTimestampTransform.instance = new ServerTimestampTransform();\n return ServerTimestampTransform;\n}();\n/** Transforms an array value via a union operation. */\n\n\nvar ArrayUnionTransformOperation =\n/** @class */\nfunction () {\n function ArrayUnionTransformOperation(elements) {\n this.elements = elements;\n }\n\n ArrayUnionTransformOperation.prototype.applyToLocalView = function (previousValue, localWriteTime) {\n return this.apply(previousValue);\n };\n\n ArrayUnionTransformOperation.prototype.applyToRemoteDocument = function (previousValue, transformResult) {\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 return this.apply(previousValue);\n };\n\n ArrayUnionTransformOperation.prototype.apply = function (previousValue) {\n var result = coercedFieldValuesArray(previousValue);\n\n var _loop_1 = function _loop_1(toUnion) {\n if (!result.find(function (element) {\n return element.isEqual(toUnion);\n })) {\n result.push(toUnion);\n }\n };\n\n for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {\n var toUnion = _a[_i];\n\n _loop_1(toUnion);\n }\n\n return new ArrayValue(result);\n };\n\n ArrayUnionTransformOperation.prototype.isEqual = function (other) {\n return other instanceof ArrayUnionTransformOperation && arrayEquals(other.elements, this.elements);\n };\n\n return ArrayUnionTransformOperation;\n}();\n/** Transforms an array value via a remove operation. */\n\n\nvar ArrayRemoveTransformOperation =\n/** @class */\nfunction () {\n function ArrayRemoveTransformOperation(elements) {\n this.elements = elements;\n }\n\n ArrayRemoveTransformOperation.prototype.applyToLocalView = function (previousValue, localWriteTime) {\n return this.apply(previousValue);\n };\n\n ArrayRemoveTransformOperation.prototype.applyToRemoteDocument = function (previousValue, transformResult) {\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 return this.apply(previousValue);\n };\n\n ArrayRemoveTransformOperation.prototype.apply = function (previousValue) {\n var result = coercedFieldValuesArray(previousValue);\n\n var _loop_2 = function _loop_2(toRemove) {\n result = result.filter(function (element) {\n return !element.isEqual(toRemove);\n });\n };\n\n for (var _i = 0, _a = this.elements; _i < _a.length; _i++) {\n var toRemove = _a[_i];\n\n _loop_2(toRemove);\n }\n\n return new ArrayValue(result);\n };\n\n ArrayRemoveTransformOperation.prototype.isEqual = function (other) {\n return other instanceof ArrayRemoveTransformOperation && arrayEquals(other.elements, this.elements);\n };\n\n return ArrayRemoveTransformOperation;\n}();\n\nfunction coercedFieldValuesArray(value) {\n if (value instanceof ArrayValue) {\n return value.internalValue.slice();\n } else {\n // coerce to empty array.\n return [];\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar ExistenceFilter =\n/** @class */\nfunction () {\n // TODO(b/33078163): just use simplest form of existence filter for now\n function ExistenceFilter(count) {\n this.count = count;\n }\n\n ExistenceFilter.prototype.isEqual = function (other) {\n return other && other.count === this.count;\n };\n\n return ExistenceFilter;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Error Codes describing the different ways GRPC can fail. These are copied\r\n * directly from GRPC's sources here:\r\n *\r\n * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h\r\n *\r\n * Important! The names of these identifiers matter because the string forms\r\n * are used for reverse lookups from the webchannel stream. Do NOT change the\r\n * names of these identifiers.\r\n */\n\n\nvar RpcCode;\n\n(function (RpcCode) {\n RpcCode[RpcCode[\"OK\"] = 0] = \"OK\";\n RpcCode[RpcCode[\"CANCELLED\"] = 1] = \"CANCELLED\";\n RpcCode[RpcCode[\"UNKNOWN\"] = 2] = \"UNKNOWN\";\n RpcCode[RpcCode[\"INVALID_ARGUMENT\"] = 3] = \"INVALID_ARGUMENT\";\n RpcCode[RpcCode[\"DEADLINE_EXCEEDED\"] = 4] = \"DEADLINE_EXCEEDED\";\n RpcCode[RpcCode[\"NOT_FOUND\"] = 5] = \"NOT_FOUND\";\n RpcCode[RpcCode[\"ALREADY_EXISTS\"] = 6] = \"ALREADY_EXISTS\";\n RpcCode[RpcCode[\"PERMISSION_DENIED\"] = 7] = \"PERMISSION_DENIED\";\n RpcCode[RpcCode[\"UNAUTHENTICATED\"] = 16] = \"UNAUTHENTICATED\";\n RpcCode[RpcCode[\"RESOURCE_EXHAUSTED\"] = 8] = \"RESOURCE_EXHAUSTED\";\n RpcCode[RpcCode[\"FAILED_PRECONDITION\"] = 9] = \"FAILED_PRECONDITION\";\n RpcCode[RpcCode[\"ABORTED\"] = 10] = \"ABORTED\";\n RpcCode[RpcCode[\"OUT_OF_RANGE\"] = 11] = \"OUT_OF_RANGE\";\n RpcCode[RpcCode[\"UNIMPLEMENTED\"] = 12] = \"UNIMPLEMENTED\";\n RpcCode[RpcCode[\"INTERNAL\"] = 13] = \"INTERNAL\";\n RpcCode[RpcCode[\"UNAVAILABLE\"] = 14] = \"UNAVAILABLE\";\n RpcCode[RpcCode[\"DATA_LOSS\"] = 15] = \"DATA_LOSS\";\n})(RpcCode || (RpcCode = {}));\n\nfunction isPermanentError(code) {\n switch (code) {\n case Code.OK:\n return fail('Treated status OK as error');\n\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: // Unauthenticated means something went wrong with our token and we need\n // to retry with new credentials which will happen automatically.\n\n case Code.UNAUTHENTICATED:\n return false;\n\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: // 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\n case Code.ABORTED:\n case Code.OUT_OF_RANGE:\n case Code.UNIMPLEMENTED:\n case Code.DATA_LOSS:\n return true;\n\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\r\n * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'.\r\n *\r\n * @returns The Code equivalent to the given status string or undefined if\r\n * there is no match.\r\n */\n\n\nfunction mapCodeFromRpcStatus(status) {\n // tslint:disable-next-line:no-any lookup by string\n var code = RpcCode[status];\n\n if (code === undefined) {\n return undefined;\n }\n\n return mapCodeFromRpcCode(code);\n}\n/**\r\n * Maps an error Code from GRPC status code number, like 0, 1, or 14. These\r\n * are not the same as HTTP status codes.\r\n *\r\n * @returns The Code equivalent to the given GRPC status code. Fails if there\r\n * is no match.\r\n */\n\n\nfunction mapCodeFromRpcCode(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 error('GRPC error has no .code');\n return Code.UNKNOWN;\n }\n\n switch (code) {\n case RpcCode.OK:\n return Code.OK;\n\n case RpcCode.CANCELLED:\n return Code.CANCELLED;\n\n case RpcCode.UNKNOWN:\n return Code.UNKNOWN;\n\n case RpcCode.DEADLINE_EXCEEDED:\n return Code.DEADLINE_EXCEEDED;\n\n case RpcCode.RESOURCE_EXHAUSTED:\n return Code.RESOURCE_EXHAUSTED;\n\n case RpcCode.INTERNAL:\n return Code.INTERNAL;\n\n case RpcCode.UNAVAILABLE:\n return Code.UNAVAILABLE;\n\n case RpcCode.UNAUTHENTICATED:\n return Code.UNAUTHENTICATED;\n\n case RpcCode.INVALID_ARGUMENT:\n return Code.INVALID_ARGUMENT;\n\n case RpcCode.NOT_FOUND:\n return Code.NOT_FOUND;\n\n case RpcCode.ALREADY_EXISTS:\n return Code.ALREADY_EXISTS;\n\n case RpcCode.PERMISSION_DENIED:\n return Code.PERMISSION_DENIED;\n\n case RpcCode.FAILED_PRECONDITION:\n return Code.FAILED_PRECONDITION;\n\n case RpcCode.ABORTED:\n return Code.ABORTED;\n\n case RpcCode.OUT_OF_RANGE:\n return Code.OUT_OF_RANGE;\n\n case RpcCode.UNIMPLEMENTED:\n return Code.UNIMPLEMENTED;\n\n case RpcCode.DATA_LOSS:\n return Code.DATA_LOSS;\n\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\r\n * Maps an RPC code from a Code. This is the reverse operation from\r\n * mapCodeFromRpcCode and should really only be used in tests.\r\n */\n\n\nfunction mapRpcCodeFromCode(code) {\n if (code === undefined) {\n return RpcCode.OK;\n }\n\n switch (code) {\n case Code.OK:\n return RpcCode.OK;\n\n case Code.CANCELLED:\n return RpcCode.CANCELLED;\n\n case Code.UNKNOWN:\n return RpcCode.UNKNOWN;\n\n case Code.DEADLINE_EXCEEDED:\n return RpcCode.DEADLINE_EXCEEDED;\n\n case Code.RESOURCE_EXHAUSTED:\n return RpcCode.RESOURCE_EXHAUSTED;\n\n case Code.INTERNAL:\n return RpcCode.INTERNAL;\n\n case Code.UNAVAILABLE:\n return RpcCode.UNAVAILABLE;\n\n case Code.UNAUTHENTICATED:\n return RpcCode.UNAUTHENTICATED;\n\n case Code.INVALID_ARGUMENT:\n return RpcCode.INVALID_ARGUMENT;\n\n case Code.NOT_FOUND:\n return RpcCode.NOT_FOUND;\n\n case Code.ALREADY_EXISTS:\n return RpcCode.ALREADY_EXISTS;\n\n case Code.PERMISSION_DENIED:\n return RpcCode.PERMISSION_DENIED;\n\n case Code.FAILED_PRECONDITION:\n return RpcCode.FAILED_PRECONDITION;\n\n case Code.ABORTED:\n return RpcCode.ABORTED;\n\n case Code.OUT_OF_RANGE:\n return RpcCode.OUT_OF_RANGE;\n\n case Code.UNIMPLEMENTED:\n return RpcCode.UNIMPLEMENTED;\n\n case Code.DATA_LOSS:\n return RpcCode.DATA_LOSS;\n\n default:\n return fail('Unknown status code: ' + code);\n }\n}\n/**\r\n * Converts an HTTP Status Code to the equivalent error code.\r\n *\r\n * @param status An HTTP Status Code, like 200, 404, 503, etc.\r\n * @returns The equivalent Code. Unknown status codes are mapped to\r\n * Code.UNKNOWN.\r\n */\n\n\nfunction mapCodeFromHttpStatus(status) {\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:\n // OK\n return Code.OK;\n\n case 400:\n // Bad Request\n return Code.INVALID_ARGUMENT;\n // Other possibilities based on the forward mapping\n // return Code.FAILED_PRECONDITION;\n // return Code.OUT_OF_RANGE;\n\n case 401:\n // Unauthorized\n return Code.UNAUTHENTICATED;\n\n case 403:\n // Forbidden\n return Code.PERMISSION_DENIED;\n\n case 404:\n // Not Found\n return Code.NOT_FOUND;\n\n case 409:\n // Conflict\n return Code.ABORTED;\n // Other possibilities:\n // return Code.ALREADY_EXISTS;\n\n case 416:\n // Range Not Satisfiable\n return Code.OUT_OF_RANGE;\n\n case 429:\n // Too Many Requests\n return Code.RESOURCE_EXHAUSTED;\n\n case 499:\n // Client Closed Request\n return Code.CANCELLED;\n\n case 500:\n // Internal Server Error\n return Code.UNKNOWN;\n // Other possibilities:\n // return Code.INTERNAL;\n // return Code.DATA_LOSS;\n\n case 501:\n // Unimplemented\n return Code.UNIMPLEMENTED;\n\n case 503:\n // Service Unavailable\n return Code.UNAVAILABLE;\n\n case 504:\n // Gateway Timeout\n return Code.DEADLINE_EXCEEDED;\n\n default:\n if (status >= 200 && status < 300) return Code.OK;\n if (status >= 400 && status < 500) return Code.FAILED_PRECONDITION;\n if (status >= 500 && status < 600) return Code.INTERNAL;\n return Code.UNKNOWN;\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar EMPTY_MAYBE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\n\nfunction maybeDocumentMap() {\n return EMPTY_MAYBE_DOCUMENT_MAP;\n}\n\nvar EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator);\n\nfunction documentMap() {\n return EMPTY_DOCUMENT_MAP;\n}\n\nvar EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator);\n\nfunction documentVersionMap() {\n return EMPTY_DOCUMENT_VERSION_MAP;\n}\n\nvar EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator);\n\nfunction documentKeySet() {\n var keys = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n keys[_i] = arguments[_i];\n }\n\n var set = EMPTY_DOCUMENT_KEY_SET;\n\n for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) {\n var key = keys_1[_a];\n set = set.add(key);\n }\n\n return set;\n}\n\nvar EMPTY_TARGET_ID_SET = new SortedSet(primitiveComparator);\n\nfunction targetIdSet() {\n return EMPTY_TARGET_ID_SET;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * DocumentSet is an immutable (copy-on-write) collection that holds documents\r\n * in order specified by the provided comparator. We always add a document key\r\n * comparator on top of what is provided to guarantee document equality based on\r\n * the key.\r\n */\n\n\nvar DocumentSet =\n/** @class */\nfunction () {\n /** The default ordering is by key if the comparator is omitted */\n function DocumentSet(comp) {\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 = function (d1, d2) {\n return comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key);\n };\n } else {\n this.comparator = function (d1, d2) {\n return DocumentKey.comparator(d1.key, d2.key);\n };\n }\n\n this.keyedMap = documentMap();\n this.sortedSet = new SortedMap(this.comparator);\n }\n /**\r\n * Returns an empty copy of the existing DocumentSet, using the same\r\n * comparator.\r\n */\n\n\n DocumentSet.emptySet = function (oldSet) {\n return new DocumentSet(oldSet.comparator);\n };\n\n DocumentSet.prototype.has = function (key) {\n return this.keyedMap.get(key) != null;\n };\n\n DocumentSet.prototype.get = function (key) {\n return this.keyedMap.get(key);\n };\n\n DocumentSet.prototype.first = function () {\n return this.sortedSet.minKey();\n };\n\n DocumentSet.prototype.last = function () {\n return this.sortedSet.maxKey();\n };\n\n DocumentSet.prototype.isEmpty = function () {\n return this.sortedSet.isEmpty();\n };\n /**\r\n * Returns the index of the provided key in the document set, or -1 if the\r\n * document key is not present in the set;\r\n */\n\n\n DocumentSet.prototype.indexOf = function (key) {\n var doc = this.keyedMap.get(key);\n return doc ? this.sortedSet.indexOf(doc) : -1;\n };\n\n Object.defineProperty(DocumentSet.prototype, \"size\", {\n get: function get() {\n return this.sortedSet.size;\n },\n enumerable: true,\n configurable: true\n });\n /** Iterates documents in order defined by \"comparator\" */\n\n DocumentSet.prototype.forEach = function (cb) {\n this.sortedSet.inorderTraversal(function (k, v) {\n cb(k);\n return false;\n });\n };\n /** Inserts or updates a document with the same key */\n\n\n DocumentSet.prototype.add = function (doc) {\n // First remove the element if we have it.\n var set = this.delete(doc.key);\n return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null));\n };\n /** Deletes a document with a given key */\n\n\n DocumentSet.prototype.delete = function (key) {\n var doc = this.get(key);\n\n if (!doc) {\n return this;\n }\n\n return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc));\n };\n\n DocumentSet.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSet)) return false;\n if (this.size !== other.size) return false;\n var thisIt = this.sortedSet.getIterator();\n var otherIt = other.sortedSet.getIterator();\n\n while (thisIt.hasNext()) {\n var thisDoc = thisIt.getNext().key;\n var otherDoc = otherIt.getNext().key;\n if (!thisDoc.isEqual(otherDoc)) return false;\n }\n\n return true;\n };\n\n DocumentSet.prototype.toString = function () {\n var docStrings = [];\n this.forEach(function (doc) {\n docStrings.push(doc.toString());\n });\n\n if (docStrings.length === 0) {\n return 'DocumentSet ()';\n } else {\n return 'DocumentSet (\\n ' + docStrings.join(' \\n') + '\\n)';\n }\n };\n\n DocumentSet.prototype.copy = function (keyedMap, sortedSet) {\n var newSet = new DocumentSet();\n newSet.comparator = this.comparator;\n newSet.keyedMap = keyedMap;\n newSet.sortedSet = sortedSet;\n return newSet;\n };\n\n return DocumentSet;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar ChangeType;\n\n(function (ChangeType) {\n ChangeType[ChangeType[\"Added\"] = 0] = \"Added\";\n ChangeType[ChangeType[\"Removed\"] = 1] = \"Removed\";\n ChangeType[ChangeType[\"Modified\"] = 2] = \"Modified\";\n ChangeType[ChangeType[\"Metadata\"] = 3] = \"Metadata\";\n})(ChangeType || (ChangeType = {}));\n\nvar SyncState;\n\n(function (SyncState) {\n SyncState[SyncState[\"Local\"] = 0] = \"Local\";\n SyncState[SyncState[\"Synced\"] = 1] = \"Synced\";\n})(SyncState || (SyncState = {}));\n/**\r\n * DocumentChangeSet keeps track of a set of changes to docs in a query, merging\r\n * duplicate events for the same doc.\r\n */\n\n\nvar DocumentChangeSet =\n/** @class */\nfunction () {\n function DocumentChangeSet() {\n this.changeMap = new SortedMap(DocumentKey.comparator);\n }\n\n DocumentChangeSet.prototype.track = function (change) {\n var key = change.doc.key;\n var oldChange = this.changeMap.get(key);\n\n if (!oldChange) {\n this.changeMap = this.changeMap.insert(key, change);\n return;\n } // Merge the new change with the existing change.\n\n\n if (change.type !== ChangeType.Added && oldChange.type === ChangeType.Metadata) {\n this.changeMap = this.changeMap.insert(key, change);\n } else if (change.type === ChangeType.Metadata && oldChange.type !== ChangeType.Removed) {\n this.changeMap = this.changeMap.insert(key, {\n type: oldChange.type,\n doc: change.doc\n });\n } else if (change.type === ChangeType.Modified && oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Modified,\n doc: change.doc\n });\n } else if (change.type === ChangeType.Modified && oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Added,\n doc: change.doc\n });\n } else if (change.type === ChangeType.Removed && oldChange.type === ChangeType.Added) {\n this.changeMap = this.changeMap.remove(key);\n } else if (change.type === ChangeType.Removed && oldChange.type === ChangeType.Modified) {\n this.changeMap = this.changeMap.insert(key, {\n type: ChangeType.Removed,\n doc: oldChange.doc\n });\n } else if (change.type === ChangeType.Added && oldChange.type === ChangeType.Removed) {\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('unsupported combination of changes: ' + JSON.stringify(change) + ' after ' + JSON.stringify(oldChange));\n }\n };\n\n DocumentChangeSet.prototype.getChanges = function () {\n var changes = [];\n this.changeMap.inorderTraversal(function (key, change) {\n changes.push(change);\n });\n return changes;\n };\n\n return DocumentChangeSet;\n}();\n\nvar ViewSnapshot =\n/** @class */\nfunction () {\n function ViewSnapshot(query, docs, oldDocs, docChanges, mutatedKeys, fromCache, syncStateChanged, excludesMetadataChanges) {\n this.query = query;\n this.docs = docs;\n this.oldDocs = oldDocs;\n this.docChanges = docChanges;\n this.mutatedKeys = mutatedKeys;\n this.fromCache = fromCache;\n this.syncStateChanged = syncStateChanged;\n this.excludesMetadataChanges = excludesMetadataChanges;\n }\n /** Returns a view snapshot as if all documents in the snapshot were added. */\n\n\n ViewSnapshot.fromInitialDocuments = function (query, documents, mutatedKeys, fromCache) {\n var changes = [];\n documents.forEach(function (doc) {\n changes.push({\n type: ChangeType.Added,\n doc: doc\n });\n });\n return new ViewSnapshot(query, documents, DocumentSet.emptySet(documents), changes, mutatedKeys, fromCache, true, false);\n };\n\n Object.defineProperty(ViewSnapshot.prototype, \"hasPendingWrites\", {\n get: function get() {\n return !this.mutatedKeys.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n\n ViewSnapshot.prototype.isEqual = function (other) {\n if (this.fromCache !== other.fromCache || this.syncStateChanged !== other.syncStateChanged || !this.mutatedKeys.isEqual(other.mutatedKeys) || !this.query.isEqual(other.query) || !this.docs.isEqual(other.docs) || !this.oldDocs.isEqual(other.oldDocs)) {\n return false;\n }\n\n var changes = this.docChanges;\n var otherChanges = other.docChanges;\n\n if (changes.length !== otherChanges.length) {\n return false;\n }\n\n for (var i = 0; i < changes.length; i++) {\n if (changes[i].type !== otherChanges[i].type || !changes[i].doc.isEqual(otherChanges[i].doc)) {\n return false;\n }\n }\n\n return true;\n };\n\n return ViewSnapshot;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * An event from the RemoteStore. It is split into targetChanges (changes to the\r\n * state or the set of documents in our watched targets) and documentUpdates\r\n * (changes to the actual documents).\r\n */\n\n\nvar RemoteEvent =\n/** @class */\nfunction () {\n function RemoteEvent(\n /**\r\n * The snapshot version this event brings us up to, or MIN if not set.\r\n */\n snapshotVersion,\n /**\r\n * A map from target to changes to the target. See TargetChange.\r\n */\n targetChanges,\n /**\r\n * A set of targets that is known to be inconsistent. Listens for these\r\n * targets should be re-established without resume tokens.\r\n */\n targetMismatches,\n /**\r\n * A set of which documents have changed or been deleted, along with the\r\n * doc's new values (if not deleted).\r\n */\n documentUpdates,\n /**\r\n * A set of which document updates are due only to limbo resolution targets.\r\n */\n resolvedLimboDocuments) {\n this.snapshotVersion = snapshotVersion;\n this.targetChanges = targetChanges;\n this.targetMismatches = targetMismatches;\n this.documentUpdates = documentUpdates;\n this.resolvedLimboDocuments = resolvedLimboDocuments;\n }\n /**\r\n * HACK: Views require RemoteEvents in order to determine whether the view is\r\n * CURRENT, but secondary tabs don't receive remote events. So this method is\r\n * used to create a synthesized RemoteEvent that can be used to apply a\r\n * CURRENT status change to a View, for queries executed in a different tab.\r\n */\n // PORTING NOTE: Multi-tab only\n\n\n RemoteEvent.createSynthesizedRemoteEventForCurrentChange = function (targetId, current) {\n var targetChanges = (_a = {}, _a[targetId] = TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current), _a);\n return new RemoteEvent(SnapshotVersion.MIN, targetChanges, targetIdSet(), maybeDocumentMap(), documentKeySet());\n\n var _a;\n };\n\n return RemoteEvent;\n}();\n/**\r\n * A TargetChange specifies the set of changes for a specific target as part of\r\n * a RemoteEvent. These changes track which documents are added, modified or\r\n * removed, as well as the target's resume token and whether the target is\r\n * marked CURRENT.\r\n * The actual changes *to* documents are not part of the TargetChange since\r\n * documents may be part of multiple targets.\r\n */\n\n\nvar TargetChange =\n/** @class */\nfunction () {\n function TargetChange(\n /**\r\n * An opaque, server-assigned token that allows watching a query to be resumed\r\n * after disconnecting without retransmitting all the data that matches the\r\n * query. The resume token essentially identifies a point in time from which\r\n * the server should resume sending results.\r\n */\n resumeToken,\n /**\r\n * The \"current\" (synced) status of this target. Note that \"current\"\r\n * has special meaning in the RPC protocol that implies that a target is\r\n * both up-to-date and consistent with the rest of the watch stream.\r\n */\n current,\n /**\r\n * The set of documents that were newly assigned to this target as part of\r\n * this remote event.\r\n */\n addedDocuments,\n /**\r\n * The set of documents that were already assigned to this target but received\r\n * an update during this remote event.\r\n */\n modifiedDocuments,\n /**\r\n * The set of documents that were removed from this target as part of this\r\n * remote event.\r\n */\n removedDocuments) {\n this.resumeToken = resumeToken;\n this.current = current;\n this.addedDocuments = addedDocuments;\n this.modifiedDocuments = modifiedDocuments;\n this.removedDocuments = removedDocuments;\n }\n /**\r\n * HACK: Views require TargetChanges in order to determine whether the view is\r\n * CURRENT, but secondary tabs don't receive remote events. So this method is\r\n * used to create a synthesized TargetChanges that can be used to apply a\r\n * CURRENT status change to a View, for queries executed in a different tab.\r\n */\n // PORTING NOTE: Multi-tab only\n\n\n TargetChange.createSynthesizedTargetChangeForCurrentChange = function (targetId, current) {\n return new TargetChange(emptyByteString(), current, documentKeySet(), documentKeySet(), documentKeySet());\n };\n\n return TargetChange;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Represents a changed document and a list of target ids to which this change\r\n * applies.\r\n *\r\n * If document has been deleted NoDocument will be provided.\r\n */\n\n\nvar DocumentWatchChange =\n/** @class */\nfunction () {\n function DocumentWatchChange(\n /** The new document applies to all of these targets. */\n updatedTargetIds,\n /** The new document is removed from all of these targets. */\n removedTargetIds,\n /** The key of the document for this change. */\n key,\n /**\r\n * The new document or NoDocument if it was deleted. Is null if the\r\n * document went out of view without the server sending a new document.\r\n */\n newDoc) {\n this.updatedTargetIds = updatedTargetIds;\n this.removedTargetIds = removedTargetIds;\n this.key = key;\n this.newDoc = newDoc;\n }\n\n return DocumentWatchChange;\n}();\n\nvar ExistenceFilterChange =\n/** @class */\nfunction () {\n function ExistenceFilterChange(targetId, existenceFilter) {\n this.targetId = targetId;\n this.existenceFilter = existenceFilter;\n }\n\n return ExistenceFilterChange;\n}();\n\nvar WatchTargetChangeState;\n\n(function (WatchTargetChangeState) {\n WatchTargetChangeState[WatchTargetChangeState[\"NoChange\"] = 0] = \"NoChange\";\n WatchTargetChangeState[WatchTargetChangeState[\"Added\"] = 1] = \"Added\";\n WatchTargetChangeState[WatchTargetChangeState[\"Removed\"] = 2] = \"Removed\";\n WatchTargetChangeState[WatchTargetChangeState[\"Current\"] = 3] = \"Current\";\n WatchTargetChangeState[WatchTargetChangeState[\"Reset\"] = 4] = \"Reset\";\n})(WatchTargetChangeState || (WatchTargetChangeState = {}));\n\nvar WatchTargetChange =\n/** @class */\nfunction () {\n function WatchTargetChange(\n /** What kind of change occurred to the watch target. */\n state,\n /** The target IDs that were added/removed/set. */\n targetIds,\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data that\r\n * matches the query. The resume token essentially identifies a point in\r\n * time from which the server should resume sending results.\r\n */\n resumeToken,\n /** An RPC error indicating why the watch failed. */\n cause) {\n if (resumeToken === void 0) {\n resumeToken = emptyByteString();\n }\n\n if (cause === void 0) {\n cause = null;\n }\n\n this.state = state;\n this.targetIds = targetIds;\n this.resumeToken = resumeToken;\n this.cause = cause;\n }\n\n return WatchTargetChange;\n}();\n/** Tracks the internal state of a Watch target. */\n\n\nvar TargetState =\n/** @class */\nfunction () {\n function TargetState() {\n /**\r\n * The number of pending responses (adds or removes) that we are waiting on.\r\n * We only consider targets active that have no pending responses.\r\n */\n this.pendingResponses = 0;\n /**\r\n * Keeps track of the document changes since the last raised snapshot.\r\n *\r\n * These changes are continuously updated as we receive document updates and\r\n * always reflect the current set of changes against the last issued snapshot.\r\n */\n\n this.documentChanges = snapshotChangesMap();\n /** See public getters for explanations of these fields. */\n\n this._resumeToken = emptyByteString();\n this._current = false;\n /**\r\n * Whether this target state should be included in the next snapshot. We\r\n * initialize to true so that newly-added targets are included in the next\r\n * RemoteEvent.\r\n */\n\n this._hasPendingChanges = true;\n }\n\n Object.defineProperty(TargetState.prototype, \"current\", {\n /**\r\n * Whether this target has been marked 'current'.\r\n *\r\n * 'Current' has special meaning in the RPC protocol: It implies that the\r\n * Watch backend has sent us all changes up to the point at which the target\r\n * was added and that the target is consistent with the rest of the watch\r\n * stream.\r\n */\n get: function get() {\n return this._current;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TargetState.prototype, \"resumeToken\", {\n /** The last resume token sent to us for this target. */\n get: function get() {\n return this._resumeToken;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TargetState.prototype, \"isPending\", {\n /** Whether this target has pending target adds or target removes. */\n get: function get() {\n return this.pendingResponses !== 0;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(TargetState.prototype, \"hasPendingChanges\", {\n /** Whether we have modified any state that should trigger a snapshot. */\n get: function get() {\n return this._hasPendingChanges;\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Applies the resume token to the TargetChange, but only when it has a new\r\n * value. Empty resumeTokens are discarded.\r\n */\n\n TargetState.prototype.updateResumeToken = function (resumeToken) {\n if (resumeToken.length > 0) {\n this._hasPendingChanges = true;\n this._resumeToken = resumeToken;\n }\n };\n /**\r\n * Creates a target change from the current set of changes.\r\n *\r\n * To reset the document changes after raising this snapshot, call\r\n * `clearPendingChanges()`.\r\n */\n\n\n TargetState.prototype.toTargetChange = function () {\n var addedDocuments = documentKeySet();\n var modifiedDocuments = documentKeySet();\n var removedDocuments = documentKeySet();\n this.documentChanges.forEach(function (key, changeType) {\n switch (changeType) {\n case ChangeType.Added:\n addedDocuments = addedDocuments.add(key);\n break;\n\n case ChangeType.Modified:\n modifiedDocuments = modifiedDocuments.add(key);\n break;\n\n case ChangeType.Removed:\n removedDocuments = removedDocuments.add(key);\n break;\n\n default:\n fail('Encountered invalid change type: ' + changeType);\n }\n });\n return new TargetChange(this._resumeToken, this._current, addedDocuments, modifiedDocuments, removedDocuments);\n };\n /**\r\n * Resets the document changes and sets `hasPendingChanges` to false.\r\n */\n\n\n TargetState.prototype.clearPendingChanges = function () {\n this._hasPendingChanges = false;\n this.documentChanges = snapshotChangesMap();\n };\n\n TargetState.prototype.addDocumentChange = function (key, changeType) {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.insert(key, changeType);\n };\n\n TargetState.prototype.removeDocumentChange = function (key) {\n this._hasPendingChanges = true;\n this.documentChanges = this.documentChanges.remove(key);\n };\n\n TargetState.prototype.recordPendingTargetRequest = function () {\n this.pendingResponses += 1;\n };\n\n TargetState.prototype.recordTargetResponse = function () {\n this.pendingResponses -= 1;\n };\n\n TargetState.prototype.markCurrent = function () {\n this._hasPendingChanges = true;\n this._current = true;\n };\n\n return TargetState;\n}();\n/**\r\n * A helper class to accumulate watch changes into a RemoteEvent.\r\n */\n\n\nvar WatchChangeAggregator =\n/** @class */\nfunction () {\n function WatchChangeAggregator(metadataProvider) {\n this.metadataProvider = metadataProvider;\n /** The internal state of all tracked targets. */\n\n this.targetStates = {};\n /** Keeps track of the documents to update since the last raised snapshot. */\n\n this.pendingDocumentUpdates = maybeDocumentMap();\n /** A mapping of document keys to their set of target IDs. */\n\n this.pendingDocumentTargetMapping = documentTargetMap();\n /**\r\n * A list of targets with existence filter mismatches. These targets are\r\n * known to be inconsistent and their listens needs to be re-established by\r\n * RemoteStore.\r\n */\n\n this.pendingTargetResets = new SortedSet(primitiveComparator);\n }\n /**\r\n * Processes and adds the DocumentWatchChange to the current set of changes.\r\n */\n\n\n WatchChangeAggregator.prototype.handleDocumentChange = function (docChange) {\n for (var _i = 0, _a = docChange.updatedTargetIds; _i < _a.length; _i++) {\n var targetId = _a[_i];\n\n if (docChange.newDoc instanceof Document) {\n this.addDocumentToTarget(targetId, docChange.newDoc);\n } else if (docChange.newDoc instanceof NoDocument) {\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n }\n\n for (var _b = 0, _c = docChange.removedTargetIds; _b < _c.length; _b++) {\n var targetId = _c[_b];\n this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc);\n }\n };\n /** Processes and adds the WatchTargetChange to the current set of changes. */\n\n\n WatchChangeAggregator.prototype.handleTargetChange = function (targetChange) {\n var _this = this;\n\n this.forEachTarget(targetChange, function (targetId) {\n var targetState = _this.ensureTargetState(targetId);\n\n switch (targetChange.state) {\n case WatchTargetChangeState.NoChange:\n if (_this.isActiveTarget(targetId)) {\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n\n break;\n\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\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\n targetState.updateResumeToken(targetChange.resumeToken);\n break;\n\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\n if (!targetState.isPending) {\n _this.removeTarget(targetId);\n }\n\n assert(!targetChange.cause, 'WatchChangeAggregator does not handle errored targets');\n break;\n\n case WatchTargetChangeState.Current:\n if (_this.isActiveTarget(targetId)) {\n targetState.markCurrent();\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n\n break;\n\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\n targetState.updateResumeToken(targetChange.resumeToken);\n }\n\n break;\n\n default:\n fail('Unknown target watch change state: ' + targetChange.state);\n }\n });\n };\n /**\r\n * Iterates over all targetIds that the watch change applies to: either the\r\n * targetIds explicitly listed in the change or the targetIds of all currently\r\n * active targets.\r\n */\n\n\n WatchChangeAggregator.prototype.forEachTarget = function (targetChange, fn) {\n if (targetChange.targetIds.length > 0) {\n targetChange.targetIds.forEach(fn);\n } else {\n forEachNumber(this.targetStates, fn);\n }\n };\n /**\r\n * Handles existence filters and synthesizes deletes for filter mismatches.\r\n * Targets that are invalidated by filter mismatches are added to\r\n * `pendingTargetResets`.\r\n */\n\n\n WatchChangeAggregator.prototype.handleExistenceFilter = function (watchChange) {\n var targetId = watchChange.targetId;\n var expectedCount = watchChange.existenceFilter.count;\n var queryData = this.queryDataForActiveTarget(targetId);\n\n if (queryData) {\n var query = queryData.query;\n\n if (query.isDocumentQuery()) {\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 var key = new DocumentKey(query.path);\n this.removeDocumentFromTarget(targetId, key, new NoDocument(key, SnapshotVersion.forDeletedDoc()));\n } else {\n assert(expectedCount === 1, 'Single document existence filter with count: ' + expectedCount);\n }\n } else {\n var currentSize = this.getCurrentDocumentCountForTarget(targetId);\n\n if (currentSize !== expectedCount) {\n // Existence filter mismatch: We reset the mapping and raise a new\n // snapshot with `isFromCache:true`.\n this.resetTarget(targetId);\n this.pendingTargetResets = this.pendingTargetResets.add(targetId);\n }\n }\n }\n };\n /**\r\n * Converts the currently accumulated state into a remote event at the\r\n * provided snapshot version. Resets the accumulated changes before returning.\r\n */\n\n\n WatchChangeAggregator.prototype.createRemoteEvent = function (snapshotVersion) {\n var _this = this;\n\n var targetChanges = {};\n forEachNumber(this.targetStates, function (targetId, targetState) {\n var queryData = _this.queryDataForActiveTarget(targetId);\n\n if (queryData) {\n if (targetState.current && queryData.query.isDocumentQuery()) {\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 query\n // instead resulting in an explicit delete message and we could\n // remove this special logic.\n var key = new DocumentKey(queryData.query.path);\n\n if (_this.pendingDocumentUpdates.get(key) === null && !_this.targetContainsDocument(targetId, key)) {\n _this.removeDocumentFromTarget(targetId, key, new NoDocument(key, snapshotVersion));\n }\n }\n\n if (targetState.hasPendingChanges) {\n targetChanges[targetId] = targetState.toTargetChange();\n targetState.clearPendingChanges();\n }\n }\n });\n var resolvedLimboDocuments = documentKeySet(); // We extract the set of limbo-only document updates as the GC logic\n // special-cases documents that do not appear in the query cache.\n //\n // TODO(gsoltis): Expand on this comment once GC is available in the JS\n // client.\n\n this.pendingDocumentTargetMapping.forEach(function (key, targets) {\n var isOnlyLimboTarget = true;\n targets.forEachWhile(function (targetId) {\n var queryData = _this.queryDataForActiveTarget(targetId);\n\n if (queryData && queryData.purpose !== QueryPurpose.LimboResolution) {\n isOnlyLimboTarget = false;\n return false;\n }\n\n return true;\n });\n\n if (isOnlyLimboTarget) {\n resolvedLimboDocuments = resolvedLimboDocuments.add(key);\n }\n });\n var remoteEvent = new RemoteEvent(snapshotVersion, targetChanges, this.pendingTargetResets, this.pendingDocumentUpdates, resolvedLimboDocuments);\n this.pendingDocumentUpdates = maybeDocumentMap();\n this.pendingDocumentTargetMapping = documentTargetMap();\n this.pendingTargetResets = new SortedSet(primitiveComparator);\n return remoteEvent;\n };\n /**\r\n * Adds the provided document to the internal list of document updates and\r\n * its document key to the given target's mapping.\r\n */\n // Visible for testing.\n\n\n WatchChangeAggregator.prototype.addDocumentToTarget = function (targetId, document) {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n var changeType = this.targetContainsDocument(targetId, document.key) ? ChangeType.Modified : ChangeType.Added;\n var targetState = this.ensureTargetState(targetId);\n targetState.addDocumentChange(document.key, changeType);\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(document.key, document);\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(document.key, this.ensureDocumentTargetMapping(document.key).add(targetId));\n };\n /**\r\n * Removes the provided document from the target mapping. If the\r\n * document no longer matches the target, but the document's state is still\r\n * known (e.g. we know that the document was deleted or we received the change\r\n * that caused the filter mismatch), the new document can be provided\r\n * to update the remote document cache.\r\n */\n // Visible for testing.\n\n\n WatchChangeAggregator.prototype.removeDocumentFromTarget = function (targetId, key, updatedDocument) {\n if (!this.isActiveTarget(targetId)) {\n return;\n }\n\n var targetState = this.ensureTargetState(targetId);\n\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 = this.pendingDocumentTargetMapping.insert(key, this.ensureDocumentTargetMapping(key).delete(targetId));\n\n if (updatedDocument) {\n this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(key, updatedDocument);\n }\n };\n\n WatchChangeAggregator.prototype.removeTarget = function (targetId) {\n delete this.targetStates[targetId];\n };\n /**\r\n * Returns the current count of documents in the target. This includes both\r\n * the number of documents that the LocalStore considers to be part of the\r\n * target as well as any accumulated changes.\r\n */\n\n\n WatchChangeAggregator.prototype.getCurrentDocumentCountForTarget = function (targetId) {\n var targetState = this.ensureTargetState(targetId);\n var targetChange = targetState.toTargetChange();\n return this.metadataProvider.getRemoteKeysForTarget(targetId).size + targetChange.addedDocuments.size - targetChange.removedDocuments.size;\n };\n /**\r\n * Increment the number of acks needed from watch before we can consider the\r\n * server to be 'in-sync' with the client's active targets.\r\n */\n\n\n WatchChangeAggregator.prototype.recordPendingTargetRequest = function (targetId) {\n // For each request we get we need to record we need a response for it.\n var targetState = this.ensureTargetState(targetId);\n targetState.recordPendingTargetRequest();\n };\n\n WatchChangeAggregator.prototype.ensureTargetState = function (targetId) {\n if (!this.targetStates[targetId]) {\n this.targetStates[targetId] = new TargetState();\n }\n\n return this.targetStates[targetId];\n };\n\n WatchChangeAggregator.prototype.ensureDocumentTargetMapping = function (key) {\n var targetMapping = this.pendingDocumentTargetMapping.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentTargetMapping = this.pendingDocumentTargetMapping.insert(key, targetMapping);\n }\n\n return targetMapping;\n };\n /**\r\n * Verifies that the user is still interested in this target (by calling\r\n * `getQueryDataForTarget()`) and that we are not waiting for pending ADDs\r\n * from watch.\r\n */\n\n\n WatchChangeAggregator.prototype.isActiveTarget = function (targetId) {\n return this.queryDataForActiveTarget(targetId) !== null;\n };\n /**\r\n * Returns the QueryData for an active target (i.e. a target that the user\r\n * is still interested in that has no outstanding target change requests).\r\n */\n\n\n WatchChangeAggregator.prototype.queryDataForActiveTarget = function (targetId) {\n var targetState = this.targetStates[targetId];\n return targetState && targetState.isPending ? null : this.metadataProvider.getQueryDataForTarget(targetId);\n };\n /**\r\n * Resets the state of a Watch target to its initial state (e.g. sets\r\n * 'current' to false, clears the resume token and removes its target mapping\r\n * from all documents).\r\n */\n\n\n WatchChangeAggregator.prototype.resetTarget = function (targetId) {\n var _this = this;\n\n assert(!this.targetStates[targetId].isPending, 'Should only reset active targets');\n this.targetStates[targetId] = new TargetState(); // 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\n var existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n existingKeys.forEach(function (key) {\n _this.removeDocumentFromTarget(targetId, key,\n /*updatedDocument=*/\n null);\n });\n };\n /**\r\n * Returns whether the LocalStore considers the document to be part of the\r\n * specified target.\r\n */\n\n\n WatchChangeAggregator.prototype.targetContainsDocument = function (targetId, key) {\n var existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId);\n return existingKeys.has(key);\n };\n\n return WatchChangeAggregator;\n}();\n\nfunction documentTargetMap() {\n return new SortedMap(DocumentKey.comparator);\n}\n\nfunction snapshotChangesMap() {\n return new SortedMap(DocumentKey.comparator);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar DIRECTIONS = function () {\n var dirs = {};\n dirs[Direction.ASCENDING.name] = 'ASCENDING';\n dirs[Direction.DESCENDING.name] = 'DESCENDING';\n return dirs;\n}();\n\nvar OPERATORS = function () {\n var ops = {};\n ops[RelationOp.LESS_THAN.name] = 'LESS_THAN';\n ops[RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';\n ops[RelationOp.GREATER_THAN.name] = 'GREATER_THAN';\n ops[RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';\n ops[RelationOp.EQUAL.name] = 'EQUAL';\n ops[RelationOp.ARRAY_CONTAINS.name] = 'ARRAY_CONTAINS';\n return ops;\n}(); // A RegExp matching ISO 8601 UTC timestamps with optional fraction.\n\n\nvar ISO_REG_EXP = new RegExp(/^\\d{4}-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d(?:\\.(\\d+))?Z$/);\n\nfunction assertPresent(value, description) {\n assert(!isNullOrUndefined(value), description + ' is missing');\n}\n\nfunction parseInt64(value) {\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 fail(\"can't parse \" + value);\n }\n}\n/**\r\n * Generates JsonObject values for the Datastore API suitable for sending to\r\n * either GRPC stub methods or via the JSON/HTTP REST API.\r\n * TODO(klimt): We can remove the databaseId argument if we keep the full\r\n * resource name in documents.\r\n */\n\n\nvar JsonProtoSerializer =\n/** @class */\nfunction () {\n function JsonProtoSerializer(databaseId, options) {\n this.databaseId = databaseId;\n this.options = options;\n }\n\n JsonProtoSerializer.prototype.emptyByteString = function () {\n if (this.options.useProto3Json) {\n return '';\n } else {\n return new Uint8Array(0);\n }\n };\n\n JsonProtoSerializer.prototype.unsafeCastProtoByteString = function (byteString) {\n // byteStrings can be either string or UInt8Array, but the typings say\n // it's always a string. Cast as string to avoid type check failing\n return byteString;\n };\n\n JsonProtoSerializer.prototype.fromRpcStatus = function (status) {\n var code = status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code);\n return new FirestoreError(code, status.message || '');\n };\n /**\r\n * Returns a value for a number (or undefined) that's appropriate to put into\r\n * a google.protobuf.Int32Value proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"number\" because that's what\r\n * our generated proto interfaces say Int32Value must be. But GRPC actually\r\n * expects a { value: } struct.\r\n */\n\n\n JsonProtoSerializer.prototype.toInt32Value = function (val) {\n if (!isNullOrUndefined(val)) {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n return {\n value: val\n };\n } else {\n return undefined;\n }\n };\n /**\r\n * Returns a number (or null) from a google.protobuf.Int32Value proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as accepting \"number\" because that's what\r\n * our generated proto interfaces say Int32Value must be, but it actually\r\n * accepts { value: number } to match our serialization in toInt32Value().\r\n */\n\n\n JsonProtoSerializer.prototype.fromInt32Value = function (val) {\n var result;\n\n if (typeof val === 'object') {\n // tslint:disable-next-line:no-any We need to match generated Proto types.\n result = val.value;\n } else {\n // We accept raw numbers (without the {value: ... } wrapper) for\n // compatibility with legacy persisted data.\n result = val;\n }\n\n return isNullOrUndefined(result) ? null : result;\n };\n /**\r\n * Returns a value for a Date that's appropriate to put into a proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"string\" because that's what\r\n * our generated proto interfaces say dates must be. But it's easier and safer\r\n * to actually return a Timestamp proto.\r\n */\n\n\n JsonProtoSerializer.prototype.toTimestamp = function (timestamp) {\n return {\n seconds: timestamp.seconds,\n nanos: timestamp.nanoseconds // tslint:disable-next-line:no-any\n\n };\n };\n\n JsonProtoSerializer.prototype.fromTimestamp = function (date) {\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 // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(this.options.useProto3Json,\n // 'The timestamp string format requires Proto3.');\n return this.fromIso8601String(date);\n } else {\n assert(!!date, 'Cannot deserialize null or undefined timestamp.'); // TODO(b/37282237): Use strings for Proto3 timestamps\n // assert(!this.options.useProto3Json,\n // 'The timestamp instance format requires Proto JS.');\n\n var seconds = parseInt64(date.seconds || '0');\n var nanos = date.nanos || 0;\n return new Timestamp(seconds, nanos);\n }\n };\n\n JsonProtoSerializer.prototype.fromIso8601String = function (utc) {\n // The date string can have higher precision (nanos) than the Date class\n // (millis), so we do some custom parsing here.\n // Parse the nanos right out of the string.\n var nanos = 0;\n var fraction = ISO_REG_EXP.exec(utc);\n assert(!!fraction, 'invalid timestamp: ' + utc);\n\n if (fraction[1]) {\n // Pad the fraction out to 9 digits (nanos).\n var nanoStr = fraction[1];\n nanoStr = (nanoStr + '000000000').substr(0, 9);\n nanos = Number(nanoStr);\n } // Parse the date to get the seconds.\n\n\n var date = new Date(utc);\n var seconds = Math.floor(date.getTime() / 1000);\n return new Timestamp(seconds, nanos);\n };\n /**\r\n * Returns a value for bytes that's appropriate to put in a proto.\r\n * DO NOT USE THIS FOR ANYTHING ELSE.\r\n * This method cheats. It's typed as returning \"string\" because that's what\r\n * our generated proto interfaces say bytes must be. But it should return\r\n * an Uint8Array in Node.\r\n */\n\n\n JsonProtoSerializer.prototype.toBytes = function (bytes) {\n if (this.options.useProto3Json) {\n return bytes.toBase64();\n } else {\n // The typings say it's a string, but it needs to be a Uint8Array in Node.\n return this.unsafeCastProtoByteString(bytes.toUint8Array());\n }\n };\n /**\r\n * Parse the blob from the protos into the internal Blob class. Note that the\r\n * typings assume all blobs are strings, but they are actually Uint8Arrays\r\n * on Node.\r\n */\n\n\n JsonProtoSerializer.prototype.fromBlob = function (blob) {\n if (typeof blob === 'string') {\n assert(this.options.useProto3Json, 'Expected bytes to be passed in as Uint8Array, but got a string instead.');\n return Blob.fromBase64String(blob);\n } else {\n assert(!this.options.useProto3Json, 'Expected bytes to be passed in as string, but got something else instead.');\n return Blob.fromUint8Array(blob);\n }\n };\n\n JsonProtoSerializer.prototype.toVersion = function (version) {\n return this.toTimestamp(version.toTimestamp());\n };\n\n JsonProtoSerializer.prototype.fromVersion = function (version) {\n assert(!!version, \"Trying to deserialize version that isn't set\");\n return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));\n };\n\n JsonProtoSerializer.prototype.toResourceName = function (databaseId, path) {\n return this.fullyQualifiedPrefixPath(databaseId).child('documents').child(path).canonicalString();\n };\n\n JsonProtoSerializer.prototype.fromResourceName = function (name) {\n var resource = ResourcePath.fromString(name);\n assert(this.isValidResourceName(resource), 'Tried to deserialize invalid key ' + resource.toString());\n return resource;\n };\n\n JsonProtoSerializer.prototype.toName = function (key) {\n return this.toResourceName(this.databaseId, key.path);\n };\n\n JsonProtoSerializer.prototype.fromName = function (name) {\n var resource = this.fromResourceName(name);\n assert(resource.get(1) === this.databaseId.projectId, 'Tried to deserialize key from different project: ' + resource.get(1) + ' vs ' + this.databaseId.projectId);\n assert(!resource.get(3) && !this.databaseId.database || resource.get(3) === this.databaseId.database, 'Tried to deserialize key from different database: ' + resource.get(3) + ' vs ' + this.databaseId.database);\n return new DocumentKey(this.extractLocalPathFromResourceName(resource));\n };\n\n JsonProtoSerializer.prototype.toQueryPath = function (path) {\n if (path.length === 0) {\n // If the path is empty, the backend requires we leave off the /documents\n // at the end.\n return this.encodedDatabaseId;\n }\n\n return this.toResourceName(this.databaseId, path);\n };\n\n JsonProtoSerializer.prototype.fromQueryPath = function (name) {\n var resourceName = this.fromResourceName(name);\n\n if (resourceName.length === 4) {\n return ResourcePath.EMPTY_PATH;\n }\n\n return this.extractLocalPathFromResourceName(resourceName);\n };\n\n Object.defineProperty(JsonProtoSerializer.prototype, \"encodedDatabaseId\", {\n get: function get() {\n var path = new ResourcePath(['projects', this.databaseId.projectId, 'databases', this.databaseId.database]);\n return path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n\n JsonProtoSerializer.prototype.fullyQualifiedPrefixPath = function (databaseId) {\n return new ResourcePath(['projects', databaseId.projectId, 'databases', databaseId.database]);\n };\n\n JsonProtoSerializer.prototype.extractLocalPathFromResourceName = function (resourceName) {\n assert(resourceName.length > 4 && resourceName.get(4) === 'documents', 'tried to deserialize invalid key ' + resourceName.toString());\n return resourceName.popFirst(5);\n };\n\n JsonProtoSerializer.prototype.isValidResourceName = function (path) {\n // Resource names have at least 4 components (project ID, database ID)\n return path.length >= 4 && path.get(0) === 'projects' && path.get(2) === 'databases';\n };\n\n JsonProtoSerializer.prototype.toValue = function (val) {\n if (val instanceof NullValue) {\n return {\n nullValue: 'NULL_VALUE'\n };\n } else if (val instanceof BooleanValue) {\n return {\n booleanValue: val.value()\n };\n } else if (val instanceof IntegerValue) {\n return {\n integerValue: '' + val.value()\n };\n } else if (val instanceof DoubleValue) {\n var doubleValue = val.value();\n\n if (this.options.useProto3Json) {\n // Proto 3 let's us encode NaN and Infinity as string values as\n // expected by the backend. This is currently not checked by our unit\n // tests because they rely on protobuf.js.\n if (isNaN(doubleValue)) {\n return {\n doubleValue: 'NaN'\n };\n } else if (doubleValue === Infinity) {\n return {\n doubleValue: 'Infinity'\n };\n } else if (doubleValue === -Infinity) {\n return {\n doubleValue: '-Infinity'\n };\n }\n }\n\n return {\n doubleValue: val.value()\n };\n } else if (val instanceof StringValue) {\n return {\n stringValue: val.value()\n };\n } else if (val instanceof ObjectValue) {\n return {\n mapValue: this.toMapValue(val)\n };\n } else if (val instanceof ArrayValue) {\n return {\n arrayValue: this.toArrayValue(val)\n };\n } else if (val instanceof TimestampValue) {\n return {\n timestampValue: this.toTimestamp(val.internalValue)\n };\n } else if (val instanceof GeoPointValue) {\n return {\n geoPointValue: {\n latitude: val.value().latitude,\n longitude: val.value().longitude\n }\n };\n } else if (val instanceof BlobValue) {\n return {\n bytesValue: this.toBytes(val.value())\n };\n } else if (val instanceof RefValue) {\n return {\n referenceValue: this.toResourceName(val.databaseId, val.key.path)\n };\n } else {\n return fail('Unknown FieldValue ' + JSON.stringify(val));\n }\n };\n\n JsonProtoSerializer.prototype.fromValue = function (obj) {\n var _this = this; // tslint:disable-next-line:no-any\n\n\n var type = obj['value_type'];\n\n if (hasTag(obj, type, 'nullValue')) {\n return NullValue.INSTANCE;\n } else if (hasTag(obj, type, 'booleanValue')) {\n return BooleanValue.of(obj.booleanValue);\n } else if (hasTag(obj, type, 'integerValue')) {\n return new IntegerValue(parseInt64(obj.integerValue));\n } else if (hasTag(obj, type, 'doubleValue')) {\n if (this.options.useProto3Json) {\n // Proto 3 uses the string values 'NaN' and 'Infinity'.\n if (obj.doubleValue === 'NaN') {\n return DoubleValue.NAN;\n } else if (obj.doubleValue === 'Infinity') {\n return DoubleValue.POSITIVE_INFINITY;\n } else if (obj.doubleValue === '-Infinity') {\n return DoubleValue.NEGATIVE_INFINITY;\n }\n }\n\n return new DoubleValue(obj.doubleValue);\n } else if (hasTag(obj, type, 'stringValue')) {\n return new StringValue(obj.stringValue);\n } else if (hasTag(obj, type, 'mapValue')) {\n return this.fromFields(obj.mapValue.fields || {});\n } else if (hasTag(obj, type, 'arrayValue')) {\n // \"values\" is not present if the array is empty\n assertPresent(obj.arrayValue, 'arrayValue');\n var values$$1 = obj.arrayValue.values || [];\n return new ArrayValue(values$$1.map(function (v) {\n return _this.fromValue(v);\n }));\n } else if (hasTag(obj, type, 'timestampValue')) {\n assertPresent(obj.timestampValue, 'timestampValue');\n return new TimestampValue(this.fromTimestamp(obj.timestampValue));\n } else if (hasTag(obj, type, 'geoPointValue')) {\n assertPresent(obj.geoPointValue, 'geoPointValue');\n var latitude = obj.geoPointValue.latitude || 0;\n var longitude = obj.geoPointValue.longitude || 0;\n return new GeoPointValue(new GeoPoint(latitude, longitude));\n } else if (hasTag(obj, type, 'bytesValue')) {\n assertPresent(obj.bytesValue, 'bytesValue');\n var blob = this.fromBlob(obj.bytesValue);\n return new BlobValue(blob);\n } else if (hasTag(obj, type, 'referenceValue')) {\n assertPresent(obj.referenceValue, 'referenceValue');\n var resourceName = this.fromResourceName(obj.referenceValue);\n var dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));\n var key = new DocumentKey(this.extractLocalPathFromResourceName(resourceName));\n return new RefValue(dbId, key);\n } else {\n return fail('Unknown Value proto ' + JSON.stringify(obj));\n }\n };\n /** Creates an api.Document from key and fields (but no create/update time) */\n\n\n JsonProtoSerializer.prototype.toMutationDocument = function (key, fields) {\n return {\n name: this.toName(key),\n fields: this.toFields(fields)\n };\n };\n\n JsonProtoSerializer.prototype.toDocument = function (document) {\n assert(!document.hasLocalMutations, \"Can't serialize documents with mutations.\");\n return {\n name: this.toName(document.key),\n fields: this.toFields(document.data),\n updateTime: this.toTimestamp(document.version.toTimestamp())\n };\n };\n\n JsonProtoSerializer.prototype.fromDocument = function (document, hasCommittedMutations) {\n return new Document(this.fromName(document.name), this.fromVersion(document.updateTime), this.fromFields(document.fields || {}), {\n hasCommittedMutations: !!hasCommittedMutations\n });\n };\n\n JsonProtoSerializer.prototype.toFields = function (fields) {\n var _this = this;\n\n var result = {};\n fields.forEach(function (key, value) {\n result[key] = _this.toValue(value);\n });\n return result;\n };\n\n JsonProtoSerializer.prototype.fromFields = function (object) {\n var _this = this; // Proto map gets mapped to Object, so cast it.\n\n\n var map = object;\n var result = ObjectValue.EMPTY;\n forEach(map, function (key, value) {\n result = result.set(new FieldPath([key]), _this.fromValue(value));\n });\n return result;\n };\n\n JsonProtoSerializer.prototype.toMapValue = function (map) {\n return {\n fields: this.toFields(map)\n };\n };\n\n JsonProtoSerializer.prototype.toArrayValue = function (array) {\n var _this = this;\n\n var result = [];\n array.forEach(function (value) {\n result.push(_this.toValue(value));\n });\n return {\n values: result\n };\n };\n\n JsonProtoSerializer.prototype.fromFound = function (doc) {\n assert(!!doc.found, 'Tried to deserialize a found document from a missing document.');\n assertPresent(doc.found.name, 'doc.found.name');\n assertPresent(doc.found.updateTime, 'doc.found.updateTime');\n var key = this.fromName(doc.found.name);\n var version = this.fromVersion(doc.found.updateTime);\n var fields = this.fromFields(doc.found.fields || {});\n return new Document(key, version, fields, {});\n };\n\n JsonProtoSerializer.prototype.fromMissing = function (result) {\n assert(!!result.missing, 'Tried to deserialize a missing document from a found document.');\n assert(!!result.readTime, 'Tried to deserialize a missing document without a read time.');\n var key = this.fromName(result.missing);\n var version = this.fromVersion(result.readTime);\n return new NoDocument(key, version);\n };\n\n JsonProtoSerializer.prototype.fromMaybeDocument = function (result) {\n // tslint:disable-next-line:no-any\n var type = result['result'];\n\n if (hasTag(result, type, 'found')) {\n return this.fromFound(result);\n } else if (hasTag(result, type, 'missing')) {\n return this.fromMissing(result);\n }\n\n return fail('invalid batch get response: ' + JSON.stringify(result));\n };\n\n JsonProtoSerializer.prototype.toWatchTargetChangeState = function (state) {\n switch (state) {\n case WatchTargetChangeState.Added:\n return 'ADD';\n\n case WatchTargetChangeState.Current:\n return 'CURRENT';\n\n case WatchTargetChangeState.NoChange:\n return 'NO_CHANGE';\n\n case WatchTargetChangeState.Removed:\n return 'REMOVE';\n\n case WatchTargetChangeState.Reset:\n return 'RESET';\n\n default:\n return fail('Unknown WatchTargetChangeState: ' + state);\n }\n };\n\n JsonProtoSerializer.prototype.toTestWatchChange = function (watchChange) {\n if (watchChange instanceof ExistenceFilterChange) {\n return {\n filter: {\n count: watchChange.existenceFilter.count,\n targetId: watchChange.targetId\n }\n };\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n if (watchChange.newDoc instanceof Document) {\n var doc = watchChange.newDoc;\n return {\n documentChange: {\n document: {\n name: this.toName(doc.key),\n fields: this.toFields(doc.data),\n updateTime: this.toVersion(doc.version)\n },\n targetIds: watchChange.updatedTargetIds,\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n } else if (watchChange.newDoc instanceof NoDocument) {\n var doc = watchChange.newDoc;\n return {\n documentDelete: {\n document: this.toName(doc.key),\n readTime: this.toVersion(doc.version),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n } else if (watchChange.newDoc === null) {\n return {\n documentRemove: {\n document: this.toName(watchChange.key),\n removedTargetIds: watchChange.removedTargetIds\n }\n };\n }\n }\n\n if (watchChange instanceof WatchTargetChange) {\n var cause = undefined;\n\n if (watchChange.cause) {\n cause = {\n code: mapRpcCodeFromCode(watchChange.cause.code),\n message: watchChange.cause.message\n };\n }\n\n return {\n targetChange: {\n targetChangeType: this.toWatchTargetChangeState(watchChange.state),\n targetIds: watchChange.targetIds,\n resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),\n cause: cause\n }\n };\n }\n\n return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));\n };\n\n JsonProtoSerializer.prototype.fromWatchChange = function (change) {\n // tslint:disable-next-line:no-any\n var type = change['response_type'];\n var watchChange;\n\n if (hasTag(change, type, 'targetChange')) {\n assertPresent(change.targetChange, 'targetChange'); // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'\n // if unset\n\n var state = this.fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE');\n var targetIds = change.targetChange.targetIds || [];\n var resumeToken = change.targetChange.resumeToken || this.emptyByteString();\n var causeProto = change.targetChange.cause;\n var cause = causeProto && this.fromRpcStatus(causeProto);\n watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null);\n } else if (hasTag(change, type, 'documentChange')) {\n assertPresent(change.documentChange, 'documentChange');\n assertPresent(change.documentChange.document, 'documentChange.name');\n assertPresent(change.documentChange.document.name, 'documentChange.document.name');\n assertPresent(change.documentChange.document.updateTime, 'documentChange.document.updateTime');\n var entityChange = change.documentChange;\n var key = this.fromName(entityChange.document.name);\n var version = this.fromVersion(entityChange.document.updateTime);\n var fields = this.fromFields(entityChange.document.fields || {});\n var doc = new Document(key, version, fields, {});\n var updatedTargetIds = entityChange.targetIds || [];\n var removedTargetIds = entityChange.removedTargetIds || [];\n watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc);\n } else if (hasTag(change, type, 'documentDelete')) {\n assertPresent(change.documentDelete, 'documentDelete');\n assertPresent(change.documentDelete.document, 'documentDelete.document');\n var docDelete = change.documentDelete;\n var key = this.fromName(docDelete.document);\n var version = docDelete.readTime ? this.fromVersion(docDelete.readTime) : SnapshotVersion.forDeletedDoc();\n var doc = new NoDocument(key, version);\n var removedTargetIds = docDelete.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);\n } else if (hasTag(change, type, 'documentRemove')) {\n assertPresent(change.documentRemove, 'documentRemove');\n assertPresent(change.documentRemove.document, 'documentRemove');\n var docRemove = change.documentRemove;\n var key = this.fromName(docRemove.document);\n var removedTargetIds = docRemove.removedTargetIds || [];\n watchChange = new DocumentWatchChange([], removedTargetIds, key, null);\n } else if (hasTag(change, type, 'filter')) {\n // TODO(dimond): implement existence filter parsing with strategy.\n assertPresent(change.filter, 'filter');\n assertPresent(change.filter.targetId, 'filter.targetId');\n var filter = change.filter;\n var count = filter.count || 0;\n var existenceFilter = new ExistenceFilter(count);\n var targetId = filter.targetId;\n watchChange = new ExistenceFilterChange(targetId, existenceFilter);\n } else {\n return fail('Unknown change type ' + JSON.stringify(change));\n }\n\n return watchChange;\n };\n\n JsonProtoSerializer.prototype.fromWatchTargetChangeState = function (state) {\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\n JsonProtoSerializer.prototype.versionFromListenResponse = function (change) {\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 // tslint:disable-next-line:no-any\n var type = change['response_type'];\n\n if (!hasTag(change, type, 'targetChange')) {\n return SnapshotVersion.MIN;\n }\n\n var targetChange = change.targetChange;\n\n if (targetChange.targetIds && targetChange.targetIds.length) {\n return SnapshotVersion.MIN;\n }\n\n if (!targetChange.readTime) {\n return SnapshotVersion.MIN;\n }\n\n return this.fromVersion(targetChange.readTime);\n };\n\n JsonProtoSerializer.prototype.toMutation = function (mutation) {\n var _this = this;\n\n var result;\n\n if (mutation instanceof SetMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.value)\n };\n } else if (mutation instanceof DeleteMutation) {\n result = {\n delete: this.toName(mutation.key)\n };\n } else if (mutation instanceof PatchMutation) {\n result = {\n update: this.toMutationDocument(mutation.key, mutation.data),\n updateMask: this.toDocumentMask(mutation.fieldMask)\n };\n } else if (mutation instanceof TransformMutation) {\n result = {\n transform: {\n document: this.toName(mutation.key),\n fieldTransforms: mutation.fieldTransforms.map(function (transform) {\n return _this.toFieldTransform(transform);\n })\n }\n };\n } else {\n return fail('Unknown mutation type ' + mutation.type);\n }\n\n if (!mutation.precondition.isNone) {\n result.currentDocument = this.toPrecondition(mutation.precondition);\n }\n\n return result;\n };\n\n JsonProtoSerializer.prototype.fromMutation = function (proto) {\n var _this = this;\n\n var precondition = proto.currentDocument ? this.fromPrecondition(proto.currentDocument) : Precondition.NONE;\n\n if (proto.update) {\n assertPresent(proto.update.name, 'name');\n var key = this.fromName(proto.update.name);\n var value = this.fromFields(proto.update.fields || {});\n\n if (proto.updateMask) {\n var fieldMask = this.fromDocumentMask(proto.updateMask);\n return new PatchMutation(key, value, fieldMask, precondition);\n } else {\n return new SetMutation(key, value, precondition);\n }\n } else if (proto.delete) {\n var key = this.fromName(proto.delete);\n return new DeleteMutation(key, precondition);\n } else if (proto.transform) {\n var key = this.fromName(proto.transform.document);\n var fieldTransforms = proto.transform.fieldTransforms.map(function (transform) {\n return _this.fromFieldTransform(transform);\n });\n assert(precondition.exists === true, 'Transforms only support precondition \"exists == true\"');\n return new TransformMutation(key, fieldTransforms);\n } else {\n return fail('unknown mutation proto: ' + JSON.stringify(proto));\n }\n };\n\n JsonProtoSerializer.prototype.toPrecondition = function (precondition) {\n assert(!precondition.isNone, \"Can't serialize an empty precondition\");\n\n if (precondition.updateTime !== undefined) {\n return {\n updateTime: this.toVersion(precondition.updateTime)\n };\n } else if (precondition.exists !== undefined) {\n return {\n exists: precondition.exists\n };\n } else {\n return fail('Unknown precondition');\n }\n };\n\n JsonProtoSerializer.prototype.fromPrecondition = function (precondition) {\n if (precondition.updateTime !== undefined) {\n return Precondition.updateTime(this.fromVersion(precondition.updateTime));\n } else if (precondition.exists !== undefined) {\n return Precondition.exists(precondition.exists);\n } else {\n return Precondition.NONE;\n }\n };\n\n JsonProtoSerializer.prototype.fromWriteResult = function (proto, commitTime) {\n var _this = this; // NOTE: Deletes don't have an updateTime.\n\n\n var version = proto.updateTime ? this.fromVersion(proto.updateTime) : this.fromVersion(commitTime);\n var transformResults = null;\n\n if (proto.transformResults && proto.transformResults.length > 0) {\n transformResults = proto.transformResults.map(function (result) {\n return _this.fromValue(result);\n });\n }\n\n return new MutationResult(version, transformResults);\n };\n\n JsonProtoSerializer.prototype.fromWriteResults = function (protos, commitTime) {\n var _this = this;\n\n if (protos && protos.length > 0) {\n assert(commitTime !== undefined, 'Received a write result without a commit time');\n return protos.map(function (proto) {\n return _this.fromWriteResult(proto, commitTime);\n });\n } else {\n return [];\n }\n };\n\n JsonProtoSerializer.prototype.toFieldTransform = function (fieldTransform) {\n var _this = this;\n\n var transform = fieldTransform.transform;\n\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.map(function (v) {\n return _this.toValue(v);\n })\n }\n };\n } else if (transform instanceof ArrayRemoveTransformOperation) {\n return {\n fieldPath: fieldTransform.field.canonicalString(),\n removeAllFromArray: {\n values: transform.elements.map(function (v) {\n return _this.toValue(v);\n })\n }\n };\n } else {\n throw fail('Unknown transform: ' + fieldTransform.transform);\n }\n };\n\n JsonProtoSerializer.prototype.fromFieldTransform = function (proto) {\n var _this = this; // tslint:disable-next-line:no-any We need to match generated Proto types.\n\n\n var type = proto['transform_type'];\n var transform = null;\n\n if (hasTag(proto, type, 'setToServerValue')) {\n assert(proto.setToServerValue === 'REQUEST_TIME', 'Unknown server value transform proto: ' + JSON.stringify(proto));\n transform = ServerTimestampTransform.instance;\n } else if (hasTag(proto, type, 'appendMissingElements')) {\n var values$$1 = proto.appendMissingElements.values || [];\n transform = new ArrayUnionTransformOperation(values$$1.map(function (v) {\n return _this.fromValue(v);\n }));\n } else if (hasTag(proto, type, 'removeAllFromArray')) {\n var values$$1 = proto.removeAllFromArray.values || [];\n transform = new ArrayRemoveTransformOperation(values$$1.map(function (v) {\n return _this.fromValue(v);\n }));\n } else {\n fail('Unknown transform proto: ' + JSON.stringify(proto));\n }\n\n var fieldPath = FieldPath.fromServerFormat(proto.fieldPath);\n return new FieldTransform(fieldPath, transform);\n };\n\n JsonProtoSerializer.prototype.toDocumentsTarget = function (query) {\n return {\n documents: [this.toQueryPath(query.path)]\n };\n };\n\n JsonProtoSerializer.prototype.fromDocumentsTarget = function (documentsTarget) {\n var count = documentsTarget.documents.length;\n assert(count === 1, 'DocumentsTarget contained other than 1 document: ' + count);\n var name = documentsTarget.documents[0];\n return Query.atPath(this.fromQueryPath(name));\n };\n\n JsonProtoSerializer.prototype.toQueryTarget = function (query) {\n // Dissect the path into parent, collectionId, and optional key filter.\n var result = {\n structuredQuery: {}\n };\n\n if (query.path.isEmpty()) {\n result.parent = this.toQueryPath(ResourcePath.EMPTY_PATH);\n } else {\n var path = query.path;\n assert(path.length % 2 !== 0, 'Document queries with filters are not supported.');\n result.parent = this.toQueryPath(path.popLast());\n result.structuredQuery.from = [{\n collectionId: path.lastSegment()\n }];\n }\n\n var where = this.toFilter(query.filters);\n\n if (where) {\n result.structuredQuery.where = where;\n }\n\n var orderBy = this.toOrder(query.orderBy);\n\n if (orderBy) {\n result.structuredQuery.orderBy = orderBy;\n }\n\n var limit = this.toInt32Value(query.limit);\n\n if (limit !== undefined) {\n result.structuredQuery.limit = limit;\n }\n\n if (query.startAt) {\n result.structuredQuery.startAt = this.toCursor(query.startAt);\n }\n\n if (query.endAt) {\n result.structuredQuery.endAt = this.toCursor(query.endAt);\n }\n\n return result;\n };\n\n JsonProtoSerializer.prototype.fromQueryTarget = function (target) {\n var path = this.fromQueryPath(target.parent);\n var query = target.structuredQuery;\n var fromCount = query.from ? query.from.length : 0;\n\n if (fromCount > 0) {\n assert(fromCount === 1, 'StructuredQuery.from with more than one collection is not supported.');\n var from = query.from[0];\n path = path.child(from.collectionId);\n }\n\n var filterBy = [];\n\n if (query.where) {\n filterBy = this.fromFilter(query.where);\n }\n\n var orderBy = [];\n\n if (query.orderBy) {\n orderBy = this.fromOrder(query.orderBy);\n }\n\n var limit = null;\n\n if (query.limit) {\n limit = this.fromInt32Value(query.limit);\n }\n\n var startAt = null;\n\n if (query.startAt) {\n startAt = this.fromCursor(query.startAt);\n }\n\n var endAt = null;\n\n if (query.endAt) {\n endAt = this.fromCursor(query.endAt);\n }\n\n return new Query(path, orderBy, filterBy, limit, startAt, endAt);\n };\n\n JsonProtoSerializer.prototype.toListenRequestLabels = function (queryData) {\n var value = this.toLabel(queryData.purpose);\n\n if (value == null) {\n return null;\n } else {\n return {\n 'goog-listen-tags': value\n };\n }\n };\n\n JsonProtoSerializer.prototype.toLabel = function (purpose) {\n switch (purpose) {\n case QueryPurpose.Listen:\n return null;\n\n case QueryPurpose.ExistenceFilterMismatch:\n return 'existence-filter-mismatch';\n\n case QueryPurpose.LimboResolution:\n return 'limbo-document';\n\n default:\n return fail('Unrecognized query purpose: ' + purpose);\n }\n };\n\n JsonProtoSerializer.prototype.toTarget = function (queryData) {\n var result;\n var query = queryData.query;\n\n if (query.isDocumentQuery()) {\n result = {\n documents: this.toDocumentsTarget(query)\n };\n } else {\n result = {\n query: this.toQueryTarget(query)\n };\n }\n\n result.targetId = queryData.targetId;\n\n if (queryData.resumeToken.length > 0) {\n result.resumeToken = this.unsafeCastProtoByteString(queryData.resumeToken);\n }\n\n return result;\n };\n\n JsonProtoSerializer.prototype.toFilter = function (filters) {\n var _this = this;\n\n if (filters.length === 0) return;\n var protos = filters.map(function (filter) {\n return filter instanceof RelationFilter ? _this.toRelationFilter(filter) : _this.toUnaryFilter(filter);\n });\n\n if (protos.length === 1) {\n return protos[0];\n }\n\n return {\n compositeFilter: {\n op: 'AND',\n filters: protos\n }\n };\n };\n\n JsonProtoSerializer.prototype.fromFilter = function (filter) {\n var _this = this;\n\n if (!filter) {\n return [];\n } else if (filter.unaryFilter !== undefined) {\n return [this.fromUnaryFilter(filter)];\n } else if (filter.fieldFilter !== undefined) {\n return [this.fromRelationFilter(filter)];\n } else if (filter.compositeFilter !== undefined) {\n return filter.compositeFilter.filters.map(function (f) {\n return _this.fromFilter(f);\n }).reduce(function (accum, current) {\n return accum.concat(current);\n });\n } else {\n return fail('Unknown filter: ' + JSON.stringify(filter));\n }\n };\n\n JsonProtoSerializer.prototype.toOrder = function (orderBys) {\n var _this = this;\n\n if (orderBys.length === 0) return;\n return orderBys.map(function (order) {\n return _this.toPropertyOrder(order);\n });\n };\n\n JsonProtoSerializer.prototype.fromOrder = function (orderBys) {\n var _this = this;\n\n return orderBys.map(function (order) {\n return _this.fromPropertyOrder(order);\n });\n };\n\n JsonProtoSerializer.prototype.toCursor = function (cursor) {\n var _this = this;\n\n return {\n before: cursor.before,\n values: cursor.position.map(function (component) {\n return _this.toValue(component);\n })\n };\n };\n\n JsonProtoSerializer.prototype.fromCursor = function (cursor) {\n var _this = this;\n\n var before = !!cursor.before;\n var position = cursor.values.map(function (component) {\n return _this.fromValue(component);\n });\n return new Bound(position, before);\n }; // visible for testing\n\n\n JsonProtoSerializer.prototype.toDirection = function (dir) {\n return DIRECTIONS[dir.name];\n }; // visible for testing\n\n\n JsonProtoSerializer.prototype.fromDirection = function (dir) {\n switch (dir) {\n case 'ASCENDING':\n return Direction.ASCENDING;\n\n case 'DESCENDING':\n return Direction.DESCENDING;\n\n default:\n return undefined;\n }\n }; // visible for testing\n\n\n JsonProtoSerializer.prototype.toOperatorName = function (op) {\n return OPERATORS[op.name];\n };\n\n JsonProtoSerializer.prototype.fromOperatorName = function (op) {\n switch (op) {\n case 'EQUAL':\n return RelationOp.EQUAL;\n\n case 'GREATER_THAN':\n return RelationOp.GREATER_THAN;\n\n case 'GREATER_THAN_OR_EQUAL':\n return RelationOp.GREATER_THAN_OR_EQUAL;\n\n case 'LESS_THAN':\n return RelationOp.LESS_THAN;\n\n case 'LESS_THAN_OR_EQUAL':\n return RelationOp.LESS_THAN_OR_EQUAL;\n\n case 'ARRAY_CONTAINS':\n return RelationOp.ARRAY_CONTAINS;\n\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified relation');\n\n default:\n return fail('Unknown relation');\n }\n };\n\n JsonProtoSerializer.prototype.toFieldPathReference = function (path) {\n return {\n fieldPath: path.canonicalString()\n };\n };\n\n JsonProtoSerializer.prototype.fromFieldPathReference = function (fieldReference) {\n return FieldPath.fromServerFormat(fieldReference.fieldPath);\n }; // visible for testing\n\n\n JsonProtoSerializer.prototype.toPropertyOrder = function (orderBy) {\n return {\n field: this.toFieldPathReference(orderBy.field),\n direction: this.toDirection(orderBy.dir)\n };\n };\n\n JsonProtoSerializer.prototype.fromPropertyOrder = function (orderBy) {\n return new OrderBy(this.fromFieldPathReference(orderBy.field), this.fromDirection(orderBy.direction));\n }; // visible for testing\n\n\n JsonProtoSerializer.prototype.toRelationFilter = function (filter) {\n if (filter instanceof RelationFilter) {\n return {\n fieldFilter: {\n field: this.toFieldPathReference(filter.field),\n op: this.toOperatorName(filter.op),\n value: this.toValue(filter.value)\n }\n };\n } else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n\n JsonProtoSerializer.prototype.fromRelationFilter = function (filter) {\n return new RelationFilter(this.fromFieldPathReference(filter.fieldFilter.field), this.fromOperatorName(filter.fieldFilter.op), this.fromValue(filter.fieldFilter.value));\n }; // visible for testing\n\n\n JsonProtoSerializer.prototype.toUnaryFilter = function (filter) {\n if (filter instanceof NanFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NAN'\n }\n };\n } else if (filter instanceof NullFilter) {\n return {\n unaryFilter: {\n field: this.toFieldPathReference(filter.field),\n op: 'IS_NULL'\n }\n };\n } else {\n return fail('Unrecognized filter: ' + JSON.stringify(filter));\n }\n };\n\n JsonProtoSerializer.prototype.fromUnaryFilter = function (filter) {\n switch (filter.unaryFilter.op) {\n case 'IS_NAN':\n var nanField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NanFilter(nanField);\n\n case 'IS_NULL':\n var nullField = this.fromFieldPathReference(filter.unaryFilter.field);\n return new NullFilter(nullField);\n\n case 'OPERATOR_UNSPECIFIED':\n return fail('Unspecified filter');\n\n default:\n return fail('Unknown filter');\n }\n };\n\n JsonProtoSerializer.prototype.toDocumentMask = function (fieldMask) {\n var canonicalFields = [];\n fieldMask.fields.forEach(function (field) {\n return canonicalFields.push(field.canonicalString());\n });\n return {\n fieldPaths: canonicalFields\n };\n };\n\n JsonProtoSerializer.prototype.fromDocumentMask = function (proto) {\n var paths = proto.fieldPaths || [];\n var fields = paths.map(function (path) {\n return FieldPath.fromServerFormat(path);\n });\n return FieldMask.fromArray(fields);\n };\n\n return JsonProtoSerializer;\n}();\n/**\r\n * Checks for a specific oneof tag in a protocol buffer message.\r\n *\r\n * This intentionally accommodates two distinct cases:\r\n *\r\n * 1) Messages containing a type tag: these are the format produced by GRPC in\r\n * return values. These may contain default-value mappings for all tags in the\r\n * oneof but the type tag specifies which one was actually set.\r\n *\r\n * 2) Messages that don't contain a type tag: these are the format required by\r\n * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would\r\n * choke claiming that the tags aren't fields in the Message.\r\n *\r\n * Allowing both formats here makes the serializer able to consume the outputs\r\n * it produces: for all messages it supports, fromX(toX(value)) == value.\r\n *\r\n * Note that case 2 suffers from ambiguity: if multiple tags are present\r\n * without a type tag then the callers are structured in such a way that the\r\n * first invocation will win. Since we only parse in this mode when parsing\r\n * the output of a serialize method this works, but it's not a general\r\n * solution.\r\n *\r\n * Unfortunately there is no general solution here because proto3 makes it\r\n * impossible to distinguish unset from explicitly set fields: both have the\r\n * default value for the type. Without the type tag but multiple value tags\r\n * it's possible to have default values for each tag in the oneof and not be\r\n * able to know which was actually in effect.\r\n */\n\n\nfunction hasTag(obj, type, tag) {\n return type === tag || !type && tag in obj;\n}\n/**\r\n * Detect React Native.\r\n *\r\n * @return {boolean} True if ReactNative environment is detected.\r\n */\n\n\nvar isReactNative = function isReactNative() {\n return typeof navigator === 'object' && navigator['product'] === 'ReactNative';\n};\n\nvar ERROR_NAME = 'FirebaseError';\nvar captureStackTrace = Error.captureStackTrace;\n\nvar FirebaseError =\n/** @class */\nfunction () {\n function FirebaseError(code, message) {\n this.code = code;\n this.message = message; // We want the stack value, if implemented by Error\n\n if (captureStackTrace) {\n // Patches this.stack, omitted calls above ErrorFactory#create\n captureStackTrace(this, ErrorFactory.prototype.create);\n } else {\n try {\n // In case of IE11, stack will be set only after error is raised.\n // https://docs.microsoft.com/en-us/scripting/javascript/reference/stack-property-error-javascript\n throw Error.apply(this, arguments);\n } catch (err) {\n this.name = ERROR_NAME; // Make non-enumerable getter for the property.\n\n Object.defineProperty(this, 'stack', {\n get: function get() {\n return err.stack;\n }\n });\n }\n }\n }\n\n return FirebaseError;\n}(); // Back-door inheritance\n\n\nFirebaseError.prototype = Object.create(Error.prototype);\nFirebaseError.prototype.constructor = FirebaseError;\nFirebaseError.prototype.name = ERROR_NAME;\n\nvar ErrorFactory =\n/** @class */\nfunction () {\n function ErrorFactory(service, serviceName, errors) {\n this.service = service;\n this.serviceName = serviceName;\n this.errors = errors; // Matches {$name}, by default.\n\n this.pattern = /\\{\\$([^}]+)}/g; // empty\n }\n\n ErrorFactory.prototype.create = function (code, data) {\n if (data === undefined) {\n data = {};\n }\n\n var template = this.errors[code];\n var fullCode = this.service + '/' + code;\n var message;\n\n if (template === undefined) {\n message = 'Error';\n } else {\n message = template.replace(this.pattern, function (match, key) {\n var value = data[key];\n return value !== undefined ? value.toString() : '<' + key + '?>';\n });\n } // Service: Error message (service/code).\n\n\n message = this.serviceName + ': ' + message + ' (' + fullCode + ').';\n var err = new FirebaseError(fullCode, message); // Populate the Error object with message parts for programmatic\n // accesses (e.g., e.file).\n\n for (var prop in data) {\n if (!data.hasOwnProperty(prop) || prop.slice(-1) === '_') {\n continue;\n }\n\n err[prop] = data[prop];\n }\n\n return err;\n };\n\n return ErrorFactory;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// Copyright 2011 The Closure Library Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\r\n * @fileoverview Abstract cryptographic hash interface.\r\n *\r\n * See Sha1 and Md5 for sample implementations.\r\n *\r\n */\n\n/**\r\n * Create a cryptographic hash instance.\r\n *\r\n * @constructor\r\n * @struct\r\n */\n\n\nvar Hash =\n/** @class */\nfunction () {\n function Hash() {\n /**\r\n * The block size for the hasher.\r\n * @type {number}\r\n */\n this.blockSize = -1;\n }\n\n return Hash;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @fileoverview SHA-1 cryptographic hash.\r\n * Variable names follow the notation in FIPS PUB 180-3:\r\n * http://csrc.nist.gov/publications/fips/fips180-3/fips180-3_final.pdf.\r\n *\r\n * Usage:\r\n * var sha1 = new sha1();\r\n * sha1.update(bytes);\r\n * var hash = sha1.digest();\r\n *\r\n * Performance:\r\n * Chrome 23: ~400 Mbit/s\r\n * Firefox 16: ~250 Mbit/s\r\n *\r\n */\n\n/**\r\n * SHA-1 cryptographic hash constructor.\r\n *\r\n * The properties declared here are discussed in the above algorithm document.\r\n * @constructor\r\n * @extends {Hash}\r\n * @final\r\n * @struct\r\n */\n\n\nvar Sha1 =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(Sha1, _super);\n\n function Sha1() {\n var _this = _super.call(this) || this;\n /**\r\n * Holds the previous values of accumulated variables a-e in the compress_\r\n * function.\r\n * @type {!Array}\r\n * @private\r\n */\n\n\n _this.chain_ = [];\n /**\r\n * A buffer holding the partially computed hash result.\r\n * @type {!Array}\r\n * @private\r\n */\n\n _this.buf_ = [];\n /**\r\n * An array of 80 bytes, each a part of the message to be hashed. Referred to\r\n * as the message schedule in the docs.\r\n * @type {!Array}\r\n * @private\r\n */\n\n _this.W_ = [];\n /**\r\n * Contains data needed to pad messages less than 64 bytes.\r\n * @type {!Array}\r\n * @private\r\n */\n\n _this.pad_ = [];\n /**\r\n * @private {number}\r\n */\n\n _this.inbuf_ = 0;\n /**\r\n * @private {number}\r\n */\n\n _this.total_ = 0;\n _this.blockSize = 512 / 8;\n _this.pad_[0] = 128;\n\n for (var i = 1; i < _this.blockSize; ++i) {\n _this.pad_[i] = 0;\n }\n\n _this.reset();\n\n return _this;\n }\n\n Sha1.prototype.reset = function () {\n this.chain_[0] = 0x67452301;\n this.chain_[1] = 0xefcdab89;\n this.chain_[2] = 0x98badcfe;\n this.chain_[3] = 0x10325476;\n this.chain_[4] = 0xc3d2e1f0;\n this.inbuf_ = 0;\n this.total_ = 0;\n };\n /**\r\n * Internal compress helper function.\r\n * @param {!Array|!Uint8Array|string} buf Block to compress.\r\n * @param {number=} opt_offset Offset of the block in the buffer.\r\n * @private\r\n */\n\n\n Sha1.prototype.compress_ = function (buf, opt_offset) {\n if (!opt_offset) {\n opt_offset = 0;\n }\n\n var W = this.W_; // get 16 big endian words\n\n if (typeof buf === 'string') {\n for (var i = 0; i < 16; i++) {\n // TODO(user): [bug 8140122] Recent versions of Safari for Mac OS and iOS\n // have a bug that turns the post-increment ++ operator into pre-increment\n // during JIT compilation. We have code that depends heavily on SHA-1 for\n // correctness and which is affected by this bug, so I've removed all uses\n // of post-increment ++ in which the result value is used. We can revert\n // this change once the Safari bug\n // (https://bugs.webkit.org/show_bug.cgi?id=109036) has been fixed and\n // most clients have been updated.\n W[i] = buf.charCodeAt(opt_offset) << 24 | buf.charCodeAt(opt_offset + 1) << 16 | buf.charCodeAt(opt_offset + 2) << 8 | buf.charCodeAt(opt_offset + 3);\n opt_offset += 4;\n }\n } else {\n for (var i = 0; i < 16; i++) {\n W[i] = buf[opt_offset] << 24 | buf[opt_offset + 1] << 16 | buf[opt_offset + 2] << 8 | buf[opt_offset + 3];\n opt_offset += 4;\n }\n } // expand to 80 words\n\n\n for (var i = 16; i < 80; i++) {\n var t = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];\n W[i] = (t << 1 | t >>> 31) & 0xffffffff;\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 e = this.chain_[4];\n var f, k; // TODO(user): Try to unroll this loop to speed up the computation.\n\n for (var i = 0; i < 80; i++) {\n if (i < 40) {\n if (i < 20) {\n f = d ^ b & (c ^ d);\n k = 0x5a827999;\n } else {\n f = b ^ c ^ d;\n k = 0x6ed9eba1;\n }\n } else {\n if (i < 60) {\n f = b & c | d & (b | c);\n k = 0x8f1bbcdc;\n } else {\n f = b ^ c ^ d;\n k = 0xca62c1d6;\n }\n }\n\n var t = (a << 5 | a >>> 27) + f + e + k + W[i] & 0xffffffff;\n e = d;\n d = c;\n c = (b << 30 | b >>> 2) & 0xffffffff;\n b = a;\n a = t;\n }\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 this.chain_[4] = this.chain_[4] + e & 0xffffffff;\n };\n\n Sha1.prototype.update = function (bytes, opt_length) {\n // TODO(johnlenz): tighten the function signature and remove this check\n if (bytes == null) {\n return;\n }\n\n if (opt_length === undefined) {\n opt_length = bytes.length;\n }\n\n var lengthMinusBlock = opt_length - this.blockSize;\n var n = 0; // Using local instead of member variables gives ~5% speedup on Firefox 16.\n\n var buf = this.buf_;\n var inbuf = this.inbuf_; // The outer while loop should execute at most twice.\n\n while (n < 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 ~25%\n // speedup on Chrome 23 and ~15% speedup on Firefox 16, but requires that\n // the data is provided in large chunks (or in multiples of 64 bytes).\n if (inbuf == 0) {\n while (n <= lengthMinusBlock) {\n this.compress_(bytes, n);\n n += this.blockSize;\n }\n }\n\n if (typeof bytes === 'string') {\n while (n < opt_length) {\n buf[inbuf] = bytes.charCodeAt(n);\n ++inbuf;\n ++n;\n\n if (inbuf == this.blockSize) {\n this.compress_(buf);\n inbuf = 0; // Jump to the outer loop so we use the full-block optimization.\n\n break;\n }\n }\n } else {\n while (n < opt_length) {\n buf[inbuf] = bytes[n];\n ++inbuf;\n ++n;\n\n if (inbuf == this.blockSize) {\n this.compress_(buf);\n inbuf = 0; // Jump to the outer loop so we use the full-block optimization.\n\n break;\n }\n }\n }\n }\n\n this.inbuf_ = inbuf;\n this.total_ += opt_length;\n };\n /** @override */\n\n\n Sha1.prototype.digest = function () {\n var digest = [];\n var totalBits = this.total_ * 8; // Add pad 0x80 0x00*.\n\n if (this.inbuf_ < 56) {\n this.update(this.pad_, 56 - this.inbuf_);\n } else {\n this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));\n } // Add # bits.\n\n\n for (var i = this.blockSize - 1; i >= 56; i--) {\n this.buf_[i] = totalBits & 255;\n totalBits /= 256; // Don't use bit-shifting here!\n }\n\n this.compress_(this.buf_);\n var n = 0;\n\n for (var i = 0; i < 5; i++) {\n for (var j = 24; j >= 0; j -= 8) {\n digest[n] = this.chain_[i] >> j & 255;\n ++n;\n }\n }\n\n return digest;\n };\n\n return Sha1;\n}(Hash);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Provides a simple helper class that implements the Stream interface to\r\n * bridge to other implementations that are streams but do not implement the\r\n * interface. The stream callbacks are invoked with the callOn... methods.\r\n */\n\n\nvar StreamBridge =\n/** @class */\nfunction () {\n function StreamBridge(args) {\n this.sendFn = args.sendFn;\n this.closeFn = args.closeFn;\n }\n\n StreamBridge.prototype.onOpen = function (callback) {\n assert(!this.wrappedOnOpen, 'Called onOpen on stream twice!');\n this.wrappedOnOpen = callback;\n };\n\n StreamBridge.prototype.onClose = function (callback) {\n assert(!this.wrappedOnClose, 'Called onClose on stream twice!');\n this.wrappedOnClose = callback;\n };\n\n StreamBridge.prototype.onMessage = function (callback) {\n assert(!this.wrappedOnMessage, 'Called onMessage on stream twice!');\n this.wrappedOnMessage = callback;\n };\n\n StreamBridge.prototype.close = function () {\n this.closeFn();\n };\n\n StreamBridge.prototype.send = function (msg) {\n this.sendFn(msg);\n };\n\n StreamBridge.prototype.callOnOpen = function () {\n assert(this.wrappedOnOpen !== undefined, 'Cannot call onOpen because no callback was set');\n this.wrappedOnOpen();\n };\n\n StreamBridge.prototype.callOnClose = function (err) {\n assert(this.wrappedOnClose !== undefined, 'Cannot call onClose because no callback was set');\n this.wrappedOnClose(err);\n };\n\n StreamBridge.prototype.callOnMessage = function (msg) {\n assert(this.wrappedOnMessage !== undefined, 'Cannot call onMessage because no callback was set');\n this.wrappedOnMessage(msg);\n };\n\n return StreamBridge;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG = 'Connection';\nvar RPC_STREAM_SERVICE = 'google.firestore.v1beta1.Firestore';\nvar RPC_URL_VERSION = 'v1beta1';\n/** Maps RPC names to the corresponding REST endpoint name. */\n\nvar RPC_NAME_REST_MAPPING = {\n BatchGetDocuments: 'batchGet',\n Commit: 'commit'\n}; // TODO(b/38203344): The SDK_VERSION is set independently from Firebase because\n// we are doing out-of-band releases. Once we release as part of Firebase, we\n// should use the Firebase version instead.\n\nvar X_GOOG_API_CLIENT_VALUE = 'gl-js/ fire/' + SDK_VERSION;\nvar XHR_TIMEOUT_SECS = 15;\n\nvar WebChannelConnection =\n/** @class */\nfunction () {\n function WebChannelConnection(info) {\n this.databaseId = info.databaseId;\n this.pool = new webchannelWrapper.XhrIoPool();\n var proto = info.ssl ? 'https' : 'http';\n this.baseUrl = proto + '://' + info.host;\n }\n /**\r\n * Modifies the headers for a request, adding any authorization token if\r\n * present and any additional headers for the request.\r\n */\n\n\n WebChannelConnection.prototype.modifyHeadersForRequest = function (headers, token) {\n if (token) {\n for (var header in token.authHeaders) {\n if (token.authHeaders.hasOwnProperty(header)) {\n headers[header] = token.authHeaders[header];\n }\n }\n }\n\n headers['X-Goog-Api-Client'] = X_GOOG_API_CLIENT_VALUE;\n };\n\n WebChannelConnection.prototype.invokeRPC = function (rpcName, request, token) {\n var _this = this;\n\n var url = this.makeUrl(rpcName);\n return new Promise(function (resolve, reject) {\n // tslint:disable-next-line:no-any XhrIoPool doesn't have TS typings.\n _this.pool.getObject(function (xhr) {\n xhr.listenOnce(webchannelWrapper.EventType.COMPLETE, function () {\n try {\n switch (xhr.getLastErrorCode()) {\n case webchannelWrapper.ErrorCode.NO_ERROR:\n var json = xhr.getResponseJson();\n debug(LOG_TAG, 'XHR received:', JSON.stringify(json));\n resolve(json);\n break;\n\n case webchannelWrapper.ErrorCode.TIMEOUT:\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" timed out');\n reject(new FirestoreError(Code.DEADLINE_EXCEEDED, 'Request time out'));\n break;\n\n case webchannelWrapper.ErrorCode.HTTP_ERROR:\n var status_1 = xhr.getStatus();\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed with status:', status_1, 'response text:', xhr.getResponseText());\n\n if (status_1 > 0) {\n reject(new FirestoreError(mapCodeFromHttpStatus(status_1), 'Server responded with status ' + xhr.getStatusText()));\n } else {\n // If we received an HTTP_ERROR but there's no status code,\n // it's most probably a connection issue\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" failed');\n reject(new FirestoreError(Code.UNAVAILABLE, 'Connection failed.'));\n }\n\n break;\n\n default:\n fail('RPC \"' + rpcName + '\" failed with unanticipated ' + 'webchannel error ' + xhr.getLastErrorCode() + ': ' + xhr.getLastError() + ', giving up.');\n }\n } finally {\n debug(LOG_TAG, 'RPC \"' + rpcName + '\" completed.');\n\n _this.pool.releaseObject(xhr);\n }\n });\n var requestString = JSON.stringify(request);\n debug(LOG_TAG, 'XHR sending: ', url + ' ' + requestString); // 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\n // $httpOverwrite parameter supported by ESF to avoid\n // triggering preflight requests.\n\n var headers = {\n 'Content-Type': 'text/plain'\n };\n\n _this.modifyHeadersForRequest(headers, token);\n\n xhr.send(url, 'POST', requestString, headers, XHR_TIMEOUT_SECS);\n });\n });\n };\n\n WebChannelConnection.prototype.invokeStreamingRPC = function (rpcName, request, token) {\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(rpcName, request, token);\n };\n\n WebChannelConnection.prototype.openStream = function (rpcName, token) {\n var urlParts = [this.baseUrl, '/', RPC_STREAM_SERVICE, '/', rpcName, '/channel'];\n var webchannelTransport = webchannelWrapper.createWebChannelTransport();\n var request = {\n // Background channel test avoids the initial two test calls and decreases\n // initial cold start time.\n // TODO(dimond): wenboz@ mentioned this might affect use with proxies and\n // we should monitor closely for any reports.\n backgroundChannelTest: true,\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 };\n this.modifyHeadersForRequest(request.initMessageHeaders, token); // 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 httpHeadersOverwriteParam option to specify that\n // the headers should instead be encoded into a special \"$httpHeaders\" query\n // parameter, which is recognized by the webchannel backend. This is\n // formally defined here:\n // https://github.com/google/closure-library/blob/b0e1815b13fb92a46d7c9b3c30de5d6a396a3245/closure/goog/net/rpc/httpcors.js#L32\n //\n // But for some unclear reason (see\n // https://github.com/firebase/firebase-js-sdk/issues/703), this breaks\n // ReactNative and so we exclude it, which just means ReactNative may be\n // subject to the extra network roundtrip for CORS preflight.\n\n if (!isReactNative()) {\n request['httpHeadersOverwriteParam'] = '$httpHeaders';\n }\n\n var url = urlParts.join('');\n debug(LOG_TAG, 'Creating WebChannel: ' + url + ' ' + request); // tslint:disable-next-line:no-any Because listen isn't defined on it.\n\n var channel = webchannelTransport.createWebChannel(url, request); // 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\n var opened = false; // 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\n var closed = false;\n var streamBridge = new StreamBridge({\n sendFn: function sendFn(msg) {\n if (!closed) {\n if (!opened) {\n debug(LOG_TAG, 'Opening WebChannel transport.');\n channel.open();\n opened = true;\n }\n\n debug(LOG_TAG, 'WebChannel sending:', msg);\n channel.send(msg);\n } else {\n debug(LOG_TAG, 'Not sending because WebChannel is closed:', msg);\n }\n },\n closeFn: function closeFn() {\n return channel.close();\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\n var unguardedEventListen = function unguardedEventListen(type, fn) {\n // TODO(dimond): closure typing seems broken because WebChannel does\n // not implement goog.events.Listenable\n channel.listen(type, function (param) {\n try {\n fn(param);\n } catch (e) {\n setTimeout(function () {\n throw e;\n }, 0);\n }\n });\n };\n\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.OPEN, function () {\n if (!closed) {\n debug(LOG_TAG, 'WebChannel transport opened.');\n }\n });\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.CLOSE, function () {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport closed');\n streamBridge.callOnClose();\n }\n });\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.ERROR, function (err) {\n if (!closed) {\n closed = true;\n debug(LOG_TAG, 'WebChannel transport errored:', err);\n streamBridge.callOnClose(new FirestoreError(Code.UNAVAILABLE, 'The operation could not be completed'));\n }\n });\n unguardedEventListen(webchannelWrapper.WebChannel.EventType.MESSAGE, function (msg) {\n if (!closed) {\n var msgData = msg.data[0];\n assert(!!msgData, 'Got a webchannel message without data.'); // 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\n var error$$1 = // tslint:disable-next-line:no-any msgData.error is not typed.\n msgData.error || msgData[0] && msgData[0].error;\n\n if (error$$1) {\n debug(LOG_TAG, 'WebChannel received error:', error$$1); // error.status will be a string like 'OK' or 'NOT_FOUND'.\n\n var status_2 = error$$1.status;\n var code = mapCodeFromRpcStatus(status_2);\n var message = error$$1.message;\n\n if (code === undefined) {\n code = Code.INTERNAL;\n message = 'Unknown error status: ' + status_2 + ' with message ' + error$$1.message;\n } // Mark closed so no further events are propagated\n\n\n closed = true;\n streamBridge.callOnClose(new FirestoreError(code, message));\n channel.close();\n } else {\n debug(LOG_TAG, 'WebChannel received:', msgData);\n streamBridge.callOnMessage(msgData);\n }\n }\n });\n setTimeout(function () {\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 }; // visible for testing\n\n\n WebChannelConnection.prototype.makeUrl = function (rpcName) {\n var urlRpcName = RPC_NAME_REST_MAPPING[rpcName];\n assert(urlRpcName !== undefined, 'Unknown REST mapping for: ' + rpcName);\n var url = [this.baseUrl, '/', RPC_URL_VERSION];\n url.push('/projects/');\n url.push(this.databaseId.projectId);\n url.push('/databases/');\n url.push(this.databaseId.database);\n url.push('/documents');\n url.push(':');\n url.push(urlRpcName);\n return url.join('');\n };\n\n return WebChannelConnection;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar BrowserPlatform =\n/** @class */\nfunction () {\n function BrowserPlatform() {\n this.emptyByteString = '';\n this.base64Available = typeof atob !== 'undefined';\n }\n\n Object.defineProperty(BrowserPlatform.prototype, \"document\", {\n get: function get() {\n return typeof document !== 'undefined' ? document : null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(BrowserPlatform.prototype, \"window\", {\n get: function get() {\n return typeof window !== 'undefined' ? window : null;\n },\n enumerable: true,\n configurable: true\n });\n\n BrowserPlatform.prototype.loadConnection = function (databaseInfo) {\n return Promise.resolve(new WebChannelConnection(databaseInfo));\n };\n\n BrowserPlatform.prototype.newSerializer = function (databaseId) {\n return new JsonProtoSerializer(databaseId, {\n useProto3Json: true\n });\n };\n\n BrowserPlatform.prototype.formatJSON = function (value) {\n return JSON.stringify(value);\n };\n\n BrowserPlatform.prototype.atob = function (encoded) {\n return atob(encoded);\n };\n\n BrowserPlatform.prototype.btoa = function (raw) {\n return btoa(raw);\n };\n\n return BrowserPlatform;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * This code needs to run before Firestore is used. This can be achieved in\r\n * several ways:\r\n * 1) Through the JSCompiler compiling this code and then (automatically)\r\n * executing it before exporting the Firestore symbols.\r\n * 2) Through importing this module first in a Firestore main module\r\n */\n\n\nPlatformSupport.setPlatform(new BrowserPlatform());\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\r\n * exceed. All subsequent calls to next will return increasing values. If provided with a\r\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\r\n * well as write out sequence numbers that it produces via `next()`.\r\n */\n\nvar ListenSequence =\n/** @class */\nfunction () {\n function ListenSequence(previousValue, sequenceNumberSyncer) {\n var _this = this;\n\n this.previousValue = previousValue;\n\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = function (sequenceNumber) {\n return _this.setPreviousValue(sequenceNumber);\n };\n\n this.writeNewSequenceNumber = function (sequenceNumber) {\n return sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n };\n }\n }\n\n ListenSequence.prototype.setPreviousValue = function (externalPreviousValue) {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n };\n\n ListenSequence.prototype.next = function () {\n var nextValue = ++this.previousValue;\n\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n\n return nextValue;\n };\n\n ListenSequence.INVALID = -1;\n return ListenSequence;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar Deferred$1 =\n/** @class */\nfunction () {\n function Deferred() {\n var _this = this;\n\n this.promise = new Promise(function (resolve, reject) {\n _this.resolve = resolve;\n _this.reject = reject;\n });\n }\n\n return Deferred;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Wellknown \"timer\" IDs used when scheduling delayed operations on the\r\n * AsyncQueue. These IDs can then be used from tests to check for the presence\r\n * of operations or to run them early.\r\n *\r\n * The string values are used when encoding these timer IDs in JSON spec tests.\r\n */\n\n\nvar TimerId;\n\n(function (TimerId) {\n /** All can be used with runDelayedOperationsEarly() to run all timers. */\n TimerId[\"All\"] = \"all\";\n /**\r\n * The following 4 timers are used in persistent_stream.ts for the listen and\r\n * write streams. The \"Idle\" timer is used to close the stream due to\r\n * inactivity. The \"ConnectionBackoff\" timer is used to restart a stream once\r\n * the appropriate backoff delay has elapsed.\r\n */\n\n TimerId[\"ListenStreamIdle\"] = \"listen_stream_idle\";\n TimerId[\"ListenStreamConnectionBackoff\"] = \"listen_stream_connection_backoff\";\n TimerId[\"WriteStreamIdle\"] = \"write_stream_idle\";\n TimerId[\"WriteStreamConnectionBackoff\"] = \"write_stream_connection_backoff\";\n /**\r\n * A timer used in online_state_tracker.ts to transition from\r\n * OnlineState.Unknown to Offline after a set timeout, rather than waiting\r\n * indefinitely for success or failure.\r\n */\n\n TimerId[\"OnlineStateTimeout\"] = \"online_state_timeout\";\n /**\r\n * A timer used to update the client metadata in IndexedDb, which is used\r\n * to determine the primary leaseholder.\r\n */\n\n TimerId[\"ClientMetadataRefresh\"] = \"client_metadata_refresh\";\n /** A timer used to periodically attempt LRU Garbage collection */\n\n TimerId[\"LruGarbageCollection\"] = \"lru_garbage_collection\";\n})(TimerId || (TimerId = {}));\n/**\r\n * Represents an operation scheduled to be run in the future on an AsyncQueue.\r\n *\r\n * It is created via DelayedOperation.createAndSchedule().\r\n *\r\n * Supports cancellation (via cancel()) and early execution (via skipDelay()).\r\n */\n\n\nvar DelayedOperation =\n/** @class */\nfunction () {\n function DelayedOperation(asyncQueue, timerId, targetTimeMs, op, removalCallback) {\n this.asyncQueue = asyncQueue;\n this.timerId = timerId;\n this.targetTimeMs = targetTimeMs;\n this.op = op;\n this.removalCallback = removalCallback;\n this.deferred = new Deferred$1();\n this.then = this.deferred.promise.then.bind(this.deferred.promise);\n this.catch = this.deferred.promise.catch.bind(this.deferred.promise); // 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\n this.deferred.promise.catch(function (err) {});\n }\n /**\r\n * Creates and returns a DelayedOperation that has been scheduled to be\r\n * executed on the provided asyncQueue after the provided delayMs.\r\n *\r\n * @param asyncQueue The queue to schedule the operation on.\r\n * @param id A Timer ID identifying the type of operation this is.\r\n * @param delayMs The delay (ms) before the operation should be scheduled.\r\n * @param op The operation to run.\r\n * @param removalCallback A callback to be called synchronously once the\r\n * operation is executed or canceled, notifying the AsyncQueue to remove it\r\n * from its delayedOperations list.\r\n * PORTING NOTE: This exists to prevent making removeDelayedOperation() and\r\n * the DelayedOperation class public.\r\n */\n\n\n DelayedOperation.createAndSchedule = function (asyncQueue, timerId, delayMs, op, removalCallback) {\n var targetTime = Date.now() + delayMs;\n var delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback);\n delayedOp.start(delayMs);\n return delayedOp;\n };\n /**\r\n * Starts the timer. This is called immediately after construction by\r\n * createAndSchedule().\r\n */\n\n\n DelayedOperation.prototype.start = function (delayMs) {\n var _this = this;\n\n this.timerHandle = setTimeout(function () {\n return _this.handleDelayElapsed();\n }, delayMs);\n };\n /**\r\n * Queues the operation to run immediately (if it hasn't already been run or\r\n * canceled).\r\n */\n\n\n DelayedOperation.prototype.skipDelay = function () {\n return this.handleDelayElapsed();\n };\n /**\r\n * Cancels the operation if it hasn't already been executed or canceled. The\r\n * promise will be rejected.\r\n *\r\n * As long as the operation has not yet been run, calling cancel() provides a\r\n * guarantee that the operation will not be run.\r\n */\n\n\n DelayedOperation.prototype.cancel = function (reason) {\n if (this.timerHandle !== null) {\n this.clearTimeout();\n this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : '')));\n }\n };\n\n DelayedOperation.prototype.handleDelayElapsed = function () {\n var _this = this;\n\n this.asyncQueue.enqueueAndForget(function () {\n if (_this.timerHandle !== null) {\n _this.clearTimeout();\n\n return _this.op().then(function (result) {\n return _this.deferred.resolve(result);\n });\n } else {\n return Promise.resolve();\n }\n });\n };\n\n DelayedOperation.prototype.clearTimeout = function () {\n if (this.timerHandle !== null) {\n this.removalCallback(this);\n clearTimeout(this.timerHandle);\n this.timerHandle = null;\n }\n };\n\n return DelayedOperation;\n}();\n\nvar AsyncQueue =\n/** @class */\nfunction () {\n function AsyncQueue() {\n // The last promise in the queue.\n this.tail = Promise.resolve(); // Operations scheduled to be queued in the future. Operations are\n // automatically removed after they are run or canceled.\n\n this.delayedOperations = []; // Flag set while there's an outstanding AsyncQueue operation, used for\n // assertion sanity-checks.\n\n this.operationInProgress = false;\n }\n /**\r\n * Adds a new operation to the queue without waiting for it to complete (i.e.\r\n * we ignore the Promise result).\r\n */\n\n\n AsyncQueue.prototype.enqueueAndForget = function (op) {\n // tslint:disable-next-line:no-floating-promises\n this.enqueue(op);\n };\n /**\r\n * Adds a new operation to the queue. Returns a promise that will be resolved\r\n * when the promise returned by the new operation is (with its value).\r\n */\n\n\n AsyncQueue.prototype.enqueue = function (op) {\n var _this = this;\n\n this.verifyNotFailed();\n var newTail = this.tail.then(function () {\n _this.operationInProgress = true;\n return op().catch(function (error$$1) {\n _this.failure = error$$1;\n _this.operationInProgress = false;\n var message = error$$1.stack || error$$1.message || '';\n error('INTERNAL UNHANDLED ERROR: ', message); // Escape the promise chain and throw the error globally so that\n // e.g. any global crash reporting library detects and reports it.\n // (but not for simulated errors in our tests since this breaks mocha)\n\n if (message.indexOf('Firestore Test Simulated Error') < 0) {\n setTimeout(function () {\n throw error$$1;\n }, 0);\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\n\n throw error$$1;\n }).then(function (result) {\n _this.operationInProgress = false;\n return result;\n });\n });\n this.tail = newTail;\n return newTail;\n };\n /**\r\n * Schedules an operation to be queued on the AsyncQueue once the specified\r\n * `delayMs` has elapsed. The returned CancelablePromise can be used to cancel\r\n * the operation prior to its running.\r\n */\n\n\n AsyncQueue.prototype.enqueueAfterDelay = function (timerId, delayMs, op) {\n var _this = this;\n\n this.verifyNotFailed();\n assert(delayMs >= 0, \"Attempted to schedule an operation with a negative delay of \" + delayMs); // While not necessarily harmful, we currently don't expect to have multiple\n // ops with the same timer id in the queue, so defensively reject them.\n\n assert(!this.containsDelayedOperation(timerId), \"Attempted to schedule multiple operations with timer id \" + timerId + \".\");\n var delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, function (op) {\n return _this.removeDelayedOperation(op);\n });\n this.delayedOperations.push(delayedOp);\n return delayedOp;\n };\n\n AsyncQueue.prototype.verifyNotFailed = function () {\n if (this.failure) {\n fail('AsyncQueue is already failed: ' + (this.failure.stack || this.failure.message));\n }\n };\n /**\r\n * Verifies there's an operation currently in-progress on the AsyncQueue.\r\n * Unfortunately we can't verify that the running code is in the promise chain\r\n * of that operation, so this isn't a foolproof check, but it should be enough\r\n * to catch some bugs.\r\n */\n\n\n AsyncQueue.prototype.verifyOperationInProgress = function () {\n assert(this.operationInProgress, 'verifyOpInProgress() called when no op in progress on this queue.');\n };\n /**\r\n * Waits until all currently queued tasks are finished executing. Delayed\r\n * operations are not run.\r\n */\n\n\n AsyncQueue.prototype.drain = function () {\n return this.enqueue(function () {\n return Promise.resolve();\n });\n };\n /**\r\n * For Tests: Determine if a delayed operation with a particular TimerId\r\n * exists.\r\n */\n\n\n AsyncQueue.prototype.containsDelayedOperation = function (timerId) {\n for (var _i = 0, _a = this.delayedOperations; _i < _a.length; _i++) {\n var op = _a[_i];\n\n if (op.timerId === timerId) {\n return true;\n }\n }\n\n return false;\n };\n /**\r\n * For Tests: Runs some or all delayed operations early.\r\n *\r\n * @param lastTimerId Delayed operations up to and including this TimerId will\r\n * be drained. Throws if no such operation exists. Pass TimerId.All to run\r\n * all delayed operations.\r\n * @returns a Promise that resolves once all operations have been run.\r\n */\n\n\n AsyncQueue.prototype.runDelayedOperationsEarly = function (lastTimerId) {\n var _this = this; // Note that draining may generate more delayed ops, so we do that first.\n\n\n return this.drain().then(function () {\n assert(lastTimerId === TimerId.All || _this.containsDelayedOperation(lastTimerId), \"Attempted to drain to missing operation \" + lastTimerId); // Run ops in the same order they'd run if they ran naturally.\n\n _this.delayedOperations.sort(function (a, b) {\n return a.targetTimeMs - b.targetTimeMs;\n });\n\n for (var _i = 0, _a = _this.delayedOperations; _i < _a.length; _i++) {\n var op = _a[_i];\n op.skipDelay();\n\n if (lastTimerId !== TimerId.All && op.timerId === lastTimerId) {\n break;\n }\n }\n\n return _this.drain();\n });\n };\n /** Called once a DelayedOperation is run or canceled. */\n\n\n AsyncQueue.prototype.removeDelayedOperation = function (op) {\n // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small.\n var index = this.delayedOperations.indexOf(op);\n assert(index >= 0, 'Delayed operation not found.');\n this.delayedOperations.splice(index, 1);\n };\n\n return AsyncQueue;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar escapeChar = \"\\x01\";\nvar encodedSeparatorChar = \"\\x01\";\nvar encodedNul = \"\\x10\";\nvar encodedEscape = \"\\x11\";\n/**\r\n * Encodes a resource path into a IndexedDb-compatible string form.\r\n */\n\nfunction encode(path) {\n var result = '';\n\n for (var i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n\n result = encodeSegment(path.get(i), result);\n }\n\n return encodeSeparator(result);\n}\n/** Encodes a single segment of a resource path into the given result */\n\n\nfunction encodeSegment(segment, resultBuf) {\n var result = resultBuf;\n var length = segment.length;\n\n for (var i = 0; i < length; i++) {\n var c = segment.charAt(i);\n\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n\n default:\n result += c;\n }\n }\n\n return result;\n}\n/** Encodes a path separator into the given result */\n\n\nfunction encodeSeparator(result) {\n return result + escapeChar + encodedSeparatorChar;\n}\n/**\r\n * Decodes the given IndexedDb-compatible string form of a resource path into\r\n * a ResourcePath instance. Note that this method is not suitable for use with\r\n * decoding resource names from the server; those are One Platform format\r\n * strings.\r\n */\n\n\nfunction decode$1(path) {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n var length = path.length;\n assert(length >= 2, 'Invalid path ' + path);\n\n if (length === 2) {\n assert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 'Non-empty path ' + path + ' had length 2');\n return ResourcePath.EMPTY_PATH;\n } // Escape characters cannot exist past the second-to-last position in the\n // source value.\n\n\n var lastReasonableEscapeIndex = length - 2;\n var segments = [];\n var segmentBuilder = '';\n\n for (var start = 0; start < length;) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n var end = path.indexOf(escapeChar, start);\n\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n var next = path.charAt(end + 1);\n\n switch (next) {\n case encodedSeparatorChar:\n var currentPiece = path.substring(start, end);\n var segment = void 0;\n\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n\n segments.push(segment);\n break;\n\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n\n default:\n fail('Invalid encoded resource path: \"' + path + '\"');\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar BATCHID_UNKNOWN = -1;\n/**\r\n * A batch of mutations that will be sent as one unit to the backend.\r\n */\n\nvar MutationBatch =\n/** @class */\nfunction () {\n function MutationBatch(batchId, localWriteTime, mutations) {\n this.batchId = batchId;\n this.localWriteTime = localWriteTime;\n this.mutations = mutations;\n assert(mutations.length > 0, 'Cannot create an empty mutation batch');\n }\n /**\r\n * Applies all the mutations in this MutationBatch to the specified document\r\n * to create a new remote document\r\n *\r\n * @param docKey The key of the document to apply mutations to.\r\n * @param maybeDoc The document to apply mutations to.\r\n * @param batchResult The result of applying the MutationBatch to the\r\n * backend.\r\n */\n\n\n MutationBatch.prototype.applyToRemoteDocument = function (docKey, maybeDoc, batchResult) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToRemoteDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n\n var mutationResults = batchResult.mutationResults;\n assert(mutationResults.length === this.mutations.length, \"Mismatch between mutations length\\n (\" + this.mutations.length + \") and mutation results length\\n (\" + mutationResults.length + \").\");\n\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n\n if (mutation.key.isEqual(docKey)) {\n var mutationResult = mutationResults[i];\n maybeDoc = mutation.applyToRemoteDocument(maybeDoc, mutationResult);\n }\n }\n\n return maybeDoc;\n };\n /**\r\n * Computes the local view of a document given all the mutations in this\r\n * batch.\r\n *\r\n * @param docKey The key of the document to apply mutations to.\r\n * @param maybeDoc The document to apply mutations to.\r\n */\n\n\n MutationBatch.prototype.applyToLocalView = function (docKey, maybeDoc) {\n if (maybeDoc) {\n assert(maybeDoc.key.isEqual(docKey), \"applyToLocalDocument: key \" + docKey + \" should match maybeDoc key\\n \" + maybeDoc.key);\n }\n\n var baseDoc = maybeDoc;\n\n for (var i = 0; i < this.mutations.length; i++) {\n var mutation = this.mutations[i];\n\n if (mutation.key.isEqual(docKey)) {\n maybeDoc = mutation.applyToLocalView(maybeDoc, baseDoc, this.localWriteTime);\n }\n }\n\n return maybeDoc;\n };\n\n MutationBatch.prototype.keys = function () {\n var keySet = documentKeySet();\n\n for (var _i = 0, _a = this.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n keySet = keySet.add(mutation.key);\n }\n\n return keySet;\n };\n\n MutationBatch.prototype.isEqual = function (other) {\n return this.batchId === other.batchId && arrayEquals(this.mutations, other.mutations);\n };\n\n return MutationBatch;\n}();\n/** The result of applying a mutation batch to the backend. */\n\n\nvar MutationBatchResult =\n/** @class */\nfunction () {\n function MutationBatchResult(batch, commitVersion, mutationResults, streamToken,\n /**\r\n * A pre-computed mapping from each mutated document to the resulting\r\n * version.\r\n */\n docVersions) {\n this.batch = batch;\n this.commitVersion = commitVersion;\n this.mutationResults = mutationResults;\n this.streamToken = streamToken;\n this.docVersions = docVersions;\n }\n /**\r\n * Creates a new MutationBatchResult for the given batch and results. There\r\n * must be one result for each mutation in the batch. This static factory\r\n * caches a document=>version mapping (docVersions).\r\n */\n\n\n MutationBatchResult.from = function (batch, commitVersion, results, streamToken) {\n assert(batch.mutations.length === results.length, 'Mutations sent ' + batch.mutations.length + ' must equal results received ' + results.length);\n var versionMap = documentVersionMap();\n var mutations = batch.mutations;\n\n for (var 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, streamToken, versionMap);\n };\n\n return MutationBatchResult;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar RESERVED_BITS = 1;\nvar GeneratorIds;\n\n(function (GeneratorIds) {\n GeneratorIds[GeneratorIds[\"QueryCache\"] = 0] = \"QueryCache\";\n GeneratorIds[GeneratorIds[\"SyncEngine\"] = 1] = \"SyncEngine\"; // The target IDs for limbo detection are odd (end in 1).\n})(GeneratorIds || (GeneratorIds = {}));\n/**\r\n * Generates monotonically increasing target IDs for sending targets to the\r\n * watch stream.\r\n *\r\n * The client constructs two generators, one for the query cache (via\r\n * forQueryCache()), and one for limbo documents (via forSyncEngine()). These\r\n * two generators produce non-overlapping IDs (by using even and odd IDs\r\n * respectively).\r\n *\r\n * By separating the target ID space, the query cache can generate target IDs\r\n * that persist across client restarts, while sync engine can independently\r\n * generate in-memory target IDs that are transient and can be reused after a\r\n * restart.\r\n */\n// TODO(mrschmidt): Explore removing this class in favor of generating these IDs\n// directly in SyncEngine and LocalStore.\n\n\nvar TargetIdGenerator =\n/** @class */\nfunction () {\n /**\r\n * Instantiates a new TargetIdGenerator. If a seed is provided, the generator\r\n * will use the seed value as the next target ID.\r\n */\n function TargetIdGenerator(generatorId, seed) {\n this.generatorId = generatorId;\n assert((generatorId & RESERVED_BITS) === generatorId, \"Generator ID \" + generatorId + \" contains more than \" + RESERVED_BITS + \" reserved bits\");\n this.seek(seed !== undefined ? seed : this.generatorId);\n }\n\n TargetIdGenerator.prototype.next = function () {\n var nextId = this.nextId;\n this.nextId += 1 << RESERVED_BITS;\n return nextId;\n };\n /**\r\n * Returns the ID that follows the given ID. Subsequent calls to `next()`\r\n * use the newly returned target ID as their base.\r\n */\n // PORTING NOTE: Multi-tab only.\n\n\n TargetIdGenerator.prototype.after = function (targetId) {\n this.seek(targetId + (1 << RESERVED_BITS));\n return this.next();\n };\n\n TargetIdGenerator.prototype.seek = function (targetId) {\n assert((targetId & RESERVED_BITS) === this.generatorId, 'Cannot supply target ID from different generator ID');\n this.nextId = targetId;\n };\n\n TargetIdGenerator.forQueryCache = function () {\n // We seed the query cache generator to return '2' as its first ID, as there\n // is no differentiation in the protocol layer between an unset number and\n // the number '0'. If we were to sent a target with target ID '0', the\n // backend would consider it unset and replace it with its own ID.\n var targetIdGenerator = new TargetIdGenerator(GeneratorIds.QueryCache, 2);\n return targetIdGenerator;\n };\n\n TargetIdGenerator.forSyncEngine = function () {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(GeneratorIds.SyncEngine);\n };\n\n return TargetIdGenerator;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * PersistencePromise<> is essentially a re-implementation of Promise<> except\r\n * it has a .next() method instead of .then() and .next() and .catch() callbacks\r\n * are executed synchronously when a PersistencePromise resolves rather than\r\n * asynchronously (Promise<> implementations use setImmediate() or similar).\r\n *\r\n * This is necessary to interoperate with IndexedDB which will automatically\r\n * commit transactions if control is returned to the event loop without\r\n * synchronously initiating another operation on the transaction.\r\n *\r\n * NOTE: .then() and .catch() only allow a single consumer, unlike normal\r\n * Promises.\r\n */\n\n\nvar PersistencePromise =\n/** @class */\nfunction () {\n function PersistencePromise(callback) {\n var _this = this; // NOTE: next/catchCallback will always point to our own wrapper functions,\n // not the user's raw next() or catch() callbacks.\n // tslint:disable-next-line:no-any Accept any result type for the next call in the Promise chain.\n\n\n this.nextCallback = null; // tslint:disable-next-line:no-any Accept any result type for the error handler.\n\n this.catchCallback = null; // When the operation resolves, we'll set result or error and mark isDone.\n\n this.result = undefined;\n this.error = undefined;\n this.isDone = false; // Set to true when .then() or .catch() are called and prevents additional\n // chaining.\n\n this.callbackAttached = false;\n callback(function (value) {\n _this.isDone = true;\n _this.result = value;\n\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 }, function (error) {\n _this.isDone = true;\n _this.error = error;\n\n if (_this.catchCallback) {\n _this.catchCallback(error);\n }\n });\n }\n\n PersistencePromise.prototype.catch = function (fn) {\n return this.next(undefined, fn);\n };\n\n PersistencePromise.prototype.next = function (nextFn, catchFn) {\n var _this = this;\n\n if (this.callbackAttached) {\n fail('Called next() or catch() twice for PersistencePromise');\n }\n\n this.callbackAttached = true;\n\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(function (resolve, reject) {\n _this.nextCallback = function (value) {\n _this.wrapSuccess(nextFn, value).next(resolve, reject);\n };\n\n _this.catchCallback = function (error) {\n _this.wrapFailure(catchFn, error).next(resolve, reject);\n };\n });\n }\n };\n\n PersistencePromise.prototype.toPromise = function () {\n var _this = this;\n\n return new Promise(function (resolve, reject) {\n _this.next(resolve, reject);\n });\n };\n\n PersistencePromise.prototype.wrapUserFunction = function (fn) {\n try {\n var result = fn();\n\n if (result instanceof PersistencePromise) {\n return result;\n } else {\n return PersistencePromise.resolve(result);\n }\n } catch (e) {\n return PersistencePromise.reject(e);\n }\n };\n\n PersistencePromise.prototype.wrapSuccess = function (nextFn, value) {\n if (nextFn) {\n return this.wrapUserFunction(function () {\n return nextFn(value);\n });\n } else {\n // If there's no nextFn, then R must be the same as T but we\n // can't express that in the type system.\n // tslint:disable-next-line:no-any\n return PersistencePromise.resolve(value);\n }\n };\n\n PersistencePromise.prototype.wrapFailure = function (catchFn, error) {\n if (catchFn) {\n return this.wrapUserFunction(function () {\n return catchFn(error);\n });\n } else {\n return PersistencePromise.reject(error);\n }\n };\n\n PersistencePromise.resolve = function (result) {\n return new PersistencePromise(function (resolve, reject) {\n resolve(result);\n });\n };\n\n PersistencePromise.reject = function (error) {\n return new PersistencePromise(function (resolve, reject) {\n reject(error);\n });\n };\n\n PersistencePromise.waitFor = function ( // tslint:disable-next-line:no-any Accept all Promise types in waitFor().\n all) {\n return new PersistencePromise(function (resolve, reject) {\n var expectedCount = 0;\n var resolvedCount = 0;\n var done = false;\n all.forEach(function (element) {\n ++expectedCount;\n element.next(function () {\n ++resolvedCount;\n\n if (done && resolvedCount === expectedCount) {\n resolve();\n }\n }, function (err) {\n return reject(err);\n });\n });\n done = true;\n\n if (resolvedCount === expectedCount) {\n resolve();\n }\n });\n };\n /**\r\n * Given an array of predicate functions that asynchronously evaluate to a\r\n * boolean, implements a short-circuiting `or` between the results. Predicates\r\n * will be evaluated until one of them returns `true`, then stop. The final\r\n * result will be whether any of them returned `true`.\r\n */\n\n\n PersistencePromise.or = function (predicates) {\n var p = PersistencePromise.resolve(false);\n\n var _loop_1 = function _loop_1(predicate) {\n p = p.next(function (isTrue) {\n if (isTrue) {\n return PersistencePromise.resolve(isTrue);\n } else {\n return predicate();\n }\n });\n };\n\n for (var _i = 0, predicates_1 = predicates; _i < predicates_1.length; _i++) {\n var predicate = predicates_1[_i];\n\n _loop_1(predicate);\n }\n\n return p;\n };\n /**\r\n * Given an iterable, call the given function on each element in the\r\n * collection and wait for all of the resulting concurrent PersistencePromises\r\n * to resolve.\r\n */\n\n\n PersistencePromise.forEach = function (collection, f) {\n var _this = this;\n\n var promises = [];\n collection.forEach(function (r, s) {\n promises.push(f.call(_this, r, s));\n });\n return this.waitFor(promises);\n };\n\n return PersistencePromise;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$1 = 'SimpleDb';\n/**\r\n * Provides a wrapper around IndexedDb with a simplified interface that uses\r\n * Promise-like return values to chain operations. Real promises cannot be used\r\n * since .then() continuations are executed asynchronously (e.g. via\r\n * .setImmediate), which would cause IndexedDB to end the transaction.\r\n * See PersistencePromise for more details.\r\n */\n\nvar SimpleDb =\n/** @class */\nfunction () {\n function SimpleDb(db) {\n this.db = db;\n }\n /** Opens the specified database, creating or upgrading it if necessary. */\n\n\n SimpleDb.openOrCreate = function (name, version, schemaConverter) {\n assert(SimpleDb.isAvailable(), 'IndexedDB not supported in current environment.');\n debug(LOG_TAG$1, 'Opening database:', name);\n return new PersistencePromise(function (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 var request = window.indexedDB.open(name, version);\n\n request.onsuccess = function (event) {\n var db = event.target.result;\n resolve(new SimpleDb(db));\n };\n\n request.onblocked = function () {\n reject(new FirestoreError(Code.FAILED_PRECONDITION, 'Cannot upgrade IndexedDB schema while another tab is open. ' + 'Close all tabs that access Firestore and reload this page to proceed.'));\n };\n\n request.onerror = function (event) {\n reject(event.target.error);\n };\n\n request.onupgradeneeded = function (event) {\n debug(LOG_TAG$1, 'Database \"' + name + '\" requires upgrade from version:', event.oldVersion);\n var db = event.target.result; // We are provided a version upgrade transaction from the request, so\n // we wrap that in a SimpleDbTransaction to allow use of our friendlier\n // API for schema migration operations.\n\n var txn = new SimpleDbTransaction(request.transaction);\n schemaConverter.createOrUpgrade(db, txn, event.oldVersion, SCHEMA_VERSION).next(function () {\n debug(LOG_TAG$1, 'Database upgrade to version ' + SCHEMA_VERSION + ' complete');\n });\n };\n }).toPromise();\n };\n /** Deletes the specified database. */\n\n\n SimpleDb.delete = function (name) {\n debug(LOG_TAG$1, 'Removing database:', name);\n return wrapRequest(window.indexedDB.deleteDatabase(name)).toPromise();\n };\n /** Returns true if IndexedDB is available in the current environment. */\n\n\n SimpleDb.isAvailable = function () {\n if (typeof window === 'undefined' || window.indexedDB == null) {\n return false;\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 // If we are running in Node using the IndexedDBShim, `window` is defined,\n // but `window.navigator` is not. In this case, we support IndexedDB and\n // return `true`.\n\n\n if (window.navigator === undefined) {\n return process.env.USE_MOCK_PERSISTENCE === 'YES';\n } // Check the UA string to find out the browser.\n // TODO(mikelehen): Move this logic into packages/util/environment.ts\n\n\n var ua = window.navigator.userAgent; // IE 10\n // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';\n // IE 11\n // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';\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 if (ua.indexOf('MSIE ') > 0 || ua.indexOf('Trident/') > 0 || ua.indexOf('Edge/') > 0) {\n return false;\n } else {\n return true;\n }\n };\n /** Helper to get a typed SimpleDbStore from a transaction. */\n\n\n SimpleDb.getStore = function (txn, store) {\n return txn.store(store);\n };\n\n SimpleDb.prototype.runTransaction = function (mode, objectStores, transactionFn) {\n var transaction = SimpleDbTransaction.open(this.db, mode, objectStores);\n var transactionFnResult = transactionFn(transaction).catch(function (error$$1) {\n // Abort the transaction if there was an error.\n transaction.abort(error$$1);\n }).toPromise(); // 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\n return transaction.completionPromise.then(function () {\n return transactionFnResult;\n });\n };\n\n SimpleDb.prototype.close = function () {\n this.db.close();\n };\n\n return SimpleDb;\n}();\n/**\r\n * A controller for iterating over a key range or index. It allows an iterate\r\n * callback to delete the currently-referenced object, or jump to a new key\r\n * within the key range or index.\r\n */\n\n\nvar IterationController =\n/** @class */\nfunction () {\n function IterationController(dbCursor) {\n this.dbCursor = dbCursor;\n this.shouldStop = false;\n this.nextKey = null;\n }\n\n Object.defineProperty(IterationController.prototype, \"isDone\", {\n get: function get() {\n return this.shouldStop;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"skipToKey\", {\n get: function get() {\n return this.nextKey;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(IterationController.prototype, \"cursor\", {\n set: function set(value) {\n this.dbCursor = value;\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * This function can be called to stop iteration at any point.\r\n */\n\n IterationController.prototype.done = function () {\n this.shouldStop = true;\n };\n /**\r\n * This function can be called to skip to that next key, which could be\r\n * an index or a primary key.\r\n */\n\n\n IterationController.prototype.skip = function (key) {\n this.nextKey = key;\n };\n /**\r\n * Delete the current cursor value from the object store.\r\n *\r\n * NOTE: You CANNOT do this with a keysOnly query.\r\n */\n\n\n IterationController.prototype.delete = function () {\n return wrapRequest(this.dbCursor.delete());\n };\n\n return IterationController;\n}();\n/**\r\n * Wraps an IDBTransaction and exposes a store() method to get a handle to a\r\n * specific object store.\r\n */\n\n\nvar SimpleDbTransaction =\n/** @class */\nfunction () {\n function SimpleDbTransaction(transaction) {\n var _this = this;\n\n this.transaction = transaction;\n this.aborted = false;\n /**\r\n * A promise that resolves with the result of the IndexedDb transaction.\r\n */\n\n this.completionDeferred = new Deferred$1();\n\n this.transaction.oncomplete = function () {\n _this.completionDeferred.resolve();\n };\n\n this.transaction.onabort = function () {\n if (transaction.error) {\n _this.completionDeferred.reject(transaction.error);\n } else {\n _this.completionDeferred.resolve();\n }\n };\n\n this.transaction.onerror = function (event) {\n _this.completionDeferred.reject(event.target.error);\n };\n }\n\n SimpleDbTransaction.open = function (db, mode, objectStoreNames) {\n return new SimpleDbTransaction(db.transaction(objectStoreNames, mode));\n };\n\n Object.defineProperty(SimpleDbTransaction.prototype, \"completionPromise\", {\n get: function get() {\n return this.completionDeferred.promise;\n },\n enumerable: true,\n configurable: true\n });\n\n SimpleDbTransaction.prototype.abort = function (error$$1) {\n if (error$$1) {\n this.completionDeferred.reject(error$$1);\n }\n\n if (!this.aborted) {\n debug(LOG_TAG$1, 'Aborting transaction:', error$$1 ? error$$1.message : 'Client-initiated abort');\n this.aborted = true;\n this.transaction.abort();\n }\n };\n /**\r\n * Returns a SimpleDbStore for the specified store. All\r\n * operations performed on the SimpleDbStore happen within the context of this\r\n * transaction and it cannot be used anymore once the transaction is\r\n * completed.\r\n *\r\n * Note that we can't actually enforce that the KeyType and ValueType are\r\n * correct, but they allow type safety through the rest of the consuming code.\r\n */\n\n\n SimpleDbTransaction.prototype.store = function (storeName) {\n var store = this.transaction.objectStore(storeName);\n assert(!!store, 'Object store not part of transaction: ' + storeName);\n return new SimpleDbStore(store);\n };\n\n return SimpleDbTransaction;\n}();\n/**\r\n * A wrapper around an IDBObjectStore providing an API that:\r\n *\r\n * 1) Has generic KeyType / ValueType parameters to provide strongly-typed\r\n * methods for acting against the object store.\r\n * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every\r\n * method return a PersistencePromise instead.\r\n * 3) Provides a higher-level API to avoid needing to do excessive wrapping of\r\n * intermediate IndexedDB types (IDBCursorWithValue, etc.)\r\n */\n\n\nvar SimpleDbStore =\n/** @class */\nfunction () {\n function SimpleDbStore(store) {\n this.store = store;\n }\n\n SimpleDbStore.prototype.put = function (keyOrValue, value) {\n var request;\n\n if (value !== undefined) {\n debug(LOG_TAG$1, 'PUT', this.store.name, keyOrValue, value);\n request = this.store.put(value, keyOrValue);\n } else {\n debug(LOG_TAG$1, 'PUT', this.store.name, '', keyOrValue);\n request = this.store.put(keyOrValue);\n }\n\n return wrapRequest(request);\n };\n /**\r\n * Adds a new value into an Object Store and returns the new key. Similar to\r\n * IndexedDb's `add()`, this method will fail on primary key collisions.\r\n *\r\n * @param value The object to write.\r\n * @return The key of the value to add.\r\n */\n\n\n SimpleDbStore.prototype.add = function (value) {\n debug(LOG_TAG$1, 'ADD', this.store.name, value, value);\n var request = this.store.add(value);\n return wrapRequest(request);\n };\n /**\r\n * Gets the object with the specified key from the specified store, or null\r\n * if no object exists with the specified key.\r\n *\r\n * @key The key of the object to get.\r\n * @return The object with the specified key or null if no object exists.\r\n */\n\n\n SimpleDbStore.prototype.get = function (key) {\n var _this = this;\n\n var request = this.store.get(key); // tslint:disable-next-line:no-any We're doing an unsafe cast to ValueType.\n\n return wrapRequest(request).next(function (result) {\n // Normalize nonexistence to null.\n if (result === undefined) {\n result = null;\n }\n\n debug(LOG_TAG$1, 'GET', _this.store.name, key, result);\n return result;\n });\n };\n\n SimpleDbStore.prototype.delete = function (key) {\n debug(LOG_TAG$1, 'DELETE', this.store.name, key);\n var request = this.store.delete(key);\n return wrapRequest(request);\n };\n /**\r\n * If we ever need more of the count variants, we can add overloads. For now,\r\n * all we need is to count everything in a store.\r\n *\r\n * Returns the number of rows in the store.\r\n */\n\n\n SimpleDbStore.prototype.count = function () {\n debug(LOG_TAG$1, 'COUNT', this.store.name);\n var request = this.store.count();\n return wrapRequest(request);\n };\n\n SimpleDbStore.prototype.loadAll = function (indexOrRange, range) {\n var cursor = this.cursor(this.options(indexOrRange, range));\n var results = [];\n return this.iterateCursor(cursor, function (key, value) {\n results.push(value);\n }).next(function () {\n return results;\n });\n };\n\n SimpleDbStore.prototype.deleteAll = function (indexOrRange, range) {\n debug(LOG_TAG$1, 'DELETE ALL', this.store.name);\n var options = this.options(indexOrRange, range);\n options.keysOnly = false;\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, function (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 SimpleDbStore.prototype.iterate = function (optionsOrCallback, callback) {\n var options;\n\n if (!callback) {\n options = {};\n callback = optionsOrCallback;\n } else {\n options = optionsOrCallback;\n }\n\n var cursor = this.cursor(options);\n return this.iterateCursor(cursor, callback);\n };\n /**\r\n * Iterates over a store, but waits for the given callback to complete for\r\n * each entry before iterating the next entry. This allows the callback to do\r\n * asynchronous work to determine if this iteration should continue.\r\n *\r\n * The provided callback should return `true` to continue iteration, and\r\n * `false` otherwise.\r\n */\n\n\n SimpleDbStore.prototype.iterateSerial = function (callback) {\n var cursorRequest = this.cursor({});\n return new PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n\n if (!cursor) {\n resolve();\n return;\n }\n\n callback(cursor.primaryKey, cursor.value).next(function (shouldContinue) {\n if (shouldContinue) {\n cursor.continue();\n } else {\n resolve();\n }\n });\n };\n });\n };\n\n SimpleDbStore.prototype.iterateCursor = function (cursorRequest, fn) {\n var results = [];\n return new PersistencePromise(function (resolve, reject) {\n cursorRequest.onerror = function (event) {\n reject(event.target.error);\n };\n\n cursorRequest.onsuccess = function (event) {\n var cursor = event.target.result;\n\n if (!cursor) {\n resolve();\n return;\n }\n\n var controller = new IterationController(cursor);\n var userResult = fn(cursor.primaryKey, cursor.value, controller);\n\n if (userResult instanceof PersistencePromise) {\n var userPromise = userResult.catch(function (err) {\n controller.done();\n return PersistencePromise.reject(err);\n });\n results.push(userPromise);\n }\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(function () {\n return PersistencePromise.waitFor(results);\n });\n };\n\n SimpleDbStore.prototype.options = function (indexOrRange, range) {\n var indexName = undefined;\n\n if (indexOrRange !== undefined) {\n if (typeof indexOrRange === 'string') {\n indexName = indexOrRange;\n } else {\n assert(range === undefined, '3rd argument must not be defined if 2nd is a range.');\n range = indexOrRange;\n }\n }\n\n return {\n index: indexName,\n range: range\n };\n };\n\n SimpleDbStore.prototype.cursor = function (options) {\n var direction = 'next';\n\n if (options.reverse) {\n direction = 'prev';\n }\n\n if (options.index) {\n var index = this.store.index(options.index);\n\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 return SimpleDbStore;\n}();\n/**\r\n * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror\r\n * handlers to resolve / reject the PersistencePromise as appropriate.\r\n */\n\n\nfunction wrapRequest(request) {\n return new PersistencePromise(function (resolve, reject) {\n request.onsuccess = function (event) {\n var result = event.target.result;\n resolve(result);\n };\n\n request.onerror = function (event) {\n reject(event.target.error);\n };\n });\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar IndexedDbQueryCache =\n/** @class */\nfunction () {\n function IndexedDbQueryCache(referenceDelegate, serializer) {\n this.referenceDelegate = referenceDelegate;\n this.serializer = serializer; // PORTING NOTE: We don't cache global metadata for the query cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n this.targetIdGenerator = TargetIdGenerator.forQueryCache();\n }\n\n IndexedDbQueryCache.prototype.allocateTargetId = function (transaction) {\n var _this = this;\n\n return this.retrieveMetadata(transaction).next(function (metadata) {\n metadata.highestTargetId = _this.targetIdGenerator.after(metadata.highestTargetId);\n return _this.saveMetadata(transaction, metadata).next(function () {\n return metadata.highestTargetId;\n });\n });\n };\n\n IndexedDbQueryCache.prototype.getLastRemoteSnapshotVersion = function (transaction) {\n return this.retrieveMetadata(transaction).next(function (metadata) {\n return SnapshotVersion.fromTimestamp(new Timestamp(metadata.lastRemoteSnapshotVersion.seconds, metadata.lastRemoteSnapshotVersion.nanoseconds));\n });\n };\n\n IndexedDbQueryCache.prototype.getHighestSequenceNumber = function (transaction) {\n return getHighestListenSequenceNumber(transaction.simpleDbTransaction);\n };\n\n IndexedDbQueryCache.prototype.setTargetsMetadata = function (transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) {\n var _this = this;\n\n return this.retrieveMetadata(transaction).next(function (metadata) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion.toTimestamp();\n }\n\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n\n return _this.saveMetadata(transaction, metadata);\n });\n };\n\n IndexedDbQueryCache.prototype.addQueryData = function (transaction, queryData) {\n var _this = this;\n\n return this.saveQueryData(transaction, queryData).next(function () {\n return _this.retrieveMetadata(transaction).next(function (metadata) {\n metadata.targetCount += 1;\n\n _this.updateMetadataFromQueryData(queryData, metadata);\n\n return _this.saveMetadata(transaction, metadata);\n });\n });\n };\n\n IndexedDbQueryCache.prototype.updateQueryData = function (transaction, queryData) {\n return this.saveQueryData(transaction, queryData);\n };\n\n IndexedDbQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n var _this = this;\n\n return this.removeMatchingKeysForTargetId(transaction, queryData.targetId).next(function () {\n return targetsStore(transaction).delete(queryData.targetId);\n }).next(function () {\n return _this.retrieveMetadata(transaction);\n }).next(function (metadata) {\n assert(metadata.targetCount > 0, 'Removing from an empty query cache');\n metadata.targetCount -= 1;\n return _this.saveMetadata(transaction, metadata);\n });\n };\n /**\r\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\r\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\r\n * Returns the number of targets removed.\r\n */\n\n\n IndexedDbQueryCache.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\n var _this = this;\n\n var count = 0;\n var promises = [];\n return targetsStore(txn).iterate(function (key, value) {\n var queryData = _this.serializer.fromDbTarget(value);\n\n if (queryData.sequenceNumber <= upperBound && activeTargetIds[queryData.targetId] === undefined) {\n count++;\n promises.push(_this.removeQueryData(txn, queryData));\n }\n }).next(function () {\n return PersistencePromise.waitFor(promises);\n }).next(function () {\n return count;\n });\n };\n /**\r\n * Call provided function with each `QueryData` that we have cached.\r\n */\n\n\n IndexedDbQueryCache.prototype.forEachTarget = function (txn, f) {\n var _this = this;\n\n return targetsStore(txn).iterate(function (key, value) {\n var queryData = _this.serializer.fromDbTarget(value);\n\n f(queryData);\n });\n };\n\n IndexedDbQueryCache.prototype.retrieveMetadata = function (transaction) {\n return retrieveMetadata(transaction.simpleDbTransaction);\n };\n\n IndexedDbQueryCache.prototype.saveMetadata = function (transaction, metadata) {\n return globalTargetStore(transaction).put(DbTargetGlobal.key, metadata);\n };\n\n IndexedDbQueryCache.prototype.saveQueryData = function (transaction, queryData) {\n return targetsStore(transaction).put(this.serializer.toDbTarget(queryData));\n };\n /**\r\n * In-place updates the provided metadata to account for values in the given\r\n * QueryData. Saving is done separately. Returns true if there were any\r\n * changes to the metadata.\r\n */\n\n\n IndexedDbQueryCache.prototype.updateMetadataFromQueryData = function (queryData, metadata) {\n var updated = false;\n\n if (queryData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = queryData.targetId;\n updated = true;\n }\n\n if (queryData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = queryData.sequenceNumber;\n updated = true;\n }\n\n return updated;\n };\n\n IndexedDbQueryCache.prototype.getQueryCount = function (transaction) {\n return this.retrieveMetadata(transaction).next(function (metadata) {\n return metadata.targetCount;\n });\n };\n\n IndexedDbQueryCache.prototype.getQueryData = function (transaction, query) {\n var _this = this; // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n\n\n var canonicalId = query.canonicalId();\n var range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]);\n var result = null;\n return targetsStore(transaction).iterate({\n range: range,\n index: DbTarget.queryTargetsIndexName\n }, function (key, value, control) {\n var found = _this.serializer.fromDbTarget(value); // After finding a potential match, check that the query is\n // actually equal to the requested query.\n\n\n if (query.isEqual(found.query)) {\n result = found;\n control.done();\n }\n }).next(function () {\n return result;\n });\n };\n\n IndexedDbQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n var _this = this; // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n\n\n var promises = [];\n var store = documentTargetStore(txn);\n keys.forEach(function (key) {\n var path = encode(key.path);\n promises.push(store.put(new DbTargetDocument(targetId, path)));\n promises.push(_this.referenceDelegate.addReference(txn, key));\n });\n return PersistencePromise.waitFor(promises);\n };\n\n IndexedDbQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n var _this = this; // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n\n\n var store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, function (key) {\n var path = encode(key.path);\n return PersistencePromise.waitFor([store.delete([targetId, path]), _this.referenceDelegate.removeReference(txn, key)]);\n });\n };\n\n IndexedDbQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n var store = documentTargetStore(txn);\n var range = IDBKeyRange.bound([targetId], [targetId + 1],\n /*lowerOpen=*/\n false,\n /*upperOpen=*/\n true);\n return store.delete(range);\n };\n\n IndexedDbQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var range = IDBKeyRange.bound([targetId], [targetId + 1],\n /*lowerOpen=*/\n false,\n /*upperOpen=*/\n true);\n var store = documentTargetStore(txn);\n var result = documentKeySet();\n return store.iterate({\n range: range,\n keysOnly: true\n }, function (key, _, control) {\n var path = decode$1(key[1]);\n var docKey = new DocumentKey(path);\n result = result.add(docKey);\n }).next(function () {\n return result;\n });\n };\n\n IndexedDbQueryCache.prototype.containsKey = function (txn, key) {\n var path = encode(key.path);\n var range = IDBKeyRange.bound([path], [immediateSuccessor(path)],\n /*lowerOpen=*/\n false,\n /*upperOpen=*/\n true);\n var count = 0;\n return documentTargetStore(txn).iterate({\n index: DbTargetDocument.documentTargetsIndex,\n keysOnly: true,\n range: range\n }, function (_a, _, control) {\n var targetId = _a[0],\n path = _a[1]; // Having a sentinel row for a document does not count as containing that document;\n // For the query cache, containing the document means the document is part of some\n // target.\n\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }).next(function () {\n return count > 0;\n });\n };\n\n IndexedDbQueryCache.prototype.getQueryDataForTarget = function (transaction, targetId) {\n var _this = this;\n\n return targetsStore(transaction).get(targetId).next(function (found) {\n if (found) {\n return _this.serializer.fromDbTarget(found);\n } else {\n return null;\n }\n });\n };\n\n return IndexedDbQueryCache;\n}();\n/**\r\n * Helper to get a typed SimpleDbStore for the queries object store.\r\n */\n\n\nfunction targetsStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbTarget.store);\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the target globals object store.\r\n */\n\n\nfunction globalTargetStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbTargetGlobal.store);\n}\n\nfunction retrieveMetadata(txn) {\n var globalStore = SimpleDb.getStore(txn, DbTargetGlobal.store);\n return globalStore.get(DbTargetGlobal.key).next(function (metadata) {\n assert(metadata !== null, 'Missing metadata row.');\n return metadata;\n });\n}\n\nfunction getHighestListenSequenceNumber(txn) {\n return retrieveMetadata(txn).next(function (targetGlobal) {\n return targetGlobal.highestListenSequenceNumber;\n });\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the document target object store.\r\n */\n\n\nfunction documentTargetStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbTargetDocument.store);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * A map implementation that uses objects as keys. Objects must implement the\r\n * Equatable interface and must be immutable. Entries in the map are stored\r\n * together with the key being produced from the mapKeyFn. This map\r\n * automatically handles collisions of keys.\r\n */\n\n\nvar ObjectMap =\n/** @class */\nfunction () {\n function ObjectMap(mapKeyFn) {\n this.mapKeyFn = mapKeyFn;\n /**\r\n * The inner map for a key -> value pair. Due to the possibility of\r\n * collisions we keep a list of entries that we do a linear search through\r\n * to find an actual match. Note that collisions should be rare, so we still\r\n * expect near constant time lookups in practice.\r\n */\n\n this.inner = {};\n }\n /** Get a value for this key, or undefined if it does not exist. */\n\n\n ObjectMap.prototype.get = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n\n if (matches === undefined) {\n return undefined;\n }\n\n for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) {\n var _a = matches_1[_i],\n otherKey = _a[0],\n value = _a[1];\n\n if (otherKey.isEqual(key)) {\n return value;\n }\n }\n\n return undefined;\n };\n\n ObjectMap.prototype.has = function (key) {\n return this.get(key) !== undefined;\n };\n /** Put this key and value in the map. */\n\n\n ObjectMap.prototype.set = function (key, value) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n\n if (matches === undefined) {\n this.inner[id] = [[key, value]];\n return;\n }\n\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n matches[i] = [key, value];\n return;\n }\n }\n\n matches.push([key, value]);\n };\n /**\r\n * Remove this key from the map. Returns a boolean if anything was deleted.\r\n */\n\n\n ObjectMap.prototype.delete = function (key) {\n var id = this.mapKeyFn(key);\n var matches = this.inner[id];\n\n if (matches === undefined) {\n return false;\n }\n\n for (var i = 0; i < matches.length; i++) {\n if (matches[i][0].isEqual(key)) {\n if (matches.length === 1) {\n delete this.inner[id];\n } else {\n matches.splice(i, 1);\n }\n\n return true;\n }\n }\n\n return false;\n };\n\n ObjectMap.prototype.forEach = function (fn) {\n forEach(this.inner, function (_, entries) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i],\n k = _a[0],\n v = _a[1];\n fn(k, v);\n }\n });\n };\n\n ObjectMap.prototype.isEmpty = function () {\n return isEmpty(this.inner);\n };\n\n return ObjectMap;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\r\n * It can be used to batch up a set of changes to be written to the cache, but\r\n * additionally supports reading entries back with the `getEntry()` method,\r\n * falling back to the underlying RemoteDocumentCache if no entry is\r\n * buffered.\r\n *\r\n * Entries added to the cache *must* be read first. This is to facilitate\r\n * calculating the size delta of the pending changes.\r\n *\r\n * PORTING NOTE: This class was implemented then removed from other platforms.\r\n * If byte-counting ends up being needed on the other platforms, consider\r\n * porting this class as part of that implementation work.\r\n */\n\n\nvar RemoteDocumentChangeBuffer =\n/** @class */\nfunction () {\n function RemoteDocumentChangeBuffer() {\n this.changes = maybeDocumentMap();\n this.documentSizes = new ObjectMap(function (key) {\n return key.toString();\n });\n }\n /** Buffers a `RemoteDocumentCache.addEntry()` call. */\n\n\n RemoteDocumentChangeBuffer.prototype.addEntry = function (maybeDocument) {\n var changes = this.assertChanges();\n this.changes = changes.insert(maybeDocument.key, maybeDocument);\n }; // NOTE: removeEntry() is intentionally omitted. If it needs to be added in\n // the future it must take byte counting into account.\n\n /**\r\n * Looks up an entry in the cache. The buffered changes will first be checked,\r\n * and if no buffered change applies, this will forward to\r\n * `RemoteDocumentCache.getEntry()`.\r\n *\r\n * @param transaction The transaction in which to perform any persistence\r\n * operations.\r\n * @param documentKey The key of the entry to look up.\r\n * @return The cached Document or NoDocument entry, or null if we have nothing\r\n * cached.\r\n */\n\n\n RemoteDocumentChangeBuffer.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n\n var changes = this.assertChanges();\n var bufferedEntry = changes.get(documentKey);\n\n if (bufferedEntry) {\n return PersistencePromise.resolve(bufferedEntry);\n } else {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.getFromCache(transaction, documentKey).next(function (getResult) {\n if (getResult === null) {\n _this.documentSizes.set(documentKey, 0);\n\n return null;\n } else {\n _this.documentSizes.set(documentKey, getResult.size);\n\n return getResult.maybeDocument;\n }\n });\n }\n };\n /**\r\n * Applies buffered changes to the underlying RemoteDocumentCache, using\r\n * the provided transaction.\r\n */\n\n\n RemoteDocumentChangeBuffer.prototype.apply = function (transaction) {\n var result = this.applyChanges(transaction); // We should not buffer any more changes.\n\n this.changes = null;\n return result;\n };\n /** Helper to assert this.changes is not null and return it. */\n\n\n RemoteDocumentChangeBuffer.prototype.assertChanges = function () {\n assert(this.changes !== null, 'Changes have already been applied.');\n return this.changes;\n };\n\n return RemoteDocumentChangeBuffer;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar REMOTE_DOCUMENT_CHANGE_MISSING_ERR_MSG = 'The remote document changelog no longer contains all changes for all ' + 'local query views. It may be necessary to rebuild these views.';\n\nvar IndexedDbRemoteDocumentCache =\n/** @class */\nfunction () {\n /**\r\n * @param {LocalSerializer} serializer The document serializer.\r\n * @param keepDocumentChangeLog Whether to keep a document change log in\r\n * IndexedDb. This change log is required for Multi-Tab synchronization, but\r\n * not needed in clients that don't share access to their remote document\r\n * cache.\r\n */\n function IndexedDbRemoteDocumentCache(serializer, keepDocumentChangeLog) {\n this.serializer = serializer;\n this.keepDocumentChangeLog = keepDocumentChangeLog;\n /** The last id read by `getNewDocumentChanges()`. */\n\n this._lastProcessedDocumentChangeId = 0;\n }\n\n Object.defineProperty(IndexedDbRemoteDocumentCache.prototype, \"lastProcessedDocumentChangeId\", {\n get: function get() {\n return this._lastProcessedDocumentChangeId;\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Starts up the remote document cache.\r\n *\r\n * Reads the ID of the last document change from the documentChanges store.\r\n * Existing changes will not be returned as part of\r\n * `getNewDocumentChanges()`.\r\n */\n // PORTING NOTE: This is only used for multi-tab synchronization.\n\n IndexedDbRemoteDocumentCache.prototype.start = function (transaction) {\n var store = SimpleDb.getStore(transaction, DbRemoteDocumentChanges.store);\n return this.synchronizeLastDocumentChangeId(store);\n };\n /**\r\n * Adds the supplied entries to the cache. Adds the given size delta to the cached size.\r\n */\n\n\n IndexedDbRemoteDocumentCache.prototype.addEntries = function (transaction, entries, sizeDelta) {\n var promises = [];\n\n if (entries.length > 0) {\n var documentStore = remoteDocumentsStore(transaction);\n var changedKeys = documentKeySet();\n\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var _a = entries_1[_i],\n key = _a.key,\n doc = _a.doc;\n promises.push(documentStore.put(dbKey(key), doc));\n changedKeys = changedKeys.add(key);\n }\n\n if (this.keepDocumentChangeLog) {\n promises.push(documentChangesStore(transaction).put({\n changes: this.serializer.toDbResourcePaths(changedKeys)\n }));\n }\n\n promises.push(this.updateSize(transaction, sizeDelta));\n }\n\n return PersistencePromise.waitFor(promises);\n };\n /**\r\n * Removes a document from the cache. Note that this method does *not* do any\r\n * size accounting. It is the responsibility of the caller to count the bytes removed\r\n * and issue a final updateSize() call after removing documents.\r\n *\r\n * @param documentKey The key of the document to remove\r\n * @return The size of the document that was removed.\r\n */\n\n\n IndexedDbRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n // We don't need to keep changelog for these removals since `removeEntry` is\n // only used for garbage collection.\n var store = remoteDocumentsStore(transaction);\n var key = dbKey(documentKey);\n return store.get(key).next(function (document) {\n if (document) {\n return store.delete(key).next(function () {\n return dbDocumentSize(document);\n });\n } else {\n return PersistencePromise.resolve(0);\n }\n });\n };\n\n IndexedDbRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var _this = this;\n\n return remoteDocumentsStore(transaction).get(dbKey(documentKey)).next(function (dbRemoteDoc) {\n return dbRemoteDoc ? _this.serializer.fromDbRemoteDocument(dbRemoteDoc) : null;\n });\n };\n /**\r\n * Looks up an entry in the cache.\r\n *\r\n * @param documentKey The key of the entry to look up.\r\n * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.\r\n */\n\n\n IndexedDbRemoteDocumentCache.prototype.getSizedEntry = function (transaction, documentKey) {\n var _this = this;\n\n return remoteDocumentsStore(transaction).get(dbKey(documentKey)).next(function (dbRemoteDoc) {\n return dbRemoteDoc ? {\n maybeDocument: _this.serializer.fromDbRemoteDocument(dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n } : null;\n });\n };\n\n IndexedDbRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var _this = this;\n\n var results = documentMap(); // 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\n var startKey = query.path.toArray();\n var range = IDBKeyRange.lowerBound(startKey);\n return remoteDocumentsStore(transaction).iterate({\n range: range\n }, function (key, dbRemoteDoc, control) {\n var maybeDoc = _this.serializer.fromDbRemoteDocument(dbRemoteDoc);\n\n if (!query.path.isPrefixOf(maybeDoc.key.path)) {\n control.done();\n } else if (maybeDoc instanceof Document && query.matches(maybeDoc)) {\n results = results.insert(maybeDoc.key, maybeDoc);\n }\n }).next(function () {\n return results;\n });\n };\n\n IndexedDbRemoteDocumentCache.prototype.getNewDocumentChanges = function (transaction) {\n var _this = this;\n\n assert(this.keepDocumentChangeLog, 'Can only call getNewDocumentChanges() when document change log is enabled');\n var changedKeys = documentKeySet();\n var changedDocs = maybeDocumentMap();\n var range = IDBKeyRange.lowerBound(this._lastProcessedDocumentChangeId + 1);\n var firstIteration = true;\n var changesStore = documentChangesStore(transaction);\n return changesStore.iterate({\n range: range\n }, function (_, documentChange) {\n if (firstIteration) {\n firstIteration = false; // If our client was throttled for more than 30 minutes, another\n // client may have garbage collected the remote document changelog.\n\n if (_this._lastProcessedDocumentChangeId + 1 !== documentChange.id) {\n // Reset the `lastProcessedDocumentChangeId` to allow further\n // invocations to successfully return the changes after this\n // rejection.\n return _this.synchronizeLastDocumentChangeId(changesStore).next(function () {\n return PersistencePromise.reject(new FirestoreError(Code.DATA_LOSS, REMOTE_DOCUMENT_CHANGE_MISSING_ERR_MSG));\n });\n }\n }\n\n changedKeys = changedKeys.unionWith(_this.serializer.fromDbResourcePaths(documentChange.changes));\n _this._lastProcessedDocumentChangeId = documentChange.id;\n }).next(function () {\n var documentPromises = [];\n changedKeys.forEach(function (key) {\n documentPromises.push(_this.getEntry(transaction, key).next(function (maybeDocument) {\n var doc = maybeDocument || new NoDocument(key, SnapshotVersion.forDeletedDoc());\n changedDocs = changedDocs.insert(key, doc);\n }));\n });\n return PersistencePromise.waitFor(documentPromises);\n }).next(function () {\n return changedDocs;\n });\n };\n /**\r\n * Removes all changes in the remote document changelog through `changeId`\r\n * (inclusive).\r\n */\n\n\n IndexedDbRemoteDocumentCache.prototype.removeDocumentChangesThroughChangeId = function (transaction, changeId) {\n var range = IDBKeyRange.upperBound(changeId);\n return documentChangesStore(transaction).delete(range);\n };\n\n IndexedDbRemoteDocumentCache.prototype.synchronizeLastDocumentChangeId = function (documentChangesStore) {\n var _this = this; // If there are no existing changes, we set `lastProcessedDocumentChangeId`\n // to 0 since IndexedDb's auto-generated keys start at 1.\n\n\n this._lastProcessedDocumentChangeId = 0;\n return documentChangesStore.iterate({\n keysOnly: true,\n reverse: true\n }, function (key, value, control) {\n _this._lastProcessedDocumentChangeId = key;\n control.done();\n });\n };\n\n IndexedDbRemoteDocumentCache.prototype.newChangeBuffer = function () {\n return new IndexedDbRemoteDocumentChangeBuffer(this);\n };\n\n IndexedDbRemoteDocumentCache.prototype.getSize = function (txn) {\n return this.getMetadata(txn).next(function (metadata) {\n return metadata.byteSize;\n });\n };\n\n IndexedDbRemoteDocumentCache.prototype.getMetadata = function (txn) {\n return documentGlobalStore(txn).get(DbRemoteDocumentGlobal.key).next(function (metadata) {\n assert(!!metadata, 'Missing document cache metadata');\n return metadata;\n });\n };\n\n IndexedDbRemoteDocumentCache.prototype.setMetadata = function (txn, metadata) {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobal.key, metadata);\n };\n /**\r\n * Adds the given delta to the cached current size. Callers to removeEntry *must* call this\r\n * afterwards to update the size of the cache.\r\n *\r\n * @param sizeDelta\r\n */\n\n\n IndexedDbRemoteDocumentCache.prototype.updateSize = function (txn, sizeDelta) {\n var _this = this;\n\n return this.getMetadata(txn).next(function (metadata) {\n metadata.byteSize += sizeDelta;\n return _this.setMetadata(txn, metadata);\n });\n };\n\n return IndexedDbRemoteDocumentCache;\n}();\n\nfunction documentGlobalStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbRemoteDocumentGlobal.store);\n}\n/**\r\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache\r\n */\n\n\nvar IndexedDbRemoteDocumentChangeBuffer =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(IndexedDbRemoteDocumentChangeBuffer, _super);\n\n function IndexedDbRemoteDocumentChangeBuffer(documentCache) {\n var _this = _super.call(this) || this;\n\n _this.documentCache = documentCache;\n return _this;\n }\n\n IndexedDbRemoteDocumentChangeBuffer.prototype.applyChanges = function (transaction) {\n var _this = this;\n\n var changes = this.assertChanges();\n var delta = 0;\n var toApply = [];\n changes.forEach(function (key, maybeDocument) {\n var doc = _this.documentCache.serializer.toDbRemoteDocument(maybeDocument);\n\n var previousSize = _this.documentSizes.get(key); // NOTE: if we ever decide we need to support doing writes without\n // reading first, this assert will need to change to do the read automatically.\n\n\n assert(previousSize !== undefined, \"Attempting to change document \" + key.toString() + \" without having read it first\");\n var size = dbDocumentSize(doc);\n delta += size - previousSize;\n toApply.push({\n key: key,\n doc: doc\n });\n });\n return this.documentCache.addEntries(transaction, toApply, delta);\n };\n\n IndexedDbRemoteDocumentChangeBuffer.prototype.getFromCache = function (transaction, documentKey) {\n return this.documentCache.getSizedEntry(transaction, documentKey);\n };\n\n return IndexedDbRemoteDocumentChangeBuffer;\n}(RemoteDocumentChangeBuffer);\n\nfunction isDocumentChangeMissingError(err) {\n return err.code === Code.DATA_LOSS && err.message === REMOTE_DOCUMENT_CHANGE_MISSING_ERR_MSG;\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\r\n */\n\n\nfunction remoteDocumentsStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbRemoteDocument.store);\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the remoteDocumentChanges object\r\n * store.\r\n */\n\n\nfunction documentChangesStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbRemoteDocumentChanges.store);\n}\n\nfunction dbKey(docKey) {\n return docKey.path.toArray();\n}\n/**\r\n * Retrusn an approximate size for the given document.\r\n */\n\n\nfunction dbDocumentSize(doc) {\n var value;\n\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail('Unknown remote document type');\n }\n\n return JSON.stringify(value).length;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Schema Version for the Web client:\r\n * 1. Initial version including Mutation Queue, Query Cache, and Remote Document\r\n * Cache\r\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\r\n * longer required because migration 3 unconditionally clears it.\r\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\r\n * to limbo resolution. Addresses\r\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\r\n * 4. Multi-Tab Support.\r\n * 5. Removal of held write acks.\r\n * 6. Create document global for tracking document cache size.\r\n * 7. Ensure every cached document has a sentinel row with a sequence number.\r\n */\n\n\nvar SCHEMA_VERSION = 7;\n/** Performs database creation and schema upgrades. */\n\nvar SchemaConverter =\n/** @class */\nfunction () {\n function SchemaConverter(serializer) {\n this.serializer = serializer;\n }\n /**\r\n * Performs database creation and schema upgrades.\r\n *\r\n * Note that in production, this method is only ever used to upgrade the schema\r\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\r\n * and local feature development.\r\n */\n\n\n SchemaConverter.prototype.createOrUpgrade = function (db, txn, fromVersion, toVersion) {\n var _this = this;\n\n assert(fromVersion < toVersion && fromVersion >= 0 && toVersion <= SCHEMA_VERSION, \"Unexpected schema upgrade from v\" + fromVersion + \" to v{toVersion}.\");\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createRemoteDocumentCache(db);\n } // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n\n var p = PersistencePromise.resolve();\n\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n\n p = p.next(function () {\n return writeEmptyTargetGlobalEntry(txn);\n });\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(function () {\n return upgradeMutationBatchSchemaAndMigrateData(db, txn);\n });\n }\n\n p = p.next(function () {\n createClientMetadataStore(db);\n createRemoteDocumentChangesStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(function () {\n return _this.removeAcknowledgedMutations(txn);\n });\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(function () {\n createDocumentGlobalStore(db);\n return _this.addDocumentGlobal(txn);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(function () {\n return _this.ensureSequenceNumbers(txn);\n });\n }\n\n return p;\n };\n\n SchemaConverter.prototype.addDocumentGlobal = function (txn) {\n var byteCount = 0;\n return txn.store(DbRemoteDocument.store).iterate(function (_, doc) {\n byteCount += dbDocumentSize(doc);\n }).next(function () {\n var metadata = new DbRemoteDocumentGlobal(byteCount);\n return txn.store(DbRemoteDocumentGlobal.store).put(DbRemoteDocumentGlobal.key, metadata);\n });\n };\n\n SchemaConverter.prototype.removeAcknowledgedMutations = function (txn) {\n var _this = this;\n\n var queuesStore = txn.store(DbMutationQueue.store);\n var mutationsStore = txn.store(DbMutationBatch.store);\n return queuesStore.loadAll().next(function (queues) {\n return PersistencePromise.forEach(queues, function (queue) {\n var range = IDBKeyRange.bound([queue.userId, BATCHID_UNKNOWN], [queue.userId, queue.lastAcknowledgedBatchId]);\n return mutationsStore.loadAll(DbMutationBatch.userMutationsIndex, range).next(function (dbBatches) {\n return PersistencePromise.forEach(dbBatches, function (dbBatch) {\n assert(dbBatch.userId === queue.userId, \"Cannot process batch \" + dbBatch.batchId + \" from unexpected user\");\n\n var batch = _this.serializer.fromDbMutationBatch(dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(function () {});\n });\n });\n });\n });\n };\n /**\r\n * Ensures that every document in the remote document cache has a corresponding sentinel row\r\n * with a sequence number. Missing rows are given the most recently used sequence number.\r\n */\n\n\n SchemaConverter.prototype.ensureSequenceNumbers = function (txn) {\n var documentTargetStore$$1 = txn.store(DbTargetDocument.store);\n var documentsStore = txn.store(DbRemoteDocument.store);\n return getHighestListenSequenceNumber(txn).next(function (currentSequenceNumber) {\n var writeSentinelKey = function writeSentinelKey(path) {\n return documentTargetStore$$1.put(new DbTargetDocument(0, encode(path), currentSequenceNumber));\n };\n\n var promises = [];\n return documentsStore.iterate(function (key, doc) {\n var path = new ResourcePath(key);\n var docSentinelKey = sentinelKey(path);\n promises.push(documentTargetStore$$1.get(docSentinelKey).next(function (maybeSentinel) {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n }));\n }).next(function () {\n return PersistencePromise.waitFor(promises);\n });\n });\n };\n\n return SchemaConverter;\n}();\n\nfunction sentinelKey(path) {\n return [0, encode(path)];\n}\n/**\r\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\r\n */\n\n\nvar DbTimestamp =\n/** @class */\nfunction () {\n function DbTimestamp(seconds, nanoseconds) {\n this.seconds = seconds;\n this.nanoseconds = nanoseconds;\n }\n\n return DbTimestamp;\n}();\n/**\r\n * A singleton object to be stored in the 'owner' store in IndexedDb.\r\n *\r\n * A given database can have a single primary tab assigned at a given time. That\r\n * tab must validate that it is still holding the primary lease before every\r\n * operation that requires locked access. The primary tab should regularly\r\n * write an updated timestamp to this lease to prevent other tabs from\r\n * \"stealing\" the primary lease\r\n */\n\n\nvar DbPrimaryClient =\n/** @class */\nfunction () {\n function DbPrimaryClient(ownerId,\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization, leaseTimestampMs) {\n this.ownerId = ownerId;\n this.allowTabSynchronization = allowTabSynchronization;\n this.leaseTimestampMs = leaseTimestampMs;\n }\n /**\r\n * Name of the IndexedDb object store.\r\n *\r\n * Note that the name 'owner' is chosen to ensure backwards compatibility with\r\n * older clients that only supported single locked access to the persistence\r\n * layer.\r\n */\n\n\n DbPrimaryClient.store = 'owner';\n /**\r\n * The key string used for the single object that exists in the\r\n * DbPrimaryClient store.\r\n */\n\n DbPrimaryClient.key = 'owner';\n return DbPrimaryClient;\n}();\n\nfunction createPrimaryClientStore(db) {\n db.createObjectStore(DbPrimaryClient.store);\n}\n/**\r\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\r\n *\r\n * Each user gets a single queue of MutationBatches to apply to the server.\r\n * DbMutationQueue tracks the metadata about the queue.\r\n */\n\n\nvar DbMutationQueue =\n/** @class */\nfunction () {\n function DbMutationQueue(\n /**\r\n * The normalized user ID to which this queue belongs.\r\n */\n userId,\n /**\r\n * An identifier for the highest numbered batch that has been acknowledged\r\n * by the server. All MutationBatches in this queue with batchIds less\r\n * than or equal to this value are considered to have been acknowledged by\r\n * the server.\r\n */\n lastAcknowledgedBatchId,\n /**\r\n * A stream token that was previously sent by the server.\r\n *\r\n * See StreamingWriteRequest in datastore.proto for more details about\r\n * usage.\r\n *\r\n * After sending this token, earlier tokens may not be used anymore so\r\n * only a single stream token is retained.\r\n */\n lastStreamToken) {\n this.userId = userId;\n this.lastAcknowledgedBatchId = lastAcknowledgedBatchId;\n this.lastStreamToken = lastStreamToken;\n }\n /** Name of the IndexedDb object store. */\n\n\n DbMutationQueue.store = 'mutationQueues';\n /** Keys are automatically assigned via the userId property. */\n\n DbMutationQueue.keyPath = 'userId';\n return DbMutationQueue;\n}();\n/**\r\n * An object to be stored in the 'mutations' store in IndexedDb.\r\n *\r\n * Represents a batch of user-level mutations intended to be sent to the server\r\n * in a single write. Each user-level batch gets a separate DbMutationBatch\r\n * with a new batchId.\r\n */\n\n\nvar DbMutationBatch =\n/** @class */\nfunction () {\n function DbMutationBatch(\n /**\r\n * The normalized user ID to which this batch belongs.\r\n */\n userId,\n /**\r\n * An identifier for this batch, allocated using an auto-generated key.\r\n */\n batchId,\n /**\r\n * The local write time of the batch, stored as milliseconds since the\r\n * epoch.\r\n */\n localWriteTimeMs,\n /**\r\n * A list of mutations to apply. All mutations will be applied atomically.\r\n *\r\n * Mutations are serialized via JsonProtoSerializer.toMutation().\r\n */\n mutations) {\n this.userId = userId;\n this.batchId = batchId;\n this.localWriteTimeMs = localWriteTimeMs;\n this.mutations = mutations;\n }\n /** Name of the IndexedDb object store. */\n\n\n DbMutationBatch.store = 'mutations';\n /** Keys are automatically assigned via the userId, batchId properties. */\n\n DbMutationBatch.keyPath = 'batchId';\n /** The index name for lookup of mutations by user. */\n\n DbMutationBatch.userMutationsIndex = 'userMutationsIndex';\n /** The user mutations index is keyed by [userId, batchId] pairs. */\n\n DbMutationBatch.userMutationsKeyPath = ['userId', 'batchId'];\n return DbMutationBatch;\n}();\n\nfunction createMutationQueue(db) {\n db.createObjectStore(DbMutationQueue.store, {\n keyPath: DbMutationQueue.keyPath\n });\n var mutationBatchesStore = db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(DbMutationBatch.userMutationsIndex, DbMutationBatch.userMutationsKeyPath, {\n unique: true\n });\n db.createObjectStore(DbDocumentMutation.store);\n}\n/**\r\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\r\n * and rewrites all data.\r\n */\n\n\nfunction upgradeMutationBatchSchemaAndMigrateData(db, txn) {\n var v1MutationsStore = txn.store(DbMutationBatch.store);\n return v1MutationsStore.loadAll().next(function (existingMutations) {\n db.deleteObjectStore(DbMutationBatch.store);\n var mutationsStore = db.createObjectStore(DbMutationBatch.store, {\n keyPath: DbMutationBatch.keyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(DbMutationBatch.userMutationsIndex, DbMutationBatch.userMutationsKeyPath, {\n unique: true\n });\n var v3MutationsStore = txn.store(DbMutationBatch.store);\n var writeAll = existingMutations.map(function (mutation) {\n return v3MutationsStore.put(mutation);\n });\n return PersistencePromise.waitFor(writeAll);\n });\n}\n/**\r\n * An object to be stored in the 'documentMutations' store in IndexedDb.\r\n *\r\n * A manually maintained index of all the mutation batches that affect a given\r\n * document key. The rows in this table are references based on the contents of\r\n * DbMutationBatch.mutations.\r\n */\n\n\nvar DbDocumentMutation =\n/** @class */\nfunction () {\n function DbDocumentMutation() {}\n /**\r\n * Creates a [userId] key for use in the DbDocumentMutations index to iterate\r\n * over all of a user's document mutations.\r\n */\n\n\n DbDocumentMutation.prefixForUser = function (userId) {\n return [userId];\n };\n /**\r\n * Creates a [userId, encodedPath] key for use in the DbDocumentMutations\r\n * index to iterate over all at document mutations for a given path or lower.\r\n */\n\n\n DbDocumentMutation.prefixForPath = function (userId, path) {\n return [userId, encode(path)];\n };\n /**\r\n * Creates a full index key of [userId, encodedPath, batchId] for inserting\r\n * and deleting into the DbDocumentMutations index.\r\n */\n\n\n DbDocumentMutation.key = function (userId, path, batchId) {\n return [userId, encode(path), batchId];\n };\n\n DbDocumentMutation.store = 'documentMutations';\n /**\r\n * Because we store all the useful information for this store in the key,\r\n * there is no useful information to store as the value. The raw (unencoded)\r\n * path cannot be stored because IndexedDb doesn't store prototype\r\n * information.\r\n */\n\n DbDocumentMutation.PLACEHOLDER = new DbDocumentMutation();\n return DbDocumentMutation;\n}();\n\nfunction createRemoteDocumentCache(db) {\n db.createObjectStore(DbRemoteDocument.store);\n}\n/**\r\n * Represents the known absence of a document at a particular version.\r\n * Stored in IndexedDb as part of a DbRemoteDocument object.\r\n */\n\n\nvar DbNoDocument =\n/** @class */\nfunction () {\n function DbNoDocument(path, readTime) {\n this.path = path;\n this.readTime = readTime;\n }\n\n return DbNoDocument;\n}();\n/**\r\n * Represents a document that is known to exist but whose data is unknown.\r\n * Stored in IndexedDb as part of a DbRemoteDocument object.\r\n */\n\n\nvar DbUnknownDocument =\n/** @class */\nfunction () {\n function DbUnknownDocument(path, version) {\n this.path = path;\n this.version = version;\n }\n\n return DbUnknownDocument;\n}();\n/**\r\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\r\n * It represents either:\r\n *\r\n * - A complete document.\r\n * - A \"no document\" representing a document that is known not to exist (at\r\n * some version).\r\n * - An \"unknown document\" representing a document that is known to exist (at\r\n * some version) but whose contents are unknown.\r\n *\r\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\r\n * be made more general if necessary.\r\n */\n\n\nvar DbRemoteDocument =\n/** @class */\nfunction () {\n function DbRemoteDocument(\n /**\r\n * Set to an instance of DbUnknownDocument if the data for a document is\r\n * not known, but it is known that a document exists at the specified\r\n * version (e.g. it had a successful update applied to it)\r\n */\n unknownDocument,\n /**\r\n * Set to an instance of a DbNoDocument if it is known that no document\r\n * exists.\r\n */\n noDocument,\n /**\r\n * Set to an instance of a Document if there's a cached version of the\r\n * document.\r\n */\n document,\n /**\r\n * Documents that were written to the remote document store based on\r\n * a write acknowledgment are marked with `hasCommittedMutations`. These\r\n * documents are potentially inconsistent with the backend's copy and use\r\n * the write's commit version as their document version.\r\n */\n hasCommittedMutations) {\n this.unknownDocument = unknownDocument;\n this.noDocument = noDocument;\n this.document = document;\n this.hasCommittedMutations = hasCommittedMutations;\n }\n\n DbRemoteDocument.store = 'remoteDocuments';\n return DbRemoteDocument;\n}();\n/**\r\n * Contains a single entry that has metadata about the remote document cache.\r\n */\n\n\nvar DbRemoteDocumentGlobal =\n/** @class */\nfunction () {\n /**\r\n * @param byteSize Approximately the total size in bytes of all the documents in the document\r\n * cache.\r\n */\n function DbRemoteDocumentGlobal(byteSize) {\n this.byteSize = byteSize;\n }\n\n DbRemoteDocumentGlobal.store = 'remoteDocumentGlobal';\n DbRemoteDocumentGlobal.key = 'remoteDocumentGlobalKey';\n return DbRemoteDocumentGlobal;\n}();\n\nfunction createDocumentGlobalStore(db) {\n db.createObjectStore(DbRemoteDocumentGlobal.store);\n}\n/**\r\n * An object to be stored in the 'targets' store in IndexedDb.\r\n *\r\n * This is based on and should be kept in sync with the proto used in the iOS\r\n * client.\r\n *\r\n * Each query the client listens to against the server is tracked on disk so\r\n * that the query can be efficiently resumed on restart.\r\n */\n\n\nvar DbTarget =\n/** @class */\nfunction () {\n function DbTarget(\n /**\r\n * An auto-generated sequential numeric identifier for the query.\r\n *\r\n * Queries are stored using their canonicalId as the key, but these\r\n * canonicalIds can be quite long so we additionally assign a unique\r\n * queryId which can be used by referenced data structures (e.g.\r\n * indexes) to minimize the on-disk cost.\r\n */\n targetId,\n /**\r\n * The canonical string representing this query. This is not unique.\r\n */\n canonicalId,\n /**\r\n * The last readTime received from the Watch Service for this query.\r\n *\r\n * This is the same value as TargetChange.read_time in the protos.\r\n */\n readTime,\n /**\r\n * An opaque, server-assigned token that allows watching a query to be\r\n * resumed after disconnecting without retransmitting all the data\r\n * that matches the query. The resume token essentially identifies a\r\n * point in time from which the server should resume sending results.\r\n *\r\n * This is related to the snapshotVersion in that the resumeToken\r\n * effectively also encodes that value, but the resumeToken is opaque\r\n * and sometimes encodes additional information.\r\n *\r\n * A consequence of this is that the resumeToken should be used when\r\n * asking the server to reason about where this client is in the watch\r\n * stream, but the client should use the snapshotVersion for its own\r\n * purposes.\r\n *\r\n * This is the same value as TargetChange.resume_token in the protos.\r\n */\n resumeToken,\n /**\r\n * A sequence number representing the last time this query was\r\n * listened to, used for garbage collection purposes.\r\n *\r\n * Conventionally this would be a timestamp value, but device-local\r\n * clocks are unreliable and they must be able to create new listens\r\n * even while disconnected. Instead this should be a monotonically\r\n * increasing number that's incremented on each listen call.\r\n *\r\n * This is different from the queryId since the queryId is an\r\n * immutable identifier assigned to the Query on first use while\r\n * lastListenSequenceNumber is updated every time the query is\r\n * listened to.\r\n */\n lastListenSequenceNumber,\n /**\r\n * The query for this target.\r\n *\r\n * Because canonical ids are not unique we must store the actual query. We\r\n * use the proto to have an object we can persist without having to\r\n * duplicate translation logic to and from a `Query` object.\r\n */\n query) {\n this.targetId = targetId;\n this.canonicalId = canonicalId;\n this.readTime = readTime;\n this.resumeToken = resumeToken;\n this.lastListenSequenceNumber = lastListenSequenceNumber;\n this.query = query;\n }\n\n DbTarget.store = 'targets';\n /** Keys are automatically assigned via the targetId property. */\n\n DbTarget.keyPath = 'targetId';\n /** The name of the queryTargets index. */\n\n DbTarget.queryTargetsIndexName = 'queryTargetsIndex';\n /**\r\n * The index of all canonicalIds to the targets that they match. This is not\r\n * a unique mapping because canonicalId does not promise a unique name for all\r\n * possible queries, so we append the targetId to make the mapping unique.\r\n */\n\n DbTarget.queryTargetsKeyPath = ['canonicalId', 'targetId'];\n return DbTarget;\n}();\n/**\r\n * An object representing an association between a target and a document, or a\r\n * sentinel row marking the last sequence number at which a document was used.\r\n * Each document cached must have a corresponding sentinel row before lru\r\n * garbage collection is enabled.\r\n *\r\n * The target associations and sentinel rows are co-located so that orphaned\r\n * documents and their sequence numbers can be identified efficiently via a scan\r\n * of this store.\r\n */\n\n\nvar DbTargetDocument =\n/** @class */\nfunction () {\n function DbTargetDocument(\n /**\r\n * The targetId identifying a target or 0 for a sentinel row.\r\n */\n targetId,\n /**\r\n * The path to the document, as encoded in the key.\r\n */\n path,\n /**\r\n * If this is a sentinel row, this should be the sequence number of the last\r\n * time the document specified by `path` was used. Otherwise, it should be\r\n * `undefined`.\r\n */\n sequenceNumber) {\n this.targetId = targetId;\n this.path = path;\n this.sequenceNumber = sequenceNumber;\n assert(targetId === 0 === (sequenceNumber !== undefined), // tslint:disable-next-line:max-line-length\n 'A target-document row must either have targetId == 0 and a defined sequence number, or a non-zero targetId and no sequence number');\n }\n /** Name of the IndexedDb object store. */\n\n\n DbTargetDocument.store = 'targetDocuments';\n /** Keys are automatically assigned via the targetId, path properties. */\n\n DbTargetDocument.keyPath = ['targetId', 'path'];\n /** The index name for the reverse index. */\n\n DbTargetDocument.documentTargetsIndex = 'documentTargetsIndex';\n /** We also need to create the reverse index for these properties. */\n\n DbTargetDocument.documentTargetsKeyPath = ['path', 'targetId'];\n return DbTargetDocument;\n}();\n/**\r\n * A record of global state tracked across all Targets, tracked separately\r\n * to avoid the need for extra indexes.\r\n *\r\n * This should be kept in-sync with the proto used in the iOS client.\r\n */\n\n\nvar DbTargetGlobal =\n/** @class */\nfunction () {\n function DbTargetGlobal(\n /**\r\n * The highest numbered target id across all targets.\r\n *\r\n * See DbTarget.targetId.\r\n */\n highestTargetId,\n /**\r\n * The highest numbered lastListenSequenceNumber across all targets.\r\n *\r\n * See DbTarget.lastListenSequenceNumber.\r\n */\n highestListenSequenceNumber,\n /**\r\n * A global snapshot version representing the last consistent snapshot we\r\n * received from the backend. This is monotonically increasing and any\r\n * snapshots received from the backend prior to this version (e.g. for\r\n * targets resumed with a resumeToken) should be suppressed (buffered)\r\n * until the backend has caught up to this snapshot version again. This\r\n * prevents our cache from ever going backwards in time.\r\n */\n lastRemoteSnapshotVersion,\n /**\r\n * The number of targets persisted.\r\n */\n targetCount) {\n this.highestTargetId = highestTargetId;\n this.highestListenSequenceNumber = highestListenSequenceNumber;\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n this.targetCount = targetCount;\n }\n /**\r\n * The key string used for the single object that exists in the\r\n * DbTargetGlobal store.\r\n */\n\n\n DbTargetGlobal.key = 'targetGlobalKey';\n DbTargetGlobal.store = 'targetGlobal';\n return DbTargetGlobal;\n}();\n\nfunction createQueryCache(db) {\n var targetDocumentsStore = db.createObjectStore(DbTargetDocument.store, {\n keyPath: DbTargetDocument.keyPath\n });\n targetDocumentsStore.createIndex(DbTargetDocument.documentTargetsIndex, DbTargetDocument.documentTargetsKeyPath, {\n unique: true\n });\n var targetStore = db.createObjectStore(DbTarget.store, {\n keyPath: DbTarget.keyPath\n }); // NOTE: This is unique only because the TargetId is the suffix.\n\n targetStore.createIndex(DbTarget.queryTargetsIndexName, DbTarget.queryTargetsKeyPath, {\n unique: true\n });\n db.createObjectStore(DbTargetGlobal.store);\n}\n\nfunction dropQueryCache(db) {\n db.deleteObjectStore(DbTargetDocument.store);\n db.deleteObjectStore(DbTarget.store);\n db.deleteObjectStore(DbTargetGlobal.store);\n}\n/**\r\n * Creates the target global singleton row.\r\n *\r\n * @param {IDBTransaction} txn The version upgrade transaction for indexeddb\r\n */\n\n\nfunction writeEmptyTargetGlobalEntry(txn) {\n var globalStore = txn.store(DbTargetGlobal.store);\n var metadata = new DbTargetGlobal(\n /*highestTargetId=*/\n 0,\n /*lastListenSequenceNumber=*/\n 0, SnapshotVersion.MIN.toTimestamp(),\n /*targetCount=*/\n 0);\n return globalStore.put(DbTargetGlobal.key, metadata);\n}\n/**\r\n * An object store to store the keys of changed documents. This is used to\r\n * facilitate storing document changelogs in the Remote Document Cache.\r\n *\r\n * PORTING NOTE: This is used for change propagation during multi-tab syncing\r\n * and not needed on iOS and Android.\r\n */\n\n\nvar DbRemoteDocumentChanges =\n/** @class */\nfunction () {\n function DbRemoteDocumentChanges(\n /** The keys of the changed documents. */\n changes) {\n this.changes = changes;\n }\n /** Name of the IndexedDb object store. */\n\n\n DbRemoteDocumentChanges.store = 'remoteDocumentChanges';\n /** Keys are auto-generated via the `id` property. */\n\n DbRemoteDocumentChanges.keyPath = 'id';\n return DbRemoteDocumentChanges;\n}();\n\nfunction createRemoteDocumentChangesStore(db) {\n db.createObjectStore(DbRemoteDocumentChanges.store, {\n keyPath: 'id',\n autoIncrement: true\n });\n}\n/**\r\n * A record of the metadata state of each client.\r\n *\r\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\r\n * to be ported to iOS or Android.\r\n */\n\n\nvar DbClientMetadata =\n/** @class */\nfunction () {\n function DbClientMetadata(\n /** The auto-generated client id assigned at client startup. */\n clientId,\n /** The last time this state was updated. */\n updateTimeMs,\n /** Whether the client's network connection is enabled. */\n networkEnabled,\n /** Whether this client is running in a foreground tab. */\n inForeground,\n /**\r\n * The last change read from the DbRemoteDocumentChanges store.\r\n * Can be undefined for backwards compatibility.\r\n */\n lastProcessedDocumentChangeId) {\n this.clientId = clientId;\n this.updateTimeMs = updateTimeMs;\n this.networkEnabled = networkEnabled;\n this.inForeground = inForeground;\n this.lastProcessedDocumentChangeId = lastProcessedDocumentChangeId;\n }\n /** Name of the IndexedDb object store. */\n\n\n DbClientMetadata.store = 'clientMetadata';\n /** Keys are automatically assigned via the clientId properties. */\n\n DbClientMetadata.keyPath = 'clientId';\n return DbClientMetadata;\n}();\n\nfunction createClientMetadataStore(db) {\n db.createObjectStore(DbClientMetadata.store, {\n keyPath: DbClientMetadata.keyPath\n });\n} // Visible for testing\n\n\nvar V1_STORES = [DbMutationQueue.store, DbMutationBatch.store, DbDocumentMutation.store, DbRemoteDocument.store, DbTarget.store, DbPrimaryClient.store, DbTargetGlobal.store, DbTargetDocument.store]; // V2 is no longer usable (see comment at top of file)\n// Visible for testing\n\nvar V3_STORES = V1_STORES; // Visible for testing\n\nvar V4_STORES = V3_STORES.concat([DbClientMetadata.store, DbRemoteDocumentChanges.store]); // V5 does not change the set of stores.\n\nvar V6_STORES = V4_STORES.concat([DbRemoteDocumentGlobal.store]);\n/**\r\n * The list of all default IndexedDB stores used throughout the SDK. This is\r\n * used when creating transactions so that access across all stores is done\r\n * atomically.\r\n */\n\nvar ALL_STORES = V6_STORES;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\n\nvar IndexedDbMutationQueue =\n/** @class */\nfunction () {\n function IndexedDbMutationQueue(\n /**\r\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\r\n * retrieve mutations.\r\n */\n userId, serializer, referenceDelegate) {\n this.userId = userId;\n this.serializer = serializer;\n this.referenceDelegate = referenceDelegate;\n /**\r\n * Caches the document keys for pending mutation batches. If the mutation\r\n * has been removed from IndexedDb, the cached value may continue to\r\n * be used to retrieve the batch's document keys. To remove a cached value\r\n * locally, `removeCachedMutationKeys()` should be invoked either directly\r\n * or through `removeMutationBatches()`.\r\n *\r\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\r\n * this cache is used by secondary clients to invalidate the local\r\n * view of the documents that were previously affected by the mutation.\r\n */\n // PORTING NOTE: Multi-tab only.\n\n this.documentKeysByBatchId = {};\n }\n /**\r\n * Creates a new mutation queue for the given user.\r\n * @param user The user for which to create a mutation queue.\r\n * @param serializer The serializer to use when persisting to IndexedDb.\r\n */\n\n\n IndexedDbMutationQueue.forUser = function (user, serializer, referenceDelegate) {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n assert(user.uid !== '', 'UserID must not be an empty string.');\n var userId = user.isAuthenticated() ? user.uid : '';\n return new IndexedDbMutationQueue(userId, serializer, referenceDelegate);\n };\n\n IndexedDbMutationQueue.prototype.checkEmpty = function (transaction) {\n var empty = true;\n var range = IDBKeyRange.bound([this.userId, Number.NEGATIVE_INFINITY], [this.userId, Number.POSITIVE_INFINITY]);\n return mutationsStore(transaction).iterate({\n index: DbMutationBatch.userMutationsIndex,\n range: range\n }, function (key, value, control) {\n empty = false;\n control.done();\n }).next(function () {\n return empty;\n });\n };\n\n IndexedDbMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n return this.getMutationQueueMetadata(transaction).next(function (metadata) {\n var batchId = batch.batchId;\n assert(batchId > metadata.lastAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n metadata.lastAcknowledgedBatchId = batchId;\n metadata.lastStreamToken = convertStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(metadata);\n });\n };\n\n IndexedDbMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return this.getMutationQueueMetadata(transaction).next(function (metadata) {\n return metadata.lastStreamToken;\n });\n };\n\n IndexedDbMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n return this.getMutationQueueMetadata(transaction).next(function (metadata) {\n metadata.lastStreamToken = convertStreamToken(streamToken);\n return mutationQueuesStore(transaction).put(metadata);\n });\n };\n\n IndexedDbMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n var _this = this;\n\n var documentStore = documentMutationsStore(transaction);\n var mutationStore = mutationsStore(transaction); // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n // tslint:disable-next-line:no-any We write an empty object to obtain key\n\n return mutationStore.add({}).next(function (batchId) {\n assert(typeof batchId === 'number', 'Auto-generated key is not a number');\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n\n var dbBatch = _this.serializer.toDbMutationBatch(_this.userId, batch);\n\n _this.documentKeysByBatchId[batchId] = batch.keys();\n var promises = [];\n\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n var indexKey = DbDocumentMutation.key(_this.userId, mutation.key.path, batchId);\n promises.push(mutationStore.put(dbBatch));\n promises.push(documentStore.put(indexKey, DbDocumentMutation.PLACEHOLDER));\n }\n\n return PersistencePromise.waitFor(promises).next(function () {\n return batch;\n });\n });\n };\n\n IndexedDbMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n var _this = this;\n\n return mutationsStore(transaction).get(batchId).next(function (dbBatch) {\n if (dbBatch) {\n assert(dbBatch.userId === _this.userId, \"Unexpected user '\" + dbBatch.userId + \"' for mutation batch \" + batchId);\n return _this.serializer.fromDbMutationBatch(dbBatch);\n }\n\n return null;\n });\n };\n\n IndexedDbMutationQueue.prototype.lookupMutationKeys = function (transaction, batchId) {\n var _this = this;\n\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(this.documentKeysByBatchId[batchId]);\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(function (batch) {\n if (batch) {\n var keys = batch.keys();\n _this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n };\n\n IndexedDbMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n var _this = this;\n\n return this.getMutationQueueMetadata(transaction).next(function (metadata) {\n // All batches with batchId <= this.metadata.lastAcknowledgedBatchId have\n // been acknowledged so the first unacknowledged batch after batchID will\n // have a batchID larger than both of these values.\n var nextBatchId = Math.max(batchId, metadata.lastAcknowledgedBatchId) + 1;\n var range = IDBKeyRange.lowerBound([_this.userId, nextBatchId]);\n var foundBatch = null;\n return mutationsStore(transaction).iterate({\n index: DbMutationBatch.userMutationsIndex,\n range: range\n }, function (key, dbBatch, control) {\n if (dbBatch.userId === _this.userId) {\n assert(dbBatch.batchId >= nextBatchId, 'Should have found mutation after ' + nextBatchId);\n foundBatch = _this.serializer.fromDbMutationBatch(dbBatch);\n }\n\n control.done();\n }).next(function () {\n return foundBatch;\n });\n });\n };\n\n IndexedDbMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n var _this = this;\n\n var range = IDBKeyRange.bound([this.userId, BATCHID_UNKNOWN], [this.userId, Number.POSITIVE_INFINITY]);\n return mutationsStore(transaction).loadAll(DbMutationBatch.userMutationsIndex, range).next(function (dbBatches) {\n return dbBatches.map(function (dbBatch) {\n return _this.serializer.fromDbMutationBatch(dbBatch);\n });\n });\n };\n\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this; // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n\n\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, documentKey.path);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix);\n var results = [];\n return documentMutationsStore(transaction).iterate({\n range: indexStart\n }, function (indexKey, _, control) {\n var userID = indexKey[0],\n encodedPath = indexKey[1],\n batchId = indexKey[2]; // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n\n var path = decode$1(encodedPath);\n\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n } // Look up the mutation batch in the store.\n\n\n return mutationsStore(transaction).get(batchId).next(function (mutation) {\n if (!mutation) {\n throw fail('Dangling document-mutation reference found: ' + indexKey + ' which points to ' + batchId);\n }\n\n assert(mutation.userId === _this.userId, \"Unexpected user '\" + mutation.userId + \"' for mutation batch \" + batchId);\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n });\n }).next(function () {\n return results;\n });\n };\n\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKeys = function (transaction, documentKeys) {\n var _this = this;\n\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n var promises = [];\n documentKeys.forEach(function (documentKey) {\n var indexStart = DbDocumentMutation.prefixForPath(_this.userId, documentKey.path);\n var range = IDBKeyRange.lowerBound(indexStart);\n var promise = documentMutationsStore(transaction).iterate({\n range: range\n }, function (indexKey, _, control) {\n var userID = indexKey[0],\n encodedPath = indexKey[1],\n batchID = indexKey[2]; // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n\n var path = decode$1(encodedPath);\n\n if (userID !== _this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n });\n promises.push(promise);\n });\n return PersistencePromise.waitFor(promises).next(function () {\n return _this.lookupMutationBatches(transaction, uniqueBatchIDs);\n });\n };\n\n IndexedDbMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n var _this = this;\n\n assert(!query.isDocumentQuery(), \"Document queries shouldn't go down this path\");\n var queryPath = query.path;\n var immediateChildrenLength = queryPath.length + 1; // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n\n var indexPrefix = DbDocumentMutation.prefixForPath(this.userId, queryPath);\n var indexStart = IDBKeyRange.lowerBound(indexPrefix); // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction).iterate({\n range: indexStart\n }, function (indexKey, _, control) {\n var userID = indexKey[0],\n encodedPath = indexKey[1],\n batchID = indexKey[2];\n var path = decode$1(encodedPath);\n\n if (userID !== _this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n } // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n\n\n if (path.length !== immediateChildrenLength) {\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }).next(function () {\n return _this.lookupMutationBatches(transaction, uniqueBatchIDs);\n });\n };\n\n IndexedDbMutationQueue.prototype.lookupMutationBatches = function (transaction, batchIDs) {\n var _this = this;\n\n var results = [];\n var promises = []; // TODO(rockwood): Implement this using iterate.\n\n batchIDs.forEach(function (batchId) {\n promises.push(mutationsStore(transaction).get(batchId).next(function (mutation) {\n if (mutation === null) {\n throw fail('Dangling document-mutation reference found, ' + 'which points to ' + batchId);\n }\n\n assert(mutation.userId === _this.userId, \"Unexpected user '\" + mutation.userId + \"' for mutation batch \" + batchId);\n results.push(_this.serializer.fromDbMutationBatch(mutation));\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () {\n return results;\n });\n };\n\n IndexedDbMutationQueue.prototype.removeMutationBatch = function (transaction, batch) {\n var _this = this;\n\n return removeMutationBatch(transaction.simpleDbTransaction, this.userId, batch).next(function (removedDocuments) {\n _this.removeCachedMutationKeys(batch.batchId);\n\n return PersistencePromise.forEach(removedDocuments, function (key) {\n return _this.referenceDelegate.removeMutationReference(transaction, key);\n });\n });\n };\n\n IndexedDbMutationQueue.prototype.removeCachedMutationKeys = function (batchId) {\n delete this.documentKeysByBatchId[batchId];\n };\n\n IndexedDbMutationQueue.prototype.performConsistencyCheck = function (txn) {\n var _this = this;\n\n return this.checkEmpty(txn).next(function (empty) {\n if (!empty) {\n return PersistencePromise.resolve();\n } // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n\n\n var startRange = IDBKeyRange.lowerBound(DbDocumentMutation.prefixForUser(_this.userId));\n var danglingMutationReferences = [];\n return documentMutationsStore(txn).iterate({\n range: startRange\n }, function (key, _, control) {\n var userID = key[0];\n\n if (userID !== _this.userId) {\n control.done();\n return;\n } else {\n var path = decode$1(key[1]);\n danglingMutationReferences.push(path);\n }\n }).next(function () {\n assert(danglingMutationReferences.length === 0, 'Document leak -- detected dangling mutation references when queue is empty. ' + 'Dangling keys: ' + danglingMutationReferences.map(function (p) {\n return p.canonicalString();\n }));\n });\n });\n };\n\n IndexedDbMutationQueue.prototype.containsKey = function (txn, key) {\n return mutationQueueContainsKey(txn, this.userId, key);\n }; // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n\n /** Returns the mutation queue's metadata from IndexedDb. */\n\n\n IndexedDbMutationQueue.prototype.getMutationQueueMetadata = function (transaction) {\n var _this = this;\n\n return mutationQueuesStore(transaction).get(this.userId).next(function (metadata) {\n return metadata || new DbMutationQueue(_this.userId, BATCHID_UNKNOWN,\n /*lastStreamToken=*/\n '');\n });\n };\n\n return IndexedDbMutationQueue;\n}();\n/**\r\n * @return true if the mutation queue for the given user contains a pending\r\n * mutation for the given key.\r\n */\n\n\nfunction mutationQueueContainsKey(txn, userId, key) {\n var indexKey = DbDocumentMutation.prefixForPath(userId, key.path);\n var encodedPath = indexKey[1];\n var startRange = IDBKeyRange.lowerBound(indexKey);\n var containsKey = false;\n return documentMutationsStore(txn).iterate({\n range: startRange,\n keysOnly: true\n }, function (key, value, control) {\n var userID = key[0],\n keyPath = key[1],\n\n /*batchID*/\n _ = key[2];\n\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n\n control.done();\n }).next(function () {\n return containsKey;\n });\n}\n/** Returns true if any mutation queue contains the given document. */\n\n\nfunction mutationQueuesContainKey(txn, docKey) {\n var found = false;\n return mutationQueuesStore(txn).iterateSerial(function (userId) {\n return mutationQueueContainsKey(txn, userId, docKey).next(function (containsKey) {\n if (containsKey) {\n found = true;\n }\n\n return PersistencePromise.resolve(!containsKey);\n });\n }).next(function () {\n return found;\n });\n}\n/**\r\n * Delete a mutation batch and the associated document mutations.\r\n * @return A PersistencePromise of the document mutations that were removed.\r\n */\n\n\nfunction removeMutationBatch(txn, userId, batch) {\n var mutationStore = txn.store(DbMutationBatch.store);\n var indexTxn = txn.store(DbDocumentMutation.store);\n var promises = [];\n var range = IDBKeyRange.only(batch.batchId);\n var numDeleted = 0;\n var removePromise = mutationStore.iterate({\n range: range\n }, function (key, value, control) {\n numDeleted++;\n return control.delete();\n });\n promises.push(removePromise.next(function () {\n assert(numDeleted === 1, 'Dangling document-mutation reference found: Missing batch ' + batch.batchId);\n }));\n var removedDocuments = [];\n\n for (var _i = 0, _a = batch.mutations; _i < _a.length; _i++) {\n var mutation = _a[_i];\n var indexKey = DbDocumentMutation.key(userId, mutation.key.path, batch.batchId);\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n\n return PersistencePromise.waitFor(promises).next(function () {\n return removedDocuments;\n });\n}\n\nfunction convertStreamToken(token) {\n if (token instanceof Uint8Array) {\n // TODO(b/78771403): Convert tokens to strings during deserialization\n assert(process.env.USE_MOCK_PERSISTENCE === 'YES', 'Persisting non-string stream tokens is only supported with mock persistence.');\n return token.toString();\n } else {\n return token;\n }\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the mutations object store.\r\n */\n\n\nfunction mutationsStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbMutationBatch.store);\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\r\n */\n\n\nfunction documentMutationsStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbDocumentMutation.store);\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\r\n */\n\n\nfunction mutationQueuesStore(txn) {\n return IndexedDbPersistence.getStore(txn, DbMutationQueue.store);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/** Serializer for values stored in the LocalStore. */\n\n\nvar LocalSerializer =\n/** @class */\nfunction () {\n function LocalSerializer(remoteSerializer) {\n this.remoteSerializer = remoteSerializer;\n }\n /** Decodes a remote document from storage locally to a Document. */\n\n\n LocalSerializer.prototype.fromDbRemoteDocument = function (remoteDoc) {\n if (remoteDoc.document) {\n return this.remoteSerializer.fromDocument(remoteDoc.document, !!remoteDoc.hasCommittedMutations);\n } else if (remoteDoc.noDocument) {\n var key = DocumentKey.fromSegments(remoteDoc.noDocument.path);\n var version = this.fromDbTimestamp(remoteDoc.noDocument.readTime);\n return new NoDocument(key, version, {\n hasCommittedMutations: !!remoteDoc.hasCommittedMutations\n });\n } else if (remoteDoc.unknownDocument) {\n var key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n var version = this.fromDbTimestamp(remoteDoc.unknownDocument.version);\n return new UnknownDocument(key, version);\n } else {\n return fail('Unexpected DbRemoteDocument');\n }\n };\n /** Encodes a document for storage locally. */\n\n\n LocalSerializer.prototype.toDbRemoteDocument = function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n var doc = this.remoteSerializer.toDocument(maybeDoc);\n var hasCommittedMutations = maybeDoc.hasCommittedMutations;\n return new DbRemoteDocument(\n /* unknownDocument= */\n null,\n /* noDocument= */\n null, doc, hasCommittedMutations);\n } else if (maybeDoc instanceof NoDocument) {\n var path = maybeDoc.key.path.toArray();\n var readTime = this.toDbTimestamp(maybeDoc.version);\n var hasCommittedMutations = maybeDoc.hasCommittedMutations;\n return new DbRemoteDocument(\n /* unknownDocument= */\n null, new DbNoDocument(path, readTime),\n /* document= */\n null, hasCommittedMutations);\n } else if (maybeDoc instanceof UnknownDocument) {\n var path = maybeDoc.key.path.toArray();\n var readTime = this.toDbTimestamp(maybeDoc.version);\n return new DbRemoteDocument(new DbUnknownDocument(path, readTime),\n /* noDocument= */\n null,\n /* document= */\n null,\n /* hasCommittedMutations= */\n true);\n } else {\n return fail('Unexpected MaybeDocumment');\n }\n };\n\n LocalSerializer.prototype.toDbTimestamp = function (snapshotVersion) {\n var timestamp = snapshotVersion.toTimestamp();\n return new DbTimestamp(timestamp.seconds, timestamp.nanoseconds);\n };\n\n LocalSerializer.prototype.fromDbTimestamp = function (dbTimestamp) {\n var timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n };\n /** Encodes a batch of mutations into a DbMutationBatch for local storage. */\n\n\n LocalSerializer.prototype.toDbMutationBatch = function (userId, batch) {\n var _this = this;\n\n var serializedMutations = batch.mutations.map(function (m) {\n return _this.remoteSerializer.toMutation(m);\n });\n return new DbMutationBatch(userId, batch.batchId, batch.localWriteTime.toMillis(), serializedMutations);\n };\n /** Decodes a DbMutationBatch into a MutationBatch */\n\n\n LocalSerializer.prototype.fromDbMutationBatch = function (dbBatch) {\n var _this = this;\n\n var mutations = dbBatch.mutations.map(function (m) {\n return _this.remoteSerializer.fromMutation(m);\n });\n var timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(dbBatch.batchId, timestamp, mutations);\n };\n /*\r\n * Encodes a set of document keys into an array of EncodedResourcePaths.\r\n */\n\n\n LocalSerializer.prototype.toDbResourcePaths = function (keys) {\n var encodedKeys = [];\n keys.forEach(function (key) {\n encodedKeys.push(encode(key.path));\n });\n return encodedKeys;\n };\n /** Decodes an array of EncodedResourcePaths into a set of document keys. */\n\n\n LocalSerializer.prototype.fromDbResourcePaths = function (encodedPaths) {\n var keys = documentKeySet();\n\n for (var _i = 0, encodedPaths_1 = encodedPaths; _i < encodedPaths_1.length; _i++) {\n var documentKey = encodedPaths_1[_i];\n keys = keys.add(new DocumentKey(decode$1(documentKey)));\n }\n\n return keys;\n };\n /** Decodes a DbTarget into QueryData */\n\n\n LocalSerializer.prototype.fromDbTarget = function (dbTarget) {\n var version = this.fromDbTimestamp(dbTarget.readTime);\n var query;\n\n if (isDocumentQuery(dbTarget.query)) {\n query = this.remoteSerializer.fromDocumentsTarget(dbTarget.query);\n } else {\n query = this.remoteSerializer.fromQueryTarget(dbTarget.query);\n }\n\n return new QueryData(query, dbTarget.targetId, QueryPurpose.Listen, dbTarget.lastListenSequenceNumber, version, dbTarget.resumeToken);\n };\n /** Encodes QueryData into a DbTarget for storage locally. */\n\n\n LocalSerializer.prototype.toDbTarget = function (queryData) {\n assert(QueryPurpose.Listen === queryData.purpose, 'Only queries with purpose ' + QueryPurpose.Listen + ' may be stored, got ' + queryData.purpose);\n var dbTimestamp = this.toDbTimestamp(queryData.snapshotVersion);\n var queryProto;\n\n if (queryData.query.isDocumentQuery()) {\n queryProto = this.remoteSerializer.toDocumentsTarget(queryData.query);\n } else {\n queryProto = this.remoteSerializer.toQueryTarget(queryData.query);\n }\n\n var resumeToken;\n\n if (queryData.resumeToken instanceof Uint8Array) {\n // TODO(b/78771403): Convert tokens to strings during deserialization\n assert(process.env.USE_MOCK_PERSISTENCE === 'YES', 'Persisting non-string stream tokens is only supported with mock persistence .');\n resumeToken = queryData.resumeToken.toString();\n } else {\n resumeToken = queryData.resumeToken;\n } // lastListenSequenceNumber is always 0 until we do real GC.\n\n\n return new DbTarget(queryData.targetId, queryData.query.canonicalId(), dbTimestamp, resumeToken, queryData.sequenceNumber, queryProto);\n };\n\n return LocalSerializer;\n}();\n/**\r\n * A helper function for figuring out what kind of query has been stored.\r\n */\n\n\nfunction isDocumentQuery(dbQuery) {\n return dbQuery.documents !== undefined;\n}\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction bufferEntryComparator(_a, _b) {\n var aSequence = _a[0],\n aIndex = _a[1];\n var bSequence = _b[0],\n bIndex = _b[1];\n var seqCmp = primitiveComparator(aSequence, bSequence);\n\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/**\r\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\r\n * lowest n values passed to `addElement`, and finally reports the largest of\r\n * them in `maxValue`.\r\n */\n\n\nvar RollingSequenceNumberBuffer =\n/** @class */\nfunction () {\n function RollingSequenceNumberBuffer(maxElements) {\n this.maxElements = maxElements;\n this.buffer = new SortedSet(bufferEntryComparator);\n this.previousIndex = 0;\n }\n\n RollingSequenceNumberBuffer.prototype.nextIndex = function () {\n return ++this.previousIndex;\n };\n\n RollingSequenceNumberBuffer.prototype.addElement = function (sequenceNumber) {\n var entry = [sequenceNumber, this.nextIndex()];\n\n if (this.buffer.size < this.maxElements) {\n this.buffer = this.buffer.add(entry);\n } else {\n var highestValue = this.buffer.last();\n\n if (bufferEntryComparator(entry, highestValue) < 0) {\n this.buffer = this.buffer.delete(highestValue).add(entry);\n }\n }\n };\n\n Object.defineProperty(RollingSequenceNumberBuffer.prototype, \"maxValue\", {\n get: function get() {\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 enumerable: true,\n configurable: true\n });\n return RollingSequenceNumberBuffer;\n}();\n\nvar GC_DID_NOT_RUN = {\n didRun: false,\n sequenceNumbersCollected: 0,\n targetsRemoved: 0,\n documentsRemoved: 0\n};\n\nvar LruParams =\n/** @class */\nfunction () {\n function LruParams( // 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 cacheSizeCollectionThreshold, // The percentage of sequence numbers that we will attempt to collect\n percentileToCollect, // 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 maximumSequenceNumbersToCollect) {\n this.cacheSizeCollectionThreshold = cacheSizeCollectionThreshold;\n this.percentileToCollect = percentileToCollect;\n this.maximumSequenceNumbersToCollect = maximumSequenceNumbersToCollect;\n }\n\n LruParams.withCacheSize = function (cacheSize) {\n return new LruParams(cacheSize, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n };\n\n LruParams.COLLECTION_DISABLED = -1;\n LruParams.MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n LruParams.DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024;\n LruParams.DEFAULT_COLLECTION_PERCENTILE = 10;\n LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000;\n LruParams.DEFAULT = new LruParams(LruParams.DEFAULT_CACHE_SIZE_BYTES, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT);\n LruParams.DISABLED = new LruParams(LruParams.COLLECTION_DISABLED, 0, 0);\n return LruParams;\n}();\n/** How long we wait to try running LRU GC after SDK initialization. */\n\n\nvar INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\n\nvar REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n/**\r\n * This class is responsible for the scheduling of LRU garbage collection. It handles checking\r\n * whether or not GC is enabled, as well as which delay to use before the next run.\r\n */\n\nvar LruScheduler =\n/** @class */\nfunction () {\n function LruScheduler(garbageCollector, asyncQueue, localStore) {\n this.garbageCollector = garbageCollector;\n this.asyncQueue = asyncQueue;\n this.localStore = localStore;\n this.gcTask = null;\n }\n\n LruScheduler.prototype.start = function () {\n assert(this.gcTask === null, 'Cannot start an already started LruScheduler');\n\n if (this.garbageCollector.params.cacheSizeCollectionThreshold !== CACHE_SIZE_UNLIMITED) {\n this.scheduleGC();\n }\n };\n\n LruScheduler.prototype.stop = function () {\n if (this.gcTask) {\n this.gcTask.cancel();\n this.gcTask = null;\n }\n };\n\n LruScheduler.prototype.scheduleGC = function () {\n var _this = this;\n\n assert(this.gcTask === null, 'Cannot schedule GC while a task is pending');\n var delay = this.hasRun ? REGULAR_GC_DELAY_MS : INITIAL_GC_DELAY_MS;\n debug('LruGarbageCollector', \"Garbage collection scheduled in \" + delay + \"ms\");\n this.gcTask = this.asyncQueue.enqueueAfterDelay(TimerId.LruGarbageCollection, delay, function () {\n _this.gcTask = null;\n _this.hasRun = true;\n return _this.localStore.collectGarbage(_this.garbageCollector).then(function () {\n return _this.scheduleGC();\n });\n });\n };\n\n return LruScheduler;\n}();\n/** Implements the steps for LRU garbage collection. */\n\n\nvar LruGarbageCollector =\n/** @class */\nfunction () {\n function LruGarbageCollector(delegate, params) {\n this.delegate = delegate;\n this.params = params;\n }\n /** Given a percentile of target to collect, returns the number of targets to collect. */\n\n\n LruGarbageCollector.prototype.calculateTargetCount = function (txn, percentile) {\n return this.delegate.getSequenceNumberCount(txn).next(function (targetCount) {\n return Math.floor(percentile / 100.0 * targetCount);\n });\n };\n /** Returns the nth sequence number, counting in order from the smallest. */\n\n\n LruGarbageCollector.prototype.nthSequenceNumber = function (txn, n) {\n var _this = this;\n\n if (n === 0) {\n return PersistencePromise.resolve(ListenSequence.INVALID);\n }\n\n var buffer = new RollingSequenceNumberBuffer(n);\n return this.delegate.forEachTarget(txn, function (target) {\n return buffer.addElement(target.sequenceNumber);\n }).next(function () {\n return _this.delegate.forEachOrphanedDocumentSequenceNumber(txn, function (sequenceNumber) {\n return buffer.addElement(sequenceNumber);\n });\n }).next(function () {\n return buffer.maxValue;\n });\n };\n /**\r\n * Removes targets with a sequence number equal to or less than the given upper bound, and removes\r\n * document associations with those targets.\r\n */\n\n\n LruGarbageCollector.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\n return this.delegate.removeTargets(txn, upperBound, activeTargetIds);\n };\n /**\r\n * Removes documents that have a sequence number equal to or less than the upper bound and are not\r\n * otherwise pinned.\r\n */\n\n\n LruGarbageCollector.prototype.removeOrphanedDocuments = function (txn, upperBound) {\n return this.delegate.removeOrphanedDocuments(txn, upperBound);\n };\n\n LruGarbageCollector.prototype.collect = function (txn, activeTargetIds) {\n var _this = this;\n\n if (this.params.cacheSizeCollectionThreshold === LruParams.COLLECTION_DISABLED) {\n debug('LruGarbageCollector', 'Garbage collection skipped; disabled');\n return PersistencePromise.resolve(GC_DID_NOT_RUN);\n }\n\n return this.getCacheSize(txn).next(function (cacheSize) {\n if (cacheSize < _this.params.cacheSizeCollectionThreshold) {\n debug('LruGarbageCollector', \"Garbage collection skipped; Cache size \" + cacheSize + \" \" + (\"is lower than threshold \" + _this.params.cacheSizeCollectionThreshold));\n return GC_DID_NOT_RUN;\n } else {\n return _this.runGarbageCollection(txn, activeTargetIds);\n }\n });\n };\n\n LruGarbageCollector.prototype.getCacheSize = function (txn) {\n return this.delegate.getCacheSize(txn);\n };\n\n LruGarbageCollector.prototype.runGarbageCollection = function (txn, activeTargetIds) {\n var _this = this;\n\n var upperBoundSequenceNumber;\n var sequenceNumbersToCollect, targetsRemoved; // Timestamps for various pieces of the process\n\n var startTs, countedTargetsTs, foundUpperBoundTs, removedTargetsTs, removedDocumentsTs;\n startTs = Date.now();\n return this.calculateTargetCount(txn, this.params.percentileToCollect).next(function (sequenceNumbers) {\n // Cap at the configured max\n if (sequenceNumbers > _this.params.maximumSequenceNumbersToCollect) {\n debug('LruGarbageCollector', 'Capping sequence numbers to collect down ' + (\"to the maximum of \" + _this.params.maximumSequenceNumbersToCollect + \" \") + (\"from \" + sequenceNumbers));\n sequenceNumbersToCollect = _this.params.maximumSequenceNumbersToCollect;\n } else {\n sequenceNumbersToCollect = sequenceNumbers;\n }\n\n countedTargetsTs = Date.now();\n return _this.nthSequenceNumber(txn, sequenceNumbersToCollect);\n }).next(function (upperBound) {\n upperBoundSequenceNumber = upperBound;\n foundUpperBoundTs = Date.now();\n return _this.removeTargets(txn, upperBoundSequenceNumber, activeTargetIds);\n }).next(function (numTargetsRemoved) {\n targetsRemoved = numTargetsRemoved;\n removedTargetsTs = Date.now();\n return _this.removeOrphanedDocuments(txn, upperBoundSequenceNumber);\n }).next(function (documentsRemoved) {\n removedDocumentsTs = Date.now();\n\n if (getLogLevel() <= LogLevel.DEBUG) {\n var desc = 'LRU Garbage Collection\\n' + (\"\\tCounted targets in \" + (countedTargetsTs - startTs) + \"ms\\n\") + (\"\\tDetermined least recently used \" + sequenceNumbersToCollect + \" in \") + (foundUpperBoundTs - countedTargetsTs + \"ms\\n\") + (\"\\tRemoved \" + targetsRemoved + \" targets in \") + (removedTargetsTs - foundUpperBoundTs + \"ms\\n\") + (\"\\tRemoved \" + documentsRemoved + \" documents in \") + (removedDocumentsTs - removedTargetsTs + \"ms\\n\") + (\"Total Duration: \" + (removedDocumentsTs - startTs) + \"ms\");\n debug('LruGarbageCollector', desc);\n }\n\n return PersistencePromise.resolve({\n didRun: true,\n sequenceNumbersCollected: sequenceNumbersToCollect,\n targetsRemoved: targetsRemoved,\n documentsRemoved: documentsRemoved\n });\n });\n };\n\n return LruGarbageCollector;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Opaque interface representing a persistence transaction.\r\n *\r\n * When you call Persistence.runTransaction(), it will create a transaction and\r\n * pass it to your callback. You then pass it to any method that operates\r\n * on persistence.\r\n */\n\n\nvar PersistenceTransaction =\n/** @class */\nfunction () {\n function PersistenceTransaction() {}\n\n return PersistenceTransaction;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$2 = 'IndexedDbPersistence';\n/**\r\n * Oldest acceptable age in milliseconds for client metadata before the client\r\n * is considered inactive and its associated data (such as the remote document\r\n * cache changelog) is garbage collected.\r\n */\n\nvar MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\r\n * Oldest acceptable metadata age for clients that may participate in the\r\n * primary lease election. Clients that have not updated their client metadata\r\n * within 5 seconds are not eligible to receive a primary lease.\r\n */\n\nvar MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n/**\r\n * The interval at which clients will update their metadata, including\r\n * refreshing their primary lease if held or potentially trying to acquire it if\r\n * not held.\r\n *\r\n * Primary clients may opportunistically refresh their metadata earlier\r\n * if they're already performing an IndexedDB operation.\r\n */\n\nvar CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\n\nvar PRIMARY_LEASE_LOST_ERROR_MSG = 'The current tab is not in the required state to perform this operation. ' + 'It might be necessary to refresh the browser tab.';\nvar PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG = 'Another tab has exclusive access to the persistence layer. ' + 'To allow shared access, make sure to invoke ' + '`enablePersistence()` with `experimentalTabSynchronization:true` in all tabs.';\nvar UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing' + ' IndexedDB or is known to have an incomplete implementation. Offline' + ' persistence has been disabled.'; // The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\n\nvar ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\nvar IndexedDbTransaction =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(IndexedDbTransaction, _super);\n\n function IndexedDbTransaction(simpleDbTransaction, currentSequenceNumber) {\n var _this = _super.call(this) || this;\n\n _this.simpleDbTransaction = simpleDbTransaction;\n _this.currentSequenceNumber = currentSequenceNumber;\n return _this;\n }\n\n return IndexedDbTransaction;\n}(PersistenceTransaction);\n\nvar IndexedDbPersistence =\n/** @class */\nfunction () {\n // Note that `multiClientParams` must be present to enable multi-client support while multi-tab\n // is still experimental. When multi-client is switched to always on, `multiClientParams` will\n // no longer be optional.\n function IndexedDbPersistence(persistenceKey, clientId, platform, queue, serializer, lruParams, multiClientParams) {\n this.persistenceKey = persistenceKey;\n this.clientId = clientId;\n this.queue = queue;\n this.multiClientParams = multiClientParams;\n this._started = false;\n this.isPrimary = false;\n this.networkEnabled = true;\n this.inForeground = false;\n /** The last time we garbage collected the Remote Document Changelog. */\n\n this.lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n /** A listener to notify on primary state changes. */\n\n this.primaryStateListener = function (_) {\n return Promise.resolve();\n };\n\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG);\n }\n\n this.referenceDelegate = new IndexedDbLruDelegate(this, lruParams);\n this.dbName = persistenceKey + IndexedDbPersistence.MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.document = platform.document;\n this.allowTabSynchronization = multiClientParams !== undefined;\n this.queryCache = new IndexedDbQueryCache(this.referenceDelegate, this.serializer);\n this.remoteDocumentCache = new IndexedDbRemoteDocumentCache(this.serializer,\n /*keepDocumentChangeLog=*/\n this.allowTabSynchronization);\n\n if (platform.window && platform.window.localStorage) {\n this.window = platform.window;\n this.webStorage = this.window.localStorage;\n } else {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'IndexedDB persistence is only available on platforms that support LocalStorage.');\n }\n }\n\n IndexedDbPersistence.getStore = function (txn, store) {\n if (txn instanceof IndexedDbTransaction) {\n return SimpleDb.getStore(txn.simpleDbTransaction, store);\n } else {\n throw fail('IndexedDbPersistence must use instances of IndexedDbTransaction');\n }\n };\n\n IndexedDbPersistence.createIndexedDbPersistence = function (persistenceKey, clientId, platform, queue, serializer, lruParams) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var persistence;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n persistence = new IndexedDbPersistence(persistenceKey, clientId, platform, queue, serializer, lruParams);\n return [4\n /*yield*/\n , persistence.start()];\n\n case 1:\n _a.sent();\n\n return [2\n /*return*/\n , persistence];\n }\n });\n });\n };\n\n IndexedDbPersistence.createMultiClientIndexedDbPersistence = function (persistenceKey, clientId, platform, queue, serializer, lruParams, multiClientParams) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var persistence;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n persistence = new IndexedDbPersistence(persistenceKey, clientId, platform, queue, serializer, lruParams, multiClientParams);\n return [4\n /*yield*/\n , persistence.start()];\n\n case 1:\n _a.sent();\n\n return [2\n /*return*/\n , persistence];\n }\n });\n });\n };\n /**\r\n * Attempt to start IndexedDb persistence.\r\n *\r\n * @return {Promise} Whether persistence was enabled.\r\n */\n\n\n IndexedDbPersistence.prototype.start = function () {\n var _this = this;\n\n assert(!this.started, 'IndexedDbPersistence double-started!');\n assert(this.window !== null, \"Expected 'window' to be defined\");\n return SimpleDb.openOrCreate(this.dbName, SCHEMA_VERSION, new SchemaConverter(this.serializer)).then(function (db) {\n _this.simpleDb = db;\n }).then(function () {\n return _this.startRemoteDocumentCache();\n }).then(function () {\n _this.attachVisibilityHandler();\n\n _this.attachWindowUnloadHook();\n\n return _this.updateClientMetadataAndTryBecomePrimary().then(function () {\n return _this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n });\n }).then(function () {\n return _this.simpleDb.runTransaction('readonly', [DbTargetGlobal.store], function (txn) {\n return getHighestListenSequenceNumber(txn).next(function (highestListenSequenceNumber) {\n var sequenceNumberSyncer = _this.multiClientParams ? _this.multiClientParams.sequenceNumberSyncer : undefined;\n _this.listenSequence = new ListenSequence(highestListenSequenceNumber, sequenceNumberSyncer);\n });\n });\n }).then(function () {\n _this._started = true;\n }).catch(function (reason) {\n _this.simpleDb && _this.simpleDb.close();\n return Promise.reject(reason);\n });\n };\n\n IndexedDbPersistence.prototype.startRemoteDocumentCache = function () {\n var _this = this;\n\n return this.simpleDb.runTransaction('readonly', ALL_STORES, function (txn) {\n return _this.remoteDocumentCache.start(txn);\n });\n };\n\n IndexedDbPersistence.prototype.setPrimaryStateListener = function (primaryStateListener) {\n var _this = this;\n\n this.primaryStateListener = function (primaryState) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (this.started) {\n return [2\n /*return*/\n , primaryStateListener(primaryState)];\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n return primaryStateListener(this.isPrimary);\n };\n\n IndexedDbPersistence.prototype.setNetworkEnabled = function (networkEnabled) {\n var _this = this;\n\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled; // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n\n this.queue.enqueueAndForget(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!this.started) return [3\n /*break*/\n , 2];\n return [4\n /*yield*/\n , this.updateClientMetadataAndTryBecomePrimary()];\n\n case 1:\n _a.sent();\n\n _a.label = 2;\n\n case 2:\n return [2\n /*return*/\n ];\n }\n });\n });\n });\n }\n };\n /**\r\n * Updates the client metadata in IndexedDb and attempts to either obtain or\r\n * extend the primary lease for the local client. Asynchronously notifies the\r\n * primary state listener if the client either newly obtained or released its\r\n * primary lease.\r\n */\n\n\n IndexedDbPersistence.prototype.updateClientMetadataAndTryBecomePrimary = function () {\n var _this = this;\n\n return this.simpleDb.runTransaction('readwrite', ALL_STORES, function (txn) {\n var metadataStore = clientMetadataStore(txn);\n return metadataStore.put(new DbClientMetadata(_this.clientId, Date.now(), _this.networkEnabled, _this.inForeground, _this.remoteDocumentCache.lastProcessedDocumentChangeId)).next(function () {\n if (_this.isPrimary) {\n return _this.verifyPrimaryLease(txn).next(function (success) {\n if (!success) {\n _this.isPrimary = false;\n\n _this.queue.enqueueAndForget(function () {\n return _this.primaryStateListener(false);\n });\n }\n });\n }\n }).next(function () {\n return _this.canActAsPrimary(txn);\n }).next(function (canActAsPrimary) {\n var wasPrimary = _this.isPrimary;\n _this.isPrimary = canActAsPrimary;\n\n if (wasPrimary !== _this.isPrimary) {\n _this.queue.enqueueAndForget(function () {\n return _this.primaryStateListener(_this.isPrimary);\n });\n }\n\n if (wasPrimary && !_this.isPrimary) {\n return _this.releasePrimaryLeaseIfHeld(txn);\n } else if (_this.isPrimary) {\n return _this.acquireOrExtendPrimaryLease(txn);\n }\n });\n });\n };\n\n IndexedDbPersistence.prototype.verifyPrimaryLease = function (txn) {\n var _this = this;\n\n var store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(function (primaryClient) {\n return PersistencePromise.resolve(_this.isLocalClient(primaryClient));\n });\n };\n\n IndexedDbPersistence.prototype.removeClientMetadata = function (txn) {\n var metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n };\n /**\r\n * If the garbage collection threshold has passed, prunes the\r\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\r\n * time of all clients.\r\n */\n\n\n IndexedDbPersistence.prototype.maybeGarbageCollectMultiClientState = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var activeClients_1, inactiveClients_1;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(this.isPrimary && !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS))) return [3\n /*break*/\n , 2];\n this.lastGarbageCollectionTime = Date.now();\n inactiveClients_1 = [];\n return [4\n /*yield*/\n , this.runTransaction('maybeGarbageCollectMultiClientState', 'readwrite-primary', function (txn) {\n var metadataStore = IndexedDbPersistence.getStore(txn, DbClientMetadata.store);\n return metadataStore.loadAll().next(function (existingClients) {\n activeClients_1 = _this.filterActiveClients(existingClients, MAX_CLIENT_AGE_MS);\n inactiveClients_1 = existingClients.filter(function (client) {\n return activeClients_1.indexOf(client) === -1;\n });\n }).next(function () {\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(inactiveClients_1, function (inactiveClient) {\n return metadataStore.delete(inactiveClient.clientId);\n });\n }).next(function () {\n // Retrieve the minimum change ID from the set of active clients.\n // The primary client doesn't read from the document change log,\n // and hence we exclude it when we determine the minimum\n // `lastProcessedDocumentChangeId`.\n activeClients_1 = activeClients_1.filter(function (client) {\n return client.clientId !== _this.clientId;\n });\n\n if (activeClients_1.length > 0) {\n var processedChangeIds = activeClients_1.map(function (client) {\n return client.lastProcessedDocumentChangeId || 0;\n });\n var oldestChangeId = Math.min.apply(Math, processedChangeIds);\n return _this.remoteDocumentCache.removeDocumentChangesThroughChangeId(txn, oldestChangeId);\n }\n });\n })];\n\n case 1:\n _a.sent(); // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n\n\n inactiveClients_1.forEach(function (inactiveClient) {\n _this.window.localStorage.removeItem(_this.zombiedClientLocalStorageKey(inactiveClient.clientId));\n });\n _a.label = 2;\n\n case 2:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Schedules a recurring timer to update the client metadata and to either\r\n * extend or acquire the primary lease if the client is eligible.\r\n */\n\n\n IndexedDbPersistence.prototype.scheduleClientMetadataAndPrimaryLeaseRefreshes = function () {\n var _this = this;\n\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(TimerId.ClientMetadataRefresh, CLIENT_METADATA_REFRESH_INTERVAL_MS, function () {\n return _this.updateClientMetadataAndTryBecomePrimary().then(function () {\n return _this.maybeGarbageCollectMultiClientState();\n }).then(function () {\n return _this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n });\n });\n };\n /** Checks whether `client` is the local client. */\n\n\n IndexedDbPersistence.prototype.isLocalClient = function (client) {\n return client ? client.ownerId === this.clientId : false;\n };\n /**\r\n * Evaluate the state of all active clients and determine whether the local\r\n * client is or can act as the holder of the primary lease. Returns whether\r\n * the client is eligible for the lease, but does not actually acquire it.\r\n * May return 'false' even if there is no active leaseholder and another\r\n * (foreground) client should become leaseholder instead.\r\n */\n\n\n IndexedDbPersistence.prototype.canActAsPrimary = function (txn) {\n var _this = this;\n\n var store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(function (currentPrimary) {\n var currentLeaseIsValid = currentPrimary !== null && _this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) && !_this.isClientZombied(currentPrimary.ownerId); // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n\n if (currentLeaseIsValid) {\n if (_this.isLocalClient(currentPrimary) && _this.networkEnabled) {\n return true;\n }\n\n if (!_this.isLocalClient(currentPrimary)) {\n if (!currentPrimary.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG);\n }\n\n return false;\n }\n }\n\n if (_this.networkEnabled && _this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn).loadAll().next(function (existingClients) {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n var preferredCandidate = _this.filterActiveClients(existingClients, MAX_PRIMARY_ELIGIBLE_AGE_MS).find(function (otherClient) {\n if (_this.clientId !== otherClient.clientId) {\n var otherClientHasBetterNetworkState = !_this.networkEnabled && otherClient.networkEnabled;\n var otherClientHasBetterVisibility = !_this.inForeground && otherClient.inForeground;\n var otherClientHasSameNetworkState = _this.networkEnabled === otherClient.networkEnabled;\n\n if (otherClientHasBetterNetworkState || otherClientHasBetterVisibility && otherClientHasSameNetworkState) {\n return true;\n }\n }\n\n return false;\n });\n\n return preferredCandidate === undefined;\n });\n }).next(function (canActAsPrimary) {\n if (_this.isPrimary !== canActAsPrimary) {\n debug(LOG_TAG$2, \"Client \" + (canActAsPrimary ? 'is' : 'is not') + \" eligible for a primary lease.\");\n }\n\n return canActAsPrimary;\n });\n };\n\n IndexedDbPersistence.prototype.shutdown = function (deleteData) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n this.markClientZombied();\n\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n }\n\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n return [4\n /*yield*/\n , this.simpleDb.runTransaction('readwrite', [DbPrimaryClient.store, DbClientMetadata.store], function (txn) {\n return _this.releasePrimaryLeaseIfHeld(txn).next(function () {\n return _this.removeClientMetadata(txn);\n });\n })];\n\n case 1:\n _a.sent();\n\n this.simpleDb.close(); // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n\n this.removeClientZombiedEntry();\n if (!deleteData) return [3\n /*break*/\n , 3];\n return [4\n /*yield*/\n , SimpleDb.delete(this.dbName)];\n\n case 2:\n _a.sent();\n\n _a.label = 3;\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Returns clients that are not zombied and have an updateTime within the\r\n * provided threshold.\r\n */\n\n\n IndexedDbPersistence.prototype.filterActiveClients = function (clients, activityThresholdMs) {\n var _this = this;\n\n return clients.filter(function (client) {\n return _this.isWithinAge(client.updateTimeMs, activityThresholdMs) && !_this.isClientZombied(client.clientId);\n });\n };\n\n IndexedDbPersistence.prototype.getActiveClients = function () {\n var _this = this;\n\n return this.simpleDb.runTransaction('readonly', [DbClientMetadata.store], function (txn) {\n return clientMetadataStore(txn).loadAll().next(function (clients) {\n return _this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(function (clientMetadata) {\n return clientMetadata.clientId;\n });\n });\n });\n };\n\n Object.defineProperty(IndexedDbPersistence.prototype, \"started\", {\n get: function get() {\n return this._started;\n },\n enumerable: true,\n configurable: true\n });\n\n IndexedDbPersistence.prototype.getMutationQueue = function (user) {\n assert(this.started, 'Cannot initialize MutationQueue before persistence is started.');\n return IndexedDbMutationQueue.forUser(user, this.serializer, this.referenceDelegate);\n };\n\n IndexedDbPersistence.prototype.getQueryCache = function () {\n assert(this.started, 'Cannot initialize QueryCache before persistence is started.');\n return this.queryCache;\n };\n\n IndexedDbPersistence.prototype.getRemoteDocumentCache = function () {\n assert(this.started, 'Cannot initialize RemoteDocumentCache before persistence is started.');\n return this.remoteDocumentCache;\n };\n\n IndexedDbPersistence.prototype.runTransaction = function (action, mode, transactionOperation) {\n var _this = this;\n\n debug(LOG_TAG$2, 'Starting transaction:', action); // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n\n return this.simpleDb.runTransaction(mode === 'readonly' ? 'readonly' : 'readwrite', ALL_STORES, function (simpleDbTxn) {\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return _this.verifyPrimaryLease(simpleDbTxn).next(function (success) {\n if (!success) {\n error(\"Failed to obtain primary lease for action '\" + action + \"'.\");\n _this.isPrimary = false;\n\n _this.queue.enqueueAndForget(function () {\n return _this.primaryStateListener(false);\n });\n\n throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_LOST_ERROR_MSG);\n }\n\n return transactionOperation(new IndexedDbTransaction(simpleDbTxn, _this.listenSequence.next()));\n }).next(function (result) {\n return _this.acquireOrExtendPrimaryLease(simpleDbTxn).next(function () {\n return result;\n });\n });\n } else {\n return _this.verifyAllowTabSynchronization(simpleDbTxn).next(function () {\n return transactionOperation(new IndexedDbTransaction(simpleDbTxn, _this.listenSequence.next()));\n });\n }\n });\n };\n /**\r\n * Verifies that the current tab is the primary leaseholder or alternatively\r\n * that the leaseholder has opted into multi-tab synchronization.\r\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n\n\n IndexedDbPersistence.prototype.verifyAllowTabSynchronization = function (txn) {\n var _this = this;\n\n var store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(function (currentPrimary) {\n var currentLeaseIsValid = currentPrimary !== null && _this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) && !_this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !_this.isLocalClient(currentPrimary)) {\n if (!currentPrimary.allowTabSynchronization) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG);\n }\n }\n });\n };\n /**\r\n * Obtains or extends the new primary lease for the local client. This\r\n * method does not verify that the client is eligible for this lease.\r\n */\n\n\n IndexedDbPersistence.prototype.acquireOrExtendPrimaryLease = function (txn) {\n var newPrimary = new DbPrimaryClient(this.clientId, this.allowTabSynchronization, Date.now());\n return primaryClientStore(txn).put(DbPrimaryClient.key, newPrimary);\n };\n\n IndexedDbPersistence.isAvailable = function () {\n return SimpleDb.isAvailable();\n };\n /**\r\n * Generates a string used as a prefix when storing data in IndexedDB and\r\n * LocalStorage.\r\n */\n\n\n IndexedDbPersistence.buildStoragePrefix = function (databaseInfo) {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n var database = databaseInfo.databaseId.projectId;\n\n if (!databaseInfo.databaseId.isDefaultDatabase) {\n database += '.' + databaseInfo.databaseId.database;\n }\n\n return 'firestore/' + databaseInfo.persistenceKey + '/' + database + '/';\n };\n /** Checks the primary lease and removes it if we are the current primary. */\n\n\n IndexedDbPersistence.prototype.releasePrimaryLeaseIfHeld = function (txn) {\n var _this = this;\n\n var store = primaryClientStore(txn);\n return store.get(DbPrimaryClient.key).next(function (primaryClient) {\n if (_this.isLocalClient(primaryClient)) {\n debug(LOG_TAG$2, 'Releasing primary lease.');\n return store.delete(DbPrimaryClient.key);\n } else {\n return PersistencePromise.resolve();\n }\n });\n };\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n\n\n IndexedDbPersistence.prototype.isWithinAge = function (updateTimeMs, maxAgeMs) {\n var now = Date.now();\n var minAcceptable = now - maxAgeMs;\n var maxAcceptable = now;\n\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n error(\"Detected an update time that is in the future: \" + updateTimeMs + \" > \" + maxAcceptable);\n return false;\n }\n\n return true;\n };\n\n IndexedDbPersistence.prototype.attachVisibilityHandler = function () {\n var _this = this;\n\n if (this.document !== null && typeof this.document.addEventListener === 'function') {\n this.documentVisibilityHandler = function () {\n _this.queue.enqueueAndForget(function () {\n _this.inForeground = _this.document.visibilityState === 'visible';\n return _this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener('visibilitychange', this.documentVisibilityHandler);\n this.inForeground = this.document.visibilityState === 'visible';\n }\n };\n\n IndexedDbPersistence.prototype.detachVisibilityHandler = function () {\n if (this.documentVisibilityHandler) {\n assert(this.document !== null && typeof this.document.addEventListener === 'function', \"Expected 'document.addEventListener' to be a function\");\n this.document.removeEventListener('visibilitychange', this.documentVisibilityHandler);\n this.documentVisibilityHandler = null;\n }\n };\n /**\r\n * Attaches a window.unload handler that will synchronously write our\r\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\r\n * by tabs trying to acquire the primary lease to determine that the lease\r\n * is no longer valid even if the timestamp is recent. This is particularly\r\n * important for the refresh case (so the tab correctly re-acquires the\r\n * primary lease). LocalStorage is used for this rather than IndexedDb because\r\n * it is a synchronous API and so can be used reliably from an unload\r\n * handler.\r\n */\n\n\n IndexedDbPersistence.prototype.attachWindowUnloadHook = function () {\n var _this = this;\n\n if (typeof this.window.addEventListener === 'function') {\n this.windowUnloadHandler = function () {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n _this.markClientZombied();\n\n _this.queue.enqueueAndForget(function () {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return _this.shutdown();\n });\n };\n\n this.window.addEventListener('unload', this.windowUnloadHandler);\n }\n };\n\n IndexedDbPersistence.prototype.detachWindowUnloadHook = function () {\n if (this.windowUnloadHandler) {\n assert(typeof this.window.removeEventListener === 'function', \"Expected 'window.removeEventListener' to be a function\");\n this.window.removeEventListener('unload', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n };\n /**\r\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\r\n * Clients become zombied when their tab closes without running all of the\r\n * cleanup logic in `shutdown()`.\r\n */\n\n\n IndexedDbPersistence.prototype.isClientZombied = function (clientId) {\n try {\n var isZombied = this.webStorage.getItem(this.zombiedClientLocalStorageKey(clientId)) !== null;\n debug(LOG_TAG$2, \"Client '\" + clientId + \"' \" + (isZombied ? 'is' : 'is not') + \" zombied in LocalStorage\");\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n error(LOG_TAG$2, 'Failed to get zombied client id.', e);\n return false;\n }\n };\n /**\r\n * Record client as zombied (a client that had its tab closed). Zombied\r\n * clients are ignored during primary tab selection.\r\n */\n\n\n IndexedDbPersistence.prototype.markClientZombied = function () {\n try {\n this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId), String(Date.now()));\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n error('Failed to set zombie client id.', e);\n }\n };\n /** Removes the zombied client entry if it exists. */\n\n\n IndexedDbPersistence.prototype.removeClientZombiedEntry = function () {\n try {\n this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId));\n } catch (e) {// Ignore\n }\n };\n\n IndexedDbPersistence.prototype.zombiedClientLocalStorageKey = function (clientId) {\n return ZOMBIED_CLIENTS_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + clientId;\n };\n /**\r\n * The name of the main (and currently only) IndexedDB database. this name is\r\n * appended to the prefix provided to the IndexedDbPersistence constructor.\r\n */\n\n\n IndexedDbPersistence.MAIN_DATABASE = 'main';\n return IndexedDbPersistence;\n}();\n\nfunction isPrimaryLeaseLostError(err) {\n return err.code === Code.FAILED_PRECONDITION && err.message === PRIMARY_LEASE_LOST_ERROR_MSG;\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the primary client object store.\r\n */\n\n\nfunction primaryClientStore(txn) {\n return txn.store(DbPrimaryClient.store);\n}\n/**\r\n * Helper to get a typed SimpleDbStore for the client metadata object store.\r\n */\n\n\nfunction clientMetadataStore(txn) {\n return txn.store(DbClientMetadata.store);\n}\n/** Provides LRU functionality for IndexedDB persistence. */\n\n\nvar IndexedDbLruDelegate =\n/** @class */\nfunction () {\n function IndexedDbLruDelegate(db, params) {\n this.db = db;\n this.garbageCollector = new LruGarbageCollector(this, params);\n }\n\n IndexedDbLruDelegate.prototype.getSequenceNumberCount = function (txn) {\n var docCountPromise = this.orphanedDocmentCount(txn);\n var targetCountPromise = this.db.getQueryCache().getQueryCount(txn);\n return targetCountPromise.next(function (targetCount) {\n return docCountPromise.next(function (docCount) {\n return targetCount + docCount;\n });\n });\n };\n\n IndexedDbLruDelegate.prototype.orphanedDocmentCount = function (txn) {\n var orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, function (_) {\n orphanedCount++;\n }).next(function () {\n return orphanedCount;\n });\n };\n\n IndexedDbLruDelegate.prototype.forEachTarget = function (txn, f) {\n return this.db.getQueryCache().forEachTarget(txn, f);\n };\n\n IndexedDbLruDelegate.prototype.forEachOrphanedDocumentSequenceNumber = function (txn, f) {\n return this.forEachOrphanedDocument(txn, function (docKey, sequenceNumber) {\n return f(sequenceNumber);\n });\n };\n\n IndexedDbLruDelegate.prototype.setInMemoryPins = function (inMemoryPins) {\n this.inMemoryPins = inMemoryPins;\n };\n\n IndexedDbLruDelegate.prototype.addReference = function (txn, key) {\n return writeSentinelKey(txn, key);\n };\n\n IndexedDbLruDelegate.prototype.removeReference = function (txn, key) {\n return writeSentinelKey(txn, key);\n };\n\n IndexedDbLruDelegate.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\n return this.db.getQueryCache().removeTargets(txn, upperBound, activeTargetIds);\n };\n\n IndexedDbLruDelegate.prototype.removeMutationReference = function (txn, key) {\n return writeSentinelKey(txn, key);\n };\n /**\r\n * Returns true if anything would prevent this document from being garbage\r\n * collected, given that the document in question is not present in any\r\n * targets and has a sequence number less than or equal to the upper bound for\r\n * the collection run.\r\n */\n\n\n IndexedDbLruDelegate.prototype.isPinned = function (txn, docKey) {\n if (this.inMemoryPins.containsKey(docKey)) {\n return PersistencePromise.resolve(true);\n } else {\n return mutationQueuesContainKey(txn, docKey);\n }\n };\n\n IndexedDbLruDelegate.prototype.removeOrphanedDocuments = function (txn, upperBound) {\n var _this = this;\n\n var count = 0;\n var bytesRemoved = 0;\n var promises = [];\n var iteration = this.forEachOrphanedDocument(txn, function (docKey, sequenceNumber) {\n if (sequenceNumber <= upperBound) {\n var p = _this.isPinned(txn, docKey).next(function (isPinned) {\n if (!isPinned) {\n count++;\n return _this.removeOrphanedDocument(txn, docKey).next(function (documentBytes) {\n bytesRemoved += documentBytes;\n });\n }\n });\n\n promises.push(p);\n }\n }); // Wait for iteration first to make sure we have a chance to add all of the\n // removal promises to the array.\n\n return iteration.next(function () {\n return PersistencePromise.waitFor(promises);\n }).next(function () {\n return _this.db.getRemoteDocumentCache().updateSize(txn, -bytesRemoved);\n }).next(function () {\n return count;\n });\n };\n /**\r\n * Clears a document from the cache. The document is assumed to be orphaned, so target-document\r\n * associations are not queried. We remove it from the remote document cache, as well as remove\r\n * its sentinel row.\r\n */\n\n\n IndexedDbLruDelegate.prototype.removeOrphanedDocument = function (txn, docKey) {\n var totalBytesRemoved = 0;\n var documentCache = this.db.getRemoteDocumentCache();\n return PersistencePromise.waitFor([documentTargetStore(txn).delete(sentinelKey$1(docKey)), documentCache.removeEntry(txn, docKey).next(function (bytesRemoved) {\n totalBytesRemoved += bytesRemoved;\n })]).next(function () {\n return totalBytesRemoved;\n });\n };\n\n IndexedDbLruDelegate.prototype.removeTarget = function (txn, queryData) {\n var updated = queryData.copy({\n sequenceNumber: txn.currentSequenceNumber\n });\n return this.db.getQueryCache().updateQueryData(txn, updated);\n };\n\n IndexedDbLruDelegate.prototype.updateLimboDocument = function (txn, key) {\n return writeSentinelKey(txn, key);\n };\n /**\r\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\r\n * means not a part of any target, so the only entry in the target-document index for\r\n * that document will be the sentinel row (targetId 0), which will also have the sequence\r\n * number for the last time the document was accessed.\r\n */\n\n\n IndexedDbLruDelegate.prototype.forEachOrphanedDocument = function (txn, f) {\n var store = documentTargetStore(txn);\n var nextToReport = ListenSequence.INVALID;\n var nextPath;\n return store.iterate({\n index: DbTargetDocument.documentTargetsIndex\n }, function (_a, _b) {\n var targetId = _a[0],\n docKey = _a[1];\n var path = _b.path,\n sequenceNumber = _b.sequenceNumber;\n\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decode$1(nextPath)), nextToReport);\n } // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n\n\n nextToReport = sequenceNumber;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }).next(function () {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decode$1(nextPath)), nextToReport);\n }\n });\n };\n\n IndexedDbLruDelegate.prototype.getCacheSize = function (txn) {\n return this.db.getRemoteDocumentCache().getSize(txn);\n };\n\n return IndexedDbLruDelegate;\n}();\n\nfunction sentinelKey$1(key) {\n return [0, encode(key.path)];\n}\n/**\r\n * @return A value suitable for writing a sentinel row in the target-document\r\n * store.\r\n */\n\n\nfunction sentinelRow(key, sequenceNumber) {\n return new DbTargetDocument(0, encode(key.path), sequenceNumber);\n}\n\nfunction writeSentinelKey(txn, key) {\n return documentTargetStore(txn).put(sentinelRow(key, txn.currentSequenceNumber));\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * A readonly view of the local state of all documents we're tracking (i.e. we\r\n * have a cached version in remoteDocumentCache or local mutations for the\r\n * document). The view is computed by applying the mutations in the\r\n * MutationQueue to the RemoteDocumentCache.\r\n */\n\n\nvar LocalDocumentsView =\n/** @class */\nfunction () {\n function LocalDocumentsView(remoteDocumentCache, mutationQueue) {\n this.remoteDocumentCache = remoteDocumentCache;\n this.mutationQueue = mutationQueue;\n }\n /**\r\n * Get the local view of the document identified by `key`.\r\n *\r\n * @return Local view of the document or null if we don't have any cached\r\n * state for it.\r\n */\n\n\n LocalDocumentsView.prototype.getDocument = function (transaction, key) {\n var _this = this;\n\n return this.mutationQueue.getAllMutationBatchesAffectingDocumentKey(transaction, key).next(function (batches) {\n return _this.getDocumentInternal(transaction, key, batches);\n });\n };\n /** Internal version of `getDocument` that allows reusing batches. */\n\n\n LocalDocumentsView.prototype.getDocumentInternal = function (transaction, key, inBatches) {\n return this.remoteDocumentCache.getEntry(transaction, key).next(function (doc) {\n for (var _i = 0, inBatches_1 = inBatches; _i < inBatches_1.length; _i++) {\n var batch = inBatches_1[_i];\n doc = batch.applyToLocalView(key, doc);\n }\n\n return doc;\n });\n };\n /**\r\n * Gets the local view of the documents identified by `keys`.\r\n *\r\n * If we don't have cached state for a document in `keys`, a NoDocument will\r\n * be stored for that key in the resulting set.\r\n */\n\n\n LocalDocumentsView.prototype.getDocuments = function (transaction, keys) {\n var _this = this;\n\n return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(transaction, keys).next(function (batches) {\n var promises = [];\n var results = maybeDocumentMap();\n keys.forEach(function (key) {\n promises.push(_this.getDocumentInternal(transaction, key, batches).next(function (maybeDoc) {\n // TODO(http://b/32275378): Don't conflate missing / deleted.\n if (!maybeDoc) {\n maybeDoc = new NoDocument(key, SnapshotVersion.forDeletedDoc());\n }\n\n results = results.insert(key, maybeDoc);\n }));\n });\n return PersistencePromise.waitFor(promises).next(function () {\n return results;\n });\n });\n };\n /** Performs a query against the local view of all documents. */\n\n\n LocalDocumentsView.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n if (DocumentKey.isDocumentKey(query.path)) {\n return this.getDocumentsMatchingDocumentQuery(transaction, query.path);\n } else {\n return this.getDocumentsMatchingCollectionQuery(transaction, query);\n }\n };\n\n LocalDocumentsView.prototype.getDocumentsMatchingDocumentQuery = function (transaction, docPath) {\n // Just do a simple document lookup.\n return this.getDocument(transaction, new DocumentKey(docPath)).next(function (maybeDoc) {\n var result = documentMap();\n\n if (maybeDoc instanceof Document) {\n result = result.insert(maybeDoc.key, maybeDoc);\n }\n\n return result;\n });\n };\n\n LocalDocumentsView.prototype.getDocumentsMatchingCollectionQuery = function (transaction, query) {\n var _this = this; // Query the remote documents and overlay mutations.\n\n\n var results;\n return this.remoteDocumentCache.getDocumentsMatchingQuery(transaction, query).next(function (queryResults) {\n results = queryResults;\n return _this.mutationQueue.getAllMutationBatchesAffectingQuery(transaction, query);\n }).next(function (matchingMutationBatches) {\n for (var _i = 0, matchingMutationBatches_1 = matchingMutationBatches; _i < matchingMutationBatches_1.length; _i++) {\n var batch = matchingMutationBatches_1[_i];\n\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n var key = mutation.key; // Only process documents belonging to the collection.\n\n if (!query.path.isImmediateParentOf(key.path)) {\n continue;\n }\n\n var baseDoc = results.get(key);\n var mutatedDoc = mutation.applyToLocalView(baseDoc, baseDoc, batch.localWriteTime);\n\n if (mutatedDoc instanceof Document) {\n results = results.insert(key, mutatedDoc);\n } else {\n results = results.remove(key);\n }\n }\n }\n }).next(function () {\n // Finally, filter out any documents that don't actually match\n // the query.\n results.forEach(function (key, doc) {\n if (!query.matches(doc)) {\n results = results.remove(key);\n }\n });\n return results;\n });\n };\n\n return LocalDocumentsView;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * A collection of references to a document from some kind of numbered entity\r\n * (either a target ID or batch ID). As references are added to or removed from\r\n * the set corresponding events are emitted to a registered garbage collector.\r\n *\r\n * Each reference is represented by a DocumentReference object. Each of them\r\n * contains enough information to uniquely identify the reference. They are all\r\n * stored primarily in a set sorted by key. A document is considered garbage if\r\n * there's no references in that set (this can be efficiently checked thanks to\r\n * sorting by key).\r\n *\r\n * ReferenceSet also keeps a secondary set that contains references sorted by\r\n * IDs. This one is used to efficiently implement removal of all references by\r\n * some target ID.\r\n */\n\n\nvar ReferenceSet =\n/** @class */\nfunction () {\n function ReferenceSet() {\n // A set of outstanding references to a document sorted by key.\n this.refsByKey = new SortedSet(DocReference.compareByKey); // A set of outstanding references to a document sorted by target id.\n\n this.refsByTarget = new SortedSet(DocReference.compareByTargetId);\n }\n /** Returns true if the reference set contains no references. */\n\n\n ReferenceSet.prototype.isEmpty = function () {\n return this.refsByKey.isEmpty();\n };\n /** Adds a reference to the given document key for the given ID. */\n\n\n ReferenceSet.prototype.addReference = function (key, id) {\n var ref = new DocReference(key, id);\n this.refsByKey = this.refsByKey.add(ref);\n this.refsByTarget = this.refsByTarget.add(ref);\n };\n /** Add references to the given document keys for the given ID. */\n\n\n ReferenceSet.prototype.addReferences = function (keys, id) {\n var _this = this;\n\n keys.forEach(function (key) {\n return _this.addReference(key, id);\n });\n };\n /**\r\n * Removes a reference to the given document key for the given\r\n * ID.\r\n */\n\n\n ReferenceSet.prototype.removeReference = function (key, id) {\n this.removeRef(new DocReference(key, id));\n };\n\n ReferenceSet.prototype.removeReferences = function (keys, id) {\n var _this = this;\n\n keys.forEach(function (key) {\n return _this.removeReference(key, id);\n });\n };\n /**\r\n * Clears all references with a given ID. Calls removeRef() for each key\r\n * removed.\r\n */\n\n\n ReferenceSet.prototype.removeReferencesForId = function (id) {\n var _this = this;\n\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n var keys = [];\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n _this.removeRef(ref);\n\n keys.push(ref.key);\n });\n return keys;\n };\n\n ReferenceSet.prototype.removeAllReferences = function () {\n var _this = this;\n\n this.refsByKey.forEach(function (ref) {\n return _this.removeRef(ref);\n });\n };\n\n ReferenceSet.prototype.removeRef = function (ref) {\n this.refsByKey = this.refsByKey.delete(ref);\n this.refsByTarget = this.refsByTarget.delete(ref);\n };\n\n ReferenceSet.prototype.referencesForId = function (id) {\n var emptyKey = DocumentKey.EMPTY;\n var startRef = new DocReference(emptyKey, id);\n var endRef = new DocReference(emptyKey, id + 1);\n var keys = documentKeySet();\n this.refsByTarget.forEachInRange([startRef, endRef], function (ref) {\n keys = keys.add(ref.key);\n });\n return keys;\n };\n\n ReferenceSet.prototype.containsKey = function (key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.refsByKey.firstAfterOrEqual(ref);\n return firstRef !== null && key.isEqual(firstRef.key);\n };\n\n return ReferenceSet;\n}();\n\nvar DocReference =\n/** @class */\nfunction () {\n function DocReference(key, targetOrBatchId) {\n this.key = key;\n this.targetOrBatchId = targetOrBatchId;\n }\n /** Compare by key then by ID */\n\n\n DocReference.compareByKey = function (left, right) {\n return DocumentKey.comparator(left.key, right.key) || primitiveComparator(left.targetOrBatchId, right.targetOrBatchId);\n };\n /** Compare by ID then by key */\n\n\n DocReference.compareByTargetId = function (left, right) {\n return primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) || DocumentKey.comparator(left.key, right.key);\n };\n\n return DocReference;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$3 = 'LocalStore';\n/**\r\n * Local storage in the Firestore client. Coordinates persistence components\r\n * like the mutation queue and remote document cache to present a\r\n * latency-compensated view of stored data.\r\n *\r\n * The LocalStore is responsible for accepting mutations from the Sync Engine.\r\n * Writes from the client are put into a queue as provisional Mutations until\r\n * they are processed by the RemoteStore and confirmed as having been written\r\n * to the server.\r\n *\r\n * The local store provides the local version of documents that have been\r\n * modified locally. It maintains the constraint:\r\n *\r\n * LocalDocument = RemoteDocument + Active(LocalMutations)\r\n *\r\n * (Active mutations are those that are enqueued and have not been previously\r\n * acknowledged or rejected).\r\n *\r\n * The RemoteDocument (\"ground truth\") state is provided via the\r\n * applyChangeBatch method. It will be some version of a server-provided\r\n * document OR will be a server-provided document PLUS acknowledged mutations:\r\n *\r\n * RemoteDocument' = RemoteDocument + Acknowledged(LocalMutations)\r\n *\r\n * Note that this \"dirty\" version of a RemoteDocument will not be identical to a\r\n * server base version, since it has LocalMutations added to it pending getting\r\n * an authoritative copy from the server.\r\n *\r\n * Since LocalMutations can be rejected by the server, we have to be able to\r\n * revert a LocalMutation that has already been applied to the LocalDocument\r\n * (typically done by replaying all remaining LocalMutations to the\r\n * RemoteDocument to re-apply).\r\n *\r\n * The LocalStore is responsible for the garbage collection of the documents it\r\n * contains. For now, it every doc referenced by a view, the mutation queue, or\r\n * the RemoteStore.\r\n *\r\n * It also maintains the persistence of mapping queries to resume tokens and\r\n * target ids. It needs to know this data about queries to properly know what\r\n * docs it would be allowed to garbage collect.\r\n *\r\n * The LocalStore must be able to efficiently execute queries against its local\r\n * cache of the documents, to provide the initial set of results before any\r\n * remote changes have been received.\r\n *\r\n * Note: In TypeScript, most methods return Promises since the implementation\r\n * may rely on fetching data from IndexedDB which is async.\r\n * These Promises will only be rejected on an I/O error or other internal\r\n * (unexpected) failure (e.g. failed assert) and always represent an\r\n * unrecoverable error (should be caught / reported by the async_queue).\r\n */\n\nvar LocalStore =\n/** @class */\nfunction () {\n function LocalStore(\n /** Manages our in-memory or durable persistence. */\n persistence, initialUser) {\n this.persistence = persistence;\n /**\r\n * The set of document references maintained by any local views.\r\n */\n\n this.localViewReferences = new ReferenceSet();\n /** Maps a targetID to data about its query. */\n\n this.queryDataByTarget = {};\n assert(persistence.started, 'LocalStore was passed an unstarted persistence implementation');\n this.persistence.referenceDelegate.setInMemoryPins(this.localViewReferences);\n this.mutationQueue = persistence.getMutationQueue(initialUser);\n this.remoteDocuments = persistence.getRemoteDocumentCache();\n this.queryCache = persistence.getQueryCache();\n this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue);\n }\n /**\r\n * Tells the LocalStore that the currently authenticated user has changed.\r\n *\r\n * In response the local store switches the mutation queue to the new user and\r\n * returns any resulting document changes.\r\n */\n // PORTING NOTE: Android and iOS only return the documents affected by the\n // change.\n\n\n LocalStore.prototype.handleUserChange = function (user) {\n var _this = this;\n\n return this.persistence.runTransaction('Handle user change', 'readonly', function (txn) {\n // Swap out the mutation queue, grabbing the pending mutation batches\n // before and after.\n var oldBatches;\n return _this.mutationQueue.getAllMutationBatches(txn).next(function (promisedOldBatches) {\n oldBatches = promisedOldBatches;\n _this.mutationQueue = _this.persistence.getMutationQueue(user); // Recreate our LocalDocumentsView using the new\n // MutationQueue.\n\n _this.localDocuments = new LocalDocumentsView(_this.remoteDocuments, _this.mutationQueue);\n return _this.mutationQueue.getAllMutationBatches(txn);\n }).next(function (newBatches) {\n var removedBatchIds = [];\n var addedBatchIds = []; // Union the old/new changed keys.\n\n var changedKeys = documentKeySet();\n\n for (var _i = 0, oldBatches_1 = oldBatches; _i < oldBatches_1.length; _i++) {\n var batch = oldBatches_1[_i];\n removedBatchIds.push(batch.batchId);\n\n for (var _a = 0, _b = batch.mutations; _a < _b.length; _a++) {\n var mutation = _b[_a];\n changedKeys = changedKeys.add(mutation.key);\n }\n }\n\n for (var _c = 0, newBatches_1 = newBatches; _c < newBatches_1.length; _c++) {\n var batch = newBatches_1[_c];\n addedBatchIds.push(batch.batchId);\n\n for (var _d = 0, _e = batch.mutations; _d < _e.length; _d++) {\n var mutation = _e[_d];\n changedKeys = changedKeys.add(mutation.key);\n }\n } // Return the set of all (potentially) changed documents and the list\n // of mutation batch IDs that were affected by change.\n\n\n return _this.localDocuments.getDocuments(txn, changedKeys).next(function (affectedDocuments) {\n return {\n affectedDocuments: affectedDocuments,\n removedBatchIds: removedBatchIds,\n addedBatchIds: addedBatchIds\n };\n });\n });\n });\n };\n /* Accept locally generated Mutations and commit them to storage. */\n\n\n LocalStore.prototype.localWrite = function (mutations) {\n var _this = this;\n\n return this.persistence.runTransaction('Locally write mutations', 'readwrite', function (txn) {\n var batch;\n var localWriteTime = Timestamp.now();\n return _this.mutationQueue.addMutationBatch(txn, localWriteTime, mutations).next(function (promisedBatch) {\n batch = promisedBatch; // TODO(koss): This is doing an N^2 update by replaying ALL the\n // mutations on each document (instead of just the ones added) in\n // this batch.\n\n var keys = batch.keys();\n return _this.localDocuments.getDocuments(txn, keys);\n }).next(function (changedDocuments) {\n return {\n batchId: batch.batchId,\n changes: changedDocuments\n };\n });\n });\n };\n /** Returns the local view of the documents affected by a mutation batch. */\n // PORTING NOTE: Multi-tab only.\n\n\n LocalStore.prototype.lookupMutationDocuments = function (batchId) {\n var _this = this;\n\n return this.persistence.runTransaction('Lookup mutation documents', 'readonly', function (txn) {\n return _this.mutationQueue.lookupMutationKeys(txn, batchId).next(function (keys) {\n if (keys) {\n return _this.localDocuments.getDocuments(txn, keys);\n } else {\n return PersistencePromise.resolve(null);\n }\n });\n });\n };\n /**\r\n * Acknowledge the given batch.\r\n *\r\n * On the happy path when a batch is acknowledged, the local store will\r\n *\r\n * + remove the batch from the mutation queue;\r\n * + apply the changes to the remote document cache;\r\n * + recalculate the latency compensated view implied by those changes (there\r\n * may be mutations in the queue that affect the documents but haven't been\r\n * acknowledged yet); and\r\n * + give the changed documents back the sync engine\r\n *\r\n * @returns The resulting (modified) documents.\r\n */\n\n\n LocalStore.prototype.acknowledgeBatch = function (batchResult) {\n var _this = this;\n\n return this.persistence.runTransaction('Acknowledge batch', 'readwrite-primary', function (txn) {\n var affected = batchResult.batch.keys();\n\n var documentBuffer = _this.remoteDocuments.newChangeBuffer();\n\n return _this.mutationQueue.acknowledgeBatch(txn, batchResult.batch, batchResult.streamToken).next(function () {\n return _this.applyWriteToRemoteDocuments(txn, batchResult, documentBuffer);\n }).next(function () {\n return documentBuffer.apply(txn);\n }).next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n }).next(function () {\n return _this.localDocuments.getDocuments(txn, affected);\n });\n });\n };\n /**\r\n * Remove mutations from the MutationQueue for the specified batch;\r\n * LocalDocuments will be recalculated.\r\n *\r\n * @returns The resulting modified documents.\r\n */\n\n\n LocalStore.prototype.rejectBatch = function (batchId) {\n var _this = this;\n\n return this.persistence.runTransaction('Reject batch', 'readwrite-primary', function (txn) {\n var affectedKeys;\n return _this.mutationQueue.lookupMutationBatch(txn, batchId).next(function (batch) {\n assert(batch !== null, 'Attempt to reject nonexistent batch!');\n affectedKeys = batch.keys();\n return _this.mutationQueue.removeMutationBatch(txn, batch);\n }).next(function () {\n return _this.mutationQueue.performConsistencyCheck(txn);\n }).next(function () {\n return _this.localDocuments.getDocuments(txn, affectedKeys);\n });\n });\n };\n /** Returns the last recorded stream token for the current user. */\n\n\n LocalStore.prototype.getLastStreamToken = function () {\n var _this = this;\n\n return this.persistence.runTransaction('Get last stream token', 'readonly', function (txn) {\n return _this.mutationQueue.getLastStreamToken(txn);\n });\n };\n /**\r\n * Sets the stream token for the current user without acknowledging any\r\n * mutation batch. This is usually only useful after a stream handshake or in\r\n * response to an error that requires clearing the stream token.\r\n */\n\n\n LocalStore.prototype.setLastStreamToken = function (streamToken) {\n var _this = this;\n\n return this.persistence.runTransaction('Set last stream token', 'readwrite-primary', function (txn) {\n return _this.mutationQueue.setLastStreamToken(txn, streamToken);\n });\n };\n /**\r\n * Returns the last consistent snapshot processed (used by the RemoteStore to\r\n * determine whether to buffer incoming snapshots from the backend).\r\n */\n\n\n LocalStore.prototype.getLastRemoteSnapshotVersion = function () {\n var _this = this;\n\n return this.persistence.runTransaction('Get last remote snapshot version', 'readonly', function (txn) {\n return _this.queryCache.getLastRemoteSnapshotVersion(txn);\n });\n };\n /**\r\n * Update the \"ground-state\" (remote) documents. We assume that the remote\r\n * event reflects any write batches that have been acknowledged or rejected\r\n * (i.e. we do not re-apply local mutations to updates from this event).\r\n *\r\n * LocalDocuments are re-calculated if there are remaining mutations in the\r\n * queue.\r\n */\n\n\n LocalStore.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n\n var documentBuffer = this.remoteDocuments.newChangeBuffer();\n return this.persistence.runTransaction('Apply remote event', 'readwrite-primary', function (txn) {\n var promises = [];\n var authoritativeUpdates = documentKeySet();\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n // Do not ref/unref unassigned targetIds - it may lead to leaks.\n var queryData = _this.queryDataByTarget[targetId];\n if (!queryData) return; // When a global snapshot contains updates (either add or modify) we\n // can completely trust these updates as authoritative and blindly\n // apply them to our cache (as a defensive measure to promote\n // self-healing in the unfortunate case that our cache is ever somehow\n // corrupted / out-of-sync).\n //\n // If the document is only updated while removing it from a target\n // then watch isn't obligated to send the absolute latest version: it\n // can send the first version that caused the document not to match.\n\n change.addedDocuments.forEach(function (key) {\n authoritativeUpdates = authoritativeUpdates.add(key);\n });\n change.modifiedDocuments.forEach(function (key) {\n authoritativeUpdates = authoritativeUpdates.add(key);\n });\n promises.push(_this.queryCache.removeMatchingKeys(txn, change.removedDocuments, targetId).next(function () {\n return _this.queryCache.addMatchingKeys(txn, change.addedDocuments, targetId);\n })); // Update the resume token if the change includes one. Don't clear\n // any preexisting value.\n\n var resumeToken = change.resumeToken;\n\n if (resumeToken.length > 0) {\n var oldQueryData = queryData;\n queryData = queryData.copy({\n resumeToken: resumeToken,\n snapshotVersion: remoteEvent.snapshotVersion\n });\n _this.queryDataByTarget[targetId] = queryData;\n\n if (LocalStore.shouldPersistQueryData(oldQueryData, queryData, change)) {\n promises.push(_this.queryCache.updateQueryData(txn, queryData));\n }\n }\n });\n var changedDocKeys = documentKeySet();\n remoteEvent.documentUpdates.forEach(function (key, doc) {\n changedDocKeys = changedDocKeys.add(key);\n promises.push(documentBuffer.getEntry(txn, key).next(function (existingDoc) {\n // If a document update isn't authoritative, make sure we don't\n // apply an old document version to the remote cache. We make an\n // exception for SnapshotVersion.MIN which can happen for\n // manufactured events (e.g. in the case of a limbo document\n // resolution failing).\n if (existingDoc == null || doc.version.isEqual(SnapshotVersion.MIN) || authoritativeUpdates.has(doc.key) && !existingDoc.hasPendingWrites || doc.version.compareTo(existingDoc.version) >= 0) {\n documentBuffer.addEntry(doc);\n } else {\n debug(LOG_TAG$3, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version);\n }\n }));\n\n if (remoteEvent.resolvedLimboDocuments.has(key)) {\n promises.push(_this.persistence.referenceDelegate.updateLimboDocument(txn, key));\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\n var remoteVersion = remoteEvent.snapshotVersion;\n\n if (!remoteVersion.isEqual(SnapshotVersion.MIN)) {\n var updateRemoteVersion = _this.queryCache.getLastRemoteSnapshotVersion(txn).next(function (lastRemoteVersion) {\n assert(remoteVersion.compareTo(lastRemoteVersion) >= 0, 'Watch stream reverted to previous snapshot?? ' + remoteVersion + ' < ' + lastRemoteVersion);\n return _this.queryCache.setTargetsMetadata(txn, txn.currentSequenceNumber, remoteVersion);\n });\n\n promises.push(updateRemoteVersion);\n }\n\n return PersistencePromise.waitFor(promises).next(function () {\n return documentBuffer.apply(txn);\n }).next(function () {\n return _this.localDocuments.getDocuments(txn, changedDocKeys);\n });\n });\n };\n /**\r\n * Returns true if the newQueryData should be persisted during an update of\r\n * an active target. QueryData should always be persisted when a target is\r\n * being released and should not call this function.\r\n *\r\n * While the target is active, QueryData updates can be omitted when nothing\r\n * about the target has changed except metadata like the resume token or\r\n * snapshot version. Occasionally it's worth the extra write to prevent these\r\n * values from getting too stale after a crash, but this doesn't have to be\r\n * too frequent.\r\n */\n\n\n LocalStore.shouldPersistQueryData = function (oldQueryData, newQueryData, change) {\n // Avoid clearing any existing value\n if (newQueryData.resumeToken.length === 0) return false; // Any resume token is interesting if there isn't one already.\n\n if (oldQueryData.resumeToken.length === 0) return true; // 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\n var timeDelta = newQueryData.snapshotVersion.toMicroseconds() - oldQueryData.snapshotVersion.toMicroseconds();\n if (timeDelta >= this.RESUME_TOKEN_MAX_AGE_MICROS) return true; // 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\n var changes = change.addedDocuments.size + change.modifiedDocuments.size + change.removedDocuments.size;\n return changes > 0;\n };\n /**\r\n * Notify local store of the changed views to locally pin documents.\r\n */\n\n\n LocalStore.prototype.notifyLocalViewChanges = function (viewChanges) {\n var _this = this;\n\n return this.persistence.runTransaction('notifyLocalViewChanges', 'readwrite', function (txn) {\n return PersistencePromise.forEach(viewChanges, function (viewChange) {\n _this.localViewReferences.addReferences(viewChange.addedKeys, viewChange.targetId);\n\n _this.localViewReferences.removeReferences(viewChange.removedKeys, viewChange.targetId);\n\n return PersistencePromise.forEach(viewChange.removedKeys, function (key) {\n return _this.persistence.referenceDelegate.removeReference(txn, key);\n });\n });\n });\n };\n /**\r\n * Gets the mutation batch after the passed in batchId in the mutation queue\r\n * or null if empty.\r\n * @param afterBatchId If provided, the batch to search after.\r\n * @returns The next mutation or null if there wasn't one.\r\n */\n\n\n LocalStore.prototype.nextMutationBatch = function (afterBatchId) {\n var _this = this;\n\n return this.persistence.runTransaction('Get next mutation batch', 'readonly', function (txn) {\n if (afterBatchId === undefined) {\n afterBatchId = BATCHID_UNKNOWN;\n }\n\n return _this.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId);\n });\n };\n /**\r\n * Read the current value of a Document with a given key or null if not\r\n * found - used for testing.\r\n */\n\n\n LocalStore.prototype.readDocument = function (key) {\n var _this = this;\n\n return this.persistence.runTransaction('read document', 'readonly', function (txn) {\n return _this.localDocuments.getDocument(txn, key);\n });\n };\n /**\r\n * Assigns the given query an internal ID so that its results can be pinned so\r\n * they don't get GC'd. A query must be allocated in the local store before\r\n * the store can be used to manage its view.\r\n */\n\n\n LocalStore.prototype.allocateQuery = function (query) {\n var _this = this;\n\n return this.persistence.runTransaction('Allocate query', 'readwrite', function (txn) {\n var queryData;\n return _this.queryCache.getQueryData(txn, query).next(function (cached) {\n if (cached) {\n // This query has been listened to previously, so reuse the\n // previous targetID.\n // TODO(mcg): freshen last accessed date?\n queryData = cached;\n return PersistencePromise.resolve();\n } else {\n return _this.queryCache.allocateTargetId(txn).next(function (targetId) {\n queryData = new QueryData(query, targetId, QueryPurpose.Listen, txn.currentSequenceNumber);\n return _this.queryCache.addQueryData(txn, queryData);\n });\n }\n }).next(function () {\n assert(!_this.queryDataByTarget[queryData.targetId], 'Tried to allocate an already allocated query: ' + query);\n _this.queryDataByTarget[queryData.targetId] = queryData;\n return queryData;\n });\n });\n };\n /**\r\n * Unpin all the documents associated with the given query. If\r\n * `keepPersistedQueryData` is set to false and Eager GC enabled, the method\r\n * directly removes the associated query data from the query cache.\r\n */\n // PORTING NOTE: `keepPersistedQueryData` is multi-tab only.\n\n\n LocalStore.prototype.releaseQuery = function (query, keepPersistedQueryData) {\n var _this = this;\n\n var mode = keepPersistedQueryData ? 'readwrite' : 'readwrite-primary';\n return this.persistence.runTransaction('Release query', mode, function (txn) {\n return _this.queryCache.getQueryData(txn, query).next(function (queryData) {\n assert(queryData != null, 'Tried to release nonexistent query: ' + query);\n var targetId = queryData.targetId;\n var cachedQueryData = _this.queryDataByTarget[targetId]; // References for documents sent via Watch are automatically removed when we delete a\n // query's target data from the reference delegate. Since this does not remove references\n // for locally mutated documents, we have to remove the target associations for these\n // documents manually.\n\n var removed = _this.localViewReferences.removeReferencesForId(targetId);\n\n delete _this.queryDataByTarget[targetId];\n\n if (!keepPersistedQueryData) {\n return PersistencePromise.forEach(removed, function (key) {\n return _this.persistence.referenceDelegate.removeReference(txn, key);\n }).next(function () {\n return _this.persistence.referenceDelegate.removeTarget(txn, cachedQueryData);\n });\n } else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n /**\r\n * Runs the specified query against all the documents in the local store and\r\n * returns the results.\r\n */\n\n\n LocalStore.prototype.executeQuery = function (query) {\n var _this = this;\n\n return this.persistence.runTransaction('Execute query', 'readonly', function (txn) {\n return _this.localDocuments.getDocumentsMatchingQuery(txn, query);\n });\n };\n /**\r\n * Returns the keys of the documents that are associated with the given\r\n * target id in the remote table.\r\n */\n\n\n LocalStore.prototype.remoteDocumentKeys = function (targetId) {\n var _this = this;\n\n return this.persistence.runTransaction('Remote document keys', 'readonly', function (txn) {\n return _this.queryCache.getMatchingKeysForTargetId(txn, targetId);\n });\n }; // PORTING NOTE: Multi-tab only.\n\n\n LocalStore.prototype.getActiveClients = function () {\n return this.persistence.getActiveClients();\n }; // PORTING NOTE: Multi-tab only.\n\n\n LocalStore.prototype.removeCachedMutationBatchMetadata = function (batchId) {\n this.mutationQueue.removeCachedMutationKeys(batchId);\n }; // PORTING NOTE: Multi-tab only.\n\n\n LocalStore.prototype.setNetworkEnabled = function (networkEnabled) {\n this.persistence.setNetworkEnabled(networkEnabled);\n };\n\n LocalStore.prototype.applyWriteToRemoteDocuments = function (txn, batchResult, documentBuffer) {\n var _this = this;\n\n var batch = batchResult.batch;\n var docKeys = batch.keys();\n var promiseChain = PersistencePromise.resolve();\n docKeys.forEach(function (docKey) {\n promiseChain = promiseChain.next(function () {\n return documentBuffer.getEntry(txn, docKey);\n }).next(function (remoteDoc) {\n var doc = remoteDoc;\n var ackVersion = batchResult.docVersions.get(docKey);\n assert(ackVersion !== null, 'ackVersions should contain every doc in the write.');\n\n if (!doc || doc.version.compareTo(ackVersion) < 0) {\n doc = batch.applyToRemoteDocument(docKey, doc, batchResult);\n\n if (!doc) {\n assert(!remoteDoc, 'Mutation batch ' + batch + ' applied to document ' + remoteDoc + ' resulted in null');\n } else {\n documentBuffer.addEntry(doc);\n }\n }\n });\n });\n return promiseChain.next(function () {\n return _this.mutationQueue.removeMutationBatch(txn, batch);\n });\n };\n\n LocalStore.prototype.collectGarbage = function (garbageCollector) {\n var _this = this;\n\n return this.persistence.runTransaction('Collect garbage', 'readwrite-primary', function (txn) {\n return garbageCollector.collect(txn, _this.queryDataByTarget);\n });\n }; // PORTING NOTE: Multi-tab only.\n\n\n LocalStore.prototype.getQueryForTarget = function (targetId) {\n var _this = this;\n\n if (this.queryDataByTarget[targetId]) {\n return Promise.resolve(this.queryDataByTarget[targetId].query);\n } else {\n return this.persistence.runTransaction('Get query data', 'readonly', function (txn) {\n return _this.queryCache.getQueryDataForTarget(txn, targetId).next(function (queryData) {\n return queryData ? queryData.query : null;\n });\n });\n }\n }; // PORTING NOTE: Multi-tab only.\n\n\n LocalStore.prototype.getNewDocumentChanges = function () {\n var _this = this;\n\n return this.persistence.runTransaction('Get new document changes', 'readonly', function (txn) {\n return _this.remoteDocuments.getNewDocumentChanges(txn);\n });\n };\n /**\r\n * The maximum time to leave a resume token buffered without writing it out.\r\n * This value is arbitrary: it's long enough to avoid several writes\r\n * (possibly indefinitely if updates come more frequently than this) but\r\n * short enough that restarting after crashing will still have a pretty\r\n * recent resume token.\r\n */\n\n\n LocalStore.RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6;\n return LocalStore;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar MemoryMutationQueue =\n/** @class */\nfunction () {\n function MemoryMutationQueue(referenceDelegate) {\n this.referenceDelegate = referenceDelegate;\n /**\r\n * The set of all mutations that have been sent but not yet been applied to\r\n * the backend.\r\n */\n\n this.mutationQueue = [];\n /** Next value to use when assigning sequential IDs to each mutation batch. */\n\n this.nextBatchId = 1;\n /** The highest acknowledged mutation in the queue. */\n\n this.highestAcknowledgedBatchId = BATCHID_UNKNOWN;\n /** The last received stream token from the server, used to acknowledge which\r\n * responses the client has processed. Stream tokens are opaque checkpoint\r\n * markers whose only real value is their inclusion in the next request.\r\n */\n\n this.lastStreamToken = emptyByteString();\n /** An ordered mapping between documents and the mutations batch IDs. */\n\n this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey);\n }\n\n MemoryMutationQueue.prototype.checkEmpty = function (transaction) {\n return PersistencePromise.resolve(this.mutationQueue.length === 0);\n };\n\n MemoryMutationQueue.prototype.acknowledgeBatch = function (transaction, batch, streamToken) {\n var batchId = batch.batchId;\n assert(batchId > this.highestAcknowledgedBatchId, 'Mutation batchIDs must be acknowledged in order');\n var batchIndex = this.indexOfExistingBatchId(batchId, 'acknowledged');\n assert(batchIndex === 0, 'Can only acknowledge the first batch in the mutation queue'); // Verify that the batch in the queue is the one to be acknowledged.\n\n var check = this.mutationQueue[batchIndex];\n assert(batchId === check.batchId, 'Queue ordering failure: expected batch ' + batchId + ', got batch ' + check.batchId);\n this.highestAcknowledgedBatchId = batchId;\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n\n MemoryMutationQueue.prototype.getLastStreamToken = function (transaction) {\n return PersistencePromise.resolve(this.lastStreamToken);\n };\n\n MemoryMutationQueue.prototype.setLastStreamToken = function (transaction, streamToken) {\n this.lastStreamToken = streamToken;\n return PersistencePromise.resolve();\n };\n\n MemoryMutationQueue.prototype.addMutationBatch = function (transaction, localWriteTime, mutations) {\n assert(mutations.length !== 0, 'Mutation batches should not be empty');\n var batchId = this.nextBatchId;\n this.nextBatchId++;\n\n if (this.mutationQueue.length > 0) {\n var prior = this.mutationQueue[this.mutationQueue.length - 1];\n assert(prior.batchId < batchId, 'Mutation batchIDs must be monotonically increasing order');\n }\n\n var batch = new MutationBatch(batchId, localWriteTime, mutations);\n this.mutationQueue.push(batch); // Track references by document key.\n\n for (var _i = 0, mutations_1 = mutations; _i < mutations_1.length; _i++) {\n var mutation = mutations_1[_i];\n this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId));\n }\n\n return PersistencePromise.resolve(batch);\n };\n\n MemoryMutationQueue.prototype.lookupMutationBatch = function (transaction, batchId) {\n return PersistencePromise.resolve(this.findMutationBatch(batchId));\n };\n\n MemoryMutationQueue.prototype.lookupMutationKeys = function (transaction, batchId) {\n var mutationBatch = this.findMutationBatch(batchId);\n assert(mutationBatch != null, 'Failed to find local mutation batch.');\n return PersistencePromise.resolve(mutationBatch.keys());\n };\n\n MemoryMutationQueue.prototype.getNextMutationBatchAfterBatchId = function (transaction, batchId) {\n // All batches with batchId <= this.highestAcknowledgedBatchId have been\n // acknowledged so the first unacknowledged batch after batchID will have a\n // batchID larger than both of these values.\n var nextBatchId = Math.max(batchId, this.highestAcknowledgedBatchId) + 1; // The requested batchId may still be out of range so normalize it to the\n // start of the queue.\n\n var rawIndex = this.indexOfBatchId(nextBatchId);\n var index = rawIndex < 0 ? 0 : rawIndex;\n return PersistencePromise.resolve(this.mutationQueue.length > index ? this.mutationQueue[index] : null);\n };\n\n MemoryMutationQueue.prototype.getAllMutationBatches = function (transaction) {\n return PersistencePromise.resolve(this.mutationQueue.slice());\n };\n\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKey = function (transaction, documentKey) {\n var _this = this;\n\n var start = new DocReference(documentKey, 0);\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n var result = [];\n this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.isEqual(ref.key), \"Should only iterate over a single key's batches\");\n\n var batch = _this.findMutationBatch(ref.targetOrBatchId);\n\n assert(batch !== null, 'Batches in the index must exist in the main table');\n result.push(batch);\n });\n return PersistencePromise.resolve(result);\n };\n\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingDocumentKeys = function (transaction, documentKeys) {\n var _this = this;\n\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n documentKeys.forEach(function (documentKey) {\n var start = new DocReference(documentKey, 0);\n var end = new DocReference(documentKey, Number.POSITIVE_INFINITY);\n\n _this.batchesByDocumentKey.forEachInRange([start, end], function (ref) {\n assert(documentKey.isEqual(ref.key), \"For each key, should only iterate over a single key's batches\");\n uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId);\n });\n });\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n };\n\n MemoryMutationQueue.prototype.getAllMutationBatchesAffectingQuery = function (transaction, query) {\n // Use the query path as a prefix for testing if a document matches the\n // query.\n var prefix = query.path;\n var immediateChildrenPathLength = prefix.length + 1; // 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\n var startPath = prefix;\n\n if (!DocumentKey.isDocumentKey(startPath)) {\n startPath = startPath.child('');\n }\n\n var start = new DocReference(new DocumentKey(startPath), 0); // Find unique batchIDs referenced by all documents potentially matching the\n // query.\n\n var uniqueBatchIDs = new SortedSet(primitiveComparator);\n this.batchesByDocumentKey.forEachWhile(function (ref) {\n var rowKeyPath = ref.key.path;\n\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\n return true;\n }\n }, start);\n return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs));\n };\n\n MemoryMutationQueue.prototype.findMutationBatches = function (batchIDs) {\n var _this = this; // 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\n\n var result = [];\n batchIDs.forEach(function (batchId) {\n var batch = _this.findMutationBatch(batchId);\n\n if (batch !== null) {\n result.push(batch);\n }\n });\n return result;\n };\n\n MemoryMutationQueue.prototype.removeMutationBatch = function (transaction, batch) {\n var _this = this; // Find the position of the first batch for removal. This need not be the\n // first entry in the queue.\n\n\n var batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed');\n assert(batchIndex === 0, 'Can only remove the first entry of the mutation queue');\n this.mutationQueue.shift();\n var references = this.batchesByDocumentKey;\n return PersistencePromise.forEach(batch.mutations, function (mutation) {\n var ref = new DocReference(mutation.key, batch.batchId);\n references = references.delete(ref);\n return _this.referenceDelegate.removeMutationReference(transaction, mutation.key);\n }).next(function () {\n _this.batchesByDocumentKey = references;\n });\n };\n\n MemoryMutationQueue.prototype.removeCachedMutationKeys = function (batchId) {// No-op since the memory mutation queue does not maintain a separate cache.\n };\n\n MemoryMutationQueue.prototype.containsKey = function (txn, key) {\n var ref = new DocReference(key, 0);\n var firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref);\n return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key));\n };\n\n MemoryMutationQueue.prototype.performConsistencyCheck = function (txn) {\n if (this.mutationQueue.length === 0) {\n assert(this.batchesByDocumentKey.isEmpty(), 'Document leak -- detected dangling mutation references when queue is empty.');\n }\n\n return PersistencePromise.resolve();\n };\n /**\r\n * Finds the index of the given batchId in the mutation queue and asserts that\r\n * the resulting index is within the bounds of the queue.\r\n *\r\n * @param batchId The batchId to search for\r\n * @param action A description of what the caller is doing, phrased in passive\r\n * form (e.g. \"acknowledged\" in a routine that acknowledges batches).\r\n */\n\n\n MemoryMutationQueue.prototype.indexOfExistingBatchId = function (batchId, action) {\n var index = this.indexOfBatchId(batchId);\n assert(index >= 0 && index < this.mutationQueue.length, 'Batches must exist to be ' + action);\n return index;\n };\n /**\r\n * Finds the index of the given batchId in the mutation queue. This operation\r\n * is O(1).\r\n *\r\n * @return The computed index of the batch with the given batchId, based on\r\n * the state of the queue. Note this index can be negative if the requested\r\n * batchId has already been remvoed from the queue or past the end of the\r\n * queue if the batchId is larger than the last added batch.\r\n */\n\n\n MemoryMutationQueue.prototype.indexOfBatchId = function (batchId) {\n if (this.mutationQueue.length === 0) {\n // As an index this is past the end of the queue\n return 0;\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\n\n var firstBatchId = this.mutationQueue[0].batchId;\n return batchId - firstBatchId;\n };\n /**\r\n * A version of lookupMutationBatch that doesn't return a promise, this makes\r\n * other functions that uses this code easier to read and more efficent.\r\n */\n\n\n MemoryMutationQueue.prototype.findMutationBatch = function (batchId) {\n var index = this.indexOfBatchId(batchId);\n\n if (index < 0 || index >= this.mutationQueue.length) {\n return null;\n }\n\n var batch = this.mutationQueue[index];\n assert(batch.batchId === batchId, 'If found batch must match');\n return batch;\n };\n\n return MemoryMutationQueue;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar MemoryQueryCache =\n/** @class */\nfunction () {\n function MemoryQueryCache(persistence) {\n this.persistence = persistence;\n /**\r\n * Maps a query to the data about that query\r\n */\n\n this.queries = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n /** The last received snapshot version. */\n\n this.lastRemoteSnapshotVersion = SnapshotVersion.MIN;\n /** The highest numbered target ID encountered. */\n\n this.highestTargetId = 0;\n /** The highest sequence number encountered. */\n\n this.highestSequenceNumber = 0;\n /**\r\n * A ordered bidirectional mapping between documents and the remote target\r\n * IDs.\r\n */\n\n this.references = new ReferenceSet();\n this.targetCount = 0;\n this.targetIdGenerator = TargetIdGenerator.forQueryCache();\n }\n\n MemoryQueryCache.prototype.getTargetCount = function (txn) {\n return PersistencePromise.resolve(this.targetCount);\n };\n\n MemoryQueryCache.prototype.forEachTarget = function (txn, f) {\n this.queries.forEach(function (_, queryData) {\n return f(queryData);\n });\n return PersistencePromise.resolve();\n };\n\n MemoryQueryCache.prototype.getLastRemoteSnapshotVersion = function (transaction) {\n return PersistencePromise.resolve(this.lastRemoteSnapshotVersion);\n };\n\n MemoryQueryCache.prototype.getHighestSequenceNumber = function (transaction) {\n return PersistencePromise.resolve(this.highestSequenceNumber);\n };\n\n MemoryQueryCache.prototype.allocateTargetId = function (transaction) {\n var nextTargetId = this.targetIdGenerator.after(this.highestTargetId);\n this.highestTargetId = nextTargetId;\n return PersistencePromise.resolve(nextTargetId);\n };\n\n MemoryQueryCache.prototype.setTargetsMetadata = function (transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) {\n if (lastRemoteSnapshotVersion) {\n this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion;\n }\n\n if (highestListenSequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = highestListenSequenceNumber;\n }\n\n return PersistencePromise.resolve();\n };\n\n MemoryQueryCache.prototype.saveQueryData = function (queryData) {\n this.queries.set(queryData.query, queryData);\n var targetId = queryData.targetId;\n\n if (targetId > this.highestTargetId) {\n this.highestTargetId = targetId;\n }\n\n if (queryData.sequenceNumber > this.highestSequenceNumber) {\n this.highestSequenceNumber = queryData.sequenceNumber;\n }\n };\n\n MemoryQueryCache.prototype.addQueryData = function (transaction, queryData) {\n assert(!this.queries.has(queryData.query), 'Adding a query that already exists');\n this.saveQueryData(queryData);\n this.targetCount += 1;\n return PersistencePromise.resolve();\n };\n\n MemoryQueryCache.prototype.updateQueryData = function (transaction, queryData) {\n assert(this.queries.has(queryData.query), 'Updating a non-existent query');\n this.saveQueryData(queryData);\n return PersistencePromise.resolve();\n };\n\n MemoryQueryCache.prototype.removeQueryData = function (transaction, queryData) {\n assert(this.targetCount > 0, 'Removing a target from an empty cache');\n assert(this.queries.has(queryData.query), 'Removing a non-existent target from the cache');\n this.queries.delete(queryData.query);\n this.references.removeReferencesForId(queryData.targetId);\n this.targetCount -= 1;\n return PersistencePromise.resolve();\n };\n\n MemoryQueryCache.prototype.removeTargets = function (transaction, upperBound, activeTargetIds) {\n var _this = this;\n\n var count = 0;\n var removals = [];\n this.queries.forEach(function (key, queryData) {\n if (queryData.sequenceNumber <= upperBound && !activeTargetIds[queryData.targetId]) {\n _this.queries.delete(key);\n\n removals.push(_this.removeMatchingKeysForTargetId(transaction, queryData.targetId));\n count++;\n }\n });\n return PersistencePromise.waitFor(removals).next(function () {\n return count;\n });\n };\n\n MemoryQueryCache.prototype.getQueryCount = function (transaction) {\n return PersistencePromise.resolve(this.targetCount);\n };\n\n MemoryQueryCache.prototype.getQueryData = function (transaction, query) {\n var queryData = this.queries.get(query) || null;\n return PersistencePromise.resolve(queryData);\n };\n\n MemoryQueryCache.prototype.getQueryDataForTarget = function (transaction, targetId) {\n // This method is only needed for multi-tab and we can't implement it\n // efficiently without additional data structures.\n return fail('Not yet implemented.');\n };\n\n MemoryQueryCache.prototype.addMatchingKeys = function (txn, keys, targetId) {\n this.references.addReferences(keys, targetId);\n var referenceDelegate = this.persistence.referenceDelegate;\n var promises = [];\n\n if (referenceDelegate) {\n keys.forEach(function (key) {\n promises.push(referenceDelegate.addReference(txn, key));\n });\n }\n\n return PersistencePromise.waitFor(promises);\n };\n\n MemoryQueryCache.prototype.removeMatchingKeys = function (txn, keys, targetId) {\n this.references.removeReferences(keys, targetId);\n var referenceDelegate = this.persistence.referenceDelegate;\n var promises = [];\n\n if (referenceDelegate) {\n keys.forEach(function (key) {\n promises.push(referenceDelegate.removeReference(txn, key));\n });\n }\n\n return PersistencePromise.waitFor(promises);\n };\n\n MemoryQueryCache.prototype.removeMatchingKeysForTargetId = function (txn, targetId) {\n this.references.removeReferencesForId(targetId);\n return PersistencePromise.resolve();\n };\n\n MemoryQueryCache.prototype.getMatchingKeysForTargetId = function (txn, targetId) {\n var matchingKeys = this.references.referencesForId(targetId);\n return PersistencePromise.resolve(matchingKeys);\n };\n\n MemoryQueryCache.prototype.containsKey = function (txn, key) {\n return PersistencePromise.resolve(this.references.containsKey(key));\n };\n\n return MemoryQueryCache;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction documentSizeMap() {\n return new SortedMap(DocumentKey.comparator);\n}\n\nvar MemoryRemoteDocumentCache =\n/** @class */\nfunction () {\n /**\r\n * @param sizer Used to assess the size of a document. For eager GC, this is expected to just\r\n * return 0 to avoid unnecessarily doing the work of calculating the size.\r\n */\n function MemoryRemoteDocumentCache(sizer) {\n this.sizer = sizer;\n this.docs = documentSizeMap();\n this.newDocumentChanges = documentKeySet();\n this.size = 0;\n }\n /**\r\n * Adds the supplied entries to the cache. Adds the given size delta to the cached size.\r\n */\n\n\n MemoryRemoteDocumentCache.prototype.addEntries = function (transaction, entries, sizeDelta) {\n for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {\n var entry = entries_1[_i];\n var key = entry.maybeDocument.key;\n this.docs = this.docs.insert(key, entry);\n this.newDocumentChanges = this.newDocumentChanges.add(key);\n }\n\n this.size += sizeDelta;\n return PersistencePromise.resolve();\n };\n /**\r\n * Removes the specified entry from the cache and updates the size as appropriate.\r\n */\n\n\n MemoryRemoteDocumentCache.prototype.removeEntry = function (transaction, documentKey) {\n var entry = this.docs.get(documentKey);\n\n if (entry) {\n this.docs = this.docs.remove(documentKey);\n this.size -= entry.size;\n return PersistencePromise.resolve(entry.size);\n } else {\n return PersistencePromise.resolve(0);\n }\n };\n\n MemoryRemoteDocumentCache.prototype.getEntry = function (transaction, documentKey) {\n var entry = this.docs.get(documentKey);\n return PersistencePromise.resolve(entry ? entry.maybeDocument : null);\n };\n /**\r\n * Looks up an entry in the cache.\r\n *\r\n * @param documentKey The key of the entry to look up.\r\n * @return The cached MaybeDocument entry and its size, or null if we have nothing cached.\r\n */\n\n\n MemoryRemoteDocumentCache.prototype.getSizedEntry = function (transaction, documentKey) {\n return PersistencePromise.resolve(this.docs.get(documentKey));\n };\n\n MemoryRemoteDocumentCache.prototype.getDocumentsMatchingQuery = function (transaction, query) {\n var results = documentMap(); // 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\n var prefix = new DocumentKey(query.path.child(''));\n var iterator = this.docs.getIteratorFrom(prefix);\n\n while (iterator.hasNext()) {\n var _a = iterator.getNext(),\n key = _a.key,\n maybeDocument = _a.value.maybeDocument;\n\n if (!query.path.isPrefixOf(key.path)) {\n break;\n }\n\n if (maybeDocument instanceof Document && query.matches(maybeDocument)) {\n results = results.insert(maybeDocument.key, maybeDocument);\n }\n }\n\n return PersistencePromise.resolve(results);\n };\n\n MemoryRemoteDocumentCache.prototype.forEachDocumentKey = function (transaction, f) {\n return PersistencePromise.forEach(this.docs, function (key) {\n return f(key);\n });\n };\n\n MemoryRemoteDocumentCache.prototype.getNewDocumentChanges = function (transaction) {\n var _this = this;\n\n var changedDocs = maybeDocumentMap();\n this.newDocumentChanges.forEach(function (key) {\n var entry = _this.docs.get(key);\n\n var changedDoc = entry ? entry.maybeDocument : new NoDocument(key, SnapshotVersion.forDeletedDoc());\n changedDocs = changedDocs.insert(key, changedDoc);\n });\n this.newDocumentChanges = documentKeySet();\n return PersistencePromise.resolve(changedDocs);\n };\n\n MemoryRemoteDocumentCache.prototype.newChangeBuffer = function () {\n return new MemoryRemoteDocumentChangeBuffer(this.sizer, this);\n };\n\n MemoryRemoteDocumentCache.prototype.getSize = function (txn) {\n return PersistencePromise.resolve(this.size);\n };\n\n return MemoryRemoteDocumentCache;\n}();\n/**\r\n * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache.\r\n */\n\n\nvar MemoryRemoteDocumentChangeBuffer =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(MemoryRemoteDocumentChangeBuffer, _super);\n\n function MemoryRemoteDocumentChangeBuffer(sizer, documentCache) {\n var _this = _super.call(this) || this;\n\n _this.sizer = sizer;\n _this.documentCache = documentCache;\n return _this;\n }\n\n MemoryRemoteDocumentChangeBuffer.prototype.applyChanges = function (transaction) {\n var _this = this;\n\n var changes = this.assertChanges();\n var delta = 0;\n var docs = [];\n changes.forEach(function (key, maybeDocument) {\n var previousSize = _this.documentSizes.get(key);\n\n assert(previousSize !== undefined, \"Attempting to change document \" + key.toString() + \" without having read it first\");\n\n var size = _this.sizer(maybeDocument);\n\n delta += size - previousSize;\n docs.push({\n maybeDocument: maybeDocument,\n size: size\n });\n });\n return this.documentCache.addEntries(transaction, docs, delta);\n };\n\n MemoryRemoteDocumentChangeBuffer.prototype.getFromCache = function (transaction, documentKey) {\n return this.documentCache.getSizedEntry(transaction, documentKey);\n };\n\n return MemoryRemoteDocumentChangeBuffer;\n}(RemoteDocumentChangeBuffer);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$4 = 'MemoryPersistence';\n/**\r\n * A memory-backed instance of Persistence. Data is stored only in RAM and\r\n * not persisted across sessions.\r\n */\n\nvar MemoryPersistence =\n/** @class */\nfunction () {\n /**\r\n * The constructor accepts a factory for creating a reference delegate. This\r\n * allows both the delegate and this instance to have strong references to\r\n * each other without having nullable fields that would then need to be\r\n * checked or asserted on every access.\r\n */\n function MemoryPersistence(clientId, referenceDelegateFactory) {\n var _this = this;\n\n this.clientId = clientId;\n /**\r\n * Note that these are retained here to make it easier to write tests\r\n * affecting both the in-memory and IndexedDB-backed persistence layers. Tests\r\n * can create a new LocalStore wrapping this Persistence instance and this\r\n * will make the in-memory persistence layer behave as if it were actually\r\n * persisting values.\r\n */\n\n this.mutationQueues = {};\n this.listenSequence = new ListenSequence(0);\n this._started = false;\n this._started = true;\n this.referenceDelegate = referenceDelegateFactory(this);\n this.queryCache = new MemoryQueryCache(this);\n\n var sizer = function sizer(doc) {\n return _this.referenceDelegate.documentSize(doc);\n };\n\n this.remoteDocumentCache = new MemoryRemoteDocumentCache(sizer);\n }\n\n MemoryPersistence.createLruPersistence = function (clientId, serializer, params) {\n var factory = function factory(p) {\n return new MemoryLruDelegate(p, new LocalSerializer(serializer), params);\n };\n\n return new MemoryPersistence(clientId, factory);\n };\n\n MemoryPersistence.createEagerPersistence = function (clientId) {\n var factory = function factory(p) {\n return new MemoryEagerDelegate(p);\n };\n\n return new MemoryPersistence(clientId, factory);\n };\n\n MemoryPersistence.prototype.shutdown = function (deleteData) {\n // No durable state to ensure is closed on shutdown.\n this._started = false;\n return Promise.resolve();\n };\n\n Object.defineProperty(MemoryPersistence.prototype, \"started\", {\n get: function get() {\n return this._started;\n },\n enumerable: true,\n configurable: true\n });\n\n MemoryPersistence.prototype.getActiveClients = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n return [2\n /*return*/\n , [this.clientId]];\n });\n });\n };\n\n MemoryPersistence.prototype.setPrimaryStateListener = function (primaryStateListener) {\n // All clients using memory persistence act as primary.\n return primaryStateListener(true);\n };\n\n MemoryPersistence.prototype.setNetworkEnabled = function (networkEnabled) {// No op.\n };\n\n MemoryPersistence.prototype.getMutationQueue = function (user) {\n var queue = this.mutationQueues[user.toKey()];\n\n if (!queue) {\n queue = new MemoryMutationQueue(this.referenceDelegate);\n this.mutationQueues[user.toKey()] = queue;\n }\n\n return queue;\n };\n\n MemoryPersistence.prototype.getQueryCache = function () {\n return this.queryCache;\n };\n\n MemoryPersistence.prototype.getRemoteDocumentCache = function () {\n return this.remoteDocumentCache;\n };\n\n MemoryPersistence.prototype.runTransaction = function (action, mode, transactionOperation) {\n var _this = this;\n\n debug(LOG_TAG$4, 'Starting transaction:', action);\n var txn = new MemoryTransaction(this.listenSequence.next());\n this.referenceDelegate.onTransactionStarted();\n return transactionOperation(txn).next(function (result) {\n return _this.referenceDelegate.onTransactionCommitted(txn).next(function () {\n return result;\n });\n }).toPromise();\n };\n\n MemoryPersistence.prototype.mutationQueuesContainKey = function (transaction, key) {\n return PersistencePromise.or(values(this.mutationQueues).map(function (queue) {\n return function () {\n return queue.containsKey(transaction, key);\n };\n }));\n };\n\n return MemoryPersistence;\n}();\n/**\r\n * Memory persistence is not actually transactional, but future implementations\r\n * may have transaction-scoped state.\r\n */\n\n\nvar MemoryTransaction =\n/** @class */\nfunction () {\n function MemoryTransaction(currentSequenceNumber) {\n this.currentSequenceNumber = currentSequenceNumber;\n }\n\n return MemoryTransaction;\n}();\n\nvar MemoryEagerDelegate =\n/** @class */\nfunction () {\n function MemoryEagerDelegate(persistence) {\n this.persistence = persistence;\n }\n\n MemoryEagerDelegate.prototype.setInMemoryPins = function (inMemoryPins) {\n this.inMemoryPins = inMemoryPins;\n };\n\n MemoryEagerDelegate.prototype.addReference = function (txn, key) {\n this.orphanedDocuments.delete(key);\n return PersistencePromise.resolve();\n };\n\n MemoryEagerDelegate.prototype.removeReference = function (txn, key) {\n this.orphanedDocuments.add(key);\n return PersistencePromise.resolve();\n };\n\n MemoryEagerDelegate.prototype.removeMutationReference = function (txn, key) {\n this.orphanedDocuments.add(key);\n return PersistencePromise.resolve();\n };\n\n MemoryEagerDelegate.prototype.removeTarget = function (txn, queryData) {\n var _this = this;\n\n var cache = this.persistence.getQueryCache();\n return cache.getMatchingKeysForTargetId(txn, queryData.targetId).next(function (keys) {\n keys.forEach(function (key) {\n return _this.orphanedDocuments.add(key);\n });\n }).next(function () {\n return cache.removeQueryData(txn, queryData);\n });\n };\n\n MemoryEagerDelegate.prototype.onTransactionStarted = function () {\n this.orphanedDocuments = new Set();\n };\n\n MemoryEagerDelegate.prototype.onTransactionCommitted = function (txn) {\n var _this = this;\n\n var cache = this.persistence.getRemoteDocumentCache();\n return PersistencePromise.forEach(this.orphanedDocuments, function (key) {\n return _this.isReferenced(txn, key).next(function (isReferenced) {\n if (!isReferenced) {\n // Since this is the eager delegate and memory persistence,\n // we don't care about the size of documents. We don't track\n // the size of the cache for eager GC.\n return cache.removeEntry(txn, key).next(function () {});\n }\n\n return PersistencePromise.resolve();\n });\n });\n };\n\n MemoryEagerDelegate.prototype.updateLimboDocument = function (txn, key) {\n var _this = this;\n\n return this.isReferenced(txn, key).next(function (isReferenced) {\n if (isReferenced) {\n _this.orphanedDocuments.delete(key);\n } else {\n _this.orphanedDocuments.add(key);\n }\n });\n };\n\n MemoryEagerDelegate.prototype.documentSize = function (doc) {\n // For eager GC, we don't care about the document size, there are no size thresholds.\n return 0;\n };\n\n MemoryEagerDelegate.prototype.isReferenced = function (txn, key) {\n var _this = this;\n\n return PersistencePromise.or([function () {\n return _this.persistence.getQueryCache().containsKey(txn, key);\n }, function () {\n return _this.persistence.mutationQueuesContainKey(txn, key);\n }, function () {\n return PersistencePromise.resolve(_this.inMemoryPins.containsKey(key));\n }]);\n };\n\n return MemoryEagerDelegate;\n}();\n\nvar MemoryLruDelegate =\n/** @class */\nfunction () {\n function MemoryLruDelegate(persistence, serializer, lruParams) {\n this.persistence = persistence;\n this.serializer = serializer;\n this.orphanedSequenceNumbers = new ObjectMap(function (k) {\n return encode(k.path);\n });\n this.garbageCollector = new LruGarbageCollector(this, lruParams);\n } // No-ops, present so memory persistence doesn't have to care which delegate\n // it has.\n\n\n MemoryLruDelegate.prototype.onTransactionStarted = function () {};\n\n MemoryLruDelegate.prototype.onTransactionCommitted = function (txn) {\n return PersistencePromise.resolve();\n };\n\n MemoryLruDelegate.prototype.forEachTarget = function (txn, f) {\n return this.persistence.getQueryCache().forEachTarget(txn, f);\n };\n\n MemoryLruDelegate.prototype.getSequenceNumberCount = function (txn) {\n var docCountPromise = this.orphanedDocumentCount(txn);\n var targetCountPromise = this.persistence.getQueryCache().getTargetCount(txn);\n return targetCountPromise.next(function (targetCount) {\n return docCountPromise.next(function (docCount) {\n return targetCount + docCount;\n });\n });\n };\n\n MemoryLruDelegate.prototype.orphanedDocumentCount = function (txn) {\n var orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, function (_) {\n orphanedCount++;\n }).next(function () {\n return orphanedCount;\n });\n };\n\n MemoryLruDelegate.prototype.forEachOrphanedDocumentSequenceNumber = function (txn, f) {\n var _this = this;\n\n return PersistencePromise.forEach(this.orphanedSequenceNumbers, function (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(function (isPinned) {\n if (!isPinned) {\n return f(sequenceNumber);\n } else {\n return PersistencePromise.resolve();\n }\n });\n });\n };\n\n MemoryLruDelegate.prototype.setInMemoryPins = function (inMemoryPins) {\n this.inMemoryPins = inMemoryPins;\n };\n\n MemoryLruDelegate.prototype.removeTargets = function (txn, upperBound, activeTargetIds) {\n return this.persistence.getQueryCache().removeTargets(txn, upperBound, activeTargetIds);\n };\n\n MemoryLruDelegate.prototype.removeOrphanedDocuments = function (txn, upperBound) {\n var _this = this;\n\n var count = 0;\n var cache = this.persistence.getRemoteDocumentCache();\n var p = cache.forEachDocumentKey(txn, function (key) {\n return _this.isPinned(txn, key, upperBound).next(function (isPinned) {\n if (isPinned) {\n return PersistencePromise.resolve();\n } else {\n count++; // The memory remote document cache does its own byte\n // accounting on removal. This is ok because updating the size\n // for memory persistence does not incur IO.\n\n return cache.removeEntry(txn, key).next();\n }\n });\n });\n return p.next(function () {\n return count;\n });\n };\n\n MemoryLruDelegate.prototype.removeMutationReference = function (txn, key) {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n };\n\n MemoryLruDelegate.prototype.removeTarget = function (txn, queryData) {\n var updated = queryData.copy({\n sequenceNumber: txn.currentSequenceNumber\n });\n return this.persistence.getQueryCache().updateQueryData(txn, updated);\n };\n\n MemoryLruDelegate.prototype.addReference = function (txn, key) {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n };\n\n MemoryLruDelegate.prototype.removeReference = function (txn, key) {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n };\n\n MemoryLruDelegate.prototype.updateLimboDocument = function (txn, key) {\n this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber);\n return PersistencePromise.resolve();\n };\n\n MemoryLruDelegate.prototype.documentSize = function (maybeDoc) {\n var remoteDocument = this.serializer.toDbRemoteDocument(maybeDoc);\n var value;\n\n if (remoteDocument.document) {\n value = remoteDocument.document;\n } else if (remoteDocument.unknownDocument) {\n value = remoteDocument.unknownDocument;\n } else if (remoteDocument.noDocument) {\n value = remoteDocument.noDocument;\n } else {\n throw fail('Unknown remote document type');\n }\n\n return JSON.stringify(value).length;\n };\n\n MemoryLruDelegate.prototype.isPinned = function (txn, key, upperBound) {\n var _this = this;\n\n return PersistencePromise.or([function () {\n return _this.persistence.mutationQueuesContainKey(txn, key);\n }, function () {\n return PersistencePromise.resolve(_this.inMemoryPins.containsKey(key));\n }, function () {\n return _this.persistence.getQueryCache().containsKey(txn, key);\n }, function () {\n var orphanedAt = _this.orphanedSequenceNumbers.get(key);\n\n return PersistencePromise.resolve(orphanedAt !== undefined && orphanedAt > upperBound);\n }]);\n };\n\n MemoryLruDelegate.prototype.getCacheSize = function (txn) {\n return this.persistence.getRemoteDocumentCache().getSize(txn);\n };\n\n return MemoryLruDelegate;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$5 = 'ExponentialBackoff';\n/**\r\n * A helper for running delayed tasks following an exponential backoff curve\r\n * between attempts.\r\n *\r\n * Each delay is made up of a \"base\" delay which follows the exponential\r\n * backoff curve, and a +/- 50% \"jitter\" that is calculated and added to the\r\n * base delay. This prevents clients from accidentally synchronizing their\r\n * delays causing spikes of load to the backend.\r\n */\n\nvar ExponentialBackoff =\n/** @class */\nfunction () {\n function ExponentialBackoff(\n /**\r\n * The AsyncQueue to run backoff operations on.\r\n */\n queue,\n /**\r\n * The ID to use when scheduling backoff operations on the AsyncQueue.\r\n */\n timerId,\n /**\r\n * The initial delay (used as the base delay on the first retry attempt).\r\n * Note that jitter will still be applied, so the actual delay could be as\r\n * little as 0.5*initialDelayMs.\r\n */\n initialDelayMs,\n /**\r\n * The multiplier to use to determine the extended base delay after each\r\n * attempt.\r\n */\n backoffFactor,\n /**\r\n * The maximum base delay after which no further backoff is performed.\r\n * Note that jitter will still be applied, so the actual delay could be as\r\n * much as 1.5*maxDelayMs.\r\n */\n maxDelayMs) {\n this.queue = queue;\n this.timerId = timerId;\n this.initialDelayMs = initialDelayMs;\n this.backoffFactor = backoffFactor;\n this.maxDelayMs = maxDelayMs;\n this.timerPromise = null;\n /** The last backoff attempt, as epoch milliseconds. */\n\n this.lastAttemptTime = Date.now();\n this.reset();\n }\n /**\r\n * Resets the backoff delay.\r\n *\r\n * The very next backoffAndWait() will have no delay. If it is called again\r\n * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and\r\n * subsequent ones will increase according to the backoffFactor.\r\n */\n\n\n ExponentialBackoff.prototype.reset = function () {\n this.currentBaseMs = 0;\n };\n /**\r\n * Resets the backoff delay to the maximum delay (e.g. for use after a\r\n * RESOURCE_EXHAUSTED error).\r\n */\n\n\n ExponentialBackoff.prototype.resetToMax = function () {\n this.currentBaseMs = this.maxDelayMs;\n };\n /**\r\n * Returns a promise that resolves after currentDelayMs, and increases the\r\n * delay for any subsequent attempts. If there was a pending backoff operation\r\n * already, it will be canceled.\r\n */\n\n\n ExponentialBackoff.prototype.backoffAndRun = function (op) {\n var _this = this; // Cancel any pending backoff operation.\n\n\n this.cancel(); // First schedule using the current base (which may be 0 and should be\n // honored as such).\n\n var desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); // Guard against lastAttemptTime being in the future due to a clock change.\n\n var delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); // Guard against the backoff delay already being past.\n\n var remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs);\n\n if (this.currentBaseMs > 0) {\n debug(LOG_TAG$5, \"Backing off for \" + remainingDelayMs + \" ms \" + (\"(base delay: \" + this.currentBaseMs + \" ms, \") + (\"delay with jitter: \" + desiredDelayWithJitterMs + \" ms, \") + (\"last attempt: \" + delaySoFarMs + \" ms ago)\"));\n }\n\n this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, function () {\n _this.lastAttemptTime = Date.now();\n return op();\n }); // Apply backoff factor to determine next delay and ensure it is within\n // bounds.\n\n this.currentBaseMs *= this.backoffFactor;\n\n if (this.currentBaseMs < this.initialDelayMs) {\n this.currentBaseMs = this.initialDelayMs;\n }\n\n if (this.currentBaseMs > this.maxDelayMs) {\n this.currentBaseMs = this.maxDelayMs;\n }\n };\n\n ExponentialBackoff.prototype.cancel = function () {\n if (this.timerPromise !== null) {\n this.timerPromise.cancel();\n this.timerPromise = null;\n }\n };\n /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */\n\n\n ExponentialBackoff.prototype.jitterDelayMs = function () {\n return (Math.random() - 0.5) * this.currentBaseMs;\n };\n\n return ExponentialBackoff;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$6 = 'PersistentStream';\n/**\r\n * PersistentStream can be in one of 5 states (each described in detail below)\r\n * based on the following state transition diagram:\r\n *\r\n * start() called auth & connection succeeded\r\n * INITIAL ----------------> STARTING -----------------------------> OPEN\r\n * ^ | |\r\n * | | error occurred |\r\n * | \\-----------------------------v-----/\r\n * | |\r\n * backoff | |\r\n * elapsed | start() called |\r\n * \\--- BACKOFF <---------------- ERROR\r\n *\r\n * [any state] --------------------------> INITIAL\r\n * stop() called or\r\n * idle timer expired\r\n */\n\nvar PersistentStreamState;\n\n(function (PersistentStreamState) {\n /**\r\n * The streaming RPC is not yet running and there's no error condition.\r\n * Calling start() will start the stream immediately without backoff.\r\n * While in this state isStarted() will return false.\r\n */\n PersistentStreamState[PersistentStreamState[\"Initial\"] = 0] = \"Initial\";\n /**\r\n * The stream is starting, either waiting for an auth token or for the stream\r\n * to successfully open. While in this state, isStarted() will return true but\r\n * isOpen() will return false.\r\n */\n\n PersistentStreamState[PersistentStreamState[\"Starting\"] = 1] = \"Starting\";\n /**\r\n * The streaming RPC is up and running. Requests and responses can flow\r\n * freely. Both isStarted() and isOpen() will return true.\r\n */\n\n PersistentStreamState[PersistentStreamState[\"Open\"] = 2] = \"Open\";\n /**\r\n * The stream encountered an error. The next start attempt will back off.\r\n * While in this state isStarted() will return false.\r\n */\n\n PersistentStreamState[PersistentStreamState[\"Error\"] = 3] = \"Error\";\n /**\r\n * An in-between state after an error where the stream is waiting before\r\n * re-starting. After waiting is complete, the stream will try to open.\r\n * While in this state isStarted() will return true but isOpen() will return\r\n * false.\r\n */\n\n PersistentStreamState[PersistentStreamState[\"Backoff\"] = 4] = \"Backoff\";\n})(PersistentStreamState || (PersistentStreamState = {}));\n/**\r\n * Initial backoff time in milliseconds after an error.\r\n * Set to 1s according to https://cloud.google.com/apis/design/errors.\r\n */\n\n\nvar BACKOFF_INITIAL_DELAY_MS = 1000;\n/** Maximum backoff time in milliseconds */\n\nvar BACKOFF_MAX_DELAY_MS = 60 * 1000;\nvar BACKOFF_FACTOR = 1.5;\n/** The time a stream stays open after it is marked idle. */\n\nvar IDLE_TIMEOUT_MS = 60 * 1000;\n/**\r\n * A PersistentStream is an abstract base class that represents a streaming RPC\r\n * to the Firestore backend. It's built on top of the connections own support\r\n * for streaming RPCs, and adds several critical features for our clients:\r\n *\r\n * - Exponential backoff on failure\r\n * - Authentication via CredentialsProvider\r\n * - Dispatching all callbacks into the shared worker queue\r\n * - Closing idle streams after 60 seconds of inactivity\r\n *\r\n * Subclasses of PersistentStream implement serialization of models to and\r\n * from the JSON representation of the protocol buffers for a specific\r\n * streaming RPC.\r\n *\r\n * ## Starting and Stopping\r\n *\r\n * Streaming RPCs are stateful and need to be start()ed before messages can\r\n * be sent and received. The PersistentStream will call the onOpen() function\r\n * of the listener once the stream is ready to accept requests.\r\n *\r\n * Should a start() fail, PersistentStream will call the registered onClose()\r\n * listener with a FirestoreError indicating what went wrong.\r\n *\r\n * A PersistentStream can be started and stopped repeatedly.\r\n *\r\n * Generic types:\r\n * SendType: The type of the outgoing message of the underlying\r\n * connection stream\r\n * ReceiveType: The type of the incoming message of the underlying\r\n * connection stream\r\n * ListenerType: The type of the listener that will be used for callbacks\r\n */\n\nvar PersistentStream =\n/** @class */\nfunction () {\n function PersistentStream(queue, connectionTimerId, idleTimerId, connection, credentialsProvider, listener) {\n this.queue = queue;\n this.idleTimerId = idleTimerId;\n this.connection = connection;\n this.credentialsProvider = credentialsProvider;\n this.listener = listener;\n this.state = PersistentStreamState.Initial;\n /**\r\n * A close count that's incremented every time the stream is closed; used by\r\n * getCloseGuardedDispatcher() to invalidate callbacks that happen after\r\n * close.\r\n */\n\n this.closeCount = 0;\n this.idleTimer = null;\n this.stream = null;\n this.backoff = new ExponentialBackoff(queue, connectionTimerId, BACKOFF_INITIAL_DELAY_MS, BACKOFF_FACTOR, BACKOFF_MAX_DELAY_MS);\n }\n /**\r\n * Returns true if start() has been called and no error has occurred. True\r\n * indicates the stream is open or in the process of opening (which\r\n * encompasses respecting backoff, getting auth tokens, and starting the\r\n * actual RPC). Use isOpen() to determine if the stream is open and ready for\r\n * outbound requests.\r\n */\n\n\n PersistentStream.prototype.isStarted = function () {\n return this.state === PersistentStreamState.Starting || this.state === PersistentStreamState.Open || this.state === PersistentStreamState.Backoff;\n };\n /**\r\n * Returns true if the underlying RPC is open (the onOpen() listener has been\r\n * called) and the stream is ready for outbound requests.\r\n */\n\n\n PersistentStream.prototype.isOpen = function () {\n return this.state === PersistentStreamState.Open;\n };\n /**\r\n * Starts the RPC. Only allowed if isStarted() returns false. The stream is\r\n * not immediately ready for use: onOpen() will be invoked when the RPC is\r\n * ready for outbound requests, at which point isOpen() will return true.\r\n *\r\n * When start returns, isStarted() will return true.\r\n */\n\n\n PersistentStream.prototype.start = function () {\n if (this.state === PersistentStreamState.Error) {\n this.performBackoff();\n return;\n }\n\n assert(this.state === PersistentStreamState.Initial, 'Already started');\n this.auth();\n };\n /**\r\n * Stops the RPC. This call is idempotent and allowed regardless of the\r\n * current isStarted() state.\r\n *\r\n * When stop returns, isStarted() and isOpen() will both return false.\r\n */\n\n\n PersistentStream.prototype.stop = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!this.isStarted()) return [3\n /*break*/\n , 2];\n return [4\n /*yield*/\n , this.close(PersistentStreamState.Initial)];\n\n case 1:\n _a.sent();\n\n _a.label = 2;\n\n case 2:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * After an error the stream will usually back off on the next attempt to\r\n * start it. If the error warrants an immediate restart of the stream, the\r\n * sender can use this to indicate that the receiver should not back off.\r\n *\r\n * Each error will call the onClose() listener. That function can decide to\r\n * inhibit backoff if required.\r\n */\n\n\n PersistentStream.prototype.inhibitBackoff = function () {\n assert(!this.isStarted(), 'Can only inhibit backoff in a stopped state');\n this.state = PersistentStreamState.Initial;\n this.backoff.reset();\n };\n /**\r\n * Marks this stream as idle. If no further actions are performed on the\r\n * stream for one minute, the stream will automatically close itself and\r\n * notify the stream's onClose() handler with Status.OK. The stream will then\r\n * be in a !isStarted() state, requiring the caller to start the stream again\r\n * before further use.\r\n *\r\n * Only streams that are in state 'Open' can be marked idle, as all other\r\n * states imply pending network operations.\r\n */\n\n\n PersistentStream.prototype.markIdle = function () {\n var _this = this; // 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\n\n if (this.isOpen() && this.idleTimer === null) {\n this.idleTimer = this.queue.enqueueAfterDelay(this.idleTimerId, IDLE_TIMEOUT_MS, function () {\n return _this.handleIdleCloseTimer();\n });\n }\n };\n /** Sends a message to the underlying stream. */\n\n\n PersistentStream.prototype.sendRequest = function (msg) {\n this.cancelIdleCheck();\n this.stream.send(msg);\n };\n /** Called by the idle timer when the stream should close due to inactivity. */\n\n\n PersistentStream.prototype.handleIdleCloseTimer = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\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 [2\n /*return*/\n , this.close(PersistentStreamState.Initial)];\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n /** Marks the stream as active again. */\n\n\n PersistentStream.prototype.cancelIdleCheck = function () {\n if (this.idleTimer) {\n this.idleTimer.cancel();\n this.idleTimer = null;\n }\n };\n /**\r\n * Closes the stream and cleans up as necessary:\r\n *\r\n * * closes the underlying GRPC stream;\r\n * * calls the onClose handler with the given 'error';\r\n * * sets internal stream state to 'finalState';\r\n * * adjusts the backoff timer based on the error\r\n *\r\n * A new stream can be opened by calling start().\r\n *\r\n * @param finalState the intended state of the stream after closing.\r\n * @param error the error the connection was closed with.\r\n */\n\n\n PersistentStream.prototype.close = function (finalState, error$$1) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n assert(this.isStarted(), 'Only started streams should be closed.');\n assert(finalState === PersistentStreamState.Error || isNullOrUndefined(error$$1), \"Can't provide an error when not in an error state.\"); // Cancel any outstanding timers (they're guaranteed not to execute).\n\n this.cancelIdleCheck();\n this.backoff.cancel(); // Invalidates any stream-related callbacks (e.g. from auth or the\n // underlying stream), guaranteeing they won't execute.\n\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$$1 && error$$1.code === Code.RESOURCE_EXHAUSTED) {\n // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.)\n error(error$$1.toString());\n error('Using maximum backoff delay to prevent overloading the backend.');\n this.backoff.resetToMax();\n } else if (error$$1 && error$$1.code === Code.UNAUTHENTICATED) {\n // \"unauthenticated\" error means the token was rejected. Try force refreshing it in case it\n // just expired.\n this.credentialsProvider.invalidateToken();\n } // Clean up the underlying stream because we are no longer interested in events.\n\n\n if (this.stream !== null) {\n this.tearDown();\n this.stream.close();\n this.stream = null;\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\n\n this.state = finalState; // Notify the listener that the stream closed.\n\n return [4\n /*yield*/\n , this.listener.onClose(error$$1)];\n\n case 1:\n // Notify the listener that the stream closed.\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Can be overridden to perform additional cleanup before the stream is closed.\r\n * Calling super.tearDown() is not required.\r\n */\n\n\n PersistentStream.prototype.tearDown = function () {};\n\n PersistentStream.prototype.auth = function () {\n var _this = this;\n\n assert(this.state === PersistentStreamState.Initial, 'Must be in initial state to auth');\n this.state = PersistentStreamState.Starting;\n var dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount); // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below.\n\n var closeCount = this.closeCount;\n this.credentialsProvider.getToken().then(function (token) {\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(token);\n }\n }, function (error$$1) {\n dispatchIfNotClosed(function () {\n var rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error$$1.message);\n return _this.handleStreamClose(rpcError);\n });\n });\n };\n\n PersistentStream.prototype.startStream = function (token) {\n var _this = this;\n\n assert(this.state === PersistentStreamState.Starting, 'Trying to start stream in a non-starting state');\n var dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount);\n this.stream = this.startRpc(token);\n this.stream.onOpen(function () {\n dispatchIfNotClosed(function () {\n assert(_this.state === PersistentStreamState.Starting, 'Expected stream to be in state Starting, but was ' + _this.state);\n _this.state = PersistentStreamState.Open;\n return _this.listener.onOpen();\n });\n });\n this.stream.onClose(function (error$$1) {\n dispatchIfNotClosed(function () {\n return _this.handleStreamClose(error$$1);\n });\n });\n this.stream.onMessage(function (msg) {\n dispatchIfNotClosed(function () {\n return _this.onMessage(msg);\n });\n });\n };\n\n PersistentStream.prototype.performBackoff = function () {\n var _this = this;\n\n assert(this.state === PersistentStreamState.Error, 'Should only perform backoff when in Error state');\n this.state = PersistentStreamState.Backoff;\n this.backoff.backoffAndRun(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n assert(this.state === PersistentStreamState.Backoff, 'Backoff elapsed but state is now: ' + this.state);\n this.state = PersistentStreamState.Initial;\n this.start();\n assert(this.isStarted(), 'PersistentStream should have started');\n return [2\n /*return*/\n ];\n });\n });\n });\n }; // Visible for tests\n\n\n PersistentStream.prototype.handleStreamClose = function (error$$1) {\n assert(this.isStarted(), \"Can't handle server close on non-started stream\");\n debug(LOG_TAG$6, \"close with error: \" + error$$1);\n this.stream = null; // 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\n return this.close(PersistentStreamState.Error, error$$1);\n };\n /**\r\n * Returns a \"dispatcher\" function that dispatches operations onto the\r\n * AsyncQueue but only runs them if closeCount remains unchanged. This allows\r\n * us to turn auth / stream callbacks into no-ops if the stream is closed /\r\n * re-opened, etc.\r\n */\n\n\n PersistentStream.prototype.getCloseGuardedDispatcher = function (startCloseCount) {\n var _this = this;\n\n return function (fn) {\n _this.queue.enqueueAndForget(function () {\n if (_this.closeCount === startCloseCount) {\n return fn();\n } else {\n debug(LOG_TAG$6, 'stream callback skipped by getCloseGuardedDispatcher.');\n return Promise.resolve();\n }\n });\n };\n };\n\n return PersistentStream;\n}();\n/**\r\n * A PersistentStream that implements the Listen RPC.\r\n *\r\n * Once the Listen stream has called the onOpen() listener, any number of\r\n * listen() and unlisten() calls can be made to control what changes will be\r\n * sent from the server for ListenResponses.\r\n */\n\n\nvar PersistentListenStream =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(PersistentListenStream, _super);\n\n function PersistentListenStream(queue, connection, credentials, serializer, listener) {\n var _this = _super.call(this, queue, TimerId.ListenStreamConnectionBackoff, TimerId.ListenStreamIdle, connection, credentials, listener) || this;\n\n _this.serializer = serializer;\n return _this;\n }\n\n PersistentListenStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Listen', token);\n };\n\n PersistentListenStream.prototype.onMessage = function (watchChangeProto) {\n // A successful response means the stream is healthy\n this.backoff.reset();\n var watchChange = this.serializer.fromWatchChange(watchChangeProto);\n var snapshot = this.serializer.versionFromListenResponse(watchChangeProto);\n return this.listener.onWatchChange(watchChange, snapshot);\n };\n /**\r\n * Registers interest in the results of the given query. If the query\r\n * includes a resumeToken it will be included in the request. Results that\r\n * affect the query will be streamed back as WatchChange messages that\r\n * reference the targetId.\r\n */\n\n\n PersistentListenStream.prototype.watch = function (queryData) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.addTarget = this.serializer.toTarget(queryData);\n var labels = this.serializer.toListenRequestLabels(queryData);\n\n if (labels) {\n request.labels = labels;\n }\n\n this.sendRequest(request);\n };\n /**\r\n * Unregisters interest in the results of the query associated with the\r\n * given targetId.\r\n */\n\n\n PersistentListenStream.prototype.unwatch = function (targetId) {\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n request.removeTarget = targetId;\n this.sendRequest(request);\n };\n\n return PersistentListenStream;\n}(PersistentStream);\n/**\r\n * A Stream that implements the Write RPC.\r\n *\r\n * The Write RPC requires the caller to maintain special streamToken\r\n * state in between calls, to help the server understand which responses the\r\n * client has processed by the time the next request is made. Every response\r\n * will contain a streamToken; this value must be passed to the next\r\n * request.\r\n *\r\n * After calling start() on this stream, the next request must be a handshake,\r\n * containing whatever streamToken is on hand. Once a response to this\r\n * request is received, all pending mutations may be submitted. When\r\n * submitting multiple batches of mutations at the same time, it's\r\n * okay to use the same streamToken for the calls to writeMutations.\r\n *\r\n * TODO(b/33271235): Use proto types\r\n */\n\n\nvar PersistentWriteStream =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(PersistentWriteStream, _super);\n\n function PersistentWriteStream(queue, connection, credentials, serializer, listener) {\n var _this = _super.call(this, queue, TimerId.WriteStreamConnectionBackoff, TimerId.WriteStreamIdle, connection, credentials, listener) || this;\n\n _this.serializer = serializer;\n _this.handshakeComplete_ = false;\n return _this;\n }\n\n Object.defineProperty(PersistentWriteStream.prototype, \"handshakeComplete\", {\n /**\r\n * Tracks whether or not a handshake has been successfully exchanged and\r\n * the stream is ready to accept mutations.\r\n */\n get: function get() {\n return this.handshakeComplete_;\n },\n enumerable: true,\n configurable: true\n }); // Override of PersistentStream.start\n\n PersistentWriteStream.prototype.start = function () {\n this.handshakeComplete_ = false;\n\n _super.prototype.start.call(this);\n };\n\n PersistentWriteStream.prototype.tearDown = function () {\n if (this.handshakeComplete_) {\n this.writeMutations([]);\n }\n };\n\n PersistentWriteStream.prototype.startRpc = function (token) {\n return this.connection.openStream('Write', token);\n };\n\n PersistentWriteStream.prototype.onMessage = function (responseProto) {\n // Always capture the last stream token.\n assert(!!responseProto.streamToken, 'Got a write response without a stream token');\n this.lastStreamToken = responseProto.streamToken;\n\n if (!this.handshakeComplete_) {\n // The first response is always the handshake response\n assert(!responseProto.writeResults || responseProto.writeResults.length === 0, 'Got mutation results for handshake');\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 var results = this.serializer.fromWriteResults(responseProto.writeResults, responseProto.commitTime);\n var commitVersion = this.serializer.fromVersion(responseProto.commitTime);\n return this.listener.onMutationResult(commitVersion, results);\n }\n };\n /**\r\n * Sends an initial streamToken to the server, performing the handshake\r\n * required to make the StreamingWrite RPC work. Subsequent\r\n * calls should wait until onHandshakeComplete was called.\r\n */\n\n\n PersistentWriteStream.prototype.writeHandshake = function () {\n assert(this.isOpen(), 'Writing handshake requires an opened stream');\n assert(!this.handshakeComplete_, 'Handshake already completed'); // 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\n var request = {};\n request.database = this.serializer.encodedDatabaseId;\n this.sendRequest(request);\n };\n /** Sends a group of mutations to the Firestore backend to apply. */\n\n\n PersistentWriteStream.prototype.writeMutations = function (mutations) {\n var _this = this;\n\n assert(this.isOpen(), 'Writing mutations requires an opened stream');\n assert(this.handshakeComplete_, 'Handshake must be complete before writing mutations');\n assert(this.lastStreamToken.length > 0, 'Trying to write mutation without a token');\n var request = {\n // Protos are typed with string, but we support UInt8Array on Node\n // tslint:disable-next-line:no-any\n streamToken: this.lastStreamToken,\n writes: mutations.map(function (mutation) {\n return _this.serializer.toMutation(mutation);\n })\n };\n this.sendRequest(request);\n };\n\n return PersistentWriteStream;\n}(PersistentStream);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Datastore is a wrapper around the external Google Cloud Datastore grpc API,\r\n * which provides an interface that is more convenient for the rest of the\r\n * client SDK architecture to consume.\r\n */\n\n\nvar Datastore =\n/** @class */\nfunction () {\n function Datastore(queue, connection, credentials, serializer) {\n this.queue = queue;\n this.connection = connection;\n this.credentials = credentials;\n this.serializer = serializer;\n }\n\n Datastore.prototype.newPersistentWriteStream = function (listener) {\n return new PersistentWriteStream(this.queue, this.connection, this.credentials, this.serializer, listener);\n };\n\n Datastore.prototype.newPersistentWatchStream = function (listener) {\n return new PersistentListenStream(this.queue, this.connection, this.credentials, this.serializer, listener);\n };\n\n Datastore.prototype.commit = function (mutations) {\n var _this = this;\n\n var params = {\n database: this.serializer.encodedDatabaseId,\n writes: mutations.map(function (m) {\n return _this.serializer.toMutation(m);\n })\n };\n return this.invokeRPC('Commit', params).then(function (response) {\n return _this.serializer.fromWriteResults(response.writeResults, response.commitTime);\n });\n };\n\n Datastore.prototype.lookup = function (keys) {\n var _this = this;\n\n var params = {\n database: this.serializer.encodedDatabaseId,\n documents: keys.map(function (k) {\n return _this.serializer.toName(k);\n })\n };\n return this.invokeStreamingRPC('BatchGetDocuments', params).then(function (response) {\n var docs = maybeDocumentMap();\n response.forEach(function (proto) {\n var doc = _this.serializer.fromMaybeDocument(proto);\n\n docs = docs.insert(doc.key, doc);\n });\n var result = [];\n keys.forEach(function (key) {\n var doc = docs.get(key);\n assert(!!doc, 'Missing entity in write response for ' + key);\n result.push(doc);\n });\n return result;\n });\n };\n /** Gets an auth token and invokes the provided RPC. */\n\n\n Datastore.prototype.invokeRPC = function (rpcName, request) {\n var _this = this;\n\n return this.credentials.getToken().then(function (token) {\n return _this.connection.invokeRPC(rpcName, request, token);\n }).catch(function (error) {\n if (error.code === Code.UNAUTHENTICATED) {\n _this.credentials.invalidateToken();\n }\n\n throw error;\n });\n };\n /** Gets an auth token and invokes the provided RPC with streamed results. */\n\n\n Datastore.prototype.invokeStreamingRPC = function (rpcName, request) {\n var _this = this;\n\n return this.credentials.getToken().then(function (token) {\n return _this.connection.invokeStreamingRPC(rpcName, request, token);\n }).catch(function (error) {\n if (error.code === Code.UNAUTHENTICATED) {\n _this.credentials.invalidateToken();\n }\n\n throw error;\n });\n };\n\n return Datastore;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Internal transaction object responsible for accumulating the mutations to\r\n * perform and the base versions for any documents read.\r\n */\n\n\nvar Transaction =\n/** @class */\nfunction () {\n function Transaction(datastore) {\n this.datastore = datastore; // The version of each document that was read during this transaction.\n\n this.readVersions = documentVersionMap();\n this.mutations = [];\n this.committed = false;\n }\n\n Transaction.prototype.recordVersion = function (doc) {\n var docVersion;\n\n if (doc instanceof Document) {\n docVersion = doc.version;\n } else if (doc instanceof NoDocument) {\n // For deleted docs, we must use baseVersion 0 when we overwrite them.\n docVersion = SnapshotVersion.forDeletedDoc();\n } else {\n throw fail('Document in a transaction was a ' + doc.constructor.name);\n }\n\n var existingVersion = this.readVersions.get(doc.key);\n\n if (existingVersion !== null) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.');\n }\n } else {\n this.readVersions = this.readVersions.insert(doc.key, docVersion);\n }\n };\n\n Transaction.prototype.lookup = function (keys) {\n var _this = this;\n\n if (this.committed) {\n return Promise.reject('Transaction has already completed.');\n }\n\n if (this.mutations.length > 0) {\n return Promise.reject('Transactions lookups are invalid after writes.');\n }\n\n return this.datastore.lookup(keys).then(function (docs) {\n docs.forEach(function (doc) {\n if (doc instanceof NoDocument || doc instanceof Document) {\n _this.recordVersion(doc);\n } else {\n fail('Document in a transaction was a ' + doc.constructor.name);\n }\n });\n return docs;\n });\n };\n\n Transaction.prototype.write = function (mutations) {\n if (this.committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Transaction has already completed.');\n }\n\n this.mutations = this.mutations.concat(mutations);\n };\n /**\r\n * Returns the version of this document when it was read in this transaction,\r\n * as a precondition, or no precondition if it was not read.\r\n */\n\n\n Transaction.prototype.precondition = function (key) {\n var version = this.readVersions.get(key);\n\n if (version) {\n return Precondition.updateTime(version);\n } else {\n return Precondition.NONE;\n }\n };\n /**\r\n * Returns the precondition for a document if the operation is an update.\r\n */\n\n\n Transaction.prototype.preconditionForUpdate = function (key) {\n var version = this.readVersions.get(key);\n\n if (version && version.isEqual(SnapshotVersion.forDeletedDoc())) {\n // The document doesn't exist, so fail the transaction.\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Can't update a document that doesn't exist.\");\n } else if (version) {\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n };\n\n Transaction.prototype.set = function (key, data) {\n this.write(data.toMutations(key, this.precondition(key)));\n };\n\n Transaction.prototype.update = function (key, data) {\n this.write(data.toMutations(key, this.preconditionForUpdate(key)));\n };\n\n Transaction.prototype.delete = function (key) {\n this.write([new DeleteMutation(key, this.precondition(key))]); // Since the delete will be applied before all following writes, we need to\n // ensure that the precondition for the next write will be exists: false.\n\n this.readVersions = this.readVersions.insert(key, SnapshotVersion.forDeletedDoc());\n };\n\n Transaction.prototype.commit = function () {\n var _this = this;\n\n var unwritten = this.readVersions; // For each mutation, note that the doc was written.\n\n this.mutations.forEach(function (mutation) {\n unwritten = unwritten.remove(mutation.key);\n });\n\n if (!unwritten.isEmpty()) {\n return Promise.reject(Error('Every document read in a transaction must also be written.'));\n }\n\n return this.datastore.commit(this.mutations).then(function () {\n _this.committed = true;\n });\n };\n\n return Transaction;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Describes the online state of the Firestore client. Note that this does not\r\n * indicate whether or not the remote store is trying to connect or not. This is\r\n * primarily used by the View / EventManager code to change their behavior while\r\n * offline (e.g. get() calls shouldn't wait for data from the server and\r\n * snapshot events should set metadata.isFromCache=true).\r\n */\n\n\nvar OnlineState;\n\n(function (OnlineState) {\n /**\r\n * The Firestore client is in an unknown online state. This means the client\r\n * is either not actively trying to establish a connection or it is currently\r\n * trying to establish a connection, but it has not succeeded or failed yet.\r\n * Higher-level components should not operate in offline mode.\r\n */\n OnlineState[OnlineState[\"Unknown\"] = 0] = \"Unknown\";\n /**\r\n * The client is connected and the connections are healthy. This state is\r\n * reached after a successful connection and there has been at least one\r\n * successful message received from the backends.\r\n */\n\n OnlineState[OnlineState[\"Online\"] = 1] = \"Online\";\n /**\r\n * The client is either trying to establish a connection but failing, or it\r\n * has been explicitly marked offline via a call to disableNetwork().\r\n * Higher-level components should operate in offline mode.\r\n */\n\n OnlineState[OnlineState[\"Offline\"] = 2] = \"Offline\";\n})(OnlineState || (OnlineState = {}));\n/** The source of an online state event. */\n\n\nvar OnlineStateSource;\n\n(function (OnlineStateSource) {\n OnlineStateSource[OnlineStateSource[\"RemoteStore\"] = 0] = \"RemoteStore\";\n OnlineStateSource[OnlineStateSource[\"SharedClientState\"] = 1] = \"SharedClientState\";\n})(OnlineStateSource || (OnlineStateSource = {}));\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$7 = 'OnlineStateTracker'; // 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.\n\nvar MAX_WATCH_STREAM_FAILURES = 1; // 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.\n\nvar ONLINE_STATE_TIMEOUT_MS = 10 * 1000;\n/**\r\n * A component used by the RemoteStore to track the OnlineState (that is,\r\n * whether or not the client as a whole should be considered to be online or\r\n * offline), implementing the appropriate heuristics.\r\n *\r\n * In particular, when the client is trying to connect to the backend, we\r\n * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for\r\n * a connection to succeed. If we have too many failures or the timeout elapses,\r\n * then we set the OnlineState to Offline, and the client will behave as if\r\n * it is offline (get()s will return cached data, etc.).\r\n */\n\nvar OnlineStateTracker =\n/** @class */\nfunction () {\n function OnlineStateTracker(asyncQueue, onlineStateHandler) {\n this.asyncQueue = asyncQueue;\n this.onlineStateHandler = onlineStateHandler;\n /** The current OnlineState. */\n\n this.state = OnlineState.Unknown;\n /**\r\n * A count of consecutive failures to open the stream. If it reaches the\r\n * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to\r\n * Offline.\r\n */\n\n this.watchStreamFailures = 0;\n /**\r\n * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we\r\n * transition from OnlineState.Unknown to OnlineState.Offline without waiting\r\n * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times).\r\n */\n\n this.onlineStateTimer = null;\n /**\r\n * Whether the client should log a warning message if it fails to connect to\r\n * the backend (initially true, cleared after a successful stream, or if we've\r\n * logged the message already).\r\n */\n\n this.shouldWarnClientIsOffline = true;\n }\n /**\r\n * Called by RemoteStore when a watch stream is started (including on each\r\n * backoff attempt).\r\n *\r\n * If this is the first attempt, it sets the OnlineState to Unknown and starts\r\n * the onlineStateTimer.\r\n */\n\n\n OnlineStateTracker.prototype.handleWatchStreamStart = function () {\n var _this = this;\n\n if (this.watchStreamFailures === 0) {\n this.setAndBroadcast(OnlineState.Unknown);\n assert(this.onlineStateTimer === null, \"onlineStateTimer shouldn't be started yet\");\n this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay(TimerId.OnlineStateTimeout, ONLINE_STATE_TIMEOUT_MS, function () {\n _this.onlineStateTimer = null;\n assert(_this.state === OnlineState.Unknown, 'Timer should be canceled if we transitioned to a different state.');\n\n _this.logClientOfflineWarningIfNecessary(\"Backend didn't respond within \" + ONLINE_STATE_TIMEOUT_MS / 1000 + \" \" + \"seconds.\");\n\n _this.setAndBroadcast(OnlineState.Offline); // NOTE: handleWatchStreamFailure() will continue to increment\n // watchStreamFailures even though we are already marked Offline,\n // but this is non-harmful.\n\n\n return Promise.resolve();\n });\n }\n };\n /**\r\n * Updates our OnlineState as appropriate after the watch stream reports a\r\n * failure. The first failure moves us to the 'Unknown' state. We then may\r\n * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we\r\n * actually transition to the 'Offline' state.\r\n */\n\n\n OnlineStateTracker.prototype.handleWatchStreamFailure = function (error$$1) {\n if (this.state === OnlineState.Online) {\n this.setAndBroadcast(OnlineState.Unknown); // To get to OnlineState.Online, set() must have been called which would\n // have reset our heuristics.\n\n assert(this.watchStreamFailures === 0, 'watchStreamFailures must be 0');\n assert(this.onlineStateTimer === null, 'onlineStateTimer must be null');\n } else {\n this.watchStreamFailures++;\n\n if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) {\n this.clearOnlineStateTimer();\n this.logClientOfflineWarningIfNecessary(\"Connection failed \" + MAX_WATCH_STREAM_FAILURES + \" \" + (\"times. Most recent error: \" + error$$1.toString()));\n this.setAndBroadcast(OnlineState.Offline);\n }\n }\n };\n /**\r\n * Explicitly sets the OnlineState to the specified state.\r\n *\r\n * Note that this resets our timers / failure counters, etc. used by our\r\n * Offline heuristics, so must not be used in place of\r\n * handleWatchStreamStart() and handleWatchStreamFailure().\r\n */\n\n\n OnlineStateTracker.prototype.set = function (newState) {\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 OnlineStateTracker.prototype.setAndBroadcast = function (newState) {\n if (newState !== this.state) {\n this.state = newState;\n this.onlineStateHandler(newState);\n }\n };\n\n OnlineStateTracker.prototype.logClientOfflineWarningIfNecessary = function (details) {\n var message = \"Could not reach Cloud Firestore backend. \" + details + \"\\n\" + \"This typically indicates that your device does not have a healthy \" + \"Internet connection at the moment. The client will operate in offline \" + \"mode until it is able to successfully connect to the backend.\";\n\n if (this.shouldWarnClientIsOffline) {\n error(message);\n this.shouldWarnClientIsOffline = false;\n } else {\n debug(LOG_TAG$7, message);\n }\n };\n\n OnlineStateTracker.prototype.clearOnlineStateTimer = function () {\n if (this.onlineStateTimer !== null) {\n this.onlineStateTimer.cancel();\n this.onlineStateTimer = null;\n }\n };\n\n return OnlineStateTracker;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$8 = 'RemoteStore'; // TODO(b/35853402): Negotiate this with the stream.\n\nvar MAX_PENDING_WRITES = 10;\n/**\r\n * RemoteStore - An interface to remotely stored data, basically providing a\r\n * wrapper around the Datastore that is more reliable for the rest of the\r\n * system.\r\n *\r\n * RemoteStore is responsible for maintaining the connection to the server.\r\n * - maintaining a list of active listens.\r\n * - reconnecting when the connection is dropped.\r\n * - resuming all the active listens on reconnect.\r\n *\r\n * RemoteStore handles all incoming events from the Datastore.\r\n * - listening to the watch stream and repackaging the events as RemoteEvents\r\n * - notifying SyncEngine of any changes to the active listens.\r\n *\r\n * RemoteStore takes writes from other components and handles them reliably.\r\n * - pulling pending mutations from LocalStore and sending them to Datastore.\r\n * - retrying mutations that failed because of network problems.\r\n * - acking mutations to the SyncEngine once they are accepted or rejected.\r\n */\n\nvar RemoteStore =\n/** @class */\nfunction () {\n function RemoteStore(\n /**\r\n * The local store, used to fill the write pipeline with outbound mutations.\r\n */\n localStore,\n /** The client-side proxy for interacting with the backend. */\n datastore, asyncQueue, onlineStateHandler) {\n this.localStore = localStore;\n this.datastore = datastore;\n /**\r\n * A list of up to MAX_PENDING_WRITES writes that we have fetched from the\r\n * LocalStore via fillWritePipeline() and have or will send to the write\r\n * stream.\r\n *\r\n * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or\r\n * restart the write stream. When the stream is established the writes in the\r\n * pipeline will be sent in order.\r\n *\r\n * Writes remain in writePipeline until they are acknowledged by the backend\r\n * and thus will automatically be re-sent if the stream is interrupted /\r\n * restarted before they're acknowledged.\r\n *\r\n * Write responses from the backend are linked to their originating request\r\n * purely based on order, and so we can just shift() writes from the front of\r\n * the writePipeline as we receive responses.\r\n */\n\n this.writePipeline = [];\n /**\r\n * A mapping of watched targets that the client cares about tracking and the\r\n * user has explicitly called a 'listen' for this target.\r\n *\r\n * These targets may or may not have been sent to or acknowledged by the\r\n * server. On re-establishing the listen stream, these targets should be sent\r\n * to the server. The targets removed with unlistens are removed eagerly\r\n * without waiting for confirmation from the listen stream.\r\n */\n\n this.listenTargets = {};\n this.watchChangeAggregator = null;\n /**\r\n * Set to true by enableNetwork() and false by disableNetwork() and indicates\r\n * the user-preferred network state.\r\n */\n\n this.networkEnabled = false;\n this.isPrimary = false;\n this.onlineStateTracker = new OnlineStateTracker(asyncQueue, onlineStateHandler); // Create streams (but note they're not started yet).\n\n this.watchStream = this.datastore.newPersistentWatchStream({\n onOpen: this.onWatchStreamOpen.bind(this),\n onClose: this.onWatchStreamClose.bind(this),\n onWatchChange: this.onWatchStreamChange.bind(this)\n });\n this.writeStream = this.datastore.newPersistentWriteStream({\n onOpen: this.onWriteStreamOpen.bind(this),\n onClose: this.onWriteStreamClose.bind(this),\n onHandshakeComplete: this.onWriteHandshakeComplete.bind(this),\n onMutationResult: this.onMutationResult.bind(this)\n });\n }\n /**\r\n * Starts up the remote store, creating streams, restoring state from\r\n * LocalStore, etc.\r\n */\n\n\n RemoteStore.prototype.start = function () {\n return this.enableNetwork();\n };\n /** Re-enables the network. Idempotent. */\n\n\n RemoteStore.prototype.enableNetwork = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _a;\n\n return tslib_1.__generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n this.networkEnabled = true;\n if (!this.canUseNetwork()) return [3\n /*break*/\n , 3];\n _a = this.writeStream;\n return [4\n /*yield*/\n , this.localStore.getLastStreamToken()];\n\n case 1:\n _a.lastStreamToken = _b.sent();\n\n if (this.shouldStartWatchStream()) {\n this.startWatchStream();\n } else {\n this.onlineStateTracker.set(OnlineState.Unknown);\n } // This will start the write stream if necessary.\n\n\n return [4\n /*yield*/\n , this.fillWritePipeline()];\n\n case 2:\n // This will start the write stream if necessary.\n _b.sent();\n\n _b.label = 3;\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Temporarily disables the network. The network can be re-enabled using\r\n * enableNetwork().\r\n */\n\n\n RemoteStore.prototype.disableNetwork = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.networkEnabled = false;\n return [4\n /*yield*/\n , this.disableNetworkInternal()];\n\n case 1:\n _a.sent(); // Set the OnlineState to Offline so get()s return from cache, etc.\n\n\n this.onlineStateTracker.set(OnlineState.Offline);\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n RemoteStore.prototype.disableNetworkInternal = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , this.writeStream.stop()];\n\n case 1:\n _a.sent();\n\n return [4\n /*yield*/\n , this.watchStream.stop()];\n\n case 2:\n _a.sent();\n\n if (this.writePipeline.length > 0) {\n debug(LOG_TAG$8, \"Stopping write stream with \" + this.writePipeline.length + \" pending writes\");\n this.writePipeline = [];\n }\n\n this.cleanUpWatchStreamState();\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n RemoteStore.prototype.shutdown = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n debug(LOG_TAG$8, 'RemoteStore shutting down.');\n this.networkEnabled = false;\n return [4\n /*yield*/\n , this.disableNetworkInternal()];\n\n case 1:\n _a.sent(); // Set the OnlineState to Unknown (rather than Offline) to avoid potentially\n // triggering spurious listener events with cached data, etc.\n\n\n this.onlineStateTracker.set(OnlineState.Unknown);\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /** Starts new listen for the given query. Uses resume token if provided */\n\n\n RemoteStore.prototype.listen = function (queryData) {\n assert(!contains(this.listenTargets, queryData.targetId), 'listen called with duplicate targetId!'); // Mark this as something the client is currently listening for.\n\n this.listenTargets[queryData.targetId] = queryData;\n\n if (this.shouldStartWatchStream()) {\n // The listen will be sent in onWatchStreamOpen\n this.startWatchStream();\n } else if (this.watchStream.isOpen()) {\n this.sendWatchRequest(queryData);\n }\n };\n /** Removes the listen from server */\n\n\n RemoteStore.prototype.unlisten = function (targetId) {\n assert(contains(this.listenTargets, targetId), 'unlisten called without assigned target ID!');\n delete this.listenTargets[targetId];\n\n if (this.watchStream.isOpen()) {\n this.sendUnwatchRequest(targetId);\n }\n\n if (isEmpty(this.listenTargets)) {\n if (this.watchStream.isOpen()) {\n this.watchStream.markIdle();\n } else if (this.canUseNetwork()) {\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 this.onlineStateTracker.set(OnlineState.Unknown);\n }\n }\n };\n /** {@link TargetMetadataProvider.getQueryDataForTarget} */\n\n\n RemoteStore.prototype.getQueryDataForTarget = function (targetId) {\n return this.listenTargets[targetId] || null;\n };\n /** {@link TargetMetadataProvider.getRemoteKeysForTarget} */\n\n\n RemoteStore.prototype.getRemoteKeysForTarget = function (targetId) {\n return this.syncEngine.getRemoteKeysForTarget(targetId);\n };\n /**\r\n * We need to increment the the expected number of pending responses we're due\r\n * from watch so we wait for the ack to process any messages from this target.\r\n */\n\n\n RemoteStore.prototype.sendWatchRequest = function (queryData) {\n this.watchChangeAggregator.recordPendingTargetRequest(queryData.targetId);\n this.watchStream.watch(queryData);\n };\n /**\r\n * We need to increment the expected number of pending responses we're due\r\n * from watch so we wait for the removal on the server before we process any\r\n * messages from this target.\r\n */\n\n\n RemoteStore.prototype.sendUnwatchRequest = function (targetId) {\n this.watchChangeAggregator.recordPendingTargetRequest(targetId);\n this.watchStream.unwatch(targetId);\n };\n\n RemoteStore.prototype.startWatchStream = function () {\n assert(this.shouldStartWatchStream(), 'startWatchStream() called when shouldStartWatchStream() is false.');\n this.watchChangeAggregator = new WatchChangeAggregator(this);\n this.watchStream.start();\n this.onlineStateTracker.handleWatchStreamStart();\n };\n /**\r\n * Returns whether the watch stream should be started because it's necessary\r\n * and has not yet been started.\r\n */\n\n\n RemoteStore.prototype.shouldStartWatchStream = function () {\n return this.canUseNetwork() && !this.watchStream.isStarted() && !isEmpty(this.listenTargets);\n };\n\n RemoteStore.prototype.canUseNetwork = function () {\n return this.isPrimary && this.networkEnabled;\n };\n\n RemoteStore.prototype.cleanUpWatchStreamState = function () {\n this.watchChangeAggregator = null;\n };\n\n RemoteStore.prototype.onWatchStreamOpen = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n return tslib_1.__generator(this, function (_a) {\n forEachNumber(this.listenTargets, function (targetId, queryData) {\n _this.sendWatchRequest(queryData);\n });\n return [2\n /*return*/\n ];\n });\n });\n };\n\n RemoteStore.prototype.onWatchStreamClose = function (error$$1) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (error$$1 === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n assert(!this.shouldStartWatchStream(), 'Watch stream was stopped gracefully while still needed.');\n }\n\n this.cleanUpWatchStreamState(); // If we still need the watch stream, retry the connection.\n\n if (this.shouldStartWatchStream()) {\n this.onlineStateTracker.handleWatchStreamFailure(error$$1);\n this.startWatchStream();\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 this.onlineStateTracker.set(OnlineState.Unknown);\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n RemoteStore.prototype.onWatchStreamChange = function (watchChange, snapshotVersion) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var lastRemoteSnapshotVersion;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n // Mark the client as online since we got a message from the server\n this.onlineStateTracker.set(OnlineState.Online);\n\n if (watchChange instanceof WatchTargetChange && watchChange.state === WatchTargetChangeState.Removed && watchChange.cause) {\n // There was an error on a target, don't wait for a consistent snapshot\n // to raise events\n return [2\n /*return*/\n , this.handleTargetError(watchChange)];\n }\n\n if (watchChange instanceof DocumentWatchChange) {\n this.watchChangeAggregator.handleDocumentChange(watchChange);\n } else if (watchChange instanceof ExistenceFilterChange) {\n this.watchChangeAggregator.handleExistenceFilter(watchChange);\n } else {\n assert(watchChange instanceof WatchTargetChange, 'Expected watchChange to be an instance of WatchTargetChange');\n this.watchChangeAggregator.handleTargetChange(watchChange);\n }\n\n if (!!snapshotVersion.isEqual(SnapshotVersion.MIN)) return [3\n /*break*/\n , 3];\n return [4\n /*yield*/\n , this.localStore.getLastRemoteSnapshotVersion()];\n\n case 1:\n lastRemoteSnapshotVersion = _a.sent();\n if (!(snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0)) return [3\n /*break*/\n , 3]; // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.MIN.\n\n return [4\n /*yield*/\n , this.raiseWatchSnapshot(snapshotVersion)];\n\n case 2:\n // We have received a target change with a global snapshot if the snapshot\n // version is not equal to SnapshotVersion.MIN.\n _a.sent();\n\n _a.label = 3;\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Takes a batch of changes from the Datastore, repackages them as a\r\n * RemoteEvent, and passes that on to the listener, which is typically the\r\n * SyncEngine.\r\n */\n\n\n RemoteStore.prototype.raiseWatchSnapshot = function (snapshotVersion) {\n var _this = this;\n\n assert(!snapshotVersion.isEqual(SnapshotVersion.MIN), \"Can't raise event for unknown SnapshotVersion\");\n var remoteEvent = this.watchChangeAggregator.createRemoteEvent(snapshotVersion); // Update in-memory resume tokens. LocalStore will update the\n // persistent view of these when applying the completed RemoteEvent.\n\n forEachNumber(remoteEvent.targetChanges, function (targetId, change) {\n if (change.resumeToken.length > 0) {\n var queryData = _this.listenTargets[targetId]; // A watched target might have been removed already.\n\n if (queryData) {\n _this.listenTargets[targetId] = queryData.copy({\n resumeToken: change.resumeToken,\n snapshotVersion: snapshotVersion\n });\n }\n }\n }); // Re-establish listens for the targets that have been invalidated by\n // existence filter mismatches.\n\n remoteEvent.targetMismatches.forEach(function (targetId) {\n var queryData = _this.listenTargets[targetId];\n\n if (!queryData) {\n // A watched target might have been removed already.\n return;\n } // Clear the resume token for the query, since we're in a known mismatch\n // state.\n\n\n _this.listenTargets[targetId] = queryData.copy({\n resumeToken: emptyByteString()\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\n _this.sendUnwatchRequest(targetId); // Mark the query 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\n\n var requestQueryData = new QueryData(queryData.query, targetId, QueryPurpose.ExistenceFilterMismatch, queryData.sequenceNumber);\n\n _this.sendWatchRequest(requestQueryData);\n }); // Finally raise remote event\n\n return this.syncEngine.applyRemoteEvent(remoteEvent);\n };\n /** Handles an error on a target */\n\n\n RemoteStore.prototype.handleTargetError = function (watchChange) {\n var _this = this;\n\n assert(!!watchChange.cause, 'Handling target error without a cause');\n var error$$1 = watchChange.cause;\n var promiseChain = Promise.resolve();\n watchChange.targetIds.forEach(function (targetId) {\n promiseChain = promiseChain.then(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n // A watched target might have been removed already.\n if (contains(this.listenTargets, targetId)) {\n delete this.listenTargets[targetId];\n this.watchChangeAggregator.removeTarget(targetId);\n return [2\n /*return*/\n , this.syncEngine.rejectListen(targetId, error$$1)];\n }\n\n return [2\n /*return*/\n ];\n });\n });\n });\n });\n return promiseChain;\n };\n /**\r\n * Attempts to fill our write pipeline with writes from the LocalStore.\r\n *\r\n * Called internally to bootstrap or refill the write pipeline and by\r\n * SyncEngine whenever there are new mutations to process.\r\n *\r\n * Starts the write stream if necessary.\r\n */\n\n\n RemoteStore.prototype.fillWritePipeline = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var lastBatchIdRetrieved, batch;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!this.canAddToWritePipeline()) return [3\n /*break*/\n , 4];\n lastBatchIdRetrieved = this.writePipeline.length > 0 ? this.writePipeline[this.writePipeline.length - 1].batchId : BATCHID_UNKNOWN;\n return [4\n /*yield*/\n , this.localStore.nextMutationBatch(lastBatchIdRetrieved)];\n\n case 1:\n batch = _a.sent();\n if (!(batch === null)) return [3\n /*break*/\n , 2];\n\n if (this.writePipeline.length === 0) {\n this.writeStream.markIdle();\n }\n\n return [3\n /*break*/\n , 4];\n\n case 2:\n this.addToWritePipeline(batch);\n return [4\n /*yield*/\n , this.fillWritePipeline()];\n\n case 3:\n _a.sent();\n\n _a.label = 4;\n\n case 4:\n if (this.shouldStartWriteStream()) {\n this.startWriteStream();\n }\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Returns true if we can add to the write pipeline (i.e. the network is\r\n * enabled and the write pipeline is not full).\r\n */\n\n\n RemoteStore.prototype.canAddToWritePipeline = function () {\n return this.canUseNetwork() && this.writePipeline.length < MAX_PENDING_WRITES;\n }; // For testing\n\n\n RemoteStore.prototype.outstandingWrites = function () {\n return this.writePipeline.length;\n };\n /**\r\n * Queues additional writes to be sent to the write stream, sending them\r\n * immediately if the write stream is established.\r\n */\n\n\n RemoteStore.prototype.addToWritePipeline = function (batch) {\n assert(this.canAddToWritePipeline(), 'addToWritePipeline called when pipeline is full');\n this.writePipeline.push(batch);\n\n if (this.writeStream.isOpen() && this.writeStream.handshakeComplete) {\n this.writeStream.writeMutations(batch.mutations);\n }\n };\n\n RemoteStore.prototype.shouldStartWriteStream = function () {\n return this.canUseNetwork() && !this.writeStream.isStarted() && this.writePipeline.length > 0;\n };\n\n RemoteStore.prototype.startWriteStream = function () {\n assert(this.shouldStartWriteStream(), 'startWriteStream() called when shouldStartWriteStream() is false.');\n this.writeStream.start();\n };\n\n RemoteStore.prototype.onWriteStreamOpen = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.writeStream.writeHandshake();\n return [2\n /*return*/\n ];\n });\n });\n };\n\n RemoteStore.prototype.onWriteHandshakeComplete = function () {\n var _this = this; // Record the stream token.\n\n\n return this.localStore.setLastStreamToken(this.writeStream.lastStreamToken).then(function () {\n // Send the write pipeline now that the stream is established.\n for (var _i = 0, _a = _this.writePipeline; _i < _a.length; _i++) {\n var batch = _a[_i];\n\n _this.writeStream.writeMutations(batch.mutations);\n }\n }).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n });\n };\n /**\r\n * Verifies the error thrown by an LocalStore operation. If a LocalStore\r\n * operation fails because the primary lease has been taken by another client,\r\n * we ignore the error. All other errors are re-thrown.\r\n *\r\n * @param err An error returned by a LocalStore operation.\r\n * @return A Promise that resolves after we recovered, or the original error.\r\n */\n\n\n RemoteStore.prototype.ignoreIfPrimaryLeaseLoss = function (err) {\n if (isPrimaryLeaseLostError(err)) {\n debug(LOG_TAG$8, 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n };\n\n RemoteStore.prototype.onMutationResult = function (commitVersion, results) {\n var _this = this; // This is a response to a write containing mutations and should be\n // correlated to the first write in our write pipeline.\n\n\n assert(this.writePipeline.length > 0, 'Got result for empty write pipeline');\n var batch = this.writePipeline.shift();\n var success = MutationBatchResult.from(batch, commitVersion, results, this.writeStream.lastStreamToken);\n return this.syncEngine.applySuccessfulWrite(success).then(function () {\n // It's possible that with the completion of this mutation another\n // slot has freed up.\n return _this.fillWritePipeline();\n });\n };\n\n RemoteStore.prototype.onWriteStreamClose = function (error$$1) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var errorHandling;\n return tslib_1.__generator(this, function (_a) {\n if (error$$1 === undefined) {\n // Graceful stop (due to stop() or idle timeout). Make sure that's\n // desirable.\n assert(!this.shouldStartWriteStream(), 'Write stream was stopped gracefully while still needed.');\n } // If the write stream closed due to an error, invoke the error callbacks if\n // there are pending writes.\n\n\n if (error$$1 && this.writePipeline.length > 0) {\n errorHandling = void 0;\n\n if (this.writeStream.handshakeComplete) {\n // This error affects the actual write.\n errorHandling = this.handleWriteError(error$$1);\n } else {\n // If there was an error before the handshake has finished, it's\n // possible that the server is unable to process the stream token\n // we're sending. (Perhaps it's too old?)\n errorHandling = this.handleHandshakeError(error$$1);\n }\n\n return [2\n /*return*/\n , errorHandling.then(function () {\n // The write stream might have been started by refilling the write\n // pipeline for failed writes\n if (_this.shouldStartWriteStream()) {\n _this.startWriteStream();\n }\n })];\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n RemoteStore.prototype.handleHandshakeError = function (error$$1) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n return tslib_1.__generator(this, function (_a) {\n // Reset the token if it's a permanent error or the error code is\n // ABORTED, signaling the write stream is no longer valid.\n if (isPermanentError(error$$1.code) || error$$1.code === Code.ABORTED) {\n debug(LOG_TAG$8, 'RemoteStore error before completed handshake; resetting stream token: ', this.writeStream.lastStreamToken);\n this.writeStream.lastStreamToken = emptyByteString();\n return [2\n /*return*/\n , this.localStore.setLastStreamToken(emptyByteString()).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n })];\n } else {// Some other error, don't reset stream token. Our stream logic will\n // just retry with exponential backoff.\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n RemoteStore.prototype.handleWriteError = function (error$$1) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var batch;\n return tslib_1.__generator(this, function (_a) {\n if (isPermanentError(error$$1.code)) {\n batch = this.writePipeline.shift(); // 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\n this.writeStream.inhibitBackoff();\n return [2\n /*return*/\n , this.syncEngine.rejectFailedWrite(batch.batchId, error$$1).then(function () {\n // It's possible that with the completion of this mutation\n // another slot has freed up.\n return _this.fillWritePipeline();\n })];\n } else {// Transient error, just let the retry logic kick in.\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n RemoteStore.prototype.createTransaction = function () {\n return new Transaction(this.datastore);\n };\n\n RemoteStore.prototype.handleCredentialChange = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!this.canUseNetwork()) return [3\n /*break*/\n , 3]; // Tear down and re-create our network streams. This will ensure we get a fresh auth token\n // for the new user and re-fill the write pipeline with new mutations from the LocalStore\n // (since mutations are per-user).\n\n debug(LOG_TAG$8, 'RemoteStore restarting streams for new credential');\n this.networkEnabled = false;\n return [4\n /*yield*/\n , this.disableNetworkInternal()];\n\n case 1:\n _a.sent();\n\n this.onlineStateTracker.set(OnlineState.Unknown);\n return [4\n /*yield*/\n , this.enableNetwork()];\n\n case 2:\n _a.sent();\n\n _a.label = 3;\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Toggles the network state when the client gains or loses its primary lease.\r\n */\n\n\n RemoteStore.prototype.applyPrimaryState = function (isPrimary) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.isPrimary = isPrimary;\n if (!(isPrimary && this.networkEnabled)) return [3\n /*break*/\n , 2];\n return [4\n /*yield*/\n , this.enableNetwork()];\n\n case 1:\n _a.sent();\n\n return [3\n /*break*/\n , 4];\n\n case 2:\n if (!!isPrimary) return [3\n /*break*/\n , 4];\n return [4\n /*yield*/\n , this.disableNetworkInternal()];\n\n case 3:\n _a.sent();\n\n this.onlineStateTracker.set(OnlineState.Unknown);\n _a.label = 4;\n\n case 4:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n return RemoteStore;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Holds the listeners and the last received ViewSnapshot for a query being\r\n * tracked by EventManager.\r\n */\n\n\nvar QueryListenersInfo =\n/** @class */\nfunction () {\n function QueryListenersInfo() {\n this.listeners = [];\n }\n\n return QueryListenersInfo;\n}();\n/**\r\n * EventManager is responsible for mapping queries to query event emitters.\r\n * It handles \"fan-out\". -- Identical queries will re-use the same watch on the\r\n * backend.\r\n */\n\n\nvar EventManager =\n/** @class */\nfunction () {\n function EventManager(syncEngine) {\n this.syncEngine = syncEngine;\n this.queries = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.onlineState = OnlineState.Unknown;\n this.syncEngine.subscribe(this);\n }\n\n EventManager.prototype.listen = function (listener) {\n var query = listener.query;\n var firstListen = false;\n var queryInfo = this.queries.get(query);\n\n if (!queryInfo) {\n firstListen = true;\n queryInfo = new QueryListenersInfo();\n this.queries.set(query, queryInfo);\n }\n\n queryInfo.listeners.push(listener);\n listener.applyOnlineStateChange(this.onlineState);\n if (queryInfo.viewSnap) listener.onViewSnapshot(queryInfo.viewSnap);\n\n if (firstListen) {\n return this.syncEngine.listen(query).then(function (targetId) {\n queryInfo.targetId = targetId;\n return targetId;\n });\n } else {\n return Promise.resolve(queryInfo.targetId);\n }\n };\n\n EventManager.prototype.unlisten = function (listener) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var query, lastListen, queryInfo, i;\n return tslib_1.__generator(this, function (_a) {\n query = listener.query;\n lastListen = false;\n queryInfo = this.queries.get(query);\n\n if (queryInfo) {\n i = queryInfo.listeners.indexOf(listener);\n\n if (i >= 0) {\n queryInfo.listeners.splice(i, 1);\n lastListen = queryInfo.listeners.length === 0;\n }\n }\n\n if (lastListen) {\n this.queries.delete(query);\n return [2\n /*return*/\n , this.syncEngine.unlisten(query)];\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n EventManager.prototype.onWatchChange = function (viewSnaps) {\n for (var _i = 0, viewSnaps_1 = viewSnaps; _i < viewSnaps_1.length; _i++) {\n var viewSnap = viewSnaps_1[_i];\n var query = viewSnap.query;\n var queryInfo = this.queries.get(query);\n\n if (queryInfo) {\n for (var _a = 0, _b = queryInfo.listeners; _a < _b.length; _a++) {\n var listener = _b[_a];\n listener.onViewSnapshot(viewSnap);\n }\n\n queryInfo.viewSnap = viewSnap;\n }\n }\n };\n\n EventManager.prototype.onWatchError = function (query, error) {\n var queryInfo = this.queries.get(query);\n\n if (queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.onError(error);\n }\n } // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten()\n // after an error.\n\n\n this.queries.delete(query);\n };\n\n EventManager.prototype.onOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n this.queries.forEach(function (_, queryInfo) {\n for (var _i = 0, _a = queryInfo.listeners; _i < _a.length; _i++) {\n var listener = _a[_i];\n listener.applyOnlineStateChange(onlineState);\n }\n });\n };\n\n return EventManager;\n}();\n/**\r\n * QueryListener takes a series of internal view snapshots and determines\r\n * when to raise the event.\r\n *\r\n * It uses an Observer to dispatch events.\r\n */\n\n\nvar QueryListener =\n/** @class */\nfunction () {\n function QueryListener(query, queryObserver, options) {\n this.query = query;\n this.queryObserver = queryObserver;\n /**\r\n * Initial snapshots (e.g. from cache) may not be propagated to the wrapped\r\n * observer. This flag is set to true once we've actually raised an event.\r\n */\n\n this.raisedInitialEvent = false;\n this.onlineState = OnlineState.Unknown;\n this.options = options || {};\n }\n\n QueryListener.prototype.onViewSnapshot = function (snap) {\n assert(snap.docChanges.length > 0 || snap.syncStateChanged, 'We got a new snapshot with no changes?');\n\n if (!this.options.includeMetadataChanges) {\n // Remove the metadata only changes.\n var docChanges = [];\n\n for (var _i = 0, _a = snap.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n\n if (docChange.type !== ChangeType.Metadata) {\n docChanges.push(docChange);\n }\n }\n\n snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.mutatedKeys, snap.fromCache, snap.syncStateChanged,\n /* excludesMetadataChanges= */\n true);\n }\n\n if (!this.raisedInitialEvent) {\n if (this.shouldRaiseInitialEvent(snap, this.onlineState)) {\n this.raiseInitialEvent(snap);\n }\n } else if (this.shouldRaiseEvent(snap)) {\n this.queryObserver.next(snap);\n }\n\n this.snap = snap;\n };\n\n QueryListener.prototype.onError = function (error) {\n this.queryObserver.error(error);\n };\n\n QueryListener.prototype.applyOnlineStateChange = function (onlineState) {\n this.onlineState = onlineState;\n\n if (this.snap && !this.raisedInitialEvent && this.shouldRaiseInitialEvent(this.snap, onlineState)) {\n this.raiseInitialEvent(this.snap);\n }\n };\n\n QueryListener.prototype.shouldRaiseInitialEvent = function (snap, onlineState) {\n assert(!this.raisedInitialEvent, 'Determining whether to raise first event but already had first event'); // Always raise the first event when we're synced\n\n if (!snap.fromCache) {\n return true;\n } // NOTE: We consider OnlineState.Unknown as online (it should become Offline\n // or Online if we wait long enough).\n\n\n var maybeOnline = onlineState !== OnlineState.Offline; // Don't raise the event if we're online, aren't synced yet (checked\n // above) and are waiting for a sync.\n\n if (this.options.waitForSyncWhenOnline && maybeOnline) {\n assert(snap.fromCache, 'Waiting for sync, but snapshot is not from cache');\n return false;\n } // Raise data from cache if we have any documents or we are offline\n\n\n return !snap.docs.isEmpty() || onlineState === OnlineState.Offline;\n };\n\n QueryListener.prototype.shouldRaiseEvent = function (snap) {\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 var hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites;\n\n if (snap.syncStateChanged || hasPendingWritesChanged) {\n return this.options.includeMetadataChanges === true;\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\n\n return false;\n };\n\n QueryListener.prototype.raiseInitialEvent = function (snap) {\n assert(!this.raisedInitialEvent, 'Trying to raise initial events for second time');\n snap = ViewSnapshot.fromInitialDocuments(snap.query, snap.docs, snap.mutatedKeys, snap.fromCache);\n this.raisedInitialEvent = true;\n this.queryObserver.next(snap);\n };\n\n return QueryListener;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * A set of changes to what documents are currently in view and out of view for\r\n * a given query. These changes are sent to the LocalStore by the View (via\r\n * the SyncEngine) and are used to pin / unpin documents as appropriate.\r\n */\n\n\nvar LocalViewChanges =\n/** @class */\nfunction () {\n function LocalViewChanges(targetId, addedKeys, removedKeys) {\n this.targetId = targetId;\n this.addedKeys = addedKeys;\n this.removedKeys = removedKeys;\n }\n\n LocalViewChanges.fromSnapshot = function (targetId, viewSnapshot) {\n var addedKeys = documentKeySet();\n var removedKeys = documentKeySet();\n\n for (var _i = 0, _a = viewSnapshot.docChanges; _i < _a.length; _i++) {\n var docChange = _a[_i];\n\n switch (docChange.type) {\n case ChangeType.Added:\n addedKeys = addedKeys.add(docChange.doc.key);\n break;\n\n case ChangeType.Removed:\n removedKeys = removedKeys.add(docChange.doc.key);\n break;\n\n default: // do nothing\n\n }\n }\n\n return new LocalViewChanges(targetId, addedKeys, removedKeys);\n };\n\n return LocalViewChanges;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar AddedLimboDocument =\n/** @class */\nfunction () {\n function AddedLimboDocument(key) {\n this.key = key;\n }\n\n return AddedLimboDocument;\n}();\n\nvar RemovedLimboDocument =\n/** @class */\nfunction () {\n function RemovedLimboDocument(key) {\n this.key = key;\n }\n\n return RemovedLimboDocument;\n}();\n/**\r\n * View is responsible for computing the final merged truth of what docs are in\r\n * a query. It gets notified of local and remote changes to docs, and applies\r\n * the query filters and limits to determine the most correct possible results.\r\n */\n\n\nvar View =\n/** @class */\nfunction () {\n function View(query,\n /** Documents included in the remote target */\n _syncedDocuments) {\n this.query = query;\n this._syncedDocuments = _syncedDocuments;\n this.syncState = null;\n /**\r\n * A flag whether the view is current with the backend. A view is considered\r\n * current after it has seen the current flag from the backend and did not\r\n * lose consistency within the watch stream (e.g. because of an existence\r\n * filter mismatch).\r\n */\n\n this.current = false;\n /** Documents in the view but not in the remote target */\n\n this.limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n\n this.mutatedKeys = documentKeySet();\n this.documentSet = new DocumentSet(query.docComparator.bind(query));\n }\n\n Object.defineProperty(View.prototype, \"syncedDocuments\", {\n /**\r\n * The set of remote documents that the server has told us belongs to the target associated with\r\n * this view.\r\n */\n get: function get() {\n return this._syncedDocuments;\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Iterates over a set of doc changes, applies the query limit, and computes\r\n * what the new results should be, what the changes were, and whether we may\r\n * need to go back to the local cache for more results. Does not make any\r\n * changes to the view.\r\n * @param docChanges The doc changes to apply to this view.\r\n * @param previousChanges If this is being called with a refill, then start\r\n * with this set of docs and changes instead of the current view.\r\n * @return a new set of docs, changes, and refill flag.\r\n */\n\n View.prototype.computeDocChanges = function (docChanges, previousChanges) {\n var _this = this;\n\n var changeSet = previousChanges ? previousChanges.changeSet : new DocumentChangeSet();\n var oldDocumentSet = previousChanges ? previousChanges.documentSet : this.documentSet;\n var newMutatedKeys = previousChanges ? previousChanges.mutatedKeys : this.mutatedKeys;\n var newDocumentSet = oldDocumentSet;\n var needsRefill = false; // 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\n var lastDocInLimit = this.query.hasLimit() && oldDocumentSet.size === this.query.limit ? oldDocumentSet.last() : null;\n docChanges.inorderTraversal(function (key, newMaybeDoc) {\n var oldDoc = oldDocumentSet.get(key);\n var newDoc = newMaybeDoc instanceof Document ? newMaybeDoc : null;\n\n if (newDoc) {\n assert(key.isEqual(newDoc.key), 'Mismatching keys found in document changes: ' + key + ' != ' + newDoc.key);\n newDoc = _this.query.matches(newDoc) ? newDoc : null;\n }\n\n var oldDocHadPendingMutations = oldDoc ? _this.mutatedKeys.has(oldDoc.key) : false;\n var newDocHasPendingMutations = newDoc ? newDoc.hasLocalMutations || // 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 : false;\n var changeApplied = false; // Calculate change\n\n if (oldDoc && newDoc) {\n var docsEqual = oldDoc.data.isEqual(newDoc.data);\n\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 (lastDocInLimit && _this.query.docComparator(newDoc, lastDocInLimit) > 0) {\n // This doc moved from inside the limit to after the limit.\n // That means there may be some doc in the local cache that's\n // actually less than this one.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({\n type: ChangeType.Metadata,\n doc: newDoc\n });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({\n type: ChangeType.Added,\n doc: newDoc\n });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({\n type: ChangeType.Removed,\n doc: oldDoc\n });\n changeApplied = true;\n\n if (lastDocInLimit) {\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\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 if (this.query.hasLimit()) {\n while (newDocumentSet.size > this.query.limit) {\n var oldDoc = newDocumentSet.last();\n newDocumentSet = newDocumentSet.delete(oldDoc.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc.key);\n changeSet.track({\n type: ChangeType.Removed,\n doc: oldDoc\n });\n }\n }\n\n assert(!needsRefill || !previousChanges, 'View was refilled using docs that themselves needed refilling.');\n return {\n documentSet: newDocumentSet,\n changeSet: changeSet,\n needsRefill: needsRefill,\n mutatedKeys: newMutatedKeys\n };\n };\n\n View.prototype.shouldWaitForSyncedDocument = function (oldDoc, newDoc) {\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 oldDoc.hasLocalMutations && newDoc.hasCommittedMutations && !newDoc.hasLocalMutations;\n };\n /**\r\n * Updates the view with the given ViewDocumentChanges and optionally updates\r\n * limbo docs and sync state from the provided target change.\r\n * @param docChanges The set of changes to make to the view's docs.\r\n * @param updateLimboDocuments Whether to update limbo documents based on this\r\n * change.\r\n * @param targetChange A target change to apply for computing limbo docs and\r\n * sync state.\r\n * @return A new ViewChange with the given docs, changes, and sync state.\r\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n\n\n View.prototype.applyChanges = function (docChanges, updateLimboDocuments, targetChange) {\n var _this = this;\n\n assert(!docChanges.needsRefill, 'Cannot apply changes that need a refill');\n var oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys; // Sort changes based on type and query comparator\n\n var changes = docChanges.changeSet.getChanges();\n changes.sort(function (c1, c2) {\n return compareChangeType(c1.type, c2.type) || _this.query.docComparator(c1.doc, c2.doc);\n });\n this.applyTargetChange(targetChange);\n var limboChanges = updateLimboDocuments ? this.updateLimboDocuments() : [];\n var synced = this.limboDocuments.size === 0 && this.current;\n var newSyncState = synced ? SyncState.Synced : SyncState.Local;\n var syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return {\n limboChanges: limboChanges\n };\n } else {\n var snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, docChanges.mutatedKeys, newSyncState === SyncState.Local, syncStateChanged,\n /* excludesMetadataChanges= */\n false);\n return {\n snapshot: snap,\n limboChanges: limboChanges\n };\n }\n };\n /**\r\n * Applies an OnlineState change to the view, potentially generating a\r\n * ViewChange if the view's syncState changes as a result.\r\n */\n\n\n View.prototype.applyOnlineStateChange = function (onlineState) {\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 documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* updateLimboDocuments= */\n false);\n } else {\n // No effect, just return a no-op ViewChange.\n return {\n limboChanges: []\n };\n }\n };\n /**\r\n * Returns whether the doc for the given key should be in limbo.\r\n */\n\n\n View.prototype.shouldBeInLimbo = function (key) {\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 } // The local store doesn't think it's a result, so it shouldn't be in limbo.\n\n\n if (!this.documentSet.has(key)) {\n return false;\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\n\n if (this.documentSet.get(key).hasLocalMutations) {\n return false;\n } // Everything else is in limbo.\n\n\n return true;\n };\n /**\r\n * Updates syncedDocuments, current, and limbo docs based on the given change.\r\n * Returns the list of changes to which docs are in limbo.\r\n */\n\n\n View.prototype.applyTargetChange = function (targetChange) {\n var _this = this;\n\n if (targetChange) {\n targetChange.addedDocuments.forEach(function (key) {\n return _this._syncedDocuments = _this._syncedDocuments.add(key);\n });\n targetChange.modifiedDocuments.forEach(function (key) {\n return assert(_this._syncedDocuments.has(key), \"Modified document \" + key + \" not found in view.\");\n });\n targetChange.removedDocuments.forEach(function (key) {\n return _this._syncedDocuments = _this._syncedDocuments.delete(key);\n });\n this.current = targetChange.current;\n }\n };\n\n View.prototype.updateLimboDocuments = function () {\n var _this = this; // We can only determine limbo documents when we're in-sync with the server.\n\n\n if (!this.current) {\n return [];\n } // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n\n\n var oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(function (doc) {\n if (_this.shouldBeInLimbo(doc.key)) {\n _this.limboDocuments = _this.limboDocuments.add(doc.key);\n }\n }); // Diff the new limbo docs with the old limbo docs.\n\n var changes = [];\n oldLimboDocuments.forEach(function (key) {\n if (!_this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(function (key) {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n };\n /**\r\n * Update the in-memory state of the current view with the state read from\r\n * persistence.\r\n *\r\n * We update the query view whenever a client's primary status changes:\r\n * - When a client transitions from primary to secondary, it can miss\r\n * LocalStorage updates and its query views may temporarily not be\r\n * synchronized with the state on disk.\r\n * - For secondary to primary transitions, the client needs to update the list\r\n * of `syncedDocuments` since secondary clients update their query views\r\n * based purely on synthesized RemoteEvents.\r\n *\r\n * @param localDocs - The documents that match the query according to the\r\n * LocalStore.\r\n * @param remoteKeys - The keys of the documents that match the query\r\n * according to the backend.\r\n *\r\n * @return The ViewChange that resulted from this synchronization.\r\n */\n // PORTING NOTE: Multi-tab only.\n\n\n View.prototype.synchronizeWithPersistedState = function (localDocs, remoteKeys) {\n this._syncedDocuments = remoteKeys;\n this.limboDocuments = documentKeySet();\n var docChanges = this.computeDocChanges(localDocs);\n return this.applyChanges(docChanges,\n /*updateLimboDocuments=*/\n true);\n };\n /**\r\n * Returns a view snapshot as if this query was just listened to. Contains\r\n * a document add for every existing document and the `fromCache` and\r\n * `hasPendingWrites` status of the already established view.\r\n */\n // PORTING NOTE: Multi-tab only.\n\n\n View.prototype.computeInitialSnapshot = function () {\n return ViewSnapshot.fromInitialDocuments(this.query, this.documentSet, this.mutatedKeys, this.syncState === SyncState.Local);\n };\n\n return View;\n}();\n\nfunction compareChangeType(c1, c2) {\n var order = function order(change) {\n switch (change) {\n case ChangeType.Added:\n return 1;\n\n case ChangeType.Modified:\n return 2;\n\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\n case ChangeType.Removed:\n return 0;\n\n default:\n return fail('Unknown ChangeType: ' + change);\n }\n };\n\n return order(c1) - order(c2);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$9 = 'SyncEngine';\n/**\r\n * QueryView contains all of the data that SyncEngine needs to keep track of for\r\n * a particular query.\r\n */\n\nvar QueryView =\n/** @class */\nfunction () {\n function QueryView(\n /**\r\n * The query itself.\r\n */\n query,\n /**\r\n * The target number created by the client that is used in the watch\r\n * stream to identify this query.\r\n */\n targetId,\n /**\r\n * The view is responsible for computing the final merged truth of what\r\n * docs are in the query. It gets notified of local and remote changes,\r\n * and applies the query filters and limits to determine the most correct\r\n * possible results.\r\n */\n view) {\n this.query = query;\n this.targetId = targetId;\n this.view = view;\n }\n\n return QueryView;\n}();\n/** Tracks a limbo resolution. */\n\n\nvar LimboResolution =\n/** @class */\nfunction () {\n function LimboResolution(key) {\n this.key = key;\n }\n\n return LimboResolution;\n}();\n/**\r\n * SyncEngine is the central controller in the client SDK architecture. It is\r\n * the glue code between the EventManager, LocalStore, and RemoteStore. Some of\r\n * SyncEngine's responsibilities include:\r\n * 1. Coordinating client requests and remote events between the EventManager\r\n * and the local and remote data stores.\r\n * 2. Managing a View object for each query, providing the unified view between\r\n * the local and remote data stores.\r\n * 3. Notifying the RemoteStore when the LocalStore has new mutations in its\r\n * queue that need sending to the backend.\r\n *\r\n * The SyncEngine’s methods should only ever be called by methods running in the\r\n * global async queue.\r\n */\n\n\nvar SyncEngine =\n/** @class */\nfunction () {\n function SyncEngine(localStore, remoteStore, // PORTING NOTE: Manages state synchronization in multi-tab environments.\n sharedClientState, currentUser) {\n this.localStore = localStore;\n this.remoteStore = remoteStore;\n this.sharedClientState = sharedClientState;\n this.currentUser = currentUser;\n this.syncEngineListener = null;\n this.queryViewsByQuery = new ObjectMap(function (q) {\n return q.canonicalId();\n });\n this.queryViewsByTarget = {};\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\n this.limboResolutionsByTarget = {};\n this.limboDocumentRefs = new ReferenceSet();\n /** Stores user completion handlers, indexed by User and BatchId. */\n\n this.mutationUserCallbacks = {};\n this.limboTargetIdGenerator = TargetIdGenerator.forSyncEngine(); // 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\n this.isPrimary = undefined;\n this.onlineState = OnlineState.Unknown;\n }\n\n Object.defineProperty(SyncEngine.prototype, \"isPrimaryClient\", {\n // Only used for testing.\n get: function get() {\n return this.isPrimary === true;\n },\n enumerable: true,\n configurable: true\n });\n /** Subscribes to SyncEngine notifications. Has to be called exactly once. */\n\n SyncEngine.prototype.subscribe = function (syncEngineListener) {\n assert(syncEngineListener !== null, 'SyncEngine listener cannot be null');\n assert(this.syncEngineListener === null, 'SyncEngine already has a subscriber.');\n this.syncEngineListener = syncEngineListener;\n };\n /**\r\n * Initiates the new listen, resolves promise when listen enqueued to the\r\n * server. All the subsequent view snapshots or errors are sent to the\r\n * subscribed handlers. Returns the targetId of the query.\r\n */\n\n\n SyncEngine.prototype.listen = function (query) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var targetId, viewSnapshot, queryView, queryData, status_1;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.assertSubscribed('listen()');\n queryView = this.queryViewsByQuery.get(query);\n if (!queryView) return [3\n /*break*/\n , 1]; // PORTING NOTE: With Mult-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\n targetId = queryView.targetId;\n this.sharedClientState.addLocalQueryTarget(targetId);\n viewSnapshot = queryView.view.computeInitialSnapshot();\n return [3\n /*break*/\n , 4];\n\n case 1:\n return [4\n /*yield*/\n , this.localStore.allocateQuery(query)];\n\n case 2:\n queryData = _a.sent();\n status_1 = this.sharedClientState.addLocalQueryTarget(queryData.targetId);\n targetId = queryData.targetId;\n return [4\n /*yield*/\n , this.initializeViewAndComputeSnapshot(queryData, status_1 === 'current')];\n\n case 3:\n viewSnapshot = _a.sent();\n\n if (this.isPrimary) {\n this.remoteStore.listen(queryData);\n }\n\n _a.label = 4;\n\n case 4:\n this.syncEngineListener.onWatchChange([viewSnapshot]);\n return [2\n /*return*/\n , targetId];\n }\n });\n });\n };\n /**\r\n * Registers a view for a previously unknown query and computes its initial\r\n * snapshot.\r\n */\n\n\n SyncEngine.prototype.initializeViewAndComputeSnapshot = function (queryData, current) {\n var _this = this;\n\n var query = queryData.query;\n return this.localStore.executeQuery(query).then(function (docs) {\n return _this.localStore.remoteDocumentKeys(queryData.targetId).then(function (remoteKeys) {\n var view = new View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs); // tslint:disable-next-line:max-line-length Prettier formats this exceed 100 characters.\n\n var synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(queryData.targetId, current && _this.onlineState !== OnlineState.Offline);\n var viewChange = view.applyChanges(viewDocChanges,\n /* updateLimboDocuments= */\n _this.isPrimary === true, synthesizedTargetChange);\n assert(viewChange.limboChanges.length === 0, 'View returned limbo docs before target ack from the server.');\n assert(!!viewChange.snapshot, 'applyChanges for new view should always return a snapshot');\n var data = new QueryView(query, queryData.targetId, view);\n\n _this.queryViewsByQuery.set(query, data);\n\n _this.queryViewsByTarget[queryData.targetId] = data;\n return viewChange.snapshot;\n });\n });\n };\n /**\r\n * Reconcile the list of synced documents in an existing view with those\r\n * from persistence.\r\n */\n // PORTING NOTE: Multi-tab only.\n\n\n SyncEngine.prototype.synchronizeViewAndComputeSnapshot = function (queryView) {\n var _this = this;\n\n return this.localStore.executeQuery(queryView.query).then(function (docs) {\n return _this.localStore.remoteDocumentKeys(queryView.targetId).then(function (remoteKeys) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var viewSnapshot;\n return tslib_1.__generator(this, function (_a) {\n viewSnapshot = queryView.view.synchronizeWithPersistedState(docs, remoteKeys);\n\n if (this.isPrimary) {\n this.updateTrackedLimbos(queryView.targetId, viewSnapshot.limboChanges);\n }\n\n return [2\n /*return*/\n , viewSnapshot];\n });\n });\n });\n });\n };\n /** Stops listening to the query. */\n\n\n SyncEngine.prototype.unlisten = function (query) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var queryView, targetRemainsActive;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.assertSubscribed('unlisten()');\n queryView = this.queryViewsByQuery.get(query);\n assert(!!queryView, 'Trying to unlisten on query not found:' + query);\n if (!this.isPrimary) return [3\n /*break*/\n , 3]; // 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\n this.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n targetRemainsActive = this.sharedClientState.isActiveQueryTarget(queryView.targetId);\n if (!!targetRemainsActive) return [3\n /*break*/\n , 2];\n return [4\n /*yield*/\n , this.localStore.releaseQuery(query,\n /*keepPersistedQueryData=*/\n false).then(function () {\n _this.sharedClientState.clearQueryState(queryView.targetId);\n\n _this.remoteStore.unlisten(queryView.targetId);\n\n _this.removeAndCleanupQuery(queryView);\n }).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n })];\n\n case 1:\n _a.sent();\n\n _a.label = 2;\n\n case 2:\n return [3\n /*break*/\n , 5];\n\n case 3:\n this.removeAndCleanupQuery(queryView);\n return [4\n /*yield*/\n , this.localStore.releaseQuery(query,\n /*keepPersistedQueryData=*/\n true)];\n\n case 4:\n _a.sent();\n\n _a.label = 5;\n\n case 5:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Initiates the write of local mutation batch which involves adding the\r\n * writes to the mutation queue, notifying the remote store about new\r\n * mutations and raising events for any changes this write caused.\r\n *\r\n * The promise returned by this call is resolved when the above steps\r\n * have completed, *not* when the write was acked by the backend. The\r\n * userCallback is resolved once the write was acked/rejected by the\r\n * backend (or failed locally for any other reason).\r\n */\n\n\n SyncEngine.prototype.write = function (batch, userCallback) {\n var _this = this;\n\n this.assertSubscribed('write()');\n return this.localStore.localWrite(batch).then(function (result) {\n _this.sharedClientState.addPendingMutation(result.batchId);\n\n _this.addMutationCallback(result.batchId, userCallback);\n\n return _this.emitNewSnapsAndNotifyLocalStore(result.changes);\n }).then(function () {\n return _this.remoteStore.fillWritePipeline();\n });\n }; // TODO(klimt): Wrap the given error in a standard Firestore error object.\n\n\n SyncEngine.prototype.wrapUpdateFunctionError = function (error$$1) {\n return error$$1;\n };\n /**\r\n * Takes an updateFunction in which a set of reads and writes can be performed\r\n * atomically. In the updateFunction, the client can read and write values\r\n * using the supplied transaction object. After the updateFunction, all\r\n * changes will be committed. If some other client has changed any of the data\r\n * referenced, then the updateFunction will be called again. If the\r\n * updateFunction still fails after the given number of retries, then the\r\n * transaction will be rejection.\r\n *\r\n * The transaction object passed to the updateFunction contains methods for\r\n * accessing documents and collections. Unlike other datastore access, data\r\n * accessed with the transaction will not reflect local changes that have not\r\n * been committed. For this reason, it is required that all reads are\r\n * performed before any writes. Transactions must be performed while online.\r\n *\r\n * The promise returned is resolved when the transaction is fully committed.\r\n */\n\n\n SyncEngine.prototype.runTransaction = function (updateFunction, retries) {\n var _this = this;\n\n if (retries === void 0) {\n retries = 5;\n }\n\n assert(retries >= 0, 'Got negative number of retries for transaction.');\n var transaction = this.remoteStore.createTransaction();\n\n var wrappedUpdateFunction = function wrappedUpdateFunction() {\n try {\n var userPromise = updateFunction(transaction);\n\n if (isNullOrUndefined(userPromise) || !userPromise.catch || !userPromise.then) {\n return Promise.reject(Error('Transaction callback must return a Promise'));\n }\n\n return userPromise.catch(function (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n });\n } catch (e) {\n return Promise.reject(_this.wrapUpdateFunctionError(e));\n }\n };\n\n return wrappedUpdateFunction().then(function (result) {\n return transaction.commit().then(function () {\n return result;\n }).catch(function (error$$1) {\n if (retries === 0) {\n return Promise.reject(error$$1);\n } // TODO(klimt): Put in a retry delay?\n\n\n return _this.runTransaction(updateFunction, retries - 1);\n });\n });\n };\n\n SyncEngine.prototype.applyRemoteEvent = function (remoteEvent) {\n var _this = this;\n\n this.assertSubscribed('applyRemoteEvent()');\n return this.localStore.applyRemoteEvent(remoteEvent).then(function (changes) {\n // Update `receivedDocument` as appropriate for any limbo targets.\n forEach(remoteEvent.targetChanges, function (targetId, targetChange) {\n var limboResolution = _this.limboResolutionsByTarget[targetId];\n\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 assert(targetChange.addedDocuments.size + targetChange.modifiedDocuments.size + targetChange.removedDocuments.size <= 1, '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 assert(limboResolution.receivedDocument, 'Received change for limbo target document without add.');\n } else if (targetChange.removedDocuments.size > 0) {\n assert(limboResolution.receivedDocument, 'Received remove for limbo target document without add.');\n limboResolution.receivedDocument = false;\n } else {// This was probably just a CURRENT targetChange or similar.\n }\n }\n });\n return _this.emitNewSnapsAndNotifyLocalStore(changes, remoteEvent);\n }).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n });\n };\n /**\r\n * Applies an OnlineState change to the sync engine and notifies any views of\r\n * the change.\r\n */\n\n\n SyncEngine.prototype.applyOnlineStateChange = function (onlineState, source) {\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 (this.isPrimary && source === OnlineStateSource.RemoteStore || !this.isPrimary && source === OnlineStateSource.SharedClientState) {\n var newViewSnapshots_1 = [];\n this.queryViewsByQuery.forEach(function (query, queryView) {\n var viewChange = queryView.view.applyOnlineStateChange(onlineState);\n assert(viewChange.limboChanges.length === 0, 'OnlineState should not affect limbo documents.');\n\n if (viewChange.snapshot) {\n newViewSnapshots_1.push(viewChange.snapshot);\n }\n });\n this.syncEngineListener.onOnlineStateChange(onlineState);\n this.syncEngineListener.onWatchChange(newViewSnapshots_1);\n this.onlineState = onlineState;\n\n if (this.isPrimary) {\n this.sharedClientState.setOnlineState(onlineState);\n }\n }\n };\n\n SyncEngine.prototype.rejectListen = function (targetId, err) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var limboResolution, limboKey, documentUpdates, resolvedLimboDocuments, event_1, queryView_1;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.assertSubscribed('rejectListens()'); // PORTING NOTE: Multi-tab only.\n\n this.sharedClientState.updateQueryState(targetId, 'rejected', err);\n limboResolution = this.limboResolutionsByTarget[targetId];\n limboKey = limboResolution && limboResolution.key;\n if (!limboKey) return [3\n /*break*/\n , 1]; // Since this query failed, we won't want to manually unlisten to it.\n // So go ahead and remove it from bookkeeping.\n\n this.limboTargetsByKey = this.limboTargetsByKey.remove(limboKey);\n delete this.limboResolutionsByTarget[targetId];\n documentUpdates = new SortedMap(DocumentKey.comparator);\n documentUpdates = documentUpdates.insert(limboKey, new NoDocument(limboKey, SnapshotVersion.forDeletedDoc()));\n resolvedLimboDocuments = documentKeySet().add(limboKey);\n event_1 = new RemoteEvent(SnapshotVersion.MIN,\n /* targetChanges= */\n {},\n /* targetMismatches= */\n new SortedSet(primitiveComparator), documentUpdates, resolvedLimboDocuments);\n return [2\n /*return*/\n , this.applyRemoteEvent(event_1)];\n\n case 1:\n queryView_1 = this.queryViewsByTarget[targetId];\n assert(!!queryView_1, 'Unknown targetId: ' + targetId);\n return [4\n /*yield*/\n , this.localStore.releaseQuery(queryView_1.query,\n /* keepPersistedQueryData */\n false).then(function () {\n return _this.removeAndCleanupQuery(queryView_1);\n }).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n })];\n\n case 2:\n _a.sent();\n\n this.syncEngineListener.onWatchError(queryView_1.query, err);\n _a.label = 3;\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n }; // PORTING NOTE: Multi-tab only\n\n\n SyncEngine.prototype.applyBatchState = function (batchId, batchState, error$$1) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var documents;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.assertSubscribed('applyBatchState()');\n return [4\n /*yield*/\n , this.localStore.lookupMutationDocuments(batchId)];\n\n case 1:\n documents = _a.sent();\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 debug(LOG_TAG$9, 'Cannot apply mutation batch with id: ' + batchId);\n return [2\n /*return*/\n ];\n }\n\n if (!(batchState === 'pending')) return [3\n /*break*/\n , 3]; // 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\n return [4\n /*yield*/\n , this.remoteStore.fillWritePipeline()];\n\n case 2:\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 _a.sent();\n\n return [3\n /*break*/\n , 4];\n\n case 3:\n if (batchState === 'acknowledged' || batchState === 'rejected') {\n // NOTE: Both these methods are no-ops for batches that originated from\n // other clients.\n this.processUserCallback(batchId, error$$1 ? error$$1 : null);\n this.localStore.removeCachedMutationBatchMetadata(batchId);\n } else {\n fail(\"Unknown batchState: \" + batchState);\n }\n\n _a.label = 4;\n\n case 4:\n return [4\n /*yield*/\n , this.emitNewSnapsAndNotifyLocalStore(documents)];\n\n case 5:\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n SyncEngine.prototype.applySuccessfulWrite = function (mutationBatchResult) {\n var _this = this;\n\n this.assertSubscribed('applySuccessfulWrite()');\n var batchId = mutationBatchResult.batch.batchId; // 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\n this.processUserCallback(batchId,\n /*error=*/\n null);\n return this.localStore.acknowledgeBatch(mutationBatchResult).then(function (changes) {\n _this.sharedClientState.updateMutationState(batchId, 'acknowledged');\n\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n }).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n });\n };\n\n SyncEngine.prototype.rejectFailedWrite = function (batchId, error$$1) {\n var _this = this;\n\n this.assertSubscribed('rejectFailedWrite()'); // 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\n this.processUserCallback(batchId, error$$1);\n return this.localStore.rejectBatch(batchId).then(function (changes) {\n _this.sharedClientState.updateMutationState(batchId, 'rejected', error$$1);\n\n return _this.emitNewSnapsAndNotifyLocalStore(changes);\n }).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n });\n };\n\n SyncEngine.prototype.addMutationCallback = function (batchId, callback) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()];\n\n if (!newCallbacks) {\n newCallbacks = new SortedMap(primitiveComparator);\n }\n\n newCallbacks = newCallbacks.insert(batchId, callback);\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n };\n /**\r\n * Resolves or rejects the user callback for the given batch and then discards\r\n * it.\r\n */\n\n\n SyncEngine.prototype.processUserCallback = function (batchId, error$$1) {\n var newCallbacks = this.mutationUserCallbacks[this.currentUser.toKey()]; // NOTE: Mutations restored from persistence won't have callbacks, so it's\n // okay for there to be no callback for this ID.\n\n if (newCallbacks) {\n var callback = newCallbacks.get(batchId);\n\n if (callback) {\n assert(batchId === newCallbacks.minKey(), 'Mutation callbacks processed out-of-order?');\n\n if (error$$1) {\n callback.reject(error$$1);\n } else {\n callback.resolve();\n }\n\n newCallbacks = newCallbacks.remove(batchId);\n }\n\n this.mutationUserCallbacks[this.currentUser.toKey()] = newCallbacks;\n }\n };\n\n SyncEngine.prototype.removeAndCleanupQuery = function (queryView) {\n var _this = this;\n\n this.sharedClientState.removeLocalQueryTarget(queryView.targetId);\n this.queryViewsByQuery.delete(queryView.query);\n delete this.queryViewsByTarget[queryView.targetId];\n\n if (this.isPrimary) {\n var limboKeys = this.limboDocumentRefs.referencesForId(queryView.targetId);\n this.limboDocumentRefs.removeReferencesForId(queryView.targetId);\n limboKeys.forEach(function (limboKey) {\n var isReferenced = _this.limboDocumentRefs.containsKey(limboKey);\n\n if (!isReferenced) {\n // We removed the last reference for this key\n _this.removeLimboTarget(limboKey);\n }\n });\n }\n };\n\n SyncEngine.prototype.removeLimboTarget = function (key) {\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 var limboTargetId = this.limboTargetsByKey.get(key);\n\n if (limboTargetId === null) {\n // This target already got removed, because the query failed.\n return;\n }\n\n this.remoteStore.unlisten(limboTargetId);\n this.limboTargetsByKey = this.limboTargetsByKey.remove(key);\n delete this.limboResolutionsByTarget[limboTargetId];\n };\n\n SyncEngine.prototype.updateTrackedLimbos = function (targetId, limboChanges) {\n for (var _i = 0, limboChanges_1 = limboChanges; _i < limboChanges_1.length; _i++) {\n var limboChange = limboChanges_1[_i];\n\n if (limboChange instanceof AddedLimboDocument) {\n this.limboDocumentRefs.addReference(limboChange.key, targetId);\n this.trackLimboChange(limboChange);\n } else if (limboChange instanceof RemovedLimboDocument) {\n debug(LOG_TAG$9, 'Document no longer in limbo: ' + limboChange.key);\n this.limboDocumentRefs.removeReference(limboChange.key, targetId);\n var isReferenced = this.limboDocumentRefs.containsKey(limboChange.key);\n\n if (!isReferenced) {\n // We removed the last reference for this key\n this.removeLimboTarget(limboChange.key);\n }\n } else {\n fail('Unknown limbo change: ' + JSON.stringify(limboChange));\n }\n }\n };\n\n SyncEngine.prototype.trackLimboChange = function (limboChange) {\n var key = limboChange.key;\n\n if (!this.limboTargetsByKey.get(key)) {\n debug(LOG_TAG$9, 'New document in limbo: ' + key);\n var limboTargetId = this.limboTargetIdGenerator.next();\n var query = Query.atPath(key.path);\n this.limboResolutionsByTarget[limboTargetId] = new LimboResolution(key);\n this.remoteStore.listen(new QueryData(query, limboTargetId, QueryPurpose.LimboResolution, ListenSequence.INVALID));\n this.limboTargetsByKey = this.limboTargetsByKey.insert(key, limboTargetId);\n }\n }; // Visible for testing\n\n\n SyncEngine.prototype.currentLimboDocs = function () {\n return this.limboTargetsByKey;\n };\n\n SyncEngine.prototype.emitNewSnapsAndNotifyLocalStore = function (changes, remoteEvent) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var newSnaps, docChangesInAllViews, queriesProcessed;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n newSnaps = [];\n docChangesInAllViews = [];\n queriesProcessed = [];\n this.queryViewsByQuery.forEach(function (_, queryView) {\n queriesProcessed.push(Promise.resolve().then(function () {\n var viewDocChanges = queryView.view.computeDocChanges(changes);\n\n if (!viewDocChanges.needsRefill) {\n return viewDocChanges;\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\n\n return _this.localStore.executeQuery(queryView.query).then(function (docs) {\n return queryView.view.computeDocChanges(docs, viewDocChanges);\n });\n }).then(function (viewDocChanges) {\n var targetChange = remoteEvent && remoteEvent.targetChanges[queryView.targetId];\n var viewChange = queryView.view.applyChanges(viewDocChanges,\n /* updateLimboDocuments= */\n _this.isPrimary === true, targetChange);\n\n _this.updateTrackedLimbos(queryView.targetId, viewChange.limboChanges);\n\n if (viewChange.snapshot) {\n if (_this.isPrimary) {\n _this.sharedClientState.updateQueryState(queryView.targetId, viewChange.snapshot.fromCache ? 'not-current' : 'current');\n }\n\n newSnaps.push(viewChange.snapshot);\n var docChanges = LocalViewChanges.fromSnapshot(queryView.targetId, viewChange.snapshot);\n docChangesInAllViews.push(docChanges);\n }\n }));\n });\n return [4\n /*yield*/\n , Promise.all(queriesProcessed)];\n\n case 1:\n _a.sent();\n\n this.syncEngineListener.onWatchChange(newSnaps);\n return [4\n /*yield*/\n , this.localStore.notifyLocalViewChanges(docChangesInAllViews)];\n\n case 2:\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Verifies the error thrown by an LocalStore operation. If a LocalStore\r\n * operation fails because the primary lease has been taken by another client,\r\n * we ignore the error (the persistence layer will immediately call\r\n * `applyPrimaryLease` to propagate the primary state change). All other\r\n * errors are re-thrown.\r\n *\r\n * @param err An error returned by a LocalStore operation.\r\n * @return A Promise that resolves after we recovered, or the original error.\r\n */\n\n\n SyncEngine.prototype.ignoreIfPrimaryLeaseLoss = function (err) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (isPrimaryLeaseLostError(err)) {\n debug(LOG_TAG$9, 'Unexpectedly lost primary lease');\n } else {\n throw err;\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n SyncEngine.prototype.assertSubscribed = function (fnName) {\n assert(this.syncEngineListener !== null, 'Trying to call ' + fnName + ' before calling subscribe().');\n };\n\n SyncEngine.prototype.handleCredentialChange = function (user) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var userChanged, result;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n userChanged = !this.currentUser.isEqual(user);\n this.currentUser = user;\n if (!userChanged) return [3\n /*break*/\n , 3];\n return [4\n /*yield*/\n , this.localStore.handleUserChange(user)];\n\n case 1:\n result = _a.sent(); // TODO(b/114226417): Consider calling this only in the primary tab.\n\n this.sharedClientState.handleUserChange(user, result.removedBatchIds, result.addedBatchIds);\n return [4\n /*yield*/\n , this.emitNewSnapsAndNotifyLocalStore(result.affectedDocuments)];\n\n case 2:\n _a.sent();\n\n _a.label = 3;\n\n case 3:\n return [4\n /*yield*/\n , this.remoteStore.handleCredentialChange()];\n\n case 4:\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n }; // PORTING NOTE: Multi-tab only\n\n\n SyncEngine.prototype.applyPrimaryState = function (isPrimary) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var activeTargets, activeQueries, _i, activeQueries_1, queryData, activeTargets_1, p_1;\n\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!(isPrimary === true && this.isPrimary !== true)) return [3\n /*break*/\n , 3];\n this.isPrimary = true;\n return [4\n /*yield*/\n , this.remoteStore.applyPrimaryState(true)];\n\n case 1:\n _a.sent();\n\n activeTargets = this.sharedClientState.getAllActiveQueryTargets();\n return [4\n /*yield*/\n , this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets.toArray())];\n\n case 2:\n activeQueries = _a.sent();\n\n for (_i = 0, activeQueries_1 = activeQueries; _i < activeQueries_1.length; _i++) {\n queryData = activeQueries_1[_i];\n this.remoteStore.listen(queryData);\n }\n\n return [3\n /*break*/\n , 7];\n\n case 3:\n if (!(isPrimary === false && this.isPrimary !== false)) return [3\n /*break*/\n , 7];\n this.isPrimary = false;\n activeTargets_1 = [];\n p_1 = Promise.resolve();\n forEachNumber(this.queryViewsByTarget, function (targetId, queryView) {\n if (_this.sharedClientState.isLocalQueryTarget(targetId)) {\n activeTargets_1.push(targetId);\n } else {\n p_1 = p_1.then(function () {\n return _this.unlisten(queryView.query);\n });\n }\n\n _this.remoteStore.unlisten(queryView.targetId);\n });\n return [4\n /*yield*/\n , p_1];\n\n case 4:\n _a.sent();\n\n return [4\n /*yield*/\n , this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets_1)];\n\n case 5:\n _a.sent();\n\n this.resetLimboDocuments();\n return [4\n /*yield*/\n , this.remoteStore.applyPrimaryState(false)];\n\n case 6:\n _a.sent();\n\n _a.label = 7;\n\n case 7:\n return [2\n /*return*/\n ];\n }\n });\n });\n }; // PORTING NOTE: Multi-tab only.\n\n\n SyncEngine.prototype.resetLimboDocuments = function () {\n var _this = this;\n\n forEachNumber(this.limboResolutionsByTarget, function (targetId) {\n _this.remoteStore.unlisten(targetId);\n });\n this.limboDocumentRefs.removeAllReferences();\n this.limboResolutionsByTarget = [];\n this.limboTargetsByKey = new SortedMap(DocumentKey.comparator);\n };\n /**\r\n * Reconcile the query views of the provided query targets with the state from\r\n * persistence. Raises snapshots for any changes that affect the local\r\n * client and returns the updated state of all target's query data.\r\n */\n // PORTING NOTE: Multi-tab only.\n\n\n SyncEngine.prototype.synchronizeQueryViewsAndRaiseSnapshots = function (targets) {\n var _this = this;\n\n var p = Promise.resolve();\n var activeQueries = [];\n var newViewSnapshots = [];\n\n var _loop_1 = function _loop_1(targetId) {\n p = p.then(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var queryData, queryView, viewChange, query;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n queryView = this.queryViewsByTarget[targetId];\n if (!queryView) return [3\n /*break*/\n , 4]; // For queries that have a local View, we need to update their state\n // in 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\n return [4\n /*yield*/\n , this.localStore.releaseQuery(queryView.query,\n /*keepPersistedQueryData=*/\n true)];\n\n case 1:\n // For queries that have a local View, we need to update their state\n // in 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 _a.sent();\n\n return [4\n /*yield*/\n , this.localStore.allocateQuery(queryView.query)];\n\n case 2:\n queryData = _a.sent();\n return [4\n /*yield*/\n , this.synchronizeViewAndComputeSnapshot(queryView)];\n\n case 3:\n viewChange = _a.sent();\n\n if (viewChange.snapshot) {\n newViewSnapshots.push(viewChange.snapshot);\n }\n\n return [3\n /*break*/\n , 8];\n\n case 4:\n assert(this.isPrimary === true, 'A secondary tab should never have an active query without an active view.');\n return [4\n /*yield*/\n , this.localStore.getQueryForTarget(targetId)];\n\n case 5:\n query = _a.sent();\n assert(!!query, \"Query data for target \" + targetId + \" not found\");\n return [4\n /*yield*/\n , this.localStore.allocateQuery(query)];\n\n case 6:\n queryData = _a.sent();\n return [4\n /*yield*/\n , this.initializeViewAndComputeSnapshot(queryData,\n /*current=*/\n false)];\n\n case 7:\n _a.sent();\n\n _a.label = 8;\n\n case 8:\n activeQueries.push(queryData);\n return [2\n /*return*/\n ];\n }\n });\n });\n });\n };\n\n for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {\n var targetId = targets_1[_i];\n\n _loop_1(targetId);\n }\n\n return p.then(function () {\n _this.syncEngineListener.onWatchChange(newViewSnapshots);\n\n return activeQueries;\n });\n }; // PORTING NOTE: Multi-tab only\n\n\n SyncEngine.prototype.getActiveClients = function () {\n return this.localStore.getActiveClients();\n }; // PORTING NOTE: Multi-tab only\n\n\n SyncEngine.prototype.applyTargetState = function (targetId, state, error$$1) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var _a, queryView;\n\n return tslib_1.__generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n if (this.isPrimary) {\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 debug(LOG_TAG$9, 'Ignoring unexpected query state notification.');\n return [2\n /*return*/\n ];\n }\n\n if (!this.queryViewsByTarget[targetId]) return [3\n /*break*/\n , 5];\n _a = state;\n\n switch (_a) {\n case 'current':\n return [3\n /*break*/\n , 1];\n\n case 'not-current':\n return [3\n /*break*/\n , 1];\n\n case 'rejected':\n return [3\n /*break*/\n , 2];\n }\n\n return [3\n /*break*/\n , 4];\n\n case 1:\n {\n return [2\n /*return*/\n , this.localStore.getNewDocumentChanges().then(function (changes) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var synthesizedRemoteEvent;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(targetId, state === 'current');\n return [4\n /*yield*/\n , this.emitNewSnapsAndNotifyLocalStore(changes, synthesizedRemoteEvent)];\n\n case 1:\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n }, function (err) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var activeTargets_2;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!isDocumentChangeMissingError(err)) return [3\n /*break*/\n , 2];\n activeTargets_2 = [];\n forEachNumber(this.queryViewsByTarget, function (target) {\n return activeTargets_2.push(target);\n });\n return [4\n /*yield*/\n , this.synchronizeQueryViewsAndRaiseSnapshots(activeTargets_2)];\n\n case 1:\n _a.sent();\n\n return [3\n /*break*/\n , 3];\n\n case 2:\n throw err;\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n })];\n }\n _b.label = 2;\n\n case 2:\n queryView = this.queryViewsByTarget[targetId];\n this.removeAndCleanupQuery(queryView);\n return [4\n /*yield*/\n , this.localStore.releaseQuery(queryView.query,\n /*keepPersistedQueryData=*/\n true)];\n\n case 3:\n _b.sent();\n\n this.syncEngineListener.onWatchError(queryView.query, error$$1);\n return [3\n /*break*/\n , 5];\n\n case 4:\n fail('Unexpected target state: ' + state);\n _b.label = 5;\n\n case 5:\n return [2\n /*return*/\n ];\n }\n });\n });\n }; // PORTING NOTE: Multi-tab only\n\n\n SyncEngine.prototype.applyActiveTargetsChange = function (added, removed) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var _i, added_1, targetId, query, queryData, _loop_2, this_1, _a, removed_1, targetId;\n\n return tslib_1.__generator(this, function (_b) {\n switch (_b.label) {\n case 0:\n if (!this.isPrimary) {\n return [2\n /*return*/\n ];\n }\n\n _i = 0, added_1 = added;\n _b.label = 1;\n\n case 1:\n if (!(_i < added_1.length)) return [3\n /*break*/\n , 6];\n targetId = added_1[_i];\n assert(!this.queryViewsByTarget[targetId], 'Trying to add an already active target');\n return [4\n /*yield*/\n , this.localStore.getQueryForTarget(targetId)];\n\n case 2:\n query = _b.sent();\n assert(!!query, \"Query data for active target \" + targetId + \" not found\");\n return [4\n /*yield*/\n , this.localStore.allocateQuery(query)];\n\n case 3:\n queryData = _b.sent();\n return [4\n /*yield*/\n , this.initializeViewAndComputeSnapshot(queryData,\n /*current=*/\n false)];\n\n case 4:\n _b.sent();\n\n this.remoteStore.listen(queryData);\n _b.label = 5;\n\n case 5:\n _i++;\n return [3\n /*break*/\n , 1];\n\n case 6:\n _loop_2 = function _loop_2(targetId) {\n var queryView;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n queryView = this_1.queryViewsByTarget[targetId];\n if (!queryView) return [3\n /*break*/\n , 2];\n return [4\n /*yield*/\n , this_1.localStore.releaseQuery(queryView.query,\n /*keepPersistedQueryData=*/\n false).then(function () {\n _this.remoteStore.unlisten(targetId);\n\n _this.removeAndCleanupQuery(queryView);\n }).catch(function (err) {\n return _this.ignoreIfPrimaryLeaseLoss(err);\n })];\n\n case 1:\n _a.sent();\n\n _a.label = 2;\n\n case 2:\n return [2\n /*return*/\n ];\n }\n });\n };\n\n this_1 = this;\n _a = 0, removed_1 = removed;\n _b.label = 7;\n\n case 7:\n if (!(_a < removed_1.length)) return [3\n /*break*/\n , 10];\n targetId = removed_1[_a];\n return [5\n /*yield**/\n , _loop_2(targetId)];\n\n case 8:\n _b.sent();\n\n _b.label = 9;\n\n case 9:\n _a++;\n return [3\n /*break*/\n , 7];\n\n case 10:\n return [2\n /*return*/\n ];\n }\n });\n });\n }; // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\n // the online state.\n\n\n SyncEngine.prototype.enableNetwork = function () {\n this.localStore.setNetworkEnabled(true);\n return this.remoteStore.enableNetwork();\n }; // PORTING NOTE: Multi-tab only. In other clients, LocalStore is unaware of\n // the online state.\n\n\n SyncEngine.prototype.disableNetwork = function () {\n this.localStore.setNetworkEnabled(false);\n return this.remoteStore.disableNetwork();\n };\n\n SyncEngine.prototype.getRemoteKeysForTarget = function (targetId) {\n var limboResolution = this.limboResolutionsByTarget[targetId];\n\n if (limboResolution && limboResolution.receivedDocument) {\n return documentKeySet().add(limboResolution.key);\n } else {\n return this.queryViewsByTarget[targetId] ? this.queryViewsByTarget[targetId].view.syncedDocuments : documentKeySet();\n }\n };\n\n return SyncEngine;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Simple wrapper around a nullable UID. Mostly exists to make code more\r\n * readable.\r\n */\n\n\nvar User =\n/** @class */\nfunction () {\n function User(uid) {\n this.uid = uid;\n }\n\n User.prototype.isAuthenticated = function () {\n return this.uid != null;\n };\n /**\r\n * Returns a key representing this user, suitable for inclusion in a\r\n * dictionary.\r\n */\n\n\n User.prototype.toKey = function () {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n };\n\n User.prototype.isEqual = function (otherUser) {\n return otherUser.uid === this.uid;\n };\n /** A user with a null UID. */\n\n\n User.UNAUTHENTICATED = new User(null); // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n\n User.GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n User.FIRST_PARTY = new User('first-party-uid');\n return User;\n}();\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$10 = 'SharedClientState'; // The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\n\nvar CLIENT_STATE_KEY_PREFIX = 'firestore_clients'; // The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\n\nvar MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations'; // The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\n\nvar QUERY_TARGET_KEY_PREFIX = 'firestore_targets'; // The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\n\nvar ONLINE_STATE_KEY_PREFIX = 'firestore_online_state'; // The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\n\nvar SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n/**\r\n * Holds the state of a mutation batch, including its user ID, batch ID and\r\n * whether the batch is 'pending', 'acknowledged' or 'rejected'.\r\n */\n// Visible for testing\n\nvar MutationMetadata =\n/** @class */\nfunction () {\n function MutationMetadata(user, batchId, state, error$$1) {\n this.user = user;\n this.batchId = batchId;\n this.state = state;\n this.error = error$$1;\n assert(error$$1 !== undefined === (state === 'rejected'), \"MutationMetadata must contain an error iff state is 'rejected'\");\n }\n /**\r\n * Parses a MutationMetadata from its JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\n\n\n MutationMetadata.fromWebStorageEntry = function (user, batchId, value) {\n var mutationBatch = JSON.parse(value);\n var validData = typeof mutationBatch === 'object' && ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !== -1 && (mutationBatch.error === undefined || typeof mutationBatch.error === 'object');\n var firestoreError = undefined;\n\n if (validData && mutationBatch.error) {\n validData = typeof mutationBatch.error.message === 'string' && typeof mutationBatch.error.code === 'string';\n\n if (validData) {\n firestoreError = new FirestoreError(mutationBatch.error.code, mutationBatch.error.message);\n }\n }\n\n if (validData) {\n return new MutationMetadata(user, batchId, mutationBatch.state, firestoreError);\n } else {\n error(LOG_TAG$10, \"Failed to parse mutation state for ID '\" + batchId + \"': \" + value);\n return null;\n }\n };\n\n MutationMetadata.prototype.toWebStorageJSON = function () {\n var batchMetadata = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n\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 return MutationMetadata;\n}();\n/**\r\n * Holds the state of a query target, including its target ID and whether the\r\n * target is 'not-current', 'current' or 'rejected'.\r\n */\n// Visible for testing\n\n\nvar QueryTargetMetadata =\n/** @class */\nfunction () {\n function QueryTargetMetadata(targetId, state, error$$1) {\n this.targetId = targetId;\n this.state = state;\n this.error = error$$1;\n assert(error$$1 !== undefined === (state === 'rejected'), \"QueryTargetMetadata must contain an error iff state is 'rejected'\");\n }\n /**\r\n * Parses a QueryTargetMetadata from its JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\n\n\n QueryTargetMetadata.fromWebStorageEntry = function (targetId, value) {\n var targetState = JSON.parse(value);\n var validData = typeof targetState === 'object' && ['not-current', 'current', 'rejected'].indexOf(targetState.state) !== -1 && (targetState.error === undefined || typeof targetState.error === 'object');\n var firestoreError = undefined;\n\n if (validData && targetState.error) {\n validData = typeof targetState.error.message === 'string' && typeof targetState.error.code === 'string';\n\n if (validData) {\n firestoreError = new FirestoreError(targetState.error.code, targetState.error.message);\n }\n }\n\n if (validData) {\n return new QueryTargetMetadata(targetId, targetState.state, firestoreError);\n } else {\n error(LOG_TAG$10, \"Failed to parse target state for ID '\" + targetId + \"': \" + value);\n return null;\n }\n };\n\n QueryTargetMetadata.prototype.toWebStorageJSON = function () {\n var targetState = {\n state: this.state,\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n\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 return QueryTargetMetadata;\n}();\n/**\r\n * This class represents the immutable ClientState for a client read from\r\n * WebStorage, containing the list of active query targets.\r\n */\n\n\nvar RemoteClientState =\n/** @class */\nfunction () {\n function RemoteClientState(clientId, activeTargetIds) {\n this.clientId = clientId;\n this.activeTargetIds = activeTargetIds;\n }\n /**\r\n * Parses a RemoteClientState from the JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\n\n\n RemoteClientState.fromWebStorageEntry = function (clientId, value) {\n var clientState = JSON.parse(value);\n var validData = typeof clientState === 'object' && clientState.activeTargetIds instanceof Array;\n var activeTargetIdsSet = targetIdSet();\n\n for (var i = 0; validData && i < clientState.activeTargetIds.length; ++i) {\n validData = isSafeInteger(clientState.activeTargetIds[i]);\n activeTargetIdsSet = activeTargetIdsSet.add(clientState.activeTargetIds[i]);\n }\n\n if (validData) {\n return new RemoteClientState(clientId, activeTargetIdsSet);\n } else {\n error(LOG_TAG$10, \"Failed to parse client data for instance '\" + clientId + \"': \" + value);\n return null;\n }\n };\n\n return RemoteClientState;\n}();\n/**\r\n * This class represents the online state for all clients participating in\r\n * multi-tab. The online state is only written to by the primary client, and\r\n * used in secondary clients to update their query views.\r\n */\n\n\nvar SharedOnlineState =\n/** @class */\nfunction () {\n function SharedOnlineState(clientId, onlineState) {\n this.clientId = clientId;\n this.onlineState = onlineState;\n }\n /**\r\n * Parses a SharedOnlineState from its JSON representation in WebStorage.\r\n * Logs a warning and returns null if the format of the data is not valid.\r\n */\n\n\n SharedOnlineState.fromWebStorageEntry = function (value) {\n var onlineState = JSON.parse(value);\n var validData = typeof onlineState === 'object' && OnlineState[onlineState.onlineState] !== undefined && typeof onlineState.clientId === 'string';\n\n if (validData) {\n return new SharedOnlineState(onlineState.clientId, OnlineState[onlineState.onlineState]);\n } else {\n error(LOG_TAG$10, \"Failed to parse online state: \" + value);\n return null;\n }\n };\n\n return SharedOnlineState;\n}();\n/**\r\n * Metadata state of the local client. Unlike `RemoteClientState`, this class is\r\n * mutable and keeps track of all pending mutations, which allows us to\r\n * update the range of pending mutation batch IDs as new mutations are added or\r\n * removed.\r\n *\r\n * The data in `LocalClientState` is not read from WebStorage and instead\r\n * updated via its instance methods. The updated state can be serialized via\r\n * `toWebStorageJSON()`.\r\n */\n// Visible for testing.\n\n\nvar LocalClientState =\n/** @class */\nfunction () {\n function LocalClientState() {\n this.activeTargetIds = targetIdSet();\n }\n\n LocalClientState.prototype.addQueryTarget = function (targetId) {\n assert(!this.activeTargetIds.has(targetId), \"Target with ID '\" + targetId + \"' already active.\");\n this.activeTargetIds = this.activeTargetIds.add(targetId);\n };\n\n LocalClientState.prototype.removeQueryTarget = function (targetId) {\n this.activeTargetIds = this.activeTargetIds.delete(targetId);\n };\n /**\r\n * Converts this entry into a JSON-encoded format we can use for WebStorage.\r\n * Does not encode `clientId` as it is part of the key in WebStorage.\r\n */\n\n\n LocalClientState.prototype.toWebStorageJSON = function () {\n var data = {\n activeTargetIds: this.activeTargetIds.toArray(),\n updateTimeMs: Date.now() // Modify the existing value to trigger update.\n\n };\n return JSON.stringify(data);\n };\n\n return LocalClientState;\n}();\n/**\r\n * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the\r\n * backing store for the SharedClientState. It keeps track of all active\r\n * clients and supports modifications of the local client's data.\r\n */\n\n\nvar WebStorageSharedClientState =\n/** @class */\nfunction () {\n function WebStorageSharedClientState(queue, platform, persistenceKey, localClientId, initialUser) {\n this.queue = queue;\n this.platform = platform;\n this.persistenceKey = persistenceKey;\n this.localClientId = localClientId;\n this.syncEngine = null;\n this.onlineStateHandler = null;\n this.sequenceNumberHandler = null;\n this.activeClients = {};\n this.storageListener = this.handleWebStorageEvent.bind(this);\n this.started = false;\n /**\r\n * Captures WebStorage events that occur before `start()` is called. These\r\n * events are replayed once `WebStorageSharedClientState` is started.\r\n */\n\n this.earlyEvents = [];\n\n if (!WebStorageSharedClientState.isAvailable(this.platform)) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'LocalStorage is not available on this platform.');\n } // Escape the special characters mentioned here:\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\n\n\n var escapedPersistenceKey = persistenceKey.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n this.storage = this.platform.window.localStorage;\n this.currentUser = initialUser;\n this.localClientStorageKey = this.toWebStorageClientStateKey(this.localClientId);\n this.sequenceNumberKey = SEQUENCE_NUMBER_KEY_PREFIX + \"_\" + persistenceKey;\n this.activeClients[this.localClientId] = new LocalClientState();\n this.clientStateKeyRe = new RegExp(\"^\" + CLIENT_STATE_KEY_PREFIX + \"_\" + escapedPersistenceKey + \"_([^_]*)$\");\n this.mutationBatchKeyRe = new RegExp(\"^\" + MUTATION_BATCH_KEY_PREFIX + \"_\" + escapedPersistenceKey + \"_(\\\\d+)(?:_(.*))?$\");\n this.queryTargetKeyRe = new RegExp(\"^\" + QUERY_TARGET_KEY_PREFIX + \"_\" + escapedPersistenceKey + \"_(\\\\d+)$\");\n this.onlineStateKey = ONLINE_STATE_KEY_PREFIX + \"_\" + persistenceKey; // 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\n this.platform.window.addEventListener('storage', this.storageListener);\n }\n /** Returns 'true' if WebStorage is available in the current environment. */\n\n\n WebStorageSharedClientState.isAvailable = function (platform) {\n return !!(platform.window && platform.window.localStorage != null);\n };\n\n WebStorageSharedClientState.prototype.start = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var existingClients, _i, existingClients_1, clientId, storageItem, clientState, onlineStateJSON, onlineState, _a, _b, event_1;\n\n return tslib_1.__generator(this, function (_c) {\n switch (_c.label) {\n case 0:\n assert(!this.started, 'WebStorageSharedClientState already started');\n assert(this.syncEngine !== null, 'syncEngine property must be set before calling start()');\n assert(this.onlineStateHandler !== null, 'onlineStateHandler property must be set before calling start()');\n return [4\n /*yield*/\n , this.syncEngine.getActiveClients()];\n\n case 1:\n existingClients = _c.sent();\n\n for (_i = 0, existingClients_1 = existingClients; _i < existingClients_1.length; _i++) {\n clientId = existingClients_1[_i];\n\n if (clientId === this.localClientId) {\n continue;\n }\n\n storageItem = this.getItem(this.toWebStorageClientStateKey(clientId));\n\n if (storageItem) {\n clientState = RemoteClientState.fromWebStorageEntry(clientId, storageItem);\n\n if (clientState) {\n this.activeClients[clientState.clientId] = clientState;\n }\n }\n }\n\n this.persistClientState();\n onlineStateJSON = this.storage.getItem(this.onlineStateKey);\n\n if (onlineStateJSON) {\n onlineState = this.fromWebStorageOnlineState(onlineStateJSON);\n\n if (onlineState) {\n this.handleOnlineStateEvent(onlineState);\n }\n }\n\n for (_a = 0, _b = this.earlyEvents; _a < _b.length; _a++) {\n event_1 = _b[_a];\n this.handleWebStorageEvent(event_1);\n }\n\n this.earlyEvents = []; // Register a window unload hook to remove the client metadata entry from\n // WebStorage even if `shutdown()` was not called.\n\n this.platform.window.addEventListener('unload', function () {\n return _this.shutdown();\n });\n this.started = true;\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n WebStorageSharedClientState.prototype.writeSequenceNumber = function (sequenceNumber) {\n this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber));\n };\n\n WebStorageSharedClientState.prototype.getAllActiveQueryTargets = function () {\n var activeTargets = targetIdSet();\n forEach(this.activeClients, function (key, value) {\n activeTargets = activeTargets.unionWith(value.activeTargetIds);\n });\n return activeTargets;\n };\n\n WebStorageSharedClientState.prototype.isActiveQueryTarget = function (targetId) {\n // This is not using `obj.forEach` since `forEach` doesn't support early\n // return.\n for (var clientId in this.activeClients) {\n if (this.activeClients.hasOwnProperty(clientId)) {\n if (this.activeClients[clientId].activeTargetIds.has(targetId)) {\n return true;\n }\n }\n }\n\n return false;\n };\n\n WebStorageSharedClientState.prototype.addPendingMutation = function (batchId) {\n this.persistMutationState(batchId, 'pending');\n };\n\n WebStorageSharedClientState.prototype.updateMutationState = function (batchId, state, error$$1) {\n this.persistMutationState(batchId, state, error$$1); // 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\n this.removeMutationState(batchId);\n };\n\n WebStorageSharedClientState.prototype.addLocalQueryTarget = function (targetId) {\n var queryState = 'not-current'; // Lookup an existing query state if the target ID was already registered\n // by another tab\n\n if (this.isActiveQueryTarget(targetId)) {\n var storageItem = this.storage.getItem(this.toWebStorageQueryTargetMetadataKey(targetId));\n\n if (storageItem) {\n var metadata = QueryTargetMetadata.fromWebStorageEntry(targetId, storageItem);\n\n if (metadata) {\n queryState = metadata.state;\n }\n }\n }\n\n this.localClientState.addQueryTarget(targetId);\n this.persistClientState();\n return queryState;\n };\n\n WebStorageSharedClientState.prototype.removeLocalQueryTarget = function (targetId) {\n this.localClientState.removeQueryTarget(targetId);\n this.persistClientState();\n };\n\n WebStorageSharedClientState.prototype.isLocalQueryTarget = function (targetId) {\n return this.localClientState.activeTargetIds.has(targetId);\n };\n\n WebStorageSharedClientState.prototype.clearQueryState = function (targetId) {\n this.removeItem(this.toWebStorageQueryTargetMetadataKey(targetId));\n };\n\n WebStorageSharedClientState.prototype.updateQueryState = function (targetId, state, error$$1) {\n this.persistQueryTargetState(targetId, state, error$$1);\n };\n\n WebStorageSharedClientState.prototype.handleUserChange = function (user, removedBatchIds, addedBatchIds) {\n var _this = this;\n\n removedBatchIds.forEach(function (batchId) {\n _this.removeMutationState(batchId);\n });\n this.currentUser = user;\n addedBatchIds.forEach(function (batchId) {\n _this.addPendingMutation(batchId);\n });\n };\n\n WebStorageSharedClientState.prototype.setOnlineState = function (onlineState) {\n this.persistOnlineState(onlineState);\n };\n\n WebStorageSharedClientState.prototype.shutdown = function () {\n if (this.started) {\n this.platform.window.removeEventListener('storage', this.storageListener);\n this.removeItem(this.localClientStorageKey);\n this.started = false;\n }\n };\n\n WebStorageSharedClientState.prototype.getItem = function (key) {\n var value = this.storage.getItem(key);\n debug(LOG_TAG$10, 'READ', key, value);\n return value;\n };\n\n WebStorageSharedClientState.prototype.setItem = function (key, value) {\n debug(LOG_TAG$10, 'SET', key, value);\n this.storage.setItem(key, value);\n };\n\n WebStorageSharedClientState.prototype.removeItem = function (key) {\n debug(LOG_TAG$10, 'REMOVE', key);\n this.storage.removeItem(key);\n };\n\n WebStorageSharedClientState.prototype.handleWebStorageEvent = function (event) {\n var _this = this;\n\n if (event.storageArea === this.storage) {\n debug(LOG_TAG$10, 'EVENT', event.key, event.newValue);\n\n if (event.key === this.localClientStorageKey) {\n error('Received WebStorage notification for local change. Another client might have ' + 'garbage-collected our state');\n return;\n }\n\n this.queue.enqueueAndForget(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var clientState, clientId, mutationMetadata, queryTargetMetadata, onlineState, sequenceNumber;\n return tslib_1.__generator(this, function (_a) {\n if (!this.started) {\n this.earlyEvents.push(event);\n return [2\n /*return*/\n ];\n }\n\n if (event.key === null) {\n return [2\n /*return*/\n ];\n }\n\n if (this.clientStateKeyRe.test(event.key)) {\n if (event.newValue != null) {\n clientState = this.fromWebStorageClientState(event.key, event.newValue);\n\n if (clientState) {\n return [2\n /*return*/\n , this.handleClientStateEvent(clientState.clientId, clientState)];\n }\n } else {\n clientId = this.fromWebStorageClientStateKey(event.key);\n return [2\n /*return*/\n , this.handleClientStateEvent(clientId, null)];\n }\n } else if (this.mutationBatchKeyRe.test(event.key)) {\n if (event.newValue !== null) {\n mutationMetadata = this.fromWebStorageMutationMetadata(event.key, event.newValue);\n\n if (mutationMetadata) {\n return [2\n /*return*/\n , this.handleMutationBatchEvent(mutationMetadata)];\n }\n }\n } else if (this.queryTargetKeyRe.test(event.key)) {\n if (event.newValue !== null) {\n queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(event.key, event.newValue);\n\n if (queryTargetMetadata) {\n return [2\n /*return*/\n , this.handleQueryTargetEvent(queryTargetMetadata)];\n }\n }\n } else if (event.key === this.onlineStateKey) {\n if (event.newValue !== null) {\n onlineState = this.fromWebStorageOnlineState(event.newValue);\n\n if (onlineState) {\n return [2\n /*return*/\n , this.handleOnlineStateEvent(onlineState)];\n }\n }\n } else if (event.key === this.sequenceNumberKey) {\n assert(!!this.sequenceNumberHandler, 'Missing sequenceNumberHandler');\n sequenceNumber = fromWebStorageSequenceNumber(event.newValue);\n\n if (sequenceNumber !== ListenSequence.INVALID) {\n this.sequenceNumberHandler(sequenceNumber);\n }\n }\n\n return [2\n /*return*/\n ];\n });\n });\n });\n }\n };\n\n Object.defineProperty(WebStorageSharedClientState.prototype, \"localClientState\", {\n get: function get() {\n return this.activeClients[this.localClientId];\n },\n enumerable: true,\n configurable: true\n });\n\n WebStorageSharedClientState.prototype.persistClientState = function () {\n this.setItem(this.localClientStorageKey, this.localClientState.toWebStorageJSON());\n };\n\n WebStorageSharedClientState.prototype.persistMutationState = function (batchId, state, error$$1) {\n var mutationState = new MutationMetadata(this.currentUser, batchId, state, error$$1);\n var mutationKey = this.toWebStorageMutationBatchKey(batchId);\n this.setItem(mutationKey, mutationState.toWebStorageJSON());\n };\n\n WebStorageSharedClientState.prototype.removeMutationState = function (batchId) {\n var mutationKey = this.toWebStorageMutationBatchKey(batchId);\n this.removeItem(mutationKey);\n };\n\n WebStorageSharedClientState.prototype.persistOnlineState = function (onlineState) {\n var entry = {\n clientId: this.localClientId,\n onlineState: OnlineState[onlineState]\n };\n this.storage.setItem(this.onlineStateKey, JSON.stringify(entry));\n };\n\n WebStorageSharedClientState.prototype.persistQueryTargetState = function (targetId, state, error$$1) {\n var targetKey = this.toWebStorageQueryTargetMetadataKey(targetId);\n var targetMetadata = new QueryTargetMetadata(targetId, state, error$$1);\n this.setItem(targetKey, targetMetadata.toWebStorageJSON());\n };\n /** Assembles the key for a client state in WebStorage */\n\n\n WebStorageSharedClientState.prototype.toWebStorageClientStateKey = function (clientId) {\n assert(clientId.indexOf('_') === -1, \"Client key cannot contain '_', but was '\" + clientId + \"'\");\n return CLIENT_STATE_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + clientId;\n };\n /** Assembles the key for a query state in WebStorage */\n\n\n WebStorageSharedClientState.prototype.toWebStorageQueryTargetMetadataKey = function (targetId) {\n return QUERY_TARGET_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + targetId;\n };\n /** Assembles the key for a mutation batch in WebStorage */\n\n\n WebStorageSharedClientState.prototype.toWebStorageMutationBatchKey = function (batchId) {\n var mutationKey = MUTATION_BATCH_KEY_PREFIX + \"_\" + this.persistenceKey + \"_\" + batchId;\n\n if (this.currentUser.isAuthenticated()) {\n mutationKey += \"_\" + this.currentUser.uid;\n }\n\n return mutationKey;\n };\n /**\r\n * Parses a client state key in WebStorage. Returns null if the key does not\r\n * match the expected key format.\r\n */\n\n\n WebStorageSharedClientState.prototype.fromWebStorageClientStateKey = function (key) {\n var match = this.clientStateKeyRe.exec(key);\n return match ? match[1] : null;\n };\n /**\r\n * Parses a client state in WebStorage. Returns 'null' if the value could not\r\n * be parsed.\r\n */\n\n\n WebStorageSharedClientState.prototype.fromWebStorageClientState = function (key, value) {\n var clientId = this.fromWebStorageClientStateKey(key);\n assert(clientId !== null, \"Cannot parse client state key '\" + key + \"'\");\n return RemoteClientState.fromWebStorageEntry(clientId, value);\n };\n /**\r\n * Parses a mutation batch state in WebStorage. Returns 'null' if the value\r\n * could not be parsed.\r\n */\n\n\n WebStorageSharedClientState.prototype.fromWebStorageMutationMetadata = function (key, value) {\n var match = this.mutationBatchKeyRe.exec(key);\n assert(match !== null, \"Cannot parse mutation batch key '\" + key + \"'\");\n var batchId = Number(match[1]);\n var userId = match[2] !== undefined ? match[2] : null;\n return MutationMetadata.fromWebStorageEntry(new User(userId), batchId, value);\n };\n /**\r\n * Parses a query target state from WebStorage. Returns 'null' if the value\r\n * could not be parsed.\r\n */\n\n\n WebStorageSharedClientState.prototype.fromWebStorageQueryTargetMetadata = function (key, value) {\n var match = this.queryTargetKeyRe.exec(key);\n assert(match !== null, \"Cannot parse query target key '\" + key + \"'\");\n var targetId = Number(match[1]);\n return QueryTargetMetadata.fromWebStorageEntry(targetId, value);\n };\n /**\r\n * Parses an online state from WebStorage. Returns 'null' if the value\r\n * could not be parsed.\r\n */\n\n\n WebStorageSharedClientState.prototype.fromWebStorageOnlineState = function (value) {\n return SharedOnlineState.fromWebStorageEntry(value);\n };\n\n WebStorageSharedClientState.prototype.handleMutationBatchEvent = function (mutationBatch) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (mutationBatch.user.uid !== this.currentUser.uid) {\n debug(LOG_TAG$10, \"Ignoring mutation for non-active user \" + mutationBatch.user.uid);\n return [2\n /*return*/\n ];\n }\n\n return [2\n /*return*/\n , this.syncEngine.applyBatchState(mutationBatch.batchId, mutationBatch.state, mutationBatch.error)];\n });\n });\n };\n\n WebStorageSharedClientState.prototype.handleQueryTargetEvent = function (targetMetadata) {\n return this.syncEngine.applyTargetState(targetMetadata.targetId, targetMetadata.state, targetMetadata.error);\n };\n\n WebStorageSharedClientState.prototype.handleClientStateEvent = function (clientId, clientState) {\n var _this = this;\n\n var existingTargets = this.getAllActiveQueryTargets();\n\n if (clientState) {\n this.activeClients[clientId] = clientState;\n } else {\n delete this.activeClients[clientId];\n }\n\n var newTargets = this.getAllActiveQueryTargets();\n var addedTargets = [];\n var removedTargets = [];\n newTargets.forEach(function (targetId) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (!existingTargets.has(targetId)) {\n addedTargets.push(targetId);\n }\n\n return [2\n /*return*/\n ];\n });\n });\n });\n existingTargets.forEach(function (targetId) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (!newTargets.has(targetId)) {\n removedTargets.push(targetId);\n }\n\n return [2\n /*return*/\n ];\n });\n });\n });\n return this.syncEngine.applyActiveTargetsChange(addedTargets, removedTargets);\n };\n\n WebStorageSharedClientState.prototype.handleOnlineStateEvent = function (onlineState) {\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[onlineState.clientId]) {\n this.onlineStateHandler(onlineState.onlineState);\n }\n };\n\n return WebStorageSharedClientState;\n}();\n\nfunction fromWebStorageSequenceNumber(seqString) {\n var sequenceNumber = ListenSequence.INVALID;\n\n if (seqString != null) {\n try {\n var parsed = JSON.parse(seqString);\n assert(typeof parsed === 'number', 'Found non-numeric sequence number');\n sequenceNumber = parsed;\n } catch (e) {\n error(LOG_TAG$10, 'Failed to read sequence number from WebStorage', e);\n }\n }\n\n return sequenceNumber;\n}\n/**\r\n * `MemorySharedClientState` is a simple implementation of SharedClientState for\r\n * clients using memory persistence. The state in this class remains fully\r\n * isolated and no synchronization is performed.\r\n */\n\n\nvar MemorySharedClientState =\n/** @class */\nfunction () {\n function MemorySharedClientState() {\n this.localState = new LocalClientState();\n this.queryState = {};\n this.syncEngine = null;\n this.onlineStateHandler = null;\n this.sequenceNumberHandler = null;\n }\n\n MemorySharedClientState.prototype.addPendingMutation = function (batchId) {// No op.\n };\n\n MemorySharedClientState.prototype.updateMutationState = function (batchId, state, error$$1) {// No op.\n };\n\n MemorySharedClientState.prototype.addLocalQueryTarget = function (targetId) {\n this.localState.addQueryTarget(targetId);\n return this.queryState[targetId] || 'not-current';\n };\n\n MemorySharedClientState.prototype.updateQueryState = function (targetId, state, error$$1) {\n this.queryState[targetId] = state;\n };\n\n MemorySharedClientState.prototype.removeLocalQueryTarget = function (targetId) {\n this.localState.removeQueryTarget(targetId);\n };\n\n MemorySharedClientState.prototype.isLocalQueryTarget = function (targetId) {\n return this.localState.activeTargetIds.has(targetId);\n };\n\n MemorySharedClientState.prototype.clearQueryState = function (targetId) {\n delete this.queryState[targetId];\n };\n\n MemorySharedClientState.prototype.getAllActiveQueryTargets = function () {\n return this.localState.activeTargetIds;\n };\n\n MemorySharedClientState.prototype.isActiveQueryTarget = function (targetId) {\n return this.localState.activeTargetIds.has(targetId);\n };\n\n MemorySharedClientState.prototype.start = function () {\n this.localState = new LocalClientState();\n return Promise.resolve();\n };\n\n MemorySharedClientState.prototype.handleUserChange = function (user, removedBatchIds, addedBatchIds) {// No op.\n };\n\n MemorySharedClientState.prototype.setOnlineState = function (onlineState) {// No op.\n };\n\n MemorySharedClientState.prototype.shutdown = function () {};\n\n MemorySharedClientState.prototype.writeSequenceNumber = function (sequenceNumber) {};\n\n return MemorySharedClientState;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LOG_TAG$11 = 'FirestoreClient';\n/** The DOMException code for an aborted operation. */\n\nvar DOM_EXCEPTION_ABORTED = 20;\n/** The DOMException code for quota exceeded. */\n\nvar DOM_EXCEPTION_QUOTA_EXCEEDED = 22;\n\nvar IndexedDbPersistenceSettings =\n/** @class */\nfunction () {\n function IndexedDbPersistenceSettings(cacheSizeBytes, experimentalTabSynchronization) {\n this.cacheSizeBytes = cacheSizeBytes;\n this.experimentalTabSynchronization = experimentalTabSynchronization;\n }\n\n IndexedDbPersistenceSettings.prototype.lruParams = function () {\n return LruParams.withCacheSize(this.cacheSizeBytes);\n };\n\n return IndexedDbPersistenceSettings;\n}();\n\nvar MemoryPersistenceSettings =\n/** @class */\nfunction () {\n function MemoryPersistenceSettings() {}\n\n return MemoryPersistenceSettings;\n}();\n/**\r\n * FirestoreClient is a top-level class that constructs and owns all of the\r\n * pieces of the client SDK architecture. It is responsible for creating the\r\n * async queue that is shared by all of the other components in the system.\r\n */\n\n\nvar FirestoreClient =\n/** @class */\nfunction () {\n function FirestoreClient(platform, databaseInfo, credentials,\n /**\r\n * Asynchronous queue responsible for all of our internal processing. When\r\n * we get incoming work from the user (via public API) or the network\r\n * (incoming GRPC messages), we should always schedule onto this queue.\r\n * This ensures all of our work is properly serialized (e.g. we don't\r\n * start processing a new operation while the previous one is waiting for\r\n * an async I/O to complete).\r\n */\n asyncQueue) {\n this.platform = platform;\n this.databaseInfo = databaseInfo;\n this.credentials = credentials;\n this.asyncQueue = asyncQueue;\n this.clientId = AutoId.newId();\n }\n /**\r\n * Starts up the FirestoreClient, returning only whether or not enabling\r\n * persistence succeeded.\r\n *\r\n * The intent here is to \"do the right thing\" as far as users are concerned.\r\n * Namely, in cases where offline persistence is requested and possible,\r\n * enable it, but otherwise fall back to persistence disabled. For the most\r\n * part we expect this to succeed one way or the other so we don't expect our\r\n * users to actually wait on the firestore.enablePersistence Promise since\r\n * they generally won't care.\r\n *\r\n * Of course some users actually do care about whether or not persistence\r\n * was successfully enabled, so the Promise returned from this method\r\n * indicates this outcome.\r\n *\r\n * This presents a problem though: even before enablePersistence resolves or\r\n * rejects, users may have made calls to e.g. firestore.collection() which\r\n * means that the FirestoreClient in there will be available and will be\r\n * enqueuing actions on the async queue.\r\n *\r\n * Meanwhile any failure of an operation on the async queue causes it to\r\n * panic and reject any further work, on the premise that unhandled errors\r\n * are fatal.\r\n *\r\n * Consequently the fallback is handled internally here in start, and if the\r\n * fallback succeeds we signal success to the async queue even though the\r\n * start() itself signals failure.\r\n *\r\n * @param persistenceSettings Settings object to configure offline\r\n * persistence.\r\n * @returns A deferred result indicating the user-visible result of enabling\r\n * offline persistence. This method will reject this if IndexedDB fails to\r\n * start for any reason. If usePersistence is false this is\r\n * unconditionally resolved.\r\n */\n\n\n FirestoreClient.prototype.start = function (persistenceSettings) {\n var _this = this; // We defer our initialization until we get the current user from\n // setChangeListener(). We block the async queue until we got the initial\n // user and the initialization is completed. This will prevent any scheduled\n // work from happening before initialization is completed.\n //\n // If initializationDone resolved then the FirestoreClient is in a usable\n // state.\n\n\n var initializationDone = new Deferred$1(); // If usePersistence is true, certain classes of errors while starting are\n // recoverable but only by falling back to persistence disabled.\n //\n // If there's an error in the first case but not in recovery we cannot\n // reject the promise blocking the async queue because this will cause the\n // async queue to panic.\n\n var persistenceResult = new Deferred$1();\n var initialized = false;\n this.credentials.setChangeListener(function (user) {\n if (!initialized) {\n initialized = true;\n\n _this.initializePersistence(persistenceSettings, persistenceResult, user).then(function (maybeLruGc) {\n return _this.initializeRest(user, maybeLruGc);\n }).then(initializationDone.resolve, initializationDone.reject);\n } else {\n _this.asyncQueue.enqueueAndForget(function () {\n return _this.handleCredentialChange(user);\n });\n }\n }); // Block the async queue until initialization is done\n\n this.asyncQueue.enqueueAndForget(function () {\n return initializationDone.promise;\n }); // Return only the result of enabling persistence. Note that this does not\n // need to await the completion of initializationDone because the result of\n // this method should not reflect any other kind of failure to start.\n\n return persistenceResult.promise;\n };\n /** Enables the network connection and requeues all pending operations. */\n\n\n FirestoreClient.prototype.enableNetwork = function () {\n var _this = this;\n\n return this.asyncQueue.enqueue(function () {\n return _this.syncEngine.enableNetwork();\n });\n };\n /**\r\n * Initializes persistent storage, attempting to use IndexedDB if\r\n * usePersistence is true or memory-only if false.\r\n *\r\n * If IndexedDB fails because it's already open in another tab or because the\r\n * platform can't possibly support our implementation then this method rejects\r\n * the persistenceResult and falls back on memory-only persistence.\r\n *\r\n * @param persistenceSettings Settings object to configure offline persistence\r\n * @param persistenceResult A deferred result indicating the user-visible\r\n * result of enabling offline persistence. This method will reject this if\r\n * IndexedDB fails to start for any reason. If usePersistence is false\r\n * this is unconditionally resolved.\r\n * @returns a Promise indicating whether or not initialization should\r\n * continue, i.e. that one of the persistence implementations actually\r\n * succeeded.\r\n */\n\n\n FirestoreClient.prototype.initializePersistence = function (persistenceSettings, persistenceResult, user) {\n var _this = this;\n\n if (persistenceSettings instanceof IndexedDbPersistenceSettings) {\n return this.startIndexedDbPersistence(user, persistenceSettings).then(function (maybeLruGc) {\n persistenceResult.resolve();\n return maybeLruGc;\n }).catch(function (error$$1) {\n // Regardless of whether or not the retry succeeds, from an user\n // perspective, offline persistence has failed.\n persistenceResult.reject(error$$1); // An unknown failure on the first stage shuts everything down.\n\n if (!_this.canFallback(error$$1)) {\n throw error$$1;\n }\n\n console.warn('Error enabling offline storage. Falling back to' + ' storage disabled: ' + error$$1);\n return _this.startMemoryPersistence();\n });\n } else {\n // When usePersistence == false, enabling offline persistence is defined\n // to unconditionally succeed. This allows start() to have the same\n // signature for both cases, despite the fact that the returned promise\n // is only used in the enablePersistence call.\n persistenceResult.resolve();\n return this.startMemoryPersistence();\n }\n };\n /**\r\n * Decides whether the provided error allows us to gracefully disable\r\n * persistence (as opposed to crashing the client).\r\n */\n\n\n FirestoreClient.prototype.canFallback = function (error$$1) {\n if (error$$1 instanceof FirestoreError) {\n return error$$1.code === Code.FAILED_PRECONDITION || error$$1.code === Code.UNIMPLEMENTED;\n } else if (typeof DOMException !== 'undefined' && error$$1 instanceof DOMException) {\n // We fall back to memory persistence if we cannot write the primary\n // lease. This can happen can during a schema migration, or if we run out\n // of quota when we try to write the primary lease.\n // For both the `QuotaExceededError` and the `AbortError`, it is safe to\n // fall back to memory persistence since all modifications to IndexedDb\n // failed to commit.\n return error$$1.code === DOM_EXCEPTION_QUOTA_EXCEEDED || error$$1.code === DOM_EXCEPTION_ABORTED;\n }\n\n return true;\n };\n /**\r\n * Starts IndexedDB-based persistence.\r\n *\r\n * @returns A promise indicating success or failure.\r\n */\n\n\n FirestoreClient.prototype.startIndexedDbPersistence = function (user, settings) {\n var _this = this; // TODO(http://b/33384523): For now we just disable garbage collection\n // when persistence is enabled.\n\n\n var storagePrefix = IndexedDbPersistence.buildStoragePrefix(this.databaseInfo); // Opt to use proto3 JSON in case the platform doesn't support Uint8Array.\n\n var serializer = new JsonProtoSerializer(this.databaseInfo.databaseId, {\n useProto3Json: true\n });\n return Promise.resolve().then(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var persistence, lruParams;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (settings.experimentalTabSynchronization && !WebStorageSharedClientState.isAvailable(this.platform)) {\n throw new FirestoreError(Code.UNIMPLEMENTED, 'IndexedDB persistence is only available on platforms that support LocalStorage.');\n }\n\n lruParams = settings.lruParams();\n if (!settings.experimentalTabSynchronization) return [3\n /*break*/\n , 2];\n this.sharedClientState = new WebStorageSharedClientState(this.asyncQueue, this.platform, storagePrefix, this.clientId, user);\n return [4\n /*yield*/\n , IndexedDbPersistence.createMultiClientIndexedDbPersistence(storagePrefix, this.clientId, this.platform, this.asyncQueue, serializer, lruParams, {\n sequenceNumberSyncer: this.sharedClientState\n })];\n\n case 1:\n persistence = _a.sent();\n return [3\n /*break*/\n , 4];\n\n case 2:\n this.sharedClientState = new MemorySharedClientState();\n return [4\n /*yield*/\n , IndexedDbPersistence.createIndexedDbPersistence(storagePrefix, this.clientId, this.platform, this.asyncQueue, serializer, lruParams)];\n\n case 3:\n persistence = _a.sent();\n _a.label = 4;\n\n case 4:\n this.persistence = persistence;\n return [2\n /*return*/\n , persistence.referenceDelegate.garbageCollector];\n }\n });\n });\n });\n };\n /**\r\n * Starts Memory-backed persistence. In practice this cannot fail.\r\n *\r\n * @returns A promise that will successfully resolve.\r\n */\n\n\n FirestoreClient.prototype.startMemoryPersistence = function () {\n this.persistence = MemoryPersistence.createEagerPersistence(this.clientId);\n this.sharedClientState = new MemorySharedClientState();\n return Promise.resolve(null);\n };\n /**\r\n * Initializes the rest of the FirestoreClient, assuming the initial user\r\n * has been obtained from the credential provider and some persistence\r\n * implementation is available in this.persistence.\r\n */\n\n\n FirestoreClient.prototype.initializeRest = function (user, maybeLruGc) {\n var _this = this;\n\n debug(LOG_TAG$11, 'Initializing. user=', user.uid);\n return this.platform.loadConnection(this.databaseInfo).then(function (connection) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n var _this = this;\n\n var serializer, datastore, remoteStoreOnlineStateChangedHandler, sharedClientStateOnlineStateChangedHandler;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n this.localStore = new LocalStore(this.persistence, user);\n\n if (maybeLruGc) {\n // We're running LRU Garbage collection. Set up the scheduler.\n this.lruScheduler = new LruScheduler(maybeLruGc, this.asyncQueue, this.localStore);\n this.lruScheduler.start();\n }\n\n serializer = this.platform.newSerializer(this.databaseInfo.databaseId);\n datastore = new Datastore(this.asyncQueue, connection, this.credentials, serializer);\n\n remoteStoreOnlineStateChangedHandler = function remoteStoreOnlineStateChangedHandler(onlineState) {\n return _this.syncEngine.applyOnlineStateChange(onlineState, OnlineStateSource.RemoteStore);\n };\n\n sharedClientStateOnlineStateChangedHandler = function sharedClientStateOnlineStateChangedHandler(onlineState) {\n return _this.syncEngine.applyOnlineStateChange(onlineState, OnlineStateSource.SharedClientState);\n };\n\n this.remoteStore = new RemoteStore(this.localStore, datastore, this.asyncQueue, remoteStoreOnlineStateChangedHandler);\n this.syncEngine = new SyncEngine(this.localStore, this.remoteStore, this.sharedClientState, user);\n this.sharedClientState.onlineStateHandler = sharedClientStateOnlineStateChangedHandler; // Set up wiring between sync engine and other components\n\n this.remoteStore.syncEngine = this.syncEngine;\n this.sharedClientState.syncEngine = this.syncEngine;\n this.eventMgr = new EventManager(this.syncEngine); // PORTING NOTE: LocalStore doesn't need an explicit start() on the Web.\n\n return [4\n /*yield*/\n , this.sharedClientState.start()];\n\n case 1:\n // PORTING NOTE: LocalStore doesn't need an explicit start() on the Web.\n _a.sent();\n\n return [4\n /*yield*/\n , this.remoteStore.start()];\n\n case 2:\n _a.sent(); // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n\n\n return [4\n /*yield*/\n , this.persistence.setPrimaryStateListener(function (isPrimary) {\n return _this.syncEngine.applyPrimaryState(isPrimary);\n })];\n\n case 3:\n // NOTE: This will immediately call the listener, so we make sure to\n // set it after localStore / remoteStore are started.\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n });\n };\n\n FirestoreClient.prototype.handleCredentialChange = function (user) {\n this.asyncQueue.verifyOperationInProgress();\n debug(LOG_TAG$11, 'Credential Changed. Current user: ' + user.uid);\n return this.syncEngine.handleCredentialChange(user);\n };\n /** Disables the network connection. Pending operations will not complete. */\n\n\n FirestoreClient.prototype.disableNetwork = function () {\n var _this = this;\n\n return this.asyncQueue.enqueue(function () {\n return _this.syncEngine.disableNetwork();\n });\n };\n\n FirestoreClient.prototype.shutdown = function (options) {\n var _this = this;\n\n return this.asyncQueue.enqueue(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n // PORTING NOTE: LocalStore does not need an explicit shutdown on web.\n if (this.lruScheduler) {\n this.lruScheduler.stop();\n }\n\n return [4\n /*yield*/\n , this.remoteStore.shutdown()];\n\n case 1:\n _a.sent();\n\n return [4\n /*yield*/\n , this.sharedClientState.shutdown()];\n\n case 2:\n _a.sent();\n\n return [4\n /*yield*/\n , this.persistence.shutdown(options && options.purgePersistenceWithDataLoss)];\n\n case 3:\n _a.sent(); // `removeChangeListener` must be called after shutting down the\n // RemoteStore as it will prevent the RemoteStore from retrieving\n // auth tokens.\n\n\n this.credentials.removeChangeListener();\n return [2\n /*return*/\n ];\n }\n });\n });\n });\n };\n\n FirestoreClient.prototype.listen = function (query, observer, options) {\n var _this = this;\n\n var listener = new QueryListener(query, observer, options);\n this.asyncQueue.enqueueAndForget(function () {\n return _this.eventMgr.listen(listener);\n });\n return listener;\n };\n\n FirestoreClient.prototype.unlisten = function (listener) {\n var _this = this;\n\n this.asyncQueue.enqueueAndForget(function () {\n return _this.eventMgr.unlisten(listener);\n });\n };\n\n FirestoreClient.prototype.getDocumentFromLocalCache = function (docKey) {\n var _this = this;\n\n return this.asyncQueue.enqueue(function () {\n return _this.localStore.readDocument(docKey);\n }).then(function (maybeDoc) {\n if (maybeDoc instanceof Document) {\n return maybeDoc;\n } else if (maybeDoc instanceof NoDocument) {\n return null;\n } else {\n throw new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from cache. (However, this document may ' + \"exist on the server. Run again without setting 'source' in \" + 'the GetOptions to attempt to retrieve the document from the ' + 'server.)');\n }\n });\n };\n\n FirestoreClient.prototype.getDocumentsFromLocalCache = function (query) {\n var _this = this;\n\n return this.asyncQueue.enqueue(function () {\n return _this.localStore.executeQuery(query);\n }).then(function (docs) {\n var remoteKeys = documentKeySet();\n var view = new View(query, remoteKeys);\n var viewDocChanges = view.computeDocChanges(docs);\n return view.applyChanges(viewDocChanges,\n /* updateLimboDocuments= */\n false).snapshot;\n });\n };\n\n FirestoreClient.prototype.write = function (mutations) {\n var _this = this;\n\n var deferred = new Deferred$1();\n this.asyncQueue.enqueueAndForget(function () {\n return _this.syncEngine.write(mutations, deferred);\n });\n return deferred.promise;\n };\n\n FirestoreClient.prototype.databaseId = function () {\n return this.databaseInfo.databaseId;\n };\n\n FirestoreClient.prototype.transaction = function (updateFunction) {\n var _this = this; // We have to wait for the async queue to be sure syncEngine is initialized.\n\n\n return this.asyncQueue.enqueue(function () {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n return [2\n /*return*/\n ];\n });\n });\n }).then(function () {\n return _this.syncEngine.runTransaction(updateFunction);\n });\n };\n\n return FirestoreClient;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/*\r\n * A wrapper implementation of Observer that will dispatch events\r\n * asynchronously. To allow immediate silencing, a mute call is added which\r\n * causes events scheduled to no longer be raised.\r\n */\n\n\nvar AsyncObserver =\n/** @class */\nfunction () {\n function AsyncObserver(observer) {\n this.observer = observer;\n /**\r\n * When set to true, will not raise future events. Necessary to deal with\r\n * async detachment of listener.\r\n */\n\n this.muted = false;\n }\n\n AsyncObserver.prototype.next = function (value) {\n this.scheduleEvent(this.observer.next, value);\n };\n\n AsyncObserver.prototype.error = function (error) {\n this.scheduleEvent(this.observer.error, error);\n };\n\n AsyncObserver.prototype.mute = function () {\n this.muted = true;\n };\n\n AsyncObserver.prototype.scheduleEvent = function (eventHandler, event) {\n var _this = this;\n\n if (!this.muted) {\n setTimeout(function () {\n if (!_this.muted) {\n eventHandler(event);\n }\n }, 0);\n }\n };\n\n return AsyncObserver;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n\n/**\r\n * A FieldPath refers to a field in a document. The path may consist of a single\r\n * field name (referring to a top-level field in the document), or a list of\r\n * field names (referring to a nested field in the document).\r\n */\n\n\nvar FieldPath$1 =\n/** @class */\nfunction () {\n /**\r\n * Creates a FieldPath from the provided field names. If more than one field\r\n * name is provided, the path will point to a nested field in a document.\r\n *\r\n * @param fieldNames A list of field names.\r\n */\n function FieldPath$$1() {\n var fieldNames = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n fieldNames[_i] = arguments[_i];\n }\n\n validateNamedArrayAtLeastNumberOfElements('FieldPath', fieldNames, 'fieldNames', 1);\n\n for (var i = 0; i < fieldNames.length; ++i) {\n validateArgType('FieldPath', 'string', i, fieldNames[i]);\n\n if (fieldNames[i].length === 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field name at argument $(i + 1). \" + 'Field names must not be empty.');\n }\n }\n\n this._internalPath = new FieldPath(fieldNames);\n }\n\n FieldPath$$1.documentId = function () {\n return FieldPath$$1._DOCUMENT_ID;\n };\n\n FieldPath$$1.prototype.isEqual = function (other) {\n if (!(other instanceof FieldPath$$1)) {\n throw invalidClassError('isEqual', 'FieldPath', 1, other);\n }\n\n return this._internalPath.isEqual(other._internalPath);\n };\n /**\r\n * Internal Note: The backend doesn't technically support querying by\r\n * document ID. Instead it queries by the entire document name (full path\r\n * included), but in the cases we currently support documentId(), the net\r\n * effect is the same.\r\n */\n\n\n FieldPath$$1._DOCUMENT_ID = new FieldPath$$1(FieldPath.keyField().canonicalString());\n return FieldPath$$1;\n}();\n/**\r\n * Matches any characters in a field path string that are reserved.\r\n */\n\n\nvar RESERVED = new RegExp('[~\\\\*/\\\\[\\\\]]');\n/**\r\n * Parses a field path string into a FieldPath, treating dots as separators.\r\n */\n\nfunction fromDotSeparatedString(path) {\n var found = path.search(RESERVED);\n\n if (found >= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not contain \" + \"'~', '*', '/', '[', or ']'\");\n }\n\n try {\n return new (FieldPath$1.bind.apply(FieldPath$1, [void 0].concat(path.split('.'))))();\n } catch (e) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid field path (\" + path + \"). Paths must not be empty, \" + \"begin with '.', end with '.', or contain '..'\");\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar OAuthToken =\n/** @class */\nfunction () {\n function OAuthToken(value, user) {\n this.user = user;\n this.type = 'OAuth';\n this.authHeaders = {\n Authorization: \"Bearer \" + value\n };\n }\n\n return OAuthToken;\n}();\n/** A CredentialsProvider that always yields an empty token. */\n\n\nvar EmptyCredentialsProvider =\n/** @class */\nfunction () {\n function EmptyCredentialsProvider() {\n /**\r\n * Stores the listener registered with setChangeListener()\r\n * This isn't actually necessary since the UID never changes, but we use this\r\n * to verify the listen contract is adhered to in tests.\r\n */\n this.changeListener = null;\n }\n\n EmptyCredentialsProvider.prototype.getToken = function () {\n return Promise.resolve(null);\n };\n\n EmptyCredentialsProvider.prototype.invalidateToken = function () {};\n\n EmptyCredentialsProvider.prototype.setChangeListener = function (changeListener) {\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\n this.changeListener = changeListener; // Fire with initial user.\n\n changeListener(User.UNAUTHENTICATED);\n };\n\n EmptyCredentialsProvider.prototype.removeChangeListener = function () {\n assert(this.changeListener !== null, 'removeChangeListener() when no listener registered');\n this.changeListener = null;\n };\n\n return EmptyCredentialsProvider;\n}();\n\nvar FirebaseCredentialsProvider =\n/** @class */\nfunction () {\n function FirebaseCredentialsProvider(app) {\n var _this = this;\n\n this.app = app;\n /**\r\n * The auth token listener registered with FirebaseApp, retained here so we\r\n * can unregister it.\r\n */\n\n this.tokenListener = null;\n /**\r\n * Counter used to detect if the token changed while a getToken request was\r\n * outstanding.\r\n */\n\n this.tokenCounter = 0;\n /** The listener registered with setChangeListener(). */\n\n this.changeListener = null;\n this.forceRefresh = false;\n\n this.tokenListener = function () {\n _this.tokenCounter++;\n _this.currentUser = _this.getUser();\n\n if (_this.changeListener) {\n _this.changeListener(_this.currentUser);\n }\n };\n\n this.tokenCounter = 0; // Will fire at least once where we set this.currentUser\n\n this.app.INTERNAL.addAuthTokenListener(this.tokenListener);\n }\n\n FirebaseCredentialsProvider.prototype.getToken = function () {\n var _this = this;\n\n assert(this.tokenListener != null, 'getToken cannot be called after listener removed.'); // 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\n var initialTokenCounter = this.tokenCounter;\n var forceRefresh = this.forceRefresh;\n this.forceRefresh = false;\n return this.app.INTERNAL.getToken(forceRefresh).then(function (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 throw new FirestoreError(Code.ABORTED, 'getToken aborted due to token change.');\n } else {\n if (tokenData) {\n assert(typeof tokenData.accessToken === 'string', 'Invalid tokenData returned from getToken():' + tokenData);\n return new OAuthToken(tokenData.accessToken, _this.currentUser);\n } else {\n return null;\n }\n }\n });\n };\n\n FirebaseCredentialsProvider.prototype.invalidateToken = function () {\n this.forceRefresh = true;\n };\n\n FirebaseCredentialsProvider.prototype.setChangeListener = function (changeListener) {\n assert(!this.changeListener, 'Can only call setChangeListener() once.');\n this.changeListener = changeListener; // Fire the initial event, but only if we received the initial user\n\n if (this.currentUser) {\n changeListener(this.currentUser);\n }\n };\n\n FirebaseCredentialsProvider.prototype.removeChangeListener = function () {\n assert(this.tokenListener != null, 'removeChangeListener() called twice');\n assert(this.changeListener !== null, 'removeChangeListener() called when no listener registered');\n this.app.INTERNAL.removeAuthTokenListener(this.tokenListener);\n this.tokenListener = null;\n this.changeListener = null;\n };\n\n FirebaseCredentialsProvider.prototype.getUser = function () {\n var currentUid = this.app.INTERNAL.getUid();\n assert(currentUid === null || typeof currentUid === 'string', 'Received invalid UID: ' + currentUid);\n return new User(currentUid);\n };\n\n return FirebaseCredentialsProvider;\n}();\n/*\r\n * FirstPartyToken provides a fresh token each time its value\r\n * is requested, because if the token is too old, requests will be rejected.\r\n * TODO(b/33147818) this implementation violates the current assumption that\r\n * tokens are immutable. We need to either revisit this assumption or come\r\n * up with some way for FPA to use the listen/unlisten interface.\r\n */\n\n\nvar FirstPartyToken =\n/** @class */\nfunction () {\n function FirstPartyToken(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n this.type = 'FirstParty';\n this.user = User.FIRST_PARTY;\n assert(this.gapi && this.gapi['auth'] && this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n\n Object.defineProperty(FirstPartyToken.prototype, \"authHeaders\", {\n get: function get() {\n return {\n Authorization: this.gapi['auth']['getAuthHeaderValueForFirstParty']([]),\n 'X-Goog-AuthUser': this.sessionIndex\n };\n },\n enumerable: true,\n configurable: true\n });\n return FirstPartyToken;\n}();\n/*\r\n * Provides user credentials required for the Firestore JavaScript SDK\r\n * to authenticate the user, using technique that is only available\r\n * to applications hosted by Google.\r\n */\n\n\nvar FirstPartyCredentialsProvider =\n/** @class */\nfunction () {\n function FirstPartyCredentialsProvider(gapi, sessionIndex) {\n this.gapi = gapi;\n this.sessionIndex = sessionIndex;\n assert(this.gapi && this.gapi['auth'] && this.gapi['auth']['getAuthHeaderValueForFirstParty'], 'unexpected gapi interface');\n }\n\n FirstPartyCredentialsProvider.prototype.getToken = function () {\n return Promise.resolve(new FirstPartyToken(this.gapi, this.sessionIndex));\n }; // TODO(33108925): can someone switch users w/o a page refresh?\n // TODO(33110621): need to understand token/session lifecycle\n\n\n FirstPartyCredentialsProvider.prototype.setChangeListener = function (changeListener) {\n // Fire with initial uid.\n changeListener(User.FIRST_PARTY);\n };\n\n FirstPartyCredentialsProvider.prototype.removeChangeListener = function () {};\n\n FirstPartyCredentialsProvider.prototype.invalidateToken = function () {};\n\n return FirstPartyCredentialsProvider;\n}();\n/**\r\n * Builds a CredentialsProvider depending on the type of\r\n * the credentials passed in.\r\n */\n\n\nfunction makeCredentialsProvider(credentials) {\n if (!credentials) {\n return new EmptyCredentialsProvider();\n }\n\n switch (credentials.type) {\n case 'gapi':\n return new FirstPartyCredentialsProvider(credentials.client, credentials.sessionIndex || '0');\n\n case 'provider':\n return credentials.client;\n\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeCredentialsProvider failed due to invalid credential type');\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction isPartialObserver(obj) {\n return implementsAnyMethods$1(obj, ['next', 'error', 'complete']);\n}\n/**\r\n * Returns true if obj is an object and contains at least one of the specified\r\n * methods.\r\n */\n\n\nfunction implementsAnyMethods$1(obj, methods) {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n var object = obj;\n\n for (var _i = 0, methods_1 = methods; _i < methods_1.length; _i++) {\n var method = methods_1[_i];\n\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n\n return false;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * An opaque base class for FieldValue sentinel objects in our public API,\r\n * with public static methods for creating said sentinel objects.\r\n */\n// tslint:disable-next-line:class-as-namespace We use this as a base class.\n\n\nvar FieldValueImpl =\n/** @class */\nfunction () {\n function FieldValueImpl(_methodName) {\n this._methodName = _methodName;\n }\n\n FieldValueImpl.delete = function () {\n return DeleteFieldValueImpl.instance;\n };\n\n FieldValueImpl.serverTimestamp = function () {\n return ServerTimestampFieldValueImpl.instance;\n };\n\n FieldValueImpl.arrayUnion = function () {\n var elements = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n elements[_i] = arguments[_i];\n }\n\n validateAtLeastNumberOfArgs('FieldValue.arrayUnion', arguments, 1); // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we need access to the Firestore instance.\n\n return new ArrayUnionFieldValueImpl(elements);\n };\n\n FieldValueImpl.arrayRemove = function () {\n var elements = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n elements[_i] = arguments[_i];\n }\n\n validateAtLeastNumberOfArgs('FieldValue.arrayRemove', arguments, 1); // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we need access to the Firestore instance.\n\n return new ArrayRemoveFieldValueImpl(elements);\n };\n\n FieldValueImpl.prototype.isEqual = function (other) {\n return this === other;\n };\n\n return FieldValueImpl;\n}();\n\nvar DeleteFieldValueImpl =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(DeleteFieldValueImpl, _super);\n\n function DeleteFieldValueImpl() {\n return _super.call(this, 'FieldValue.delete') || this;\n }\n /** Singleton instance. */\n\n\n DeleteFieldValueImpl.instance = new DeleteFieldValueImpl();\n return DeleteFieldValueImpl;\n}(FieldValueImpl);\n\nvar ServerTimestampFieldValueImpl =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ServerTimestampFieldValueImpl, _super);\n\n function ServerTimestampFieldValueImpl() {\n return _super.call(this, 'FieldValue.serverTimestamp') || this;\n }\n /** Singleton instance. */\n\n\n ServerTimestampFieldValueImpl.instance = new ServerTimestampFieldValueImpl();\n return ServerTimestampFieldValueImpl;\n}(FieldValueImpl);\n\nvar ArrayUnionFieldValueImpl =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ArrayUnionFieldValueImpl, _super);\n\n function ArrayUnionFieldValueImpl(_elements) {\n var _this = _super.call(this, 'FieldValue.arrayUnion') || this;\n\n _this._elements = _elements;\n return _this;\n }\n\n return ArrayUnionFieldValueImpl;\n}(FieldValueImpl);\n\nvar ArrayRemoveFieldValueImpl =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(ArrayRemoveFieldValueImpl, _super);\n\n function ArrayRemoveFieldValueImpl(_elements) {\n var _this = _super.call(this, 'FieldValue.arrayRemove') || this;\n\n _this._elements = _elements;\n return _this;\n }\n\n return ArrayRemoveFieldValueImpl;\n}(FieldValueImpl); // Public instance that disallows construction at runtime. This constructor is\n// used when exporting FieldValueImpl on firebase.firestore.FieldValue and will\n// be called FieldValue publicly. Internally we still use FieldValueImpl which\n// has a type-checked private constructor. Note that FieldValueImpl and\n// PublicFieldValue can be used interchangeably in instanceof checks.\n// For our internal TypeScript code PublicFieldValue doesn't exist as a type,\n// and so we need to use FieldValueImpl as type and export it too.\n// tslint:disable-next-line:variable-name We treat this as a class name.\n\n\nvar PublicFieldValue = makeConstructorPrivate(FieldValueImpl, 'Use FieldValue.() instead.');\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar RESERVED_FIELD_REGEX = /^__.*__$/;\n/** The result of parsing document data (e.g. for a setData call). */\n\nvar ParsedSetData =\n/** @class */\nfunction () {\n function ParsedSetData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n\n ParsedSetData.prototype.toMutations = function (key, precondition) {\n var mutations = [];\n\n if (this.fieldMask !== null) {\n mutations.push(new PatchMutation(key, this.data, this.fieldMask, precondition));\n } else {\n mutations.push(new SetMutation(key, this.data, precondition));\n }\n\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n\n return mutations;\n };\n\n return ParsedSetData;\n}();\n/** The result of parsing \"update\" data (i.e. for an updateData call). */\n\n\nvar ParsedUpdateData =\n/** @class */\nfunction () {\n function ParsedUpdateData(data, fieldMask, fieldTransforms) {\n this.data = data;\n this.fieldMask = fieldMask;\n this.fieldTransforms = fieldTransforms;\n }\n\n ParsedUpdateData.prototype.toMutations = function (key, precondition) {\n var mutations = [new PatchMutation(key, this.data, this.fieldMask, precondition)];\n\n if (this.fieldTransforms.length > 0) {\n mutations.push(new TransformMutation(key, this.fieldTransforms));\n }\n\n return mutations;\n };\n\n return ParsedUpdateData;\n}();\n/*\r\n * Represents what type of API method provided the data being parsed; useful\r\n * for determining which error conditions apply during parsing and providing\r\n * better error messages.\r\n */\n\n\nvar UserDataSource;\n\n(function (UserDataSource) {\n UserDataSource[UserDataSource[\"Set\"] = 0] = \"Set\";\n UserDataSource[UserDataSource[\"Update\"] = 1] = \"Update\";\n UserDataSource[UserDataSource[\"MergeSet\"] = 2] = \"MergeSet\";\n /**\r\n * Indicates the source is a where clause, cursor bound, arrayUnion()\r\n * element, etc. Of note, isWrite(source) will return false.\r\n */\n\n UserDataSource[UserDataSource[\"Argument\"] = 3] = \"Argument\";\n})(UserDataSource || (UserDataSource = {}));\n\nfunction isWrite(dataSource) {\n switch (dataSource) {\n case UserDataSource.Set: // fall through\n\n case UserDataSource.MergeSet: // fall through\n\n case UserDataSource.Update:\n return true;\n\n case UserDataSource.Argument:\n return false;\n\n default:\n throw fail(\"Unexpected case for UserDataSource: \" + dataSource);\n }\n}\n/** A \"context\" object passed around while parsing user data. */\n\n\nvar ParseContext =\n/** @class */\nfunction () {\n /**\r\n * Initializes a ParseContext with the given source and path.\r\n *\r\n * @param dataSource Indicates what kind of API method this data came from.\r\n * @param methodName The name of the method the user called to create this\r\n * ParseContext.\r\n * @param path A path within the object being parsed. This could be an empty\r\n * path (in which case the context represents the root of the data being\r\n * parsed), or a nonempty path (indicating the context represents a nested\r\n * location within the data).\r\n * @param arrayElement Whether or not this context corresponds to an element\r\n * of an array.\r\n * @param fieldTransforms A mutable list of field transforms encountered while\r\n * parsing the data.\r\n * @param fieldMask A mutable list of field paths encountered while parsing\r\n * the data.\r\n *\r\n * TODO(b/34871131): We don't support array paths right now, so path can be\r\n * null to indicate the context represents any location within an array (in\r\n * which case certain features will not work and errors will be somewhat\r\n * compromised).\r\n */\n function ParseContext(dataSource, methodName, path, arrayElement, fieldTransforms, fieldMask) {\n this.dataSource = dataSource;\n this.methodName = methodName;\n this.path = path;\n this.arrayElement = arrayElement; // Minor hack: If fieldTransforms is undefined, we assume this is an\n // external call and we need to validate the entire path.\n\n if (fieldTransforms === undefined) {\n this.validatePath();\n }\n\n this.arrayElement = arrayElement !== undefined ? arrayElement : false;\n this.fieldTransforms = fieldTransforms || [];\n this.fieldMask = fieldMask || [];\n }\n\n ParseContext.prototype.childContextForField = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath,\n /*arrayElement=*/\n false, this.fieldTransforms, this.fieldMask);\n context.validatePathSegment(field);\n return context;\n };\n\n ParseContext.prototype.childContextForFieldPath = function (field) {\n var childPath = this.path == null ? null : this.path.child(field);\n var context = new ParseContext(this.dataSource, this.methodName, childPath,\n /*arrayElement=*/\n false, this.fieldTransforms, this.fieldMask);\n context.validatePath();\n return context;\n };\n\n ParseContext.prototype.childContextForArray = function (index) {\n // TODO(b/34871131): We don't support array paths right now; so make path\n // null.\n return new ParseContext(this.dataSource, this.methodName,\n /*path=*/\n null,\n /*arrayElement=*/\n true, this.fieldTransforms, this.fieldMask);\n };\n\n ParseContext.prototype.createError = function (reason) {\n var fieldDescription = this.path === null || this.path.isEmpty() ? '' : \" (found in field \" + this.path.toString() + \")\";\n return new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + this.methodName + \"() called with invalid data. \" + reason + fieldDescription);\n };\n /** Returns 'true' if 'fieldPath' was traversed when creating this context. */\n\n\n ParseContext.prototype.contains = function (fieldPath) {\n return this.fieldMask.find(function (field) {\n return fieldPath.isPrefixOf(field);\n }) !== undefined || this.fieldTransforms.find(function (transform) {\n return fieldPath.isPrefixOf(transform.field);\n }) !== undefined;\n };\n\n ParseContext.prototype.validatePath = function () {\n // TODO(b/34871131): Remove null check once we have proper paths for fields\n // within arrays.\n if (this.path === null) {\n return;\n }\n\n for (var i = 0; i < this.path.length; i++) {\n this.validatePathSegment(this.path.get(i));\n }\n };\n\n ParseContext.prototype.validatePathSegment = function (segment) {\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 return ParseContext;\n}();\n/**\r\n * A placeholder object for DocumentReferences in this file, in order to\r\n * avoid a circular dependency. See the comments for `DataPreConverter` for\r\n * the full context.\r\n */\n\n\nvar DocumentKeyReference =\n/** @class */\nfunction () {\n function DocumentKeyReference(databaseId, key) {\n this.databaseId = databaseId;\n this.key = key;\n }\n\n return DocumentKeyReference;\n}();\n/**\r\n * Helper for parsing raw user input (provided via the API) into internal model\r\n * classes.\r\n */\n\n\nvar UserDataConverter =\n/** @class */\nfunction () {\n function UserDataConverter(preConverter) {\n this.preConverter = preConverter;\n }\n /** Parse document data from a non-merge set() call. */\n\n\n UserDataConverter.prototype.parseSetData = function (methodName, input) {\n var context = new ParseContext(UserDataSource.Set, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n return new ParsedSetData(updateData,\n /* fieldMask= */\n null, context.fieldTransforms);\n };\n /** Parse document data from a set() call with '{merge:true}'. */\n\n\n UserDataConverter.prototype.parseMergeData = function (methodName, input, fieldPaths) {\n var context = new ParseContext(UserDataSource.MergeSet, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var updateData = this.parseData(input, context);\n var fieldMask;\n var fieldTransforms;\n\n if (!fieldPaths) {\n fieldMask = FieldMask.fromArray(context.fieldMask);\n fieldTransforms = context.fieldTransforms;\n } else {\n var validatedFieldPaths = [];\n\n for (var _i = 0, fieldPaths_1 = fieldPaths; _i < fieldPaths_1.length; _i++) {\n var stringOrFieldPath = fieldPaths_1[_i];\n var fieldPath = void 0;\n\n if (stringOrFieldPath instanceof FieldPath$1) {\n fieldPath = stringOrFieldPath._internalPath;\n } else if (typeof stringOrFieldPath === 'string') {\n fieldPath = fieldPathFromDotSeparatedString(methodName, stringOrFieldPath);\n } else {\n throw fail('Expected stringOrFieldPath to be a string or a FieldPath');\n }\n\n if (!context.contains(fieldPath)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Field '\" + fieldPath + \"' is specified in your field mask but missing from your input data.\");\n }\n\n validatedFieldPaths.push(fieldPath);\n }\n\n fieldMask = FieldMask.fromArray(validatedFieldPaths);\n fieldTransforms = context.fieldTransforms.filter(function (transform) {\n return fieldMask.covers(transform.field);\n });\n }\n\n return new ParsedSetData(updateData, fieldMask, fieldTransforms);\n };\n /** Parse update data from an update() call. */\n\n\n UserDataConverter.prototype.parseUpdateData = function (methodName, input) {\n var _this = this;\n\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n validatePlainObject('Data must be an object, but it was:', context, input);\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n forEach(input, function (key, value) {\n var path = fieldPathFromDotSeparatedString(methodName, key);\n var childContext = context.childContextForFieldPath(path);\n value = _this.runPreConverter(value, childContext);\n\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 var parsedValue = _this.parseData(value, childContext);\n\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n });\n var mask = FieldMask.fromArray(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /** Parse update data from a list of field/value arguments. */\n\n\n UserDataConverter.prototype.parseUpdateVarargs = function (methodName, field, value, moreFieldsAndValues) {\n var context = new ParseContext(UserDataSource.Update, methodName, FieldPath.EMPTY_PATH);\n var keys = [fieldPathFromArgument(methodName, field)];\n var values$$1 = [value];\n\n if (moreFieldsAndValues.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() needs to be called with an even number \" + 'of arguments that alternate between field names and values.');\n }\n\n for (var i = 0; i < moreFieldsAndValues.length; i += 2) {\n keys.push(fieldPathFromArgument(methodName, moreFieldsAndValues[i]));\n values$$1.push(moreFieldsAndValues[i + 1]);\n }\n\n var fieldMaskPaths = [];\n var updateData = ObjectValue.EMPTY;\n\n for (var i = 0; i < keys.length; ++i) {\n var path = keys[i];\n var childContext = context.childContextForFieldPath(path);\n var value_1 = this.runPreConverter(values$$1[i], childContext);\n\n if (value_1 instanceof DeleteFieldValueImpl) {\n // Add it to the field mask, but don't add anything to updateData.\n fieldMaskPaths.push(path);\n } else {\n var parsedValue = this.parseData(value_1, childContext);\n\n if (parsedValue != null) {\n fieldMaskPaths.push(path);\n updateData = updateData.set(path, parsedValue);\n }\n }\n }\n\n var mask = FieldMask.fromArray(fieldMaskPaths);\n return new ParsedUpdateData(updateData, mask, context.fieldTransforms);\n };\n /**\r\n * Parse a \"query value\" (e.g. value in a where filter or a value in a cursor\r\n * bound).\r\n */\n\n\n UserDataConverter.prototype.parseQueryValue = function (methodName, input) {\n var context = new ParseContext(UserDataSource.Argument, methodName, FieldPath.EMPTY_PATH);\n var parsed = this.parseData(input, context);\n assert(parsed != null, 'Parsed data should not be null.');\n assert(context.fieldTransforms.length === 0, 'Field transforms should have been disallowed.');\n return parsed;\n };\n /** Sends data through this.preConverter, handling any thrown errors. */\n\n\n UserDataConverter.prototype.runPreConverter = function (input, context) {\n try {\n return this.preConverter(input);\n } catch (e) {\n var message = errorMessage(e);\n throw context.createError(message);\n }\n };\n /**\r\n * Internal helper for parsing user data.\r\n *\r\n * @param input Data to be parsed.\r\n * @param context A context object representing the current path being parsed,\r\n * the source of the data being parsed, etc.\r\n * @return The parsed value, or null if the value was a FieldValue sentinel\r\n * that should not be included in the resulting parsed data.\r\n */\n\n\n UserDataConverter.prototype.parseData = function (input, context) {\n input = this.runPreConverter(input, context);\n\n if (looksLikeJsonObject(input)) {\n validatePlainObject('Unsupported field value:', context, input);\n return this.parseObject(input, context);\n } else if (input instanceof FieldValueImpl) {\n // FieldValues usually parse into transforms (except FieldValue.delete())\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 this.parseSentinelFieldValue(input, context);\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 if (context.arrayElement) {\n throw context.createError('Nested arrays are not supported');\n }\n\n return this.parseArray(input, context);\n } else {\n return this.parseScalarValue(input, context);\n }\n }\n };\n\n UserDataConverter.prototype.parseObject = function (obj, context) {\n var _this = this;\n\n var result = new SortedMap(primitiveComparator);\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, function (key, val) {\n var parsedValue = _this.parseData(val, context.childContextForField(key));\n\n if (parsedValue != null) {\n result = result.insert(key, parsedValue);\n }\n });\n }\n\n return new ObjectValue(result);\n };\n\n UserDataConverter.prototype.parseArray = function (array, context) {\n var result = [];\n var entryIndex = 0;\n\n for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {\n var entry = array_1[_i];\n var parsedEntry = this.parseData(entry, 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.INSTANCE;\n }\n\n result.push(parsedEntry);\n entryIndex++;\n }\n\n return new ArrayValue(result);\n };\n /**\r\n * \"Parses\" the provided FieldValueImpl, adding any necessary transforms to\r\n * context.fieldTransforms.\r\n */\n\n\n UserDataConverter.prototype.parseSentinelFieldValue = function (value, context) {\n // Sentinels are only supported with writes, and not within arrays.\n if (!isWrite(context.dataSource)) {\n throw context.createError(value._methodName + \"() can only be used with update() and set()\");\n }\n\n if (context.path === null) {\n throw context.createError(value._methodName + \"() is not currently supported inside arrays\");\n }\n\n if (value instanceof DeleteFieldValueImpl) {\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 assert(context.path.length > 0, 'FieldValue.delete() at the top level should have already' + ' been handled.');\n throw context.createError('FieldValue.delete() can only appear at the top level ' + 'of your update data');\n } else {\n // We shouldn't encounter delete sentinels for queries or non-merge set() calls.\n throw context.createError('FieldValue.delete() cannot be used with set() unless you pass ' + '{merge:true}');\n }\n } else if (value instanceof ServerTimestampFieldValueImpl) {\n context.fieldTransforms.push(new FieldTransform(context.path, ServerTimestampTransform.instance));\n } else if (value instanceof ArrayUnionFieldValueImpl) {\n var parsedElements = this.parseArrayTransformElements(value._methodName, value._elements);\n var arrayUnion = new ArrayUnionTransformOperation(parsedElements);\n context.fieldTransforms.push(new FieldTransform(context.path, arrayUnion));\n } else if (value instanceof ArrayRemoveFieldValueImpl) {\n var parsedElements = this.parseArrayTransformElements(value._methodName, value._elements);\n var arrayRemove = new ArrayRemoveTransformOperation(parsedElements);\n context.fieldTransforms.push(new FieldTransform(context.path, arrayRemove));\n } else {\n fail('Unknown FieldValue type: ' + value);\n }\n };\n /**\r\n * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue)\r\n *\r\n * @return The parsed value\r\n */\n\n\n UserDataConverter.prototype.parseScalarValue = function (value, context) {\n if (value === null) {\n return NullValue.INSTANCE;\n } else if (typeof value === 'number') {\n if (isSafeInteger(value)) {\n return new IntegerValue(value);\n } else {\n return new DoubleValue(value);\n }\n } else if (typeof value === 'boolean') {\n return BooleanValue.of(value);\n } else if (typeof value === 'string') {\n return new StringValue(value);\n } else if (value instanceof Date) {\n return new TimestampValue(Timestamp.fromDate(value));\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 return new TimestampValue(new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000));\n } else if (value instanceof GeoPoint) {\n return new GeoPointValue(value);\n } else if (value instanceof Blob) {\n return new BlobValue(value);\n } else if (value instanceof DocumentKeyReference) {\n return new RefValue(value.databaseId, value.key);\n } else {\n throw context.createError(\"Unsupported field value: \" + valueDescription(value));\n }\n };\n\n UserDataConverter.prototype.parseArrayTransformElements = function (methodName, elements) {\n var _this = this;\n\n return elements.map(function (element, i) {\n // Although array transforms are used with writes, the actual elements\n // being unioned or removed are not considered writes since they cannot\n // contain any FieldValue sentinels, etc.\n var context = new ParseContext(UserDataSource.Argument, methodName, FieldPath.EMPTY_PATH);\n return _this.parseData(element, context.childContextForArray(i));\n });\n };\n\n return UserDataConverter;\n}();\n/**\r\n * Checks whether an object looks like a JSON object that should be converted\r\n * into a struct. Normal class/prototype instances are considered to look like\r\n * JSON objects since they should be converted to a struct value. Arrays, Dates,\r\n * GeoPoints, etc. are not considered to look like JSON objects since they map\r\n * to specific FieldValue types other than ObjectValue.\r\n */\n\n\nfunction looksLikeJsonObject(input) {\n return typeof input === 'object' && input !== null && !(input instanceof Array) && !(input instanceof Date) && !(input instanceof Timestamp) && !(input instanceof GeoPoint) && !(input instanceof Blob) && !(input instanceof DocumentKeyReference) && !(input instanceof FieldValueImpl);\n}\n\nfunction validatePlainObject(message, context, input) {\n if (!looksLikeJsonObject(input) || !isPlainObject(input)) {\n var description = valueDescription(input);\n\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/**\r\n * Helper that calls fromDotSeparatedString() but wraps any error thrown.\r\n */\n\n\nfunction fieldPathFromArgument(methodName, path) {\n if (path instanceof FieldPath$1) {\n return path._internalPath;\n } else if (typeof path === 'string') {\n return fieldPathFromDotSeparatedString(methodName, path);\n } else {\n var message = 'Field path arguments must be of type string or FieldPath.';\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\r\n * Wraps fromDotSeparatedString with an error message about the method that\r\n * was thrown.\r\n * @param methodName The publicly visible method name\r\n * @param path The dot-separated string form of a field path which will be split\r\n * on dots.\r\n */\n\n\nfunction fieldPathFromDotSeparatedString(methodName, path) {\n try {\n return fromDotSeparatedString(path)._internalPath;\n } catch (e) {\n var message = errorMessage(e);\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function \" + methodName + \"() called with invalid data. \" + message);\n }\n}\n/**\r\n * Extracts the message from a caught exception, which should be an Error object\r\n * though JS doesn't guarantee that.\r\n */\n\n\nfunction errorMessage(error) {\n return error instanceof Error ? error.message : error.toString();\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n// The objects that are a part of this API are exposed to third-parties as\n// compiled javascript so we want to flag our private members with a leading\n// underscore to discourage their use.\n// tslint:disable:strip-private-property-underscore\n// settings() defaults:\n\n\nvar DEFAULT_HOST = 'firestore.googleapis.com';\nvar DEFAULT_SSL = true;\nvar DEFAULT_TIMESTAMPS_IN_SNAPSHOTS = false;\n/**\r\n * Constant used to indicate the LRU garbage collection should be disabled.\r\n * Set this value as the `cacheSizeBytes` on the settings passed to the\r\n * `Firestore` instance.\r\n */\n\nvar CACHE_SIZE_UNLIMITED = LruParams.COLLECTION_DISABLED; // enablePersistence() defaults:\n\nvar DEFAULT_SYNCHRONIZE_TABS = false;\n/**\r\n * A concrete type describing all the values that can be applied via a\r\n * user-supplied firestore.Settings object. This is a separate type so that\r\n * defaults can be supplied and the value can be checked for equality.\r\n */\n\nvar FirestoreSettings =\n/** @class */\nfunction () {\n function FirestoreSettings(settings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"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 validateNamedType('settings', 'non-empty string', 'host', settings.host);\n this.host = settings.host;\n validateNamedOptionalType('settings', 'boolean', 'ssl', settings.ssl);\n this.ssl = defaulted(settings.ssl, DEFAULT_SSL);\n }\n\n validateOptionNames('settings', settings, ['host', 'ssl', 'credentials', 'timestampsInSnapshots', 'cacheSizeBytes']);\n validateNamedOptionalType('settings', 'object', 'credentials', settings.credentials);\n this.credentials = settings.credentials;\n validateNamedOptionalType('settings', 'boolean', 'timestampsInSnapshots', settings.timestampsInSnapshots);\n this.timestampsInSnapshots = defaulted(settings.timestampsInSnapshots, DEFAULT_TIMESTAMPS_IN_SNAPSHOTS);\n validateNamedOptionalType('settings', 'number', 'cacheSizeBytes', settings.cacheSizeBytes);\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LruParams.DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED && settings.cacheSizeBytes < LruParams.MINIMUM_CACHE_SIZE_BYTES) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"cacheSizeBytes must be at least \" + LruParams.MINIMUM_CACHE_SIZE_BYTES);\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n }\n\n FirestoreSettings.prototype.isEqual = function (other) {\n return this.host === other.host && this.ssl === other.ssl && this.timestampsInSnapshots === other.timestampsInSnapshots && this.credentials === other.credentials && this.cacheSizeBytes === other.cacheSizeBytes;\n };\n\n return FirestoreSettings;\n}();\n\nvar FirestoreConfig =\n/** @class */\nfunction () {\n function FirestoreConfig() {}\n\n return FirestoreConfig;\n}();\n/**\r\n * The root reference to the database.\r\n */\n\n\nvar Firestore =\n/** @class */\nfunction () {\n function Firestore(databaseIdOrApp) {\n var _this = this; // Public for use in tests.\n // TODO(mikelehen): Use modularized initialization instead.\n\n\n this._queue = new AsyncQueue();\n this.INTERNAL = {\n delete: function _delete(options) {\n return tslib_1.__awaiter(_this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n if (this._firestoreClient) {\n return [2\n /*return*/\n , this._firestoreClient.shutdown(options)];\n }\n\n return [2\n /*return*/\n ];\n });\n });\n }\n };\n var config = new FirestoreConfig();\n\n if (typeof databaseIdOrApp.options === 'object') {\n // This is very likely a Firebase app object\n // TODO(b/34177605): Can we somehow use instanceof?\n var app = databaseIdOrApp;\n config.firebaseApp = app;\n config.databaseId = Firestore.databaseIdFromApp(app);\n config.persistenceKey = config.firebaseApp.name;\n config.credentials = new FirebaseCredentialsProvider(app);\n } else {\n var external_1 = databaseIdOrApp;\n\n if (!external_1.projectId) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide projectId');\n }\n\n config.databaseId = new DatabaseId(external_1.projectId, external_1.database); // Use a default persistenceKey that lines up with FirebaseApp.\n\n config.persistenceKey = '[DEFAULT]';\n config.credentials = new EmptyCredentialsProvider();\n }\n\n config.settings = new FirestoreSettings({});\n this._config = config;\n this._databaseId = config.databaseId;\n }\n\n Firestore.prototype.settings = function (settingsLiteral) {\n validateExactNumberOfArgs('Firestore.settings', arguments, 1);\n validateArgType('Firestore.settings', 'object', 1, settingsLiteral);\n\n if (contains(settingsLiteral, 'persistence')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"persistence\" is now specified with a separate call to ' + 'firestore.enablePersistence().');\n }\n\n var newSettings = new FirestoreSettings(settingsLiteral);\n\n if (this._firestoreClient && !this._config.settings.isEqual(newSettings)) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + 'be changed. You can only call settings() before calling any other ' + 'methods on a Firestore object.');\n }\n\n this._config.settings = newSettings;\n\n if (newSettings.credentials !== undefined) {\n this._config.credentials = makeCredentialsProvider(newSettings.credentials);\n }\n };\n\n Firestore.prototype.enableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.enableNetwork();\n };\n\n Firestore.prototype.disableNetwork = function () {\n this.ensureClientConfigured();\n return this._firestoreClient.disableNetwork();\n };\n\n Firestore.prototype.enablePersistence = function (settings) {\n if (this._firestoreClient) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer ' + 'be enabled. You can only call enablePersistence() before calling ' + 'any other methods on a Firestore object.');\n }\n\n return this.configureClient(new IndexedDbPersistenceSettings(this._config.settings.cacheSizeBytes, settings !== undefined && defaulted(settings.experimentalTabSynchronization, DEFAULT_SYNCHRONIZE_TABS)));\n };\n\n Firestore.prototype.ensureClientConfigured = function () {\n if (!this._firestoreClient) {\n // Kick off starting the client but don't actually wait for it.\n // tslint:disable-next-line:no-floating-promises\n this.configureClient(new MemoryPersistenceSettings());\n }\n\n return this._firestoreClient;\n };\n\n Firestore.prototype.configureClient = function (persistenceSettings) {\n var _this = this;\n\n assert(!!this._config.settings.host, 'FirestoreSettings.host cannot be falsey');\n\n if (!this._config.settings.timestampsInSnapshots) {\n error(\"\\nThe behavior for Date objects stored in Firestore is going to change\\nAND YOUR APP MAY BREAK.\\nTo hide this warning and ensure your app does not break, you need to add the\\nfollowing code to your app before calling any other Cloud Firestore methods:\\n\\n const firestore = firebase.firestore();\\n const settings = {/* your settings... */ timestampsInSnapshots: true};\\n firestore.settings(settings);\\n\\nWith this change, timestamps stored in Cloud Firestore will be read back as\\nFirebase Timestamp objects instead of as system Date objects. So you will also\\nneed to update code expecting a Date to instead expect a Timestamp. For example:\\n\\n // Old:\\n const date = snapshot.get('created_at');\\n // New:\\n const timestamp = snapshot.get('created_at');\\n const date = timestamp.toDate();\\n\\nPlease audit all existing usages of Date when you enable the new behavior. In a\\nfuture release, the behavior will change to the new behavior, so if you do not\\nfollow these steps, YOUR APP MAY BREAK.\");\n }\n\n assert(!this._firestoreClient, 'configureClient() called multiple times');\n var databaseInfo = new DatabaseInfo(this._config.databaseId, this._config.persistenceKey, this._config.settings.host, this._config.settings.ssl);\n\n var preConverter = function preConverter(value) {\n if (value instanceof DocumentReference) {\n var thisDb = _this._config.databaseId;\n var otherDb = value.firestore._config.databaseId;\n\n if (!otherDb.isEqual(thisDb)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document reference is for database ' + (otherDb.projectId + \"/\" + otherDb.database + \" but should be \") + (\"for database \" + thisDb.projectId + \"/\" + thisDb.database));\n }\n\n return new DocumentKeyReference(_this._config.databaseId, value._key);\n } else {\n return value;\n }\n };\n\n this._dataConverter = new UserDataConverter(preConverter);\n this._firestoreClient = new FirestoreClient(PlatformSupport.getPlatform(), databaseInfo, this._config.credentials, this._queue);\n return this._firestoreClient.start(persistenceSettings);\n };\n\n Firestore.databaseIdFromApp = function (app) {\n var options = app.options;\n\n if (!contains(options, 'projectId')) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, '\"projectId\" not provided in firebase.initializeApp.');\n }\n\n var projectId = options['projectId'];\n\n if (!projectId || typeof projectId !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'projectId must be a string in FirebaseApp.options');\n }\n\n return new DatabaseId(projectId);\n };\n\n Object.defineProperty(Firestore.prototype, \"app\", {\n get: function get() {\n if (!this._config.firebaseApp) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, \"Firestore was not initialized using the Firebase SDK. 'app' is \" + 'not available');\n }\n\n return this._config.firebaseApp;\n },\n enumerable: true,\n configurable: true\n });\n\n Firestore.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('Firestore.collection', arguments, 1);\n validateArgType('Firestore.collection', 'non-empty string', 1, pathString);\n\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection path to collection()');\n }\n\n this.ensureClientConfigured();\n return new CollectionReference(ResourcePath.fromString(pathString), this);\n };\n\n Firestore.prototype.doc = function (pathString) {\n validateExactNumberOfArgs('Firestore.doc', arguments, 1);\n validateArgType('Firestore.doc', 'non-empty string', 1, pathString);\n\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty document path to doc()');\n }\n\n this.ensureClientConfigured();\n return DocumentReference.forPath(ResourcePath.fromString(pathString), this);\n };\n\n Firestore.prototype.runTransaction = function (updateFunction) {\n var _this = this;\n\n validateExactNumberOfArgs('Firestore.runTransaction', arguments, 1);\n validateArgType('Firestore.runTransaction', 'function', 1, updateFunction);\n return this.ensureClientConfigured().transaction(function (transaction) {\n return updateFunction(new Transaction$1(_this, transaction));\n });\n };\n\n Firestore.prototype.batch = function () {\n this.ensureClientConfigured();\n return new WriteBatch(this);\n };\n\n Object.defineProperty(Firestore, \"logLevel\", {\n get: function get() {\n switch (getLogLevel()) {\n case LogLevel.DEBUG:\n return 'debug';\n\n case LogLevel.ERROR:\n return 'error';\n\n case LogLevel.SILENT:\n return 'silent';\n\n default:\n return fail('Unknown log level: ' + getLogLevel());\n }\n },\n enumerable: true,\n configurable: true\n });\n\n Firestore.setLogLevel = function (level) {\n validateExactNumberOfArgs('Firestore.setLogLevel', arguments, 1);\n validateArgType('Firestore.setLogLevel', 'non-empty string', 1, level);\n\n switch (level) {\n case 'debug':\n setLogLevel(LogLevel.DEBUG);\n break;\n\n case 'error':\n setLogLevel(LogLevel.ERROR);\n break;\n\n case 'silent':\n setLogLevel(LogLevel.SILENT);\n break;\n\n default:\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid log level: ' + level);\n }\n }; // Note: this is not a property because the minifier can't work correctly with\n // the way TypeScript compiler outputs properties.\n\n\n Firestore.prototype._areTimestampsInSnapshotsEnabled = function () {\n return this._config.settings.timestampsInSnapshots;\n };\n\n return Firestore;\n}();\n/**\r\n * A reference to a transaction.\r\n */\n\n\nvar Transaction$1 =\n/** @class */\nfunction () {\n function Transaction(_firestore, _transaction) {\n this._firestore = _firestore;\n this._transaction = _transaction;\n }\n\n Transaction.prototype.get = function (documentRef) {\n var _this = this;\n\n validateExactNumberOfArgs('Transaction.get', arguments, 1);\n var ref = validateReference('Transaction.get', documentRef, this._firestore);\n return this._transaction.lookup([ref._key]).then(function (docs) {\n if (!docs || docs.length !== 1) {\n return fail('Mismatch in docs returned from document lookup.');\n }\n\n var doc = docs[0];\n\n if (doc instanceof NoDocument) {\n return new DocumentSnapshot(_this._firestore, ref._key, null,\n /* fromCache= */\n false,\n /* hasPendingWrites= */\n false);\n } else if (doc instanceof Document) {\n return new DocumentSnapshot(_this._firestore, ref._key, doc,\n /* fromCache= */\n false,\n /* hasPendingWrites= */\n false);\n } else {\n throw fail(\"BatchGetDocumentsRequest returned unexpected document type: \" + doc.constructor.name);\n }\n });\n };\n\n Transaction.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('Transaction.set', arguments, 2, 3);\n var ref = validateReference('Transaction.set', documentRef, this._firestore);\n options = validateSetOptions('Transaction.set', options);\n var parsed = options.merge || options.mergeFields ? this._firestore._dataConverter.parseMergeData('Transaction.set', value, options.mergeFields) : this._firestore._dataConverter.parseSetData('Transaction.set', value);\n\n this._transaction.set(ref._key, parsed);\n\n return this;\n };\n\n Transaction.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n\n var ref;\n var parsed;\n\n if (typeof fieldOrUpdateData === 'string' || fieldOrUpdateData instanceof FieldPath$1) {\n validateAtLeastNumberOfArgs('Transaction.update', arguments, 3);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('Transaction.update', fieldOrUpdateData, value, moreFieldsAndValues);\n } else {\n validateExactNumberOfArgs('Transaction.update', arguments, 2);\n ref = validateReference('Transaction.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('Transaction.update', fieldOrUpdateData);\n }\n\n this._transaction.update(ref._key, parsed);\n\n return this;\n };\n\n Transaction.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('Transaction.delete', arguments, 1);\n var ref = validateReference('Transaction.delete', documentRef, this._firestore);\n\n this._transaction.delete(ref._key);\n\n return this;\n };\n\n return Transaction;\n}();\n\nvar WriteBatch =\n/** @class */\nfunction () {\n function WriteBatch(_firestore) {\n this._firestore = _firestore;\n this._mutations = [];\n this._committed = false;\n }\n\n WriteBatch.prototype.set = function (documentRef, value, options) {\n validateBetweenNumberOfArgs('WriteBatch.set', arguments, 2, 3);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.set', documentRef, this._firestore);\n options = validateSetOptions('WriteBatch.set', options);\n var parsed = options.merge || options.mergeFields ? this._firestore._dataConverter.parseMergeData('WriteBatch.set', value, options.mergeFields) : this._firestore._dataConverter.parseSetData('WriteBatch.set', value);\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.NONE));\n return this;\n };\n\n WriteBatch.prototype.update = function (documentRef, fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n\n for (var _i = 3; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 3] = arguments[_i];\n }\n\n this.verifyNotCommitted();\n var ref;\n var parsed;\n\n if (typeof fieldOrUpdateData === 'string' || fieldOrUpdateData instanceof FieldPath$1) {\n validateAtLeastNumberOfArgs('WriteBatch.update', arguments, 3);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateVarargs('WriteBatch.update', fieldOrUpdateData, value, moreFieldsAndValues);\n } else {\n validateExactNumberOfArgs('WriteBatch.update', arguments, 2);\n ref = validateReference('WriteBatch.update', documentRef, this._firestore);\n parsed = this._firestore._dataConverter.parseUpdateData('WriteBatch.update', fieldOrUpdateData);\n }\n\n this._mutations = this._mutations.concat(parsed.toMutations(ref._key, Precondition.exists(true)));\n return this;\n };\n\n WriteBatch.prototype.delete = function (documentRef) {\n validateExactNumberOfArgs('WriteBatch.delete', arguments, 1);\n this.verifyNotCommitted();\n var ref = validateReference('WriteBatch.delete', documentRef, this._firestore);\n this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.NONE));\n return this;\n };\n\n WriteBatch.prototype.commit = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n return tslib_1.__generator(this, function (_a) {\n this.verifyNotCommitted();\n this._committed = true;\n\n if (this._mutations.length > 0) {\n return [2\n /*return*/\n , this._firestore.ensureClientConfigured().write(this._mutations)];\n }\n\n return [2\n /*return*/\n ];\n });\n });\n };\n\n WriteBatch.prototype.verifyNotCommitted = function () {\n if (this._committed) {\n throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + 'has been called.');\n }\n };\n\n return WriteBatch;\n}();\n/**\r\n * A reference to a particular document in a collection in the database.\r\n */\n\n\nvar DocumentReference =\n/** @class */\nfunction () {\n function DocumentReference(_key, firestore) {\n this._key = _key;\n this.firestore = firestore;\n this._firestoreClient = this.firestore.ensureClientConfigured();\n }\n\n DocumentReference.forPath = function (path, firestore) {\n if (path.length % 2 !== 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid document reference. Document ' + 'references must have an even number of segments, but ' + (path.canonicalString() + \" has \" + path.length));\n }\n\n return new DocumentReference(new DocumentKey(path), firestore);\n };\n\n Object.defineProperty(DocumentReference.prototype, \"id\", {\n get: function get() {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"parent\", {\n get: function get() {\n return new CollectionReference(this._key.path.popLast(), this.firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentReference.prototype, \"path\", {\n get: function get() {\n return this._key.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n\n DocumentReference.prototype.collection = function (pathString) {\n validateExactNumberOfArgs('DocumentReference.collection', arguments, 1);\n validateArgType('DocumentReference.collection', 'non-empty string', 1, pathString);\n\n if (!pathString) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Must provide a non-empty collection name to collection()');\n }\n\n var path = ResourcePath.fromString(pathString);\n return new CollectionReference(this._key.path.child(path), this.firestore);\n };\n\n DocumentReference.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentReference)) {\n throw invalidClassError('isEqual', 'DocumentReference', 1, other);\n }\n\n return this.firestore === other.firestore && this._key.isEqual(other._key);\n };\n\n DocumentReference.prototype.set = function (value, options) {\n validateBetweenNumberOfArgs('DocumentReference.set', arguments, 1, 2);\n options = validateSetOptions('DocumentReference.set', options);\n var parsed = options.merge || options.mergeFields ? this.firestore._dataConverter.parseMergeData('DocumentReference.set', value, options.mergeFields) : this.firestore._dataConverter.parseSetData('DocumentReference.set', value);\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.NONE));\n };\n\n DocumentReference.prototype.update = function (fieldOrUpdateData, value) {\n var moreFieldsAndValues = [];\n\n for (var _i = 2; _i < arguments.length; _i++) {\n moreFieldsAndValues[_i - 2] = arguments[_i];\n }\n\n var parsed;\n\n if (typeof fieldOrUpdateData === 'string' || fieldOrUpdateData instanceof FieldPath$1) {\n validateAtLeastNumberOfArgs('DocumentReference.update', arguments, 2);\n parsed = this.firestore._dataConverter.parseUpdateVarargs('DocumentReference.update', fieldOrUpdateData, value, moreFieldsAndValues);\n } else {\n validateExactNumberOfArgs('DocumentReference.update', arguments, 1);\n parsed = this.firestore._dataConverter.parseUpdateData('DocumentReference.update', fieldOrUpdateData);\n }\n\n return this._firestoreClient.write(parsed.toMutations(this._key, Precondition.exists(true)));\n };\n\n DocumentReference.prototype.delete = function () {\n validateExactNumberOfArgs('DocumentReference.delete', arguments, 0);\n return this._firestoreClient.write([new DeleteMutation(this._key, Precondition.NONE)]);\n };\n\n DocumentReference.prototype.onSnapshot = function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n validateBetweenNumberOfArgs('DocumentReference.onSnapshot', arguments, 1, 4);\n var options = {\n includeMetadataChanges: false\n };\n var observer;\n var currArg = 0;\n\n if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('DocumentReference.onSnapshot', options, ['includeMetadataChanges']);\n validateNamedOptionalType('DocumentReference.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n\n var internalOptions = {\n includeMetadataChanges: options.includeMetadataChanges\n };\n\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n } else {\n validateArgType('DocumentReference.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('DocumentReference.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n\n return this.onSnapshotInternal(internalOptions, observer);\n };\n\n DocumentReference.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n\n var errHandler = function errHandler(err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n\n var asyncObserver = new AsyncObserver({\n next: function next(snapshot) {\n if (observer.next) {\n assert(snapshot.docs.size <= 1, 'Too many documents returned on a document query');\n var doc = snapshot.docs.get(_this._key);\n observer.next(new DocumentSnapshot(_this.firestore, _this._key, doc, snapshot.fromCache, snapshot.hasPendingWrites));\n }\n },\n error: errHandler\n });\n\n var internalListener = this._firestoreClient.listen(Query.atPath(this._key.path), asyncObserver, options);\n\n return function () {\n asyncObserver.mute();\n\n _this._firestoreClient.unlisten(internalListener);\n };\n };\n\n DocumentReference.prototype.get = function (options) {\n var _this = this;\n\n validateBetweenNumberOfArgs('DocumentReference.get', arguments, 0, 1);\n validateGetOptions('DocumentReference.get', options);\n return new Promise(function (resolve, reject) {\n if (options && options.source === 'cache') {\n _this.firestore.ensureClientConfigured().getDocumentFromLocalCache(_this._key).then(function (doc) {\n resolve(new DocumentSnapshot(_this.firestore, _this._key, doc,\n /*fromCache=*/\n true, doc instanceof Document ? doc.hasLocalMutations : false));\n }, reject);\n } else {\n _this.getViaSnapshotListener(resolve, reject, options);\n }\n });\n };\n\n DocumentReference.prototype.getViaSnapshotListener = function (resolve, reject, options) {\n var unlisten = this.onSnapshotInternal({\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function next(snap) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n\n if (!snap.exists && snap.metadata.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 reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document because the client is ' + 'offline.'));\n } else if (snap.exists && snap.metadata.fromCache && options && options.source === 'server') {\n reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from server. (However, this ' + 'document does exist in the local cache. Run again ' + 'without setting source to \"server\" to ' + 'retrieve the cached document.)'));\n } else {\n resolve(snap);\n }\n },\n error: reject\n });\n };\n\n return DocumentReference;\n}();\n\nvar SnapshotMetadata =\n/** @class */\nfunction () {\n function SnapshotMetadata(hasPendingWrites, fromCache) {\n this.hasPendingWrites = hasPendingWrites;\n this.fromCache = fromCache;\n }\n\n SnapshotMetadata.prototype.isEqual = function (other) {\n return this.hasPendingWrites === other.hasPendingWrites && this.fromCache === other.fromCache;\n };\n\n return SnapshotMetadata;\n}();\n\nvar DocumentSnapshot =\n/** @class */\nfunction () {\n function DocumentSnapshot(_firestore, _key, _document, _fromCache, _hasPendingWrites) {\n this._firestore = _firestore;\n this._key = _key;\n this._document = _document;\n this._fromCache = _fromCache;\n this._hasPendingWrites = _hasPendingWrites;\n }\n\n DocumentSnapshot.prototype.data = function (options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.data', arguments, 0, 1);\n options = validateSnapshotOptions('DocumentSnapshot.data', options);\n return !this._document ? undefined : this.convertObject(this._document.data, FieldValueOptions.fromSnapshotOptions(options, this._firestore._areTimestampsInSnapshotsEnabled()));\n };\n\n DocumentSnapshot.prototype.get = function (fieldPath, options) {\n validateBetweenNumberOfArgs('DocumentSnapshot.get', arguments, 1, 2);\n options = validateSnapshotOptions('DocumentSnapshot.get', options);\n\n if (this._document) {\n var value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath));\n\n if (value !== undefined) {\n return this.convertValue(value, FieldValueOptions.fromSnapshotOptions(options, this._firestore._areTimestampsInSnapshotsEnabled()));\n }\n }\n\n return undefined;\n };\n\n Object.defineProperty(DocumentSnapshot.prototype, \"id\", {\n get: function get() {\n return this._key.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"ref\", {\n get: function get() {\n return new DocumentReference(this._key, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"exists\", {\n get: function get() {\n return this._document !== null;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(DocumentSnapshot.prototype, \"metadata\", {\n get: function get() {\n return new SnapshotMetadata(this._hasPendingWrites, this._fromCache);\n },\n enumerable: true,\n configurable: true\n });\n\n DocumentSnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof DocumentSnapshot)) {\n throw invalidClassError('isEqual', 'DocumentSnapshot', 1, other);\n }\n\n return this._firestore === other._firestore && this._fromCache === other._fromCache && this._key.isEqual(other._key) && (this._document === null ? other._document === null : this._document.isEqual(other._document));\n };\n\n DocumentSnapshot.prototype.convertObject = function (data, options) {\n var _this = this;\n\n var result = {};\n data.forEach(function (key, value) {\n result[key] = _this.convertValue(value, options);\n });\n return result;\n };\n\n DocumentSnapshot.prototype.convertValue = function (value, options) {\n if (value instanceof ObjectValue) {\n return this.convertObject(value, options);\n } else if (value instanceof ArrayValue) {\n return this.convertArray(value, options);\n } else if (value instanceof RefValue) {\n var key = value.value(options);\n\n var database = this._firestore.ensureClientConfigured().databaseId();\n\n if (!value.databaseId.isEqual(database)) {\n // TODO(b/64130202): Somehow support foreign references.\n error(\"Document \" + this._key.path + \" contains a document \" + \"reference within a different database (\" + (value.databaseId.projectId + \"/\" + value.databaseId.database + \") which is not \") + \"supported. It will be treated as a reference in the current \" + (\"database (\" + database.projectId + \"/\" + database.database + \") \") + \"instead.\");\n }\n\n return new DocumentReference(key, this._firestore);\n } else {\n return value.value(options);\n }\n };\n\n DocumentSnapshot.prototype.convertArray = function (data, options) {\n var _this = this;\n\n return data.internalValue.map(function (value) {\n return _this.convertValue(value, options);\n });\n };\n\n return DocumentSnapshot;\n}();\n\nvar QueryDocumentSnapshot =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(QueryDocumentSnapshot, _super);\n\n function QueryDocumentSnapshot(firestore, key, document, fromCache, hasPendingWrites) {\n return _super.call(this, firestore, key, document, fromCache, hasPendingWrites) || this;\n }\n\n QueryDocumentSnapshot.prototype.data = function (options) {\n var data = _super.prototype.data.call(this, options);\n\n assert(typeof data === 'object', 'Document in a QueryDocumentSnapshot should exist');\n return data;\n };\n\n return QueryDocumentSnapshot;\n}(DocumentSnapshot);\n\nvar Query$1 =\n/** @class */\nfunction () {\n function Query$$1(_query, firestore) {\n this._query = _query;\n this.firestore = firestore;\n }\n\n Query$$1.prototype.where = function (field, opStr, value) {\n validateExactNumberOfArgs('Query.where', arguments, 3);\n validateArgType('Query.where', 'non-empty string', 2, opStr);\n validateDefined('Query.where', 3, value);\n var fieldValue;\n var fieldPath = fieldPathFromArgument('Query.where', field);\n var relationOp = RelationOp.fromString(opStr);\n\n if (fieldPath.isKeyField()) {\n if (relationOp === RelationOp.ARRAY_CONTAINS) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. You can't perform array-contains queries on \" + 'FieldPath.documentId() since document IDs are not arrays.');\n }\n\n if (typeof value === 'string') {\n if (value.indexOf('/') !== -1) {\n // TODO(dimond): Allow slashes once ancestor queries are supported\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' + 'valid document ID if the first parameter is ' + 'FieldPath.documentId(), but it contains a slash.');\n }\n\n if (value === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Function Query.where() requires its third parameter to be a ' + 'valid document ID if the first parameter is ' + 'FieldPath.documentId(), but it was an empty string.');\n }\n\n var path = this._query.path.child(new ResourcePath([value]));\n\n assert(path.length % 2 === 0, 'Path should be a document key');\n fieldValue = new RefValue(this.firestore._databaseId, new DocumentKey(path));\n } else if (value instanceof DocumentReference) {\n var ref = value;\n fieldValue = new RefValue(this.firestore._databaseId, ref._key);\n } else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.where() requires its third parameter to be a \" + \"string or a DocumentReference if the first parameter is \" + \"FieldPath.documentId(), but it was: \" + (valueDescription(value) + \".\"));\n }\n } else {\n fieldValue = this.firestore._dataConverter.parseQueryValue('Query.where', value);\n }\n\n var filter = Filter.create(fieldPath, relationOp, fieldValue);\n this.validateNewFilter(filter);\n return new Query$$1(this._query.addFilter(filter), this.firestore);\n };\n\n Query$$1.prototype.orderBy = function (field, directionStr) {\n validateBetweenNumberOfArgs('Query.orderBy', arguments, 1, 2);\n validateOptionalArgType('Query.orderBy', 'non-empty string', 2, directionStr);\n var direction;\n\n if (directionStr === undefined || directionStr === 'asc') {\n direction = Direction.ASCENDING;\n } else if (directionStr === 'desc') {\n direction = Direction.DESCENDING;\n } else {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Function Query.orderBy() has unknown direction '\" + directionStr + \"', \" + \"expected 'asc' or 'desc'.\");\n }\n\n if (this._query.startAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.startAt() or ' + 'Query.startAfter() before calling Query.orderBy().');\n }\n\n if (this._query.endAt !== null) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call Query.endAt() or ' + 'Query.endBefore() before calling Query.orderBy().');\n }\n\n var fieldPath = fieldPathFromArgument('Query.orderBy', field);\n var orderBy = new OrderBy(fieldPath, direction);\n this.validateNewOrderBy(orderBy);\n return new Query$$1(this._query.addOrderBy(orderBy), this.firestore);\n };\n\n Query$$1.prototype.limit = function (n) {\n validateExactNumberOfArgs('Query.limit', arguments, 1);\n validateArgType('Query.limit', 'number', 1, n);\n\n if (n <= 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid Query. Query limit (\" + n + \") is invalid. Limit must be \" + 'positive.');\n }\n\n return new Query$$1(this._query.withLimit(n), this.firestore);\n };\n\n Query$$1.prototype.startAt = function (docOrField) {\n var fields = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n\n validateAtLeastNumberOfArgs('Query.startAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAt', docOrField, fields,\n /*before=*/\n true);\n return new Query$$1(this._query.withStartAt(bound), this.firestore);\n };\n\n Query$$1.prototype.startAfter = function (docOrField) {\n var fields = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n\n validateAtLeastNumberOfArgs('Query.startAfter', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.startAfter', docOrField, fields,\n /*before=*/\n false);\n return new Query$$1(this._query.withStartAt(bound), this.firestore);\n };\n\n Query$$1.prototype.endBefore = function (docOrField) {\n var fields = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n\n validateAtLeastNumberOfArgs('Query.endBefore', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endBefore', docOrField, fields,\n /*before=*/\n true);\n return new Query$$1(this._query.withEndAt(bound), this.firestore);\n };\n\n Query$$1.prototype.endAt = function (docOrField) {\n var fields = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n fields[_i - 1] = arguments[_i];\n }\n\n validateAtLeastNumberOfArgs('Query.endAt', arguments, 1);\n var bound = this.boundFromDocOrFields('Query.endAt', docOrField, fields,\n /*before=*/\n false);\n return new Query$$1(this._query.withEndAt(bound), this.firestore);\n };\n\n Query$$1.prototype.isEqual = function (other) {\n if (!(other instanceof Query$$1)) {\n throw invalidClassError('isEqual', 'Query', 1, other);\n }\n\n return this.firestore === other.firestore && this._query.isEqual(other._query);\n };\n /** Helper function to create a bound from a document or fields */\n\n\n Query$$1.prototype.boundFromDocOrFields = function (methodName, docOrField, fields, before) {\n validateDefined(methodName, 1, docOrField);\n\n if (docOrField instanceof DocumentSnapshot) {\n if (fields.length > 0) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"().\");\n }\n\n var snap = docOrField;\n\n if (!snap.exists) {\n throw new FirestoreError(Code.NOT_FOUND, \"Can't use a DocumentSnapshot that doesn't exist for \" + (methodName + \"().\"));\n }\n\n return this.boundFromDocument(methodName, snap._document, before);\n } else {\n var allFields = [docOrField].concat(fields);\n return this.boundFromFields(methodName, allFields, before);\n }\n };\n /**\r\n * Create a Bound from a query and a document.\r\n *\r\n * Note that the Bound will always include the key of the document\r\n * and so only the provided document will compare equal to the returned\r\n * position.\r\n *\r\n * Will throw if the document does not contain all fields of the order by\r\n * of the query.\r\n */\n\n\n Query$$1.prototype.boundFromDocument = function (methodName, doc, before) {\n var components = []; // 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\n for (var _i = 0, _a = this._query.orderBy; _i < _a.length; _i++) {\n var orderBy = _a[_i];\n\n if (orderBy.field.isKeyField()) {\n components.push(new RefValue(this.firestore._databaseId, doc.key));\n } else {\n var value = doc.field(orderBy.field);\n\n if (value !== undefined) {\n components.push(value);\n } else {\n var field = orderBy.field.canonicalString();\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You are trying to start or end a query using a \" + (\"document for which the field '\" + field + \"' (used as the \") + \"orderBy) does not exist.\");\n }\n }\n }\n\n return new Bound(components, before);\n };\n /**\r\n * Converts a list of field values to a Bound for the given query.\r\n */\n\n\n Query$$1.prototype.boundFromFields = function (methodName, values$$1, before) {\n // Use explicit order by's because it has to match the query the user made\n var orderBy = this._query.explicitOrderBy;\n\n if (values$$1.length > orderBy.length) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Too many arguments provided to \" + methodName + \"(). \" + \"The number of arguments must be less than or equal to the \" + \"number of Query.orderBy() clauses\");\n }\n\n var components = [];\n\n for (var i = 0; i < values$$1.length; i++) {\n var rawValue = values$$1[i];\n var orderByComponent = orderBy[i];\n\n if (orderByComponent.field.isKeyField()) {\n if (typeof rawValue !== 'string') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Expected a string for document ID in \" + (methodName + \"(), but got a \" + typeof rawValue));\n }\n\n if (rawValue.indexOf('/') !== -1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. Document ID '\" + rawValue + \"' contains a slash in \" + (methodName + \"()\"));\n }\n\n var key = new DocumentKey(this._query.path.child(rawValue));\n components.push(new RefValue(this.firestore._databaseId, key));\n } else {\n var wrapped = this.firestore._dataConverter.parseQueryValue(methodName, rawValue);\n\n components.push(wrapped);\n }\n }\n\n return new Bound(components, before);\n };\n\n Query$$1.prototype.onSnapshot = function () {\n var args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n args[_i] = arguments[_i];\n }\n\n validateBetweenNumberOfArgs('Query.onSnapshot', arguments, 1, 4);\n var options = {};\n var observer;\n var currArg = 0;\n\n if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) {\n options = args[currArg];\n validateOptionNames('Query.onSnapshot', options, ['includeMetadataChanges']);\n validateNamedOptionalType('Query.onSnapshot', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n currArg++;\n }\n\n if (isPartialObserver(args[currArg])) {\n observer = args[currArg];\n } else {\n validateArgType('Query.onSnapshot', 'function', currArg, args[currArg]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 1, args[currArg + 1]);\n validateOptionalArgType('Query.onSnapshot', 'function', currArg + 2, args[currArg + 2]);\n observer = {\n next: args[currArg],\n error: args[currArg + 1],\n complete: args[currArg + 2]\n };\n }\n\n return this.onSnapshotInternal(options, observer);\n };\n\n Query$$1.prototype.onSnapshotInternal = function (options, observer) {\n var _this = this;\n\n var errHandler = function errHandler(err) {\n console.error('Uncaught Error in onSnapshot:', err);\n };\n\n if (observer.error) {\n errHandler = observer.error.bind(observer);\n }\n\n var asyncObserver = new AsyncObserver({\n next: function next(result) {\n if (observer.next) {\n observer.next(new QuerySnapshot(_this.firestore, _this._query, result));\n }\n },\n error: errHandler\n });\n var firestoreClient = this.firestore.ensureClientConfigured();\n var internalListener = firestoreClient.listen(this._query, asyncObserver, options);\n return function () {\n asyncObserver.mute();\n firestoreClient.unlisten(internalListener);\n };\n };\n\n Query$$1.prototype.get = function (options) {\n var _this = this;\n\n validateBetweenNumberOfArgs('Query.get', arguments, 0, 1);\n validateGetOptions('Query.get', options);\n return new Promise(function (resolve, reject) {\n if (options && options.source === 'cache') {\n _this.firestore.ensureClientConfigured().getDocumentsFromLocalCache(_this._query).then(function (viewSnap) {\n resolve(new QuerySnapshot(_this.firestore, _this._query, viewSnap));\n }, reject);\n } else {\n _this.getViaSnapshotListener(resolve, reject, options);\n }\n });\n };\n\n Query$$1.prototype.getViaSnapshotListener = function (resolve, reject, options) {\n var unlisten = this.onSnapshotInternal({\n includeMetadataChanges: true,\n waitForSyncWhenOnline: true\n }, {\n next: function next(result) {\n // Remove query first before passing event to user to avoid\n // user actions affecting the now stale query.\n unlisten();\n\n if (result.metadata.fromCache && options && options.source === 'server') {\n reject(new FirestoreError(Code.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.)'));\n } else {\n resolve(result);\n }\n },\n error: reject\n });\n };\n\n Query$$1.prototype.validateNewFilter = function (filter) {\n if (filter instanceof RelationFilter) {\n if (filter.isInequality()) {\n var existingField = this._query.getInequalityFilterField();\n\n if (existingField !== null && !existingField.isEqual(filter.field)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' + ' (<, <=, >, or >=) must be on the same field. But you have' + (\" inequality filters on '\" + existingField.toString() + \"'\") + (\" and '\" + filter.field.toString() + \"'\"));\n }\n\n var firstOrderByField = this._query.getFirstOrderByField();\n\n if (firstOrderByField !== null) {\n this.validateOrderByAndInequalityMatch(filter.field, firstOrderByField);\n }\n } else if (filter.op === RelationOp.ARRAY_CONTAINS) {\n if (this._query.hasArrayContainsFilter()) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. Queries only support a single array-contains ' + 'filter.');\n }\n }\n }\n };\n\n Query$$1.prototype.validateNewOrderBy = function (orderBy) {\n if (this._query.getFirstOrderByField() === null) {\n // This is the first order by. It must match any inequality.\n var inequalityField = this._query.getInequalityFilterField();\n\n if (inequalityField !== null) {\n this.validateOrderByAndInequalityMatch(inequalityField, orderBy.field);\n }\n }\n };\n\n Query$$1.prototype.validateOrderByAndInequalityMatch = function (inequality, orderBy) {\n if (!orderBy.isEqual(inequality)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid query. You have a where filter with an inequality \" + (\"(<, <=, >, or >=) on field '\" + inequality.toString() + \"' \") + (\"and so you must also use '\" + inequality.toString() + \"' \") + \"as your first Query.orderBy(), but your first Query.orderBy() \" + (\"is on field '\" + orderBy.toString() + \"' instead.\"));\n }\n };\n\n return Query$$1;\n}();\n\nvar QuerySnapshot =\n/** @class */\nfunction () {\n function QuerySnapshot(_firestore, _originalQuery, _snapshot) {\n this._firestore = _firestore;\n this._originalQuery = _originalQuery;\n this._snapshot = _snapshot;\n this._cachedChanges = null;\n this._cachedChangesIncludeMetadataChanges = null;\n this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache);\n }\n\n Object.defineProperty(QuerySnapshot.prototype, \"docs\", {\n get: function get() {\n var result = [];\n this.forEach(function (doc) {\n return result.push(doc);\n });\n return result;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"empty\", {\n get: function get() {\n return this._snapshot.docs.isEmpty();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(QuerySnapshot.prototype, \"size\", {\n get: function get() {\n return this._snapshot.docs.size;\n },\n enumerable: true,\n configurable: true\n });\n\n QuerySnapshot.prototype.forEach = function (callback, thisArg) {\n var _this = this;\n\n validateBetweenNumberOfArgs('QuerySnapshot.forEach', arguments, 1, 2);\n validateArgType('QuerySnapshot.forEach', 'function', 1, callback);\n\n this._snapshot.docs.forEach(function (doc) {\n callback.call(thisArg, _this.convertToDocumentImpl(doc));\n });\n };\n\n Object.defineProperty(QuerySnapshot.prototype, \"query\", {\n get: function get() {\n return new Query$1(this._originalQuery, this._firestore);\n },\n enumerable: true,\n configurable: true\n });\n\n QuerySnapshot.prototype.docChanges = function (options) {\n if (options) {\n validateOptionNames('QuerySnapshot.docChanges', options, ['includeMetadataChanges']);\n validateNamedOptionalType('QuerySnapshot.docChanges', 'boolean', 'includeMetadataChanges', options.includeMetadataChanges);\n }\n\n var includeMetadataChanges = !!(options && options.includeMetadataChanges);\n\n if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'To include metadata changes with your document changes, you must ' + 'also pass { includeMetadataChanges:true } to onSnapshot().');\n }\n\n if (!this._cachedChanges || this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges) {\n this._cachedChanges = changesFromSnapshot(this._firestore, includeMetadataChanges, this._snapshot);\n this._cachedChangesIncludeMetadataChanges = includeMetadataChanges;\n }\n\n return this._cachedChanges;\n };\n /** Check the equality. The call can be very expensive. */\n\n\n QuerySnapshot.prototype.isEqual = function (other) {\n if (!(other instanceof QuerySnapshot)) {\n throw invalidClassError('isEqual', 'QuerySnapshot', 1, other);\n }\n\n return this._firestore === other._firestore && this._originalQuery.isEqual(other._originalQuery) && this._snapshot.isEqual(other._snapshot);\n };\n\n QuerySnapshot.prototype.convertToDocumentImpl = function (doc) {\n return new QueryDocumentSnapshot(this._firestore, doc.key, doc, this.metadata.fromCache, this._snapshot.mutatedKeys.has(doc.key));\n };\n\n return QuerySnapshot;\n}(); // TODO(2018/11/01): As of 2018/04/17 we're changing docChanges from an array\n// into a method. Because this is a runtime breaking change and somewhat subtle\n// (both Array and Function have a .length, etc.), we'll replace commonly-used\n// properties (including Symbol.iterator) to throw a custom error message. In\n// ~6 months we can delete the custom error as most folks will have hopefully\n// migrated.\n\n\nfunction throwDocChangesMethodError() {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'QuerySnapshot.docChanges has been changed from a property into a ' + 'method, so usages like \"querySnapshot.docChanges\" should become ' + '\"querySnapshot.docChanges()\"');\n}\n\nvar docChangesPropertiesToOverride = ['length', 'forEach', 'map'].concat(typeof Symbol !== 'undefined' ? [Symbol.iterator] : []);\ndocChangesPropertiesToOverride.forEach(function (property) {\n /**\r\n * We are (re-)defining properties on QuerySnapshot.prototype.docChanges which\r\n * is a Function. This could fail, in particular in the case of 'length' which\r\n * already exists on Function.prototype and on IE11 is improperly defined with\r\n * `{ configurable: false }`. So we wrap this in a try/catch to ensure that we\r\n * still have a functional SDK.\r\n */\n try {\n Object.defineProperty(QuerySnapshot.prototype.docChanges, property, {\n get: function get() {\n return throwDocChangesMethodError();\n }\n });\n } catch (err) {} // Ignore this failure intentionally\n\n});\n\nvar CollectionReference =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(CollectionReference, _super);\n\n function CollectionReference(path, firestore) {\n var _this = _super.call(this, Query.atPath(path), firestore) || this;\n\n if (path.length % 2 !== 1) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid collection reference. Collection ' + 'references must have an odd number of segments, but ' + (path.canonicalString() + \" has \" + path.length));\n }\n\n return _this;\n }\n\n Object.defineProperty(CollectionReference.prototype, \"id\", {\n get: function get() {\n return this._query.path.lastSegment();\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"parent\", {\n get: function get() {\n var parentPath = this._query.path.popLast();\n\n if (parentPath.isEmpty()) {\n return null;\n } else {\n return new DocumentReference(new DocumentKey(parentPath), this.firestore);\n }\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(CollectionReference.prototype, \"path\", {\n get: function get() {\n return this._query.path.canonicalString();\n },\n enumerable: true,\n configurable: true\n });\n\n CollectionReference.prototype.doc = function (pathString) {\n validateBetweenNumberOfArgs('CollectionReference.doc', arguments, 0, 1); // We allow omission of 'pathString' but explicitly prohibit passing in both\n // 'undefined' and 'null'.\n\n if (arguments.length === 0) {\n pathString = AutoId.newId();\n }\n\n validateArgType('CollectionReference.doc', 'non-empty string', 1, pathString);\n\n if (pathString === '') {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Document path must be a non-empty string');\n }\n\n var path = ResourcePath.fromString(pathString);\n return DocumentReference.forPath(this._query.path.child(path), this.firestore);\n };\n\n CollectionReference.prototype.add = function (value) {\n validateExactNumberOfArgs('CollectionReference.add', arguments, 1);\n validateArgType('CollectionReference.add', 'object', 1, value);\n var docRef = this.doc();\n return docRef.set(value).then(function () {\n return docRef;\n });\n };\n\n return CollectionReference;\n}(Query$1);\n\nfunction validateSetOptions(methodName, options) {\n if (options === undefined) {\n return {\n merge: false\n };\n }\n\n validateOptionNames(methodName, options, ['merge', 'mergeFields']);\n validateNamedOptionalType(methodName, 'boolean', 'merge', options.merge);\n validateOptionalArrayElements(methodName, 'mergeFields', 'a string or a FieldPath', options.mergeFields, function (element) {\n return typeof element === 'string' || element instanceof FieldPath$1;\n });\n\n if (options.mergeFields !== undefined && options.merge !== undefined) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, \"Invalid options passed to function \" + methodName + \"(): You cannot specify both \\\"merge\\\" \" + \"and \\\"mergeFields\\\".\");\n }\n\n return options;\n}\n\nfunction validateSnapshotOptions(methodName, options) {\n if (options === undefined) {\n return {};\n }\n\n validateOptionNames(methodName, options, ['serverTimestamps']);\n validateNamedOptionalPropertyEquals(methodName, 'options', 'serverTimestamps', options.serverTimestamps, ['estimate', 'previous', 'none']);\n return options;\n}\n\nfunction validateGetOptions(methodName, options) {\n validateOptionalArgType(methodName, 'object', 1, options);\n\n if (options) {\n validateOptionNames(methodName, options, ['source']);\n validateNamedOptionalPropertyEquals(methodName, 'options', 'source', options.source, ['default', 'server', 'cache']);\n }\n}\n\nfunction validateReference(methodName, documentRef, firestore) {\n if (!(documentRef instanceof DocumentReference)) {\n throw invalidClassError(methodName, 'DocumentReference', 1, documentRef);\n } else if (documentRef.firestore !== firestore) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.');\n } else {\n return documentRef;\n }\n}\n/**\r\n * Calculates the array of firestore.DocumentChange's for a given ViewSnapshot.\r\n *\r\n * Exported for testing.\r\n */\n\n\nfunction changesFromSnapshot(firestore, includeMetadataChanges, snapshot) {\n if (snapshot.oldDocs.isEmpty()) {\n // Special case the first snapshot because index calculation is easy and\n // fast\n var lastDoc_1;\n var index_1 = 0;\n return snapshot.docChanges.map(function (change) {\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache, snapshot.mutatedKeys.has(change.doc.key));\n assert(change.type === ChangeType.Added, 'Invalid event type for first snapshot');\n assert(!lastDoc_1 || snapshot.query.docComparator(lastDoc_1, change.doc) < 0, 'Got added events in wrong order');\n lastDoc_1 = change.doc;\n return {\n type: 'added',\n doc: doc,\n oldIndex: -1,\n newIndex: index_1++\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 var indexTracker_1 = snapshot.oldDocs;\n return snapshot.docChanges.filter(function (change) {\n return includeMetadataChanges || change.type !== ChangeType.Metadata;\n }).map(function (change) {\n var doc = new QueryDocumentSnapshot(firestore, change.doc.key, change.doc, snapshot.fromCache, snapshot.mutatedKeys.has(change.doc.key));\n var oldIndex = -1;\n var newIndex = -1;\n\n if (change.type !== ChangeType.Added) {\n oldIndex = indexTracker_1.indexOf(change.doc.key);\n assert(oldIndex >= 0, 'Index for document not found');\n indexTracker_1 = indexTracker_1.delete(change.doc.key);\n }\n\n if (change.type !== ChangeType.Removed) {\n indexTracker_1 = indexTracker_1.add(change.doc);\n newIndex = indexTracker_1.indexOf(change.doc.key);\n }\n\n return {\n type: resultChangeType(change.type),\n doc: doc,\n oldIndex: oldIndex,\n newIndex: newIndex\n };\n });\n }\n}\n\nfunction resultChangeType(type) {\n switch (type) {\n case ChangeType.Added:\n return 'added';\n\n case ChangeType.Modified:\n case ChangeType.Metadata:\n return 'modified';\n\n case ChangeType.Removed:\n return 'removed';\n\n default:\n return fail('Unknown change type: ' + type);\n }\n} // Export the classes with a private constructor (it will fail if invoked\n// at runtime). Note that this still allows instanceof checks.\n// We're treating the variables as class names, so disable checking for lower\n// case variable names.\n// tslint:disable:variable-name\n\n\nvar PublicFirestore = makeConstructorPrivate(Firestore, 'Use firebase.firestore() instead.');\nvar PublicTransaction = makeConstructorPrivate(Transaction$1, 'Use firebase.firestore().runTransaction() instead.');\nvar PublicWriteBatch = makeConstructorPrivate(WriteBatch, 'Use firebase.firestore().batch() instead.');\nvar PublicDocumentReference = makeConstructorPrivate(DocumentReference, 'Use firebase.firestore().doc() instead.');\nvar PublicDocumentSnapshot = makeConstructorPrivate(DocumentSnapshot);\nvar PublicQueryDocumentSnapshot = makeConstructorPrivate(QueryDocumentSnapshot);\nvar PublicQuery = makeConstructorPrivate(Query$1);\nvar PublicQuerySnapshot = makeConstructorPrivate(QuerySnapshot);\nvar PublicCollectionReference = makeConstructorPrivate(CollectionReference, 'Use firebase.firestore().collection() instead.'); // tslint:enable:variable-name\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar firestoreNamespace = {\n Firestore: PublicFirestore,\n GeoPoint: GeoPoint,\n Timestamp: Timestamp,\n Blob: PublicBlob,\n Transaction: PublicTransaction,\n WriteBatch: PublicWriteBatch,\n DocumentReference: PublicDocumentReference,\n DocumentSnapshot: PublicDocumentSnapshot,\n Query: PublicQuery,\n QueryDocumentSnapshot: PublicQueryDocumentSnapshot,\n QuerySnapshot: PublicQuerySnapshot,\n CollectionReference: PublicCollectionReference,\n FieldPath: FieldPath$1,\n FieldValue: PublicFieldValue,\n setLogLevel: Firestore.setLogLevel,\n CACHE_SIZE_UNLIMITED: CACHE_SIZE_UNLIMITED\n};\n/**\r\n * Configures Firestore as part of the Firebase SDK by calling registerService.\r\n */\n\nfunction configureForFirebase(firebase$$1) {\n firebase$$1.INTERNAL.registerService('firestore', function (app) {\n return new Firestore(app);\n }, shallowCopy(firestoreNamespace));\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction registerFirestore(instance) {\n configureForFirebase(instance);\n}\n\nregisterFirestore(firebase);\nexports.registerFirestore = registerFirestore;","var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};\nvar e,\n goog = goog || {},\n h = commonjsGlobal;\n\nfunction l(a) {\n return \"string\" == typeof a;\n}\n\nfunction m(a, b) {\n a = a.split(\".\");\n b = b || h;\n\n for (var c = 0; c < a.length; c++) {\n if (b = b[a[c]], null == b) return null;\n }\n\n return b;\n}\n\nfunction aa() {}\n\nfunction ba(a) {\n var b = typeof a;\n if (\"object\" == b) {\n if (a) {\n if (a instanceof Array) return \"array\";\n if (a instanceof Object) return b;\n var c = Object.prototype.toString.call(a);\n if (\"[object Window]\" == c) return \"object\";\n if (\"[object Array]\" == c || \"number\" == typeof a.length && \"undefined\" != typeof a.splice && \"undefined\" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable(\"splice\")) return \"array\";\n if (\"[object Function]\" == c || \"undefined\" != typeof a.call && \"undefined\" != typeof a.propertyIsEnumerable && !a.propertyIsEnumerable(\"call\")) return \"function\";\n } else return \"null\";\n } else if (\"function\" == b && \"undefined\" == typeof a.call) return \"object\";\n return b;\n}\n\nfunction n(a) {\n return \"array\" == ba(a);\n}\n\nfunction ca(a) {\n var b = ba(a);\n return \"array\" == b || \"object\" == b && \"number\" == typeof a.length;\n}\n\nfunction q(a) {\n return \"function\" == ba(a);\n}\n\nfunction r(a) {\n var b = typeof a;\n return \"object\" == b && null != a || \"function\" == b;\n}\n\nvar t = \"closure_uid_\" + (1E9 * Math.random() >>> 0),\n da = 0;\n\nfunction ea(a, b, c) {\n return a.call.apply(a.bind, arguments);\n}\n\nfunction fa(a, b, c) {\n if (!a) throw Error();\n\n if (2 < arguments.length) {\n var d = Array.prototype.slice.call(arguments, 2);\n return function () {\n var c = Array.prototype.slice.call(arguments);\n Array.prototype.unshift.apply(c, d);\n return a.apply(b, c);\n };\n }\n\n return function () {\n return a.apply(b, arguments);\n };\n}\n\nfunction u(a, b, c) {\n u = Function.prototype.bind && -1 != Function.prototype.bind.toString().indexOf(\"native code\") ? ea : fa;\n return u.apply(null, arguments);\n}\n\nfunction v(a, b) {\n var c = Array.prototype.slice.call(arguments, 1);\n return function () {\n var b = c.slice();\n b.push.apply(b, arguments);\n return a.apply(this, b);\n };\n}\n\nvar w = Date.now || function () {\n return +new Date();\n};\n\nfunction x(a, b) {\n function c() {}\n\n c.prototype = b.prototype;\n a.L = b.prototype;\n a.prototype = new c();\n a.prototype.constructor = a;\n\n a.mh = function (a, c, g) {\n for (var d = Array(arguments.length - 2), f = 2; f < arguments.length; f++) {\n d[f - 2] = arguments[f];\n }\n\n return b.prototype[c].apply(a, d);\n };\n}\n\nfunction y(a) {\n if (Error.captureStackTrace) Error.captureStackTrace(this, y);else {\n var b = Error().stack;\n b && (this.stack = b);\n }\n a && (this.message = String(a));\n}\n\nx(y, Error);\ny.prototype.name = \"CustomError\";\n\nfunction ha(a, b) {\n a = a.split(\"%s\");\n\n for (var c = \"\", d = a.length - 1, f = 0; f < d; f++) {\n c += a[f] + (f < b.length ? b[f] : \"%s\");\n }\n\n y.call(this, c + a[d]);\n}\n\nx(ha, y);\nha.prototype.name = \"AssertionError\";\n\nfunction ia(a, b) {\n throw new ha(\"Failure\" + (a ? \": \" + a : \"\"), Array.prototype.slice.call(arguments, 1));\n}\n\nfunction z() {\n 0 != ja && (ka[this[t] || (this[t] = ++da)] = this);\n this.Ka = this.Ka;\n this.Qa = this.Qa;\n}\n\nvar ja = 0,\n ka = {};\nz.prototype.Ka = !1;\n\nz.prototype.bb = function () {\n if (!this.Ka && (this.Ka = !0, this.F(), 0 != ja)) {\n var a = this[t] || (this[t] = ++da);\n if (0 != ja && this.Qa && 0 < this.Qa.length) throw Error(this + \" did not empty its onDisposeCallbacks queue. This probably means it overrode dispose() or disposeInternal() without calling the superclass' method.\");\n delete ka[a];\n }\n};\n\nz.prototype.F = function () {\n if (this.Qa) for (; this.Qa.length;) {\n this.Qa.shift()();\n }\n};\n\nvar la = Array.prototype.indexOf ? function (a, b) {\n return Array.prototype.indexOf.call(a, b, void 0);\n} : function (a, b) {\n if (l(a)) return l(b) && 1 == b.length ? a.indexOf(b, 0) : -1;\n\n for (var c = 0; c < a.length; c++) {\n if (c in a && a[c] === b) return c;\n }\n\n return -1;\n},\n ma = Array.prototype.lastIndexOf ? function (a, b) {\n return Array.prototype.lastIndexOf.call(a, b, a.length - 1);\n} : function (a, b) {\n var c = a.length - 1;\n 0 > c && (c = Math.max(0, a.length + c));\n if (l(a)) return l(b) && 1 == b.length ? a.lastIndexOf(b, c) : -1;\n\n for (; 0 <= c; c--) {\n if (c in a && a[c] === b) return c;\n }\n\n return -1;\n},\n na = Array.prototype.forEach ? function (a, b, c) {\n Array.prototype.forEach.call(a, b, c);\n} : function (a, b, c) {\n for (var d = a.length, f = l(a) ? a.split(\"\") : a, g = 0; g < d; g++) {\n g in f && b.call(c, f[g], g, a);\n }\n},\n oa = Array.prototype.some ? function (a, b) {\n return Array.prototype.some.call(a, b, void 0);\n} : function (a, b) {\n for (var c = a.length, d = l(a) ? a.split(\"\") : a, f = 0; f < c; f++) {\n if (f in d && b.call(void 0, d[f], f, a)) return !0;\n }\n\n return !1;\n};\n\nfunction pa(a) {\n a: {\n var b = qa;\n\n for (var c = a.length, d = l(a) ? a.split(\"\") : a, f = 0; f < c; f++) {\n if (f in d && b.call(void 0, d[f], f, a)) {\n b = f;\n break a;\n }\n }\n\n b = -1;\n }\n\n return 0 > b ? null : l(a) ? a.charAt(b) : a[b];\n}\n\nfunction ra(a) {\n if (!n(a)) for (var b = a.length - 1; 0 <= b; b--) {\n delete a[b];\n }\n a.length = 0;\n}\n\nfunction sa(a, b) {\n b = la(a, b);\n var c;\n (c = 0 <= b) && Array.prototype.splice.call(a, b, 1);\n return c;\n}\n\nfunction ta(a) {\n return Array.prototype.concat.apply([], arguments);\n}\n\nfunction ua(a) {\n var b = a.length;\n\n if (0 < b) {\n for (var c = Array(b), d = 0; d < b; d++) {\n c[d] = a[d];\n }\n\n return c;\n }\n\n return [];\n}\n\nfunction va(a) {\n return /^[\\s\\xa0]*$/.test(a);\n}\n\nvar wa = String.prototype.trim ? function (a) {\n return a.trim();\n} : function (a) {\n return /^[\\s\\xa0]*([\\s\\S]*?)[\\s\\xa0]*$/.exec(a)[1];\n};\n\nfunction xa(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nvar A;\n\na: {\n var ya = h.navigator;\n\n if (ya) {\n var za = ya.userAgent;\n\n if (za) {\n A = za;\n break a;\n }\n }\n\n A = \"\";\n}\n\nfunction B(a) {\n return -1 != A.indexOf(a);\n}\n\nfunction Aa(a, b, c) {\n for (var d in a) {\n b.call(c, a[d], d, a);\n }\n}\n\nfunction Ba(a) {\n var b = [],\n c = 0,\n d;\n\n for (d in a) {\n b[c++] = a[d];\n }\n\n return b;\n}\n\nfunction Ca(a) {\n var b = [],\n c = 0,\n d;\n\n for (d in a) {\n b[c++] = d;\n }\n\n return b;\n}\n\nfunction Da(a) {\n var b = {},\n c;\n\n for (c in a) {\n b[c] = a[c];\n }\n\n return b;\n}\n\nvar Ea = \"constructor hasOwnProperty isPrototypeOf propertyIsEnumerable toLocaleString toString valueOf\".split(\" \");\n\nfunction Fa(a, b) {\n for (var c, d, f = 1; f < arguments.length; f++) {\n d = arguments[f];\n\n for (c in d) {\n a[c] = d[c];\n }\n\n for (var g = 0; g < Ea.length; g++) {\n c = Ea[g], Object.prototype.hasOwnProperty.call(d, c) && (a[c] = d[c]);\n }\n }\n}\n\nfunction Ga(a) {\n Ga[\" \"](a);\n return a;\n}\n\nGa[\" \"] = aa;\n\nfunction Ha(a, b) {\n var c = Ia;\n return Object.prototype.hasOwnProperty.call(c, a) ? c[a] : c[a] = b(a);\n}\n\nvar Ja = B(\"Opera\"),\n C = B(\"Trident\") || B(\"MSIE\"),\n Ka = B(\"Edge\"),\n La = Ka || C,\n Ma = B(\"Gecko\") && !(-1 != A.toLowerCase().indexOf(\"webkit\") && !B(\"Edge\")) && !(B(\"Trident\") || B(\"MSIE\")) && !B(\"Edge\"),\n Na = -1 != A.toLowerCase().indexOf(\"webkit\") && !B(\"Edge\");\n\nfunction Oa() {\n var a = h.document;\n return a ? a.documentMode : void 0;\n}\n\nvar Pa;\n\na: {\n var Qa = \"\",\n Ra = function () {\n var a = A;\n if (Ma) return /rv:([^\\);]+)(\\)|;)/.exec(a);\n if (Ka) return /Edge\\/([\\d\\.]+)/.exec(a);\n if (C) return /\\b(?:MSIE|rv)[: ]([^\\);]+)(\\)|;)/.exec(a);\n if (Na) return /WebKit\\/(\\S+)/.exec(a);\n if (Ja) return /(?:Version)[ \\/]?(\\S+)/.exec(a);\n }();\n\n Ra && (Qa = Ra ? Ra[1] : \"\");\n\n if (C) {\n var Sa = Oa();\n\n if (null != Sa && Sa > parseFloat(Qa)) {\n Pa = String(Sa);\n break a;\n }\n }\n\n Pa = Qa;\n}\n\nvar Ia = {};\n\nfunction Ta(a) {\n return Ha(a, function () {\n for (var b = 0, c = wa(String(Pa)).split(\".\"), d = wa(String(a)).split(\".\"), f = Math.max(c.length, d.length), g = 0; 0 == b && g < f; g++) {\n var k = c[g] || \"\",\n p = d[g] || \"\";\n\n do {\n k = /(\\d*)(\\D*)(.*)/.exec(k) || [\"\", \"\", \"\", \"\"];\n p = /(\\d*)(\\D*)(.*)/.exec(p) || [\"\", \"\", \"\", \"\"];\n if (0 == k[0].length && 0 == p[0].length) break;\n b = xa(0 == k[1].length ? 0 : parseInt(k[1], 10), 0 == p[1].length ? 0 : parseInt(p[1], 10)) || xa(0 == k[2].length, 0 == p[2].length) || xa(k[2], p[2]);\n k = k[3];\n p = p[3];\n } while (0 == b);\n }\n\n return 0 <= b;\n });\n}\n\nvar Ua;\nvar Va = h.document;\nUa = Va && C ? Oa() || (\"CSS1Compat\" == Va.compatMode ? parseInt(Pa, 10) : 5) : void 0;\n\nvar Wa = Object.freeze || function (a) {\n return a;\n};\n\nvar Xa = !C || 9 <= Number(Ua),\n Ya = C && !Ta(\"9\"),\n Za = function () {\n if (!h.addEventListener || !Object.defineProperty) return !1;\n var a = !1,\n b = Object.defineProperty({}, \"passive\", {\n get: function get() {\n a = !0;\n }\n });\n\n try {\n h.addEventListener(\"test\", aa, b), h.removeEventListener(\"test\", aa, b);\n } catch (c) {}\n\n return a;\n}();\n\nfunction D(a, b) {\n this.type = a;\n this.currentTarget = this.target = b;\n this.defaultPrevented = this.Ea = !1;\n this.Be = !0;\n}\n\nD.prototype.stopPropagation = function () {\n this.Ea = !0;\n};\n\nD.prototype.preventDefault = function () {\n this.defaultPrevented = !0;\n this.Be = !1;\n};\n\nfunction E(a, b) {\n D.call(this, a ? a.type : \"\");\n this.relatedTarget = this.currentTarget = this.target = null;\n this.button = this.screenY = this.screenX = this.clientY = this.clientX = this.offsetY = this.offsetX = 0;\n this.key = \"\";\n this.charCode = this.keyCode = 0;\n this.metaKey = this.shiftKey = this.altKey = this.ctrlKey = !1;\n this.state = null;\n this.pointerId = 0;\n this.pointerType = \"\";\n this.fb = null;\n a && this.Kf(a, b);\n}\n\nx(E, D);\nvar $a = Wa({\n 2: \"touch\",\n 3: \"pen\",\n 4: \"mouse\"\n});\n\nE.prototype.Kf = function (a, b) {\n var c = this.type = a.type,\n d = a.changedTouches ? a.changedTouches[0] : null;\n this.target = a.target || a.srcElement;\n this.currentTarget = b;\n\n if (b = a.relatedTarget) {\n if (Ma) {\n a: {\n try {\n Ga(b.nodeName);\n var f = !0;\n break a;\n } catch (g) {}\n\n f = !1;\n }\n\n f || (b = null);\n }\n } else \"mouseover\" == c ? b = a.fromElement : \"mouseout\" == c && (b = a.toElement);\n\n this.relatedTarget = b;\n null === d ? (this.offsetX = Na || void 0 !== a.offsetX ? a.offsetX : a.layerX, this.offsetY = Na || void 0 !== a.offsetY ? a.offsetY : a.layerY, this.clientX = void 0 !== a.clientX ? a.clientX : a.pageX, this.clientY = void 0 !== a.clientY ? a.clientY : a.pageY, this.screenX = a.screenX || 0, this.screenY = a.screenY || 0) : (this.clientX = void 0 !== d.clientX ? d.clientX : d.pageX, this.clientY = void 0 !== d.clientY ? d.clientY : d.pageY, this.screenX = d.screenX || 0, this.screenY = d.screenY || 0);\n this.button = a.button;\n this.keyCode = a.keyCode || 0;\n this.key = a.key || \"\";\n this.charCode = a.charCode || (\"keypress\" == c ? a.keyCode : 0);\n this.ctrlKey = a.ctrlKey;\n this.altKey = a.altKey;\n this.shiftKey = a.shiftKey;\n this.metaKey = a.metaKey;\n this.pointerId = a.pointerId || 0;\n this.pointerType = l(a.pointerType) ? a.pointerType : $a[a.pointerType] || \"\";\n this.state = a.state;\n this.fb = a;\n a.defaultPrevented && this.preventDefault();\n};\n\nE.prototype.stopPropagation = function () {\n E.L.stopPropagation.call(this);\n this.fb.stopPropagation ? this.fb.stopPropagation() : this.fb.cancelBubble = !0;\n};\n\nE.prototype.preventDefault = function () {\n E.L.preventDefault.call(this);\n var a = this.fb;\n if (a.preventDefault) a.preventDefault();else if (a.returnValue = !1, Ya) try {\n if (a.ctrlKey || 112 <= a.keyCode && 123 >= a.keyCode) a.keyCode = -1;\n } catch (b) {}\n};\n\nvar ab = \"closure_listenable_\" + (1E6 * Math.random() | 0);\n\nfunction F(a) {\n return !(!a || !a[ab]);\n}\n\nvar bb = 0;\n\nfunction cb(a, b, c, d, f) {\n this.listener = a;\n this.proxy = null;\n this.src = b;\n this.type = c;\n this.capture = !!d;\n this.Ob = f;\n this.key = ++bb;\n this.Sa = this.Eb = !1;\n}\n\ncb.prototype.Vb = function () {\n this.Sa = !0;\n this.Ob = this.src = this.proxy = this.listener = null;\n};\n\nfunction db(a) {\n this.src = a;\n this.J = {};\n this.xb = 0;\n}\n\ne = db.prototype;\n\ne.add = function (a, b, c, d, f) {\n var g = a.toString();\n a = this.J[g];\n a || (a = this.J[g] = [], this.xb++);\n var k = eb(a, b, d, f);\n -1 < k ? (b = a[k], c || (b.Eb = !1)) : (b = new cb(b, this.src, g, !!d, f), b.Eb = c, a.push(b));\n return b;\n};\n\ne.remove = function (a, b, c, d) {\n a = a.toString();\n if (!(a in this.J)) return !1;\n var f = this.J[a];\n b = eb(f, b, c, d);\n return -1 < b ? (f[b].Vb(), Array.prototype.splice.call(f, b, 1), 0 == f.length && (delete this.J[a], this.xb--), !0) : !1;\n};\n\ne.ye = function (a) {\n var b = a.type;\n b in this.J && sa(this.J[b], a) && (a.Vb(), 0 == this.J[b].length && (delete this.J[b], this.xb--));\n};\n\ne.pb = function (a) {\n a = a && a.toString();\n var c;\n\n for (c in this.J) {\n if (!a || c == a) {\n for (var d = this.J[c], f = 0; f < d.length; f++) {\n d[f].Vb();\n }\n\n delete this.J[c];\n this.xb--;\n }\n }\n};\n\ne.jb = function (a, b, c, d) {\n a = this.J[a.toString()];\n var f = -1;\n a && (f = eb(a, b, c, d));\n return -1 < f ? a[f] : null;\n};\n\nfunction eb(a, b, c, d) {\n for (var f = 0; f < a.length; ++f) {\n var g = a[f];\n if (!g.Sa && g.listener == b && g.capture == !!c && g.Ob == d) return f;\n }\n\n return -1;\n}\n\nvar fb = \"closure_lm_\" + (1E6 * Math.random() | 0),\n gb = {};\n\nfunction ib(a, b, c, d, f) {\n if (d && d.once) return jb(a, b, c, d, f);\n\n if (n(b)) {\n for (var g = 0; g < b.length; g++) {\n ib(a, b[g], c, d, f);\n }\n\n return null;\n }\n\n c = kb(c);\n return F(a) ? a.nb(b, c, r(d) ? !!d.capture : !!d, f) : lb(a, b, c, !1, d, f);\n}\n\nfunction lb(a, b, c, d, f, g) {\n if (!b) throw Error(\"Invalid event type\");\n var k = r(f) ? !!f.capture : !!f,\n p = G(a);\n p || (a[fb] = p = new db(a));\n c = p.add(b, c, d, k, g);\n if (c.proxy) return c;\n d = mb();\n c.proxy = d;\n d.src = a;\n d.listener = c;\n if (a.addEventListener) Za || (f = k), void 0 === f && (f = !1), a.addEventListener(b.toString(), d, f);else if (a.attachEvent) a.attachEvent(nb(b.toString()), d);else if (a.addListener && a.removeListener) a.addListener(d);else throw Error(\"addEventListener and attachEvent are unavailable.\");\n return c;\n}\n\nfunction mb() {\n var a = ob,\n b = Xa ? function (c) {\n return a.call(b.src, b.listener, c);\n } : function (c) {\n c = a.call(b.src, b.listener, c);\n if (!c) return c;\n };\n return b;\n}\n\nfunction jb(a, b, c, d, f) {\n if (n(b)) {\n for (var g = 0; g < b.length; g++) {\n jb(a, b[g], c, d, f);\n }\n\n return null;\n }\n\n c = kb(c);\n return F(a) ? a.Oc(b, c, r(d) ? !!d.capture : !!d, f) : lb(a, b, c, !0, d, f);\n}\n\nfunction pb(a, b, c, d, f) {\n if (n(b)) for (var g = 0; g < b.length; g++) {\n pb(a, b[g], c, d, f);\n } else d = r(d) ? !!d.capture : !!d, c = kb(c), F(a) ? a.ed(b, c, d, f) : a && (a = G(a)) && (b = a.jb(b, c, d, f)) && qb(b);\n}\n\nfunction qb(a) {\n if (\"number\" != typeof a && a && !a.Sa) {\n var b = a.src;\n if (F(b)) b.Le(a);else {\n var c = a.type,\n d = a.proxy;\n b.removeEventListener ? b.removeEventListener(c, d, a.capture) : b.detachEvent ? b.detachEvent(nb(c), d) : b.addListener && b.removeListener && b.removeListener(d);\n (c = G(b)) ? (c.ye(a), 0 == c.xb && (c.src = null, b[fb] = null)) : a.Vb();\n }\n }\n}\n\nfunction nb(a) {\n return a in gb ? gb[a] : gb[a] = \"on\" + a;\n}\n\nfunction rb(a, b, c, d) {\n var f = !0;\n if (a = G(a)) if (b = a.J[b.toString()]) for (b = b.concat(), a = 0; a < b.length; a++) {\n var g = b[a];\n g && g.capture == c && !g.Sa && (g = sb(g, d), f = f && !1 !== g);\n }\n return f;\n}\n\nfunction sb(a, b) {\n var c = a.listener,\n d = a.Ob || a.src;\n a.Eb && qb(a);\n return c.call(d, b);\n}\n\nfunction ob(a, b) {\n if (a.Sa) return !0;\n\n if (!Xa) {\n var c = b || m(\"window.event\");\n b = new E(c, this);\n var d = !0;\n\n if (!(0 > c.keyCode || void 0 != c.returnValue)) {\n a: {\n var f = !1;\n if (0 == c.keyCode) try {\n c.keyCode = -1;\n break a;\n } catch (k) {\n f = !0;\n }\n if (f || void 0 == c.returnValue) c.returnValue = !0;\n }\n\n c = [];\n\n for (f = b.currentTarget; f; f = f.parentNode) {\n c.push(f);\n }\n\n a = a.type;\n\n for (f = c.length - 1; !b.Ea && 0 <= f; f--) {\n b.currentTarget = c[f];\n var g = rb(c[f], a, !0, b);\n d = d && g;\n }\n\n for (f = 0; !b.Ea && f < c.length; f++) {\n b.currentTarget = c[f], g = rb(c[f], a, !1, b), d = d && g;\n }\n }\n\n return d;\n }\n\n return sb(a, new E(b, this));\n}\n\nfunction G(a) {\n a = a[fb];\n return a instanceof db ? a : null;\n}\n\nvar tb = \"__closure_events_fn_\" + (1E9 * Math.random() >>> 0);\n\nfunction kb(a) {\n if (q(a)) return a;\n a[tb] || (a[tb] = function (b) {\n return a.handleEvent(b);\n });\n return a[tb];\n}\n\nfunction H() {\n z.call(this);\n this.ka = new db(this);\n this.Pe = this;\n this.Uc = null;\n}\n\nx(H, z);\nH.prototype[ab] = !0;\ne = H.prototype;\n\ne.addEventListener = function (a, b, c, d) {\n ib(this, a, b, c, d);\n};\n\ne.removeEventListener = function (a, b, c, d) {\n pb(this, a, b, c, d);\n};\n\ne.dispatchEvent = function (a) {\n var b,\n c = this.Uc;\n if (c) for (b = []; c; c = c.Uc) {\n b.push(c);\n }\n c = this.Pe;\n var d = a.type || a;\n if (l(a)) a = new D(a, c);else if (a instanceof D) a.target = a.target || c;else {\n var f = a;\n a = new D(d, c);\n Fa(a, f);\n }\n f = !0;\n if (b) for (var g = b.length - 1; !a.Ea && 0 <= g; g--) {\n var k = a.currentTarget = b[g];\n f = k.Lb(d, !0, a) && f;\n }\n a.Ea || (k = a.currentTarget = c, f = k.Lb(d, !0, a) && f, a.Ea || (f = k.Lb(d, !1, a) && f));\n if (b) for (g = 0; !a.Ea && g < b.length; g++) {\n k = a.currentTarget = b[g], f = k.Lb(d, !1, a) && f;\n }\n return f;\n};\n\ne.F = function () {\n H.L.F.call(this);\n this.pg();\n this.Uc = null;\n};\n\ne.nb = function (a, b, c, d) {\n return this.ka.add(String(a), b, !1, c, d);\n};\n\ne.Oc = function (a, b, c, d) {\n return this.ka.add(String(a), b, !0, c, d);\n};\n\ne.ed = function (a, b, c, d) {\n this.ka.remove(String(a), b, c, d);\n};\n\ne.Le = function (a) {\n this.ka.ye(a);\n};\n\ne.pg = function () {\n this.ka && this.ka.pb(void 0);\n};\n\ne.Lb = function (a, b, c) {\n a = this.ka.J[String(a)];\n if (!a) return !0;\n a = a.concat();\n\n for (var d = !0, f = 0; f < a.length; ++f) {\n var g = a[f];\n\n if (g && !g.Sa && g.capture == b) {\n var k = g.listener,\n p = g.Ob || g.src;\n g.Eb && this.Le(g);\n d = !1 !== k.call(p, c) && d;\n }\n }\n\n return d && 0 != c.Be;\n};\n\ne.jb = function (a, b, c, d) {\n return this.ka.jb(String(a), b, c, d);\n};\n\nvar ub = h.JSON.stringify;\n\nfunction vb(a, b) {\n this.Sf = 100;\n this.ef = a;\n this.ug = b;\n this.Zb = 0;\n this.Pb = null;\n}\n\nvb.prototype.get = function () {\n if (0 < this.Zb) {\n this.Zb--;\n var a = this.Pb;\n this.Pb = a.next;\n a.next = null;\n } else a = this.ef();\n\n return a;\n};\n\nvb.prototype.put = function (a) {\n this.ug(a);\n this.Zb < this.Sf && (this.Zb++, a.next = this.Pb, this.Pb = a);\n};\n\nfunction I() {\n this.lc = this.Va = null;\n}\n\nvar xb = new vb(function () {\n return new wb();\n}, function (a) {\n a.reset();\n});\n\nI.prototype.add = function (a, b) {\n var c = this.Af();\n c.set(a, b);\n this.lc ? this.lc.next = c : this.Va = c;\n this.lc = c;\n};\n\nI.prototype.remove = function () {\n var a = null;\n this.Va && (a = this.Va, this.Va = this.Va.next, this.Va || (this.lc = null), a.next = null);\n return a;\n};\n\nI.prototype.wg = function (a) {\n xb.put(a);\n};\n\nI.prototype.Af = function () {\n return xb.get();\n};\n\nfunction wb() {\n this.next = this.scope = this.Gc = null;\n}\n\nwb.prototype.set = function (a, b) {\n this.Gc = a;\n this.scope = b;\n this.next = null;\n};\n\nwb.prototype.reset = function () {\n this.next = this.scope = this.Gc = null;\n};\n\nfunction yb(a) {\n h.setTimeout(function () {\n throw a;\n }, 0);\n}\n\nvar zb;\n\nfunction Ab() {\n var a = h.MessageChannel;\n \"undefined\" === typeof a && \"undefined\" !== typeof window && window.postMessage && window.addEventListener && !B(\"Presto\") && (a = function a() {\n var a = document.createElement(\"IFRAME\");\n a.style.display = \"none\";\n a.src = \"\";\n document.documentElement.appendChild(a);\n var b = a.contentWindow;\n a = b.document;\n a.open();\n a.write(\"\");\n a.close();\n var c = \"callImmediate\" + Math.random(),\n d = \"file:\" == b.location.protocol ? \"*\" : b.location.protocol + \"//\" + b.location.host;\n a = u(function (a) {\n if ((\"*\" == d || a.origin == d) && a.data == c) this.port1.onmessage();\n }, this);\n b.addEventListener(\"message\", a, !1);\n this.port1 = {};\n this.port2 = {\n postMessage: function postMessage() {\n b.postMessage(c, d);\n }\n };\n });\n\n if (\"undefined\" !== typeof a && !B(\"Trident\") && !B(\"MSIE\")) {\n var b = new a(),\n c = {},\n d = c;\n\n b.port1.onmessage = function () {\n if (void 0 !== c.next) {\n c = c.next;\n var a = c.rd;\n c.rd = null;\n a();\n }\n };\n\n return function (a) {\n d.next = {\n rd: a\n };\n d = d.next;\n b.port2.postMessage(0);\n };\n }\n\n return \"undefined\" !== typeof document && \"onreadystatechange\" in document.createElement(\"SCRIPT\") ? function (a) {\n var b = document.createElement(\"SCRIPT\");\n\n b.onreadystatechange = function () {\n b.onreadystatechange = null;\n b.parentNode.removeChild(b);\n b = null;\n a();\n a = null;\n };\n\n document.documentElement.appendChild(b);\n } : function (a) {\n h.setTimeout(a, 0);\n };\n}\n\nvar Bb;\n\nfunction Cb() {\n if (h.Promise && h.Promise.resolve) {\n var a = h.Promise.resolve(void 0);\n\n Bb = function Bb() {\n a.then(Db);\n };\n } else Bb = function Bb() {\n var a = Db;\n !q(h.setImmediate) || h.Window && h.Window.prototype && !B(\"Edge\") && h.Window.prototype.setImmediate == h.setImmediate ? (zb || (zb = Ab()), zb(a)) : h.setImmediate(a);\n };\n}\n\nvar Eb = !1,\n Fb = new I();\n\nfunction Db() {\n for (var a; a = Fb.remove();) {\n try {\n a.Gc.call(a.scope);\n } catch (b) {\n yb(b);\n }\n\n Fb.wg(a);\n }\n\n Eb = !1;\n}\n\nfunction Gb(a, b) {\n H.call(this);\n this.Na = a || 1;\n this.wb = b || h;\n this.nd = u(this.Rg, this);\n this.ie = w();\n}\n\nx(Gb, H);\ne = Gb.prototype;\ne.enabled = !1;\ne.B = null;\n\ne.setInterval = function (a) {\n this.Na = a;\n this.B && this.enabled ? (this.stop(), this.start()) : this.B && this.stop();\n};\n\ne.Rg = function () {\n if (this.enabled) {\n var a = w() - this.ie;\n 0 < a && a < .8 * this.Na ? this.B = this.wb.setTimeout(this.nd, this.Na - a) : (this.B && (this.wb.clearTimeout(this.B), this.B = null), this.ff(), this.enabled && (this.stop(), this.start()));\n }\n};\n\ne.ff = function () {\n this.dispatchEvent(\"tick\");\n};\n\ne.start = function () {\n this.enabled = !0;\n this.B || (this.B = this.wb.setTimeout(this.nd, this.Na), this.ie = w());\n};\n\ne.stop = function () {\n this.enabled = !1;\n this.B && (this.wb.clearTimeout(this.B), this.B = null);\n};\n\ne.F = function () {\n Gb.L.F.call(this);\n this.stop();\n delete this.wb;\n};\n\nfunction Hb(a, b, c) {\n if (q(a)) c && (a = u(a, c));else if (a && \"function\" == typeof a.handleEvent) a = u(a.handleEvent, a);else throw Error(\"Invalid listener argument\");\n return 2147483647 < Number(b) ? -1 : h.setTimeout(a, b || 0);\n}\n\nfunction Ib(a, b, c) {\n z.call(this);\n this.Uf = null != c ? u(a, c) : a;\n this.Na = b;\n this.Xe = u(this.fg, this);\n this.qc = [];\n}\n\nx(Ib, z);\ne = Ib.prototype;\ne.Ta = !1;\ne.ob = 0;\ne.B = null;\n\ne.mf = function (a) {\n this.qc = arguments;\n this.B || this.ob ? this.Ta = !0 : this.Cc();\n};\n\ne.stop = function () {\n this.B && (h.clearTimeout(this.B), this.B = null, this.Ta = !1, this.qc = []);\n};\n\ne.pause = function () {\n this.ob++;\n};\n\ne.resume = function () {\n this.ob--;\n this.ob || !this.Ta || this.B || (this.Ta = !1, this.Cc());\n};\n\ne.F = function () {\n Ib.L.F.call(this);\n this.stop();\n};\n\ne.fg = function () {\n this.B = null;\n this.Ta && !this.ob && (this.Ta = !1, this.Cc());\n};\n\ne.Cc = function () {\n this.B = Hb(this.Xe, this.Na);\n this.Uf.apply(null, this.qc);\n};\n\nfunction Jb(a) {\n z.call(this);\n this.i = a;\n this.o = {};\n}\n\nx(Jb, z);\nvar Kb = [];\ne = Jb.prototype;\n\ne.nb = function (a, b, c, d) {\n return this.Tf(a, b, c, d);\n};\n\ne.Tf = function (a, b, c, d) {\n n(b) || (b && (Kb[0] = b.toString()), b = Kb);\n\n for (var f = 0; f < b.length; f++) {\n var g = ib(a, b[f], c || this.handleEvent, d || !1, this.i || this);\n if (!g) break;\n this.o[g.key] = g;\n }\n\n return this;\n};\n\ne.Oc = function (a, b, c, d) {\n return this.je(a, b, c, d);\n};\n\ne.je = function (a, b, c, d, f) {\n if (n(b)) for (var g = 0; g < b.length; g++) {\n this.je(a, b[g], c, d, f);\n } else {\n a = jb(a, b, c || this.handleEvent, d, f || this.i || this);\n if (!a) return this;\n this.o[a.key] = a;\n }\n return this;\n};\n\ne.ed = function (a, b, c, d, f) {\n if (n(b)) for (var g = 0; g < b.length; g++) {\n this.ed(a, b[g], c, d, f);\n } else c = c || this.handleEvent, d = r(d) ? !!d.capture : !!d, f = f || this.i || this, c = kb(c), d = !!d, b = F(a) ? a.jb(b, c, d, f) : a ? (a = G(a)) ? a.jb(b, c, d, f) : null : null, b && (qb(b), delete this.o[b.key]);\n};\n\ne.pb = function () {\n Aa(this.o, function (a, b) {\n this.o.hasOwnProperty(b) && qb(a);\n }, this);\n this.o = {};\n};\n\ne.F = function () {\n Jb.L.F.call(this);\n this.pb();\n};\n\ne.handleEvent = function () {\n throw Error(\"EventHandler.handleEvent not implemented\");\n};\n\nfunction J(a, b, c) {\n this.reset(a, b, c, void 0, void 0);\n}\n\nJ.prototype.Md = null;\n\nJ.prototype.reset = function (a, b, c, d, f) {\n this.mb = a;\n delete this.Md;\n};\n\nJ.prototype.Bg = function (a) {\n this.Md = a;\n};\n\nJ.prototype.Ge = function (a) {\n this.mb = a;\n};\n\nfunction Mb(a) {\n this.pe = a;\n this.Zd = this.uc = this.mb = this.$b = null;\n}\n\nfunction K(a, b) {\n this.name = a;\n this.value = b;\n}\n\nK.prototype.toString = function () {\n return this.name;\n};\n\nvar Nb = new K(\"SEVERE\", 1E3),\n Ob = new K(\"WARNING\", 900),\n Pb = new K(\"INFO\", 800),\n Qb = new K(\"CONFIG\", 700),\n Rb = new K(\"FINE\", 500);\ne = Mb.prototype;\n\ne.getName = function () {\n return this.pe;\n};\n\ne.getParent = function () {\n return this.$b;\n};\n\ne.pf = function () {\n this.uc || (this.uc = {});\n return this.uc;\n};\n\ne.Ge = function (a) {\n this.mb = a;\n};\n\ne.Qd = function () {\n if (this.mb) return this.mb;\n if (this.$b) return this.$b.Qd();\n ia(\"Root logger has no level set.\");\n return null;\n};\n\ne.Pf = function (a) {\n return a.value >= this.Qd().value;\n};\n\ne.log = function (a, b, c) {\n this.Pf(a) && (q(b) && (b = b()), this.gf(this.uf(a, b, c)));\n};\n\ne.uf = function (a, b, c) {\n a = new J(a, String(b), this.pe);\n c && a.Bg(c);\n return a;\n};\n\ne.ca = function (a, b) {\n this.log(Nb, a, b);\n};\n\ne.T = function (a, b) {\n this.log(Ob, a, b);\n};\n\ne.info = function (a, b) {\n this.log(Pb, a, b);\n};\n\ne.lf = function (a) {\n this.log(Rb, a, void 0);\n};\n\ne.gf = function (a) {\n for (var b = this; b;) {\n b.We(a), b = b.getParent();\n }\n};\n\ne.We = function (a) {\n if (this.Zd) for (var b = 0, c; c = this.Zd[b]; b++) {\n c(a);\n }\n};\n\ne.Fg = function (a) {\n this.$b = a;\n};\n\ne.Qe = function (a, b) {\n this.pf()[a] = b;\n};\n\nvar Sb = {},\n Tb = null;\n\nfunction Vb(a) {\n Tb || (Tb = new Mb(\"\"), Sb[\"\"] = Tb, Tb.Ge(Qb));\n var b;\n\n if (!(b = Sb[a])) {\n b = new Mb(a);\n var c = a.lastIndexOf(\".\"),\n d = a.substr(c + 1);\n c = Vb(a.substr(0, c));\n c.Qe(d, b);\n b.Fg(c);\n Sb[a] = b;\n }\n\n return b;\n}\n\nfunction Wb(a, b) {\n a && a.info(b, void 0);\n}\n\nfunction L(a, b) {\n a && a.lf(b);\n}\n\nfunction Xb() {\n this.s = Vb(\"goog.labs.net.webChannel.WebChannelDebug\");\n this.Wc = !0;\n}\n\ne = Xb.prototype;\n\ne.Id = function () {\n this.Wc = !1;\n};\n\ne.Tg = function (a, b, c, d, f) {\n var g = this;\n this.info(function () {\n return \"XMLHTTP REQ (\" + c + \") [attempt \" + d + \"]: \" + a + \"\\n\" + b + \"\\n\" + g.Xf(f);\n });\n};\n\ne.Ug = function (a, b, c, d, f, g) {\n this.info(function () {\n return \"XMLHTTP RESP (\" + c + \") [ attempt \" + d + \"]: \" + a + \"\\n\" + b + \"\\n\" + f + \" \" + g;\n });\n};\n\ne.Wa = function (a, b, c) {\n var d = this;\n this.info(function () {\n return \"XMLHTTP TEXT (\" + a + \"): \" + d.ng(b) + (c ? \" \" + c : \"\");\n });\n};\n\ne.Sg = function (a) {\n this.info(function () {\n return \"TIMEOUT: \" + a;\n });\n};\n\ne.debug = function (a) {\n L(this.s, a);\n};\n\ne.cb = function (a, b) {\n var c = this.s;\n c && c.ca(b || \"Exception\", a);\n};\n\ne.info = function (a) {\n Wb(this.s, a);\n};\n\ne.T = function (a) {\n var b = this.s;\n b && b.T(a, void 0);\n};\n\ne.ca = function (a) {\n var b = this.s;\n b && b.ca(a, void 0);\n};\n\ne.ng = function (a) {\n if (!this.Wc) return a;\n if (!a) return null;\n\n try {\n var b = JSON.parse(a);\n if (b) for (var c = 0; c < b.length; c++) {\n n(b[c]) && this.Wf(b[c]);\n }\n return ub(b);\n } catch (d) {\n return this.debug(\"Exception parsing expected JS array - probably was not JS\"), a;\n }\n};\n\ne.Wf = function (a) {\n if (!(2 > a.length || (a = a[1], !n(a) || 1 > a.length))) {\n var b = a[0];\n if (\"noop\" != b && \"stop\" != b && \"close\" != b) for (b = 1; b < a.length; b++) {\n a[b] = \"\";\n }\n }\n};\n\ne.Xf = function (a) {\n if (!this.Wc) return a;\n if (!a) return null;\n var b = \"\";\n a = a.split(\"&\");\n\n for (var c = 0; c < a.length; c++) {\n var d = a[c].split(\"=\");\n\n if (1 < d.length) {\n var f = d[0];\n d = d[1];\n var g = f.split(\"_\");\n b = 2 <= g.length && \"type\" == g[1] ? b + (f + \"=\" + d + \"&\") : b + (f + \"=redacted&\");\n }\n }\n\n return b;\n};\n\nvar M = new H();\n\nfunction Yb(a) {\n D.call(this, \"serverreachability\", a);\n}\n\nx(Yb, D);\n\nfunction N(a) {\n M.dispatchEvent(new Yb(M, a));\n}\n\nfunction Zb(a, b) {\n D.call(this, \"statevent\", a);\n this.stat = b;\n}\n\nx(Zb, D);\n\nfunction O(a) {\n M.dispatchEvent(new Zb(M, a));\n}\n\nfunction $b(a, b, c) {\n D.call(this, \"timingevent\", a);\n this.size = b;\n this.rtt = c;\n}\n\nx($b, D);\n\nfunction ac(a, b, c) {\n M.dispatchEvent(new $b(M, a, b, c));\n}\n\nfunction P(a, b) {\n if (!q(a)) throw Error(\"Fn must not be null and must be a function\");\n return h.setTimeout(function () {\n a();\n }, b);\n}\n\nvar bc = {\n NO_ERROR: 0,\n Vg: 1,\n bh: 2,\n ah: 3,\n Yg: 4,\n $g: 5,\n dh: 6,\n Ne: 7,\n TIMEOUT: 8,\n gh: 9\n};\nvar cc = {\n Xg: \"complete\",\n kh: \"success\",\n Oe: \"error\",\n Ne: \"abort\",\n ih: \"ready\",\n jh: \"readystatechange\",\n TIMEOUT: \"timeout\",\n eh: \"incrementaldata\",\n hh: \"progress\",\n Zg: \"downloadprogress\",\n lh: \"uploadprogress\"\n};\n\nfunction dc() {}\n\ndc.prototype.pd = null;\n\ndc.prototype.Vd = function () {\n return this.pd || (this.pd = this.Mf());\n};\n\nfunction ec() {}\n\nvar Q = {\n OPEN: \"a\",\n Wg: \"b\",\n Oe: \"c\",\n fh: \"d\"\n};\n\nfunction fc() {\n D.call(this, \"d\");\n}\n\nx(fc, D);\n\nfunction gc() {\n D.call(this, \"c\");\n}\n\nx(gc, D);\nvar hc;\n\nfunction ic() {}\n\nx(ic, dc);\n\nic.prototype.Dd = function () {\n var a = this.Wd();\n return a ? new ActiveXObject(a) : new XMLHttpRequest();\n};\n\nic.prototype.Mf = function () {\n var a = {};\n this.Wd() && (a[0] = !0, a[1] = !0);\n return a;\n};\n\nic.prototype.Wd = function () {\n if (!this.be && \"undefined\" == typeof XMLHttpRequest && \"undefined\" != typeof ActiveXObject) {\n for (var a = [\"MSXML2.XMLHTTP.6.0\", \"MSXML2.XMLHTTP.3.0\", \"MSXML2.XMLHTTP\", \"Microsoft.XMLHTTP\"], b = 0; b < a.length; b++) {\n var c = a[b];\n\n try {\n return new ActiveXObject(c), this.be = c;\n } catch (d) {}\n }\n\n throw Error(\"Could not create ActiveXObject. ActiveX might be disabled, or MSXML might not be installed\");\n }\n\n return this.be;\n};\n\nhc = new ic();\n\nfunction R(a, b, c, d, f) {\n this.b = a;\n this.a = b;\n this.ra = c;\n this.R = d;\n this.Xc = f || 1;\n this.Fc = new Jb(this);\n this.Ua = jc;\n a = La ? 125 : void 0;\n this.Vc = new Gb(a);\n this.A = null;\n this.S = !1;\n this.Da = this.pa = this.ua = this.ic = this.qb = this.hd = this.Ga = null;\n this.ba = [];\n this.h = null;\n this.Bb = 0;\n this.I = this.Fa = null;\n this.w = -1;\n this.Za = !1;\n this.Ra = 0;\n this.ac = null;\n this.lb = this.Ed = this.yc = !1;\n}\n\nvar jc = 45E3;\n\nfunction kc(a, b) {\n switch (a) {\n case 0:\n return \"Non-200 return code (\" + b + \")\";\n\n case 1:\n return \"XMLHTTP failure (no data)\";\n\n case 2:\n return \"HttpConnection timeout\";\n\n default:\n return \"Unknown error\";\n }\n}\n\nvar lc = {},\n mc = {};\ne = R.prototype;\n\ne.ga = function (a) {\n this.A = a;\n};\n\ne.setTimeout = function (a) {\n this.Ua = a;\n};\n\ne.He = function (a) {\n this.Ra = a;\n};\n\ne.Gg = function (a) {\n this.ba = a;\n};\n\ne.la = function () {\n return this.ba;\n};\n\ne.kd = function (a, b) {\n this.ic = 1;\n this.ua = a.clone().Ub();\n this.Da = b;\n this.yc = !0;\n this.Ce(null);\n};\n\ne.jd = function (a, b, c) {\n this.ic = 1;\n this.ua = a.clone().Ub();\n this.Da = null;\n this.yc = b;\n this.Ce(c);\n};\n\ne.Ce = function (a) {\n this.qb = w();\n this.eb();\n this.pa = this.ua.clone();\n this.pa.dc(\"t\", this.Xc);\n this.Bb = 0;\n this.h = this.b.Jb(this.b.fc() ? a : null);\n 0 < this.Ra && (this.ac = new Ib(u(this.Me, this, this.h), this.Ra));\n this.Fc.nb(this.h, \"readystatechange\", this.mg);\n a = this.A ? Da(this.A) : {};\n this.Da ? (this.Fa || (this.Fa = \"POST\"), a[\"Content-Type\"] = \"application/x-www-form-urlencoded\", this.h.send(this.pa, this.Fa, this.Da, a)) : (this.Fa = \"GET\", this.h.send(this.pa, this.Fa, null, a));\n N(1);\n this.a.Tg(this.Fa, this.pa, this.R, this.Xc, this.Da);\n};\n\ne.mg = function (a) {\n a = a.target;\n var b = this.ac;\n b && 3 == a.ma() ? (this.a.debug(\"Throttling readystatechange.\"), b.mf()) : this.Me(a);\n};\n\ne.Me = function (a) {\n try {\n a == this.h ? this.hg() : this.a.T(\"Called back with an unexpected xmlhttp\");\n } catch (c) {\n if (this.a.debug(\"Failed call to OnXmlHttpReadyStateChanged_\"), this.h && this.h.ya()) {\n var b = this;\n this.a.cb(c, function () {\n return \"ResponseText: \" + b.h.ya();\n });\n } else this.a.cb(c, \"No response text\");\n } finally {}\n};\n\ne.hg = function () {\n var a = this.h.ma(),\n b = this.h.Ud(),\n c = this.h.za();\n\n if (!(3 > a || 3 == a && !La && !this.h.ya())) {\n this.Za || 4 != a || 7 == b || (8 == b || 0 >= c ? N(3) : N(2));\n this.Fb();\n var d = this.h.za();\n this.w = d;\n b = this.h.ya();\n\n if (!b) {\n var f = this;\n this.a.debug(function () {\n return \"No response text for uri \" + f.pa + \" status \" + d;\n });\n }\n\n this.S = 200 == d;\n this.a.Ug(this.Fa, this.pa, this.R, this.Xc, a, d);\n\n if (this.S) {\n if (this.Ig()) if (c = this.sf()) this.a.Wa(this.R, c, \"Initial handshake response via X-HTTP-Initial-Response\"), this.lb = !0, this.Yc(c);else {\n this.S = !1;\n this.I = 3;\n O(12);\n this.a.T(\"XMLHTTP Missing X_HTTP_INITIAL_RESPONSE (\" + this.R + \")\");\n this.Ia();\n this.Kb();\n return;\n }\n this.yc ? (this.Fd(a, b), La && this.S && 3 == a && this.Ng()) : (this.a.Wa(this.R, b, null), this.Yc(b));\n 4 == a && this.Ia();\n this.S && !this.Za && (4 == a ? this.b.Tc(this) : (this.S = !1, this.eb()));\n } else 400 == d && 0 < b.indexOf(\"Unknown SID\") ? (this.I = 3, O(12), this.a.T(\"XMLHTTP Unknown SID (\" + this.R + \")\")) : (this.I = 0, O(13), this.a.T(\"XMLHTTP Bad status \" + d + \" (\" + this.R + \")\")), this.Ia(), this.Kb();\n }\n};\n\ne.Ig = function () {\n return this.Ed && !this.lb;\n};\n\ne.sf = function () {\n if (this.h) {\n var a = this.h.kb(\"X-HTTP-Initial-Response\");\n if (a && !va(a)) return a;\n }\n\n return null;\n};\n\ne.Ag = function () {\n this.Ed = !0;\n};\n\ne.Fd = function (a, b) {\n for (var c = !0; !this.Za && this.Bb < b.length;) {\n var d = this.vf(b);\n\n if (d == mc) {\n 4 == a && (this.I = 4, O(14), c = !1);\n this.a.Wa(this.R, null, \"[Incomplete Response]\");\n break;\n } else if (d == lc) {\n this.I = 4;\n O(15);\n this.a.Wa(this.R, b, \"[Invalid Chunk]\");\n c = !1;\n break;\n } else this.a.Wa(this.R, d, null), this.Yc(d);\n }\n\n 4 == a && 0 == b.length && (this.I = 1, O(16), c = !1);\n this.S = this.S && c;\n c || (this.a.Wa(this.R, b, \"[Invalid Chunked Response]\"), this.Ia(), this.Kb());\n};\n\ne.kg = function () {\n if (this.h) {\n var a = this.h.ma(),\n b = this.h.ya();\n this.Bb < b.length && (this.Fb(), this.Fd(a, b), this.S && 4 != a && this.eb());\n }\n};\n\ne.Ng = function () {\n this.Fc.nb(this.Vc, \"tick\", this.kg);\n this.Vc.start();\n};\n\ne.vf = function (a) {\n var b = this.Bb,\n c = a.indexOf(\"\\n\", b);\n if (-1 == c) return mc;\n b = Number(a.substring(b, c));\n if (isNaN(b)) return lc;\n c += 1;\n if (c + b > a.length) return mc;\n a = a.substr(c, b);\n this.Bb = c + b;\n return a;\n};\n\ne.yg = function (a) {\n this.ic = 2;\n this.ua = a.clone().Ub();\n a = !1;\n h.navigator && h.navigator.sendBeacon && (a = h.navigator.sendBeacon(this.ua.toString(), \"\"));\n !a && h.Image && (new Image().src = this.ua, a = !0);\n a || (this.h = this.b.Jb(null), this.h.send(this.ua));\n this.qb = w();\n this.eb();\n};\n\ne.cancel = function () {\n this.Za = !0;\n this.Ia();\n};\n\ne.tg = function (a) {\n a && this.setTimeout(a);\n this.Ga && (this.Fb(), this.eb());\n};\n\ne.eb = function () {\n this.hd = w() + this.Ua;\n this.Ke(this.Ua);\n};\n\ne.Ke = function (a) {\n if (null != this.Ga) throw Error(\"WatchDog timer not null\");\n this.Ga = P(u(this.gg, this), a);\n};\n\ne.Fb = function () {\n this.Ga && (h.clearTimeout(this.Ga), this.Ga = null);\n};\n\ne.gg = function () {\n this.Ga = null;\n var a = w();\n 0 <= a - this.hd ? this.Df() : (this.a.T(\"WatchDog timer called too early\"), this.Ke(this.hd - a));\n};\n\ne.Df = function () {\n this.S && this.a.ca(\"Received watchdog timeout even though request loaded successfully\");\n this.a.Sg(this.pa);\n 2 != this.ic && (N(3), O(17));\n this.Ia();\n this.I = 2;\n this.Kb();\n};\n\ne.Kb = function () {\n this.b.de() || this.Za || this.b.Tc(this);\n};\n\ne.Ia = function () {\n this.Fb();\n var a = this.ac;\n a && \"function\" == typeof a.bb && a.bb();\n this.ac = null;\n this.Vc.stop();\n this.Fc.pb();\n this.h && (a = this.h, this.h = null, a.abort(), a.bb());\n};\n\ne.Hc = function () {\n return this.I;\n};\n\ne.Yc = function (a) {\n try {\n this.b.ue(this, a), N(4);\n } catch (b) {\n this.a.cb(b, \"Error in httprequest callback\");\n }\n};\n\nfunction nc(a) {\n if (a.H && \"function\" == typeof a.H) return a.H();\n if (l(a)) return a.split(\"\");\n\n if (ca(a)) {\n for (var b = [], c = a.length, d = 0; d < c; d++) {\n b.push(a[d]);\n }\n\n return b;\n }\n\n return Ba(a);\n}\n\nfunction oc(a, b, c) {\n if (a.forEach && \"function\" == typeof a.forEach) a.forEach(b, c);else if (ca(a) || l(a)) na(a, b, c);else {\n if (a.W && \"function\" == typeof a.W) var d = a.W();else if (a.H && \"function\" == typeof a.H) d = void 0;else if (ca(a) || l(a)) {\n d = [];\n\n for (var f = a.length, g = 0; g < f; g++) {\n d.push(g);\n }\n } else d = Ca(a);\n f = nc(a);\n g = f.length;\n\n for (var k = 0; k < g; k++) {\n b.call(c, f[k], d && d[k], a);\n }\n }\n}\n\nfunction S(a, b) {\n this.D = {};\n this.o = [];\n this.j = 0;\n var c = arguments.length;\n\n if (1 < c) {\n if (c % 2) throw Error(\"Uneven number of arguments\");\n\n for (var d = 0; d < c; d += 2) {\n this.set(arguments[d], arguments[d + 1]);\n }\n } else a && this.addAll(a);\n}\n\ne = S.prototype;\n\ne.C = function () {\n return this.j;\n};\n\ne.H = function () {\n this.wc();\n\n for (var a = [], b = 0; b < this.o.length; b++) {\n a.push(this.D[this.o[b]]);\n }\n\n return a;\n};\n\ne.W = function () {\n this.wc();\n return this.o.concat();\n};\n\ne.va = function (a) {\n return T(this.D, a);\n};\n\ne.X = function () {\n return 0 == this.j;\n};\n\ne.clear = function () {\n this.D = {};\n this.j = this.o.length = 0;\n};\n\ne.remove = function (a) {\n return T(this.D, a) ? (delete this.D[a], this.j--, this.o.length > 2 * this.j && this.wc(), !0) : !1;\n};\n\ne.wc = function () {\n if (this.j != this.o.length) {\n for (var a = 0, b = 0; a < this.o.length;) {\n var c = this.o[a];\n T(this.D, c) && (this.o[b++] = c);\n a++;\n }\n\n this.o.length = b;\n }\n\n if (this.j != this.o.length) {\n var d = {};\n\n for (b = a = 0; a < this.o.length;) {\n c = this.o[a], T(d, c) || (this.o[b++] = c, d[c] = 1), a++;\n }\n\n this.o.length = b;\n }\n};\n\ne.get = function (a, b) {\n return T(this.D, a) ? this.D[a] : b;\n};\n\ne.set = function (a, b) {\n T(this.D, a) || (this.j++, this.o.push(a));\n this.D[a] = b;\n};\n\ne.addAll = function (a) {\n if (a instanceof S) for (var b = a.W(), c = 0; c < b.length; c++) {\n this.set(b[c], a.get(b[c]));\n } else for (b in a) {\n this.set(b, a[b]);\n }\n};\n\ne.forEach = function (a, b) {\n for (var c = this.W(), d = 0; d < c.length; d++) {\n var f = c[d],\n g = this.get(f);\n a.call(b, g, f, this);\n }\n};\n\ne.clone = function () {\n return new S(this);\n};\n\nfunction T(a, b) {\n return Object.prototype.hasOwnProperty.call(a, b);\n}\n\nvar pc = /^(?:([^:/?#.]+):)?(?:\\/\\/(?:([^/?#]*)@)?([^/#?]*?)(?::([0-9]+))?(?=[/#?]|$))?([^?#]+)?(?:\\?([^#]*))?(?:#([\\s\\S]*))?$/;\n\nfunction qc(a, b) {\n if (a) {\n a = a.split(\"&\");\n\n for (var c = 0; c < a.length; c++) {\n var d = a[c].indexOf(\"=\"),\n f = null;\n\n if (0 <= d) {\n var g = a[c].substring(0, d);\n f = a[c].substring(d + 1);\n } else g = a[c];\n\n b(g, f ? decodeURIComponent(f.replace(/\\+/g, \" \")) : \"\");\n }\n }\n}\n\nfunction U(a, b) {\n this.xa = this.zb = this.qa = \"\";\n this.Ca = null;\n this.ib = this.K = \"\";\n this.O = this.Qf = !1;\n var c;\n a instanceof U ? (this.O = void 0 !== b ? b : a.O, this.tb(a.qa), this.cd(a.zb), this.rb(a.xa), this.sb(a.Ca), this.ec(a.K), this.bd(a.P.clone()), this.$c(a.ib)) : a && (c = String(a).match(pc)) ? (this.O = !!b, this.tb(c[1] || \"\", !0), this.cd(c[2] || \"\", !0), this.rb(c[3] || \"\", !0), this.sb(c[4]), this.ec(c[5] || \"\", !0), this.bd(c[6] || \"\", !0), this.$c(c[7] || \"\", !0)) : (this.O = !!b, this.P = new rc(null, this.O));\n}\n\ne = U.prototype;\n\ne.toString = function () {\n var a = [],\n b = this.qa;\n b && a.push(sc(b, tc, !0), \":\");\n var c = this.xa;\n if (c || \"file\" == b) a.push(\"//\"), (b = this.zb) && a.push(sc(b, tc, !0), \"@\"), a.push(encodeURIComponent(String(c)).replace(/%25([0-9a-fA-F]{2})/g, \"%$1\")), c = this.Ca, null != c && a.push(\":\", String(c));\n if (c = this.K) this.Ic() && \"/\" != c.charAt(0) && a.push(\"/\"), a.push(sc(c, \"/\" == c.charAt(0) ? uc : wc, !0));\n (c = this.Rd()) && a.push(\"?\", c);\n (c = this.ib) && a.push(\"#\", sc(c, xc));\n return a.join(\"\");\n};\n\ne.resolve = function (a) {\n var b = this.clone(),\n c = a.Hf();\n c ? b.tb(a.qa) : c = a.If();\n c ? b.cd(a.zb) : c = a.Ic();\n c ? b.rb(a.xa) : c = a.Ff();\n var d = a.K;\n if (c) b.sb(a.Ca);else if (c = a.ae()) {\n if (\"/\" != d.charAt(0)) if (this.Ic() && !this.ae()) d = \"/\" + d;else {\n var f = b.K.lastIndexOf(\"/\");\n -1 != f && (d = b.K.substr(0, f + 1) + d);\n }\n f = d;\n if (\"..\" == f || \".\" == f) d = \"\";else if (-1 != f.indexOf(\"./\") || -1 != f.indexOf(\"/.\")) {\n d = 0 == f.lastIndexOf(\"/\", 0);\n f = f.split(\"/\");\n\n for (var g = [], k = 0; k < f.length;) {\n var p = f[k++];\n \".\" == p ? d && k == f.length && g.push(\"\") : \"..\" == p ? ((1 < g.length || 1 == g.length && \"\" != g[0]) && g.pop(), d && k == f.length && g.push(\"\")) : (g.push(p), d = !0);\n }\n\n d = g.join(\"/\");\n } else d = f;\n }\n c ? b.ec(d) : c = a.Gf();\n c ? b.bd(a.P.clone()) : c = a.Ef();\n c && b.$c(a.ib);\n return b;\n};\n\ne.clone = function () {\n return new U(this);\n};\n\ne.tb = function (a, b) {\n this.U();\n if (this.qa = b ? yc(a, !0) : a) this.qa = this.qa.replace(/:$/, \"\");\n};\n\ne.Hf = function () {\n return !!this.qa;\n};\n\ne.cd = function (a, b) {\n this.U();\n this.zb = b ? yc(a) : a;\n};\n\ne.If = function () {\n return !!this.zb;\n};\n\ne.rb = function (a, b) {\n this.U();\n this.xa = b ? yc(a, !0) : a;\n};\n\ne.Ic = function () {\n return !!this.xa;\n};\n\ne.sb = function (a) {\n this.U();\n\n if (a) {\n a = Number(a);\n if (isNaN(a) || 0 > a) throw Error(\"Bad port number \" + a);\n this.Ca = a;\n } else this.Ca = null;\n};\n\ne.Ff = function () {\n return null != this.Ca;\n};\n\ne.ec = function (a, b) {\n this.U();\n this.K = b ? yc(a, !0) : a;\n};\n\ne.ae = function () {\n return !!this.K;\n};\n\ne.Gf = function () {\n return \"\" !== this.P.toString();\n};\n\ne.bd = function (a, b) {\n this.U();\n a instanceof rc ? (this.P = a, this.P.ad(this.O)) : (b || (a = sc(a, zc)), this.P = new rc(a, this.O));\n};\n\ne.Rd = function () {\n return this.P.toString();\n};\n\ne.getQuery = function () {\n return this.Rd();\n};\n\ne.l = function (a, b) {\n this.U();\n this.P.set(a, b);\n};\n\ne.dc = function (a, b) {\n this.U();\n n(b) || (b = [String(b)]);\n this.P.Ie(a, b);\n};\n\ne.$c = function (a, b) {\n this.U();\n this.ib = b ? yc(a) : a;\n};\n\ne.Ef = function () {\n return !!this.ib;\n};\n\ne.Ub = function () {\n this.U();\n this.l(\"zx\", Math.floor(2147483648 * Math.random()).toString(36) + Math.abs(Math.floor(2147483648 * Math.random()) ^ w()).toString(36));\n return this;\n};\n\ne.removeParameter = function (a) {\n this.U();\n this.P.remove(a);\n return this;\n};\n\ne.U = function () {\n if (this.Qf) throw Error(\"Tried to modify a read-only Uri\");\n};\n\ne.ad = function (a) {\n this.O = a;\n this.P && this.P.ad(a);\n};\n\nfunction Ac(a) {\n return a instanceof U ? a.clone() : new U(a, void 0);\n}\n\nfunction Bc(a, b, c, d) {\n var f = new U(null, void 0);\n a && f.tb(a);\n b && f.rb(b);\n c && f.sb(c);\n d && f.ec(d);\n return f;\n}\n\nfunction yc(a, b) {\n return a ? b ? decodeURI(a.replace(/%25/g, \"%2525\")) : decodeURIComponent(a) : \"\";\n}\n\nfunction sc(a, b, c) {\n return l(a) ? (a = encodeURI(a).replace(b, Cc), c && (a = a.replace(/%25([0-9a-fA-F]{2})/g, \"%$1\")), a) : null;\n}\n\nfunction Cc(a) {\n a = a.charCodeAt(0);\n return \"%\" + (a >> 4 & 15).toString(16) + (a & 15).toString(16);\n}\n\nvar tc = /[#\\/\\?@]/g,\n wc = /[#\\?:]/g,\n uc = /[#\\?]/g,\n zc = /[#\\?@]/g,\n xc = /#/g;\n\nfunction rc(a, b) {\n this.j = this.m = null;\n this.ja = a || null;\n this.O = !!b;\n}\n\ne = rc.prototype;\n\ne.$ = function () {\n if (!this.m && (this.m = new S(), this.j = 0, this.ja)) {\n var a = this;\n qc(this.ja, function (b, c) {\n a.add(decodeURIComponent(b.replace(/\\+/g, \" \")), c);\n });\n }\n};\n\ne.C = function () {\n this.$();\n return this.j;\n};\n\ne.add = function (a, b) {\n this.$();\n this.Oa();\n a = this.Ma(a);\n var c = this.m.get(a);\n c || this.m.set(a, c = []);\n c.push(b);\n this.j += 1;\n return this;\n};\n\ne.remove = function (a) {\n this.$();\n a = this.Ma(a);\n return this.m.va(a) ? (this.Oa(), this.j -= this.m.get(a).length, this.m.remove(a)) : !1;\n};\n\ne.clear = function () {\n this.Oa();\n this.m = null;\n this.j = 0;\n};\n\ne.X = function () {\n this.$();\n return 0 == this.j;\n};\n\ne.va = function (a) {\n this.$();\n a = this.Ma(a);\n return this.m.va(a);\n};\n\ne.forEach = function (a, b) {\n this.$();\n this.m.forEach(function (c, d) {\n na(c, function (c) {\n a.call(b, c, d, this);\n }, this);\n }, this);\n};\n\ne.W = function () {\n this.$();\n\n for (var a = this.m.H(), b = this.m.W(), c = [], d = 0; d < b.length; d++) {\n for (var f = a[d], g = 0; g < f.length; g++) {\n c.push(b[d]);\n }\n }\n\n return c;\n};\n\ne.H = function (a) {\n this.$();\n var b = [];\n if (l(a)) this.va(a) && (b = ta(b, this.m.get(this.Ma(a))));else {\n a = this.m.H();\n\n for (var c = 0; c < a.length; c++) {\n b = ta(b, a[c]);\n }\n }\n return b;\n};\n\ne.set = function (a, b) {\n this.$();\n this.Oa();\n a = this.Ma(a);\n this.va(a) && (this.j -= this.m.get(a).length);\n this.m.set(a, [b]);\n this.j += 1;\n return this;\n};\n\ne.get = function (a, b) {\n if (!a) return b;\n a = this.H(a);\n return 0 < a.length ? String(a[0]) : b;\n};\n\ne.Ie = function (a, b) {\n this.remove(a);\n 0 < b.length && (this.Oa(), this.m.set(this.Ma(a), ua(b)), this.j += b.length);\n};\n\ne.toString = function () {\n if (this.ja) return this.ja;\n if (!this.m) return \"\";\n\n for (var a = [], b = this.m.W(), c = 0; c < b.length; c++) {\n var d = b[c],\n f = encodeURIComponent(String(d));\n d = this.H(d);\n\n for (var g = 0; g < d.length; g++) {\n var k = f;\n \"\" !== d[g] && (k += \"=\" + encodeURIComponent(String(d[g])));\n a.push(k);\n }\n }\n\n return this.ja = a.join(\"&\");\n};\n\ne.Oa = function () {\n this.ja = null;\n};\n\ne.clone = function () {\n var a = new rc();\n a.ja = this.ja;\n this.m && (a.m = this.m.clone(), a.j = this.j);\n return a;\n};\n\ne.Ma = function (a) {\n a = String(a);\n this.O && (a = a.toLowerCase());\n return a;\n};\n\ne.ad = function (a) {\n a && !this.O && (this.$(), this.Oa(), this.m.forEach(function (a, c) {\n var b = c.toLowerCase();\n c != b && (this.remove(c), this.Ie(b, a));\n }, this));\n this.O = a;\n};\n\ne.extend = function (a) {\n for (var b = 0; b < arguments.length; b++) {\n oc(arguments[b], function (a, b) {\n this.add(b, a);\n }, this);\n }\n};\n\nfunction Fc() {}\n\nfunction Gc() {}\n\nx(Gc, Fc);\n\nfunction Hc(a, b) {\n this.b = a;\n this.a = b;\n this.f = this.A = null;\n this.bc = !1;\n this.K = null;\n this.w = -1;\n this.Ad = this.na = null;\n}\n\ne = Hc.prototype;\ne.g = null;\n\ne.ga = function (a) {\n this.A = a;\n};\n\ne.connect = function (a) {\n this.K = a;\n a = this.b.Sd(this.K);\n O(3);\n var b = this.b.Ib.$d;\n null != b ? (this.na = this.b.$a(b[0]), this.g = 1, this.xd()) : (a.dc(\"MODE\", \"init\"), !this.b.ta && this.b.aa && a.dc(\"X-HTTP-Session-Id\", this.b.aa), this.f = new R(this, this.a, void 0, void 0, void 0), this.f.ga(this.A), this.f.jd(a, !1, null), this.g = 0);\n};\n\ne.xd = function () {\n this.a.debug(\"TestConnection: starting stage 2\");\n var a = this.b.Ib.od;\n if (null != a) this.a.debug(function () {\n return \"TestConnection: skipping stage 2, precomputed result is \" + a ? \"Buffered\" : \"Unbuffered\";\n }), O(4), a ? (O(10), this.b.ub(this, !1)) : (O(11), this.b.ub(this, !0));else {\n this.f = new R(this, this.a, void 0, void 0, void 0);\n this.f.ga(this.A);\n var b = this.b.Pd(this.na, this.K);\n O(4);\n b.dc(\"TYPE\", \"xmlhttp\");\n var c = this.b.aa,\n d = this.b.Kc;\n c && d && b.l(c, d);\n this.f.jd(b, !1, this.na);\n }\n};\n\ne.Jb = function (a) {\n return this.b.Jb(a);\n};\n\ne.abort = function () {\n this.f && (this.f.cancel(), this.f = null);\n this.w = -1;\n};\n\ne.de = function () {\n return !1;\n};\n\ne.ue = function (a, b) {\n this.w = a.w;\n if (0 == this.g) {\n if (this.a.debug(\"TestConnection: Got data for stage 1\"), this.pc(a), b) {\n try {\n var c = this.b.kc.zc(b);\n } catch (d) {\n this.a.cb(d);\n this.b.dd(this);\n return;\n }\n\n this.na = this.b.$a(c[0]);\n } else this.a.debug(\"TestConnection: Null responseText\"), this.b.dd(this);\n } else 1 == this.g && (this.bc ? O(6) : \"11111\" == b ? (O(5), this.bc = !0, this.Ze() && (this.w = 200, this.f.cancel(), this.a.debug(\"Test connection succeeded; using streaming connection\"), O(11), this.b.ub(this, !0))) : (O(7), this.bc = !1));\n};\n\ne.Tc = function () {\n this.w = this.f.w;\n this.f.S ? 0 == this.g ? (this.g = 1, this.a.debug(\"TestConnection: request complete for initial check\"), this.xd()) : 1 == this.g && (this.a.debug(\"TestConnection: request complete for stage 2\"), this.bc ? (this.a.debug(\"Test connection succeeded; using streaming connection\"), O(11), this.b.ub(this, !0)) : (this.a.debug(\"Test connection failed; not using streaming\"), O(10), this.b.ub(this, !1))) : (this.a.debug(\"TestConnection: request failed, in state \" + this.g), 0 == this.g ? O(8) : 1 == this.g && O(9), this.b.dd(this));\n};\n\ne.pc = function (a) {\n if (!this.b.ta && (a = a.h)) {\n var b = a.kb(\"X-Client-Wire-Protocol\");\n this.Ad = b ? b : null;\n this.b.aa && ((a = a.kb(\"X-HTTP-Session-Id\")) ? this.b.Fe(a) : this.a.T(\"Missing X_HTTP_SESSION_ID in the handshake response\"));\n }\n};\n\ne.fc = function () {\n return this.b.fc();\n};\n\ne.Ba = function () {\n return this.b.Ba();\n};\n\ne.Ze = function () {\n return !C || 10 <= Number(Ua);\n};\n\nfunction Ic() {\n this.od = this.$d = null;\n}\n\nfunction Jc(a) {\n this.D = new S();\n a && this.addAll(a);\n}\n\nfunction Kc(a) {\n var b = typeof a;\n return \"object\" == b && a || \"function\" == b ? \"o\" + (a[t] || (a[t] = ++da)) : b.substr(0, 1) + a;\n}\n\ne = Jc.prototype;\n\ne.C = function () {\n return this.D.C();\n};\n\ne.add = function (a) {\n this.D.set(Kc(a), a);\n};\n\ne.addAll = function (a) {\n a = nc(a);\n\n for (var b = a.length, c = 0; c < b; c++) {\n this.add(a[c]);\n }\n};\n\ne.pb = function (a) {\n a = nc(a);\n\n for (var b = a.length, c = 0; c < b; c++) {\n this.remove(a[c]);\n }\n};\n\ne.remove = function (a) {\n return this.D.remove(Kc(a));\n};\n\ne.clear = function () {\n this.D.clear();\n};\n\ne.X = function () {\n return this.D.X();\n};\n\ne.contains = function (a) {\n return this.D.va(Kc(a));\n};\n\ne.H = function () {\n return this.D.H();\n};\n\ne.clone = function () {\n return new Jc(this);\n};\n\nfunction Lc(a, b) {\n this.Pc = a;\n this.map = b;\n this.context = null;\n}\n\nfunction Mc(a) {\n this.me = a || Nc;\n h.PerformanceNavigationTiming ? (a = h.performance.getEntriesByType(\"navigation\"), a = 0 < a.length && (\"hq\" == a[0].nextHopProtocol || \"h2\" == a[0].nextHopProtocol)) : a = !!(h.vc && h.vc.ke && h.vc.ke() && h.vc.ke().nh);\n this.Xb = a ? this.me : 1;\n this.v = null;\n 1 < this.Xb && (this.v = new Jc());\n this.f = null;\n this.ba = [];\n}\n\nvar Nc = 10;\ne = Mc.prototype;\n\ne.ld = function (a) {\n this.v || -1 == a.indexOf(\"spdy\") && -1 == a.indexOf(\"quic\") && -1 == a.indexOf(\"h2\") || (this.Xb = this.me, this.v = new Jc(), this.f && (this.oc(this.f), this.f = null));\n};\n\ne.ee = function () {\n return this.f ? !0 : this.v ? this.v.C() >= this.Xb : !1;\n};\n\ne.xf = function () {\n return this.f ? 1 : this.v ? this.v.C() : 0;\n};\n\ne.Jc = function (a) {\n return this.f ? this.f == a : this.v ? this.v.contains(a) : !1;\n};\n\ne.oc = function (a) {\n this.v ? this.v.add(a) : this.f = a;\n};\n\ne.ze = function (a) {\n this.f && this.f == a ? this.f = null : this.v && this.v.contains(a) && this.v.remove(a);\n};\n\ne.cancel = function () {\n this.ba = this.la();\n this.f ? (this.f.cancel(), this.f = null) : this.v && !this.v.X() && (na(this.v.H(), function (a) {\n a.cancel();\n }), this.v.clear());\n};\n\ne.la = function () {\n if (null != this.f) return this.ba.concat(this.f.la());\n\n if (null != this.v && !this.v.X()) {\n var a = this.ba;\n na(this.v.H(), function (b) {\n a = a.concat(b.la());\n });\n return a;\n }\n\n return ua(this.ba);\n};\n\ne.Re = function (a) {\n this.ba = this.ba.concat(a);\n};\n\ne.$e = function () {\n this.ba.length = 0;\n};\n\nfunction Oc() {\n this.xg = this.rg = void 0;\n}\n\nOc.prototype.stringify = function (a) {\n return h.JSON.stringify(a, this.rg);\n};\n\nOc.prototype.parse = function (a) {\n return h.JSON.parse(a, this.xg);\n};\n\nfunction Pc() {\n this.jg = new Oc();\n}\n\nPc.prototype.hf = function (a, b, c) {\n var d = c || \"\";\n\n try {\n oc(a, function (a, c) {\n var f = a;\n r(a) && (f = ub(a));\n b.push(d + c + \"=\" + encodeURIComponent(f));\n });\n } catch (f) {\n throw b.push(d + \"type=\" + encodeURIComponent(\"_badmap\")), f;\n }\n};\n\nPc.prototype.jf = function (a, b, c) {\n for (var d = -1;;) {\n var f = [\"count=\" + b];\n -1 == d ? 0 < b ? (d = a[0].Pc, f.push(\"ofs=\" + d)) : d = 0 : f.push(\"ofs=\" + d);\n\n for (var g = !0, k = 0; k < b; k++) {\n var p = a[k].Pc,\n Ub = a[k].map;\n p -= d;\n if (0 > p) d = Math.max(0, a[k].Pc - 100), g = !1;else try {\n this.hf(Ub, f, \"req\" + p + \"_\");\n } catch (md) {\n c && c(Ub);\n }\n }\n\n if (g) return f.join(\"&\");\n }\n};\n\nPc.prototype.zc = function (a) {\n return this.jg.parse(a);\n};\n\nfunction Qc(a, b) {\n var c = new Xb();\n c.debug(\"TestLoadImage: loading \" + a);\n var d = new Image();\n d.onload = v(Rc, c, d, \"TestLoadImage: loaded\", !0, b);\n d.onerror = v(Rc, c, d, \"TestLoadImage: error\", !1, b);\n d.onabort = v(Rc, c, d, \"TestLoadImage: abort\", !1, b);\n d.ontimeout = v(Rc, c, d, \"TestLoadImage: timeout\", !1, b);\n h.setTimeout(function () {\n if (d.ontimeout) d.ontimeout();\n }, 1E4);\n d.src = a;\n}\n\nfunction Rc(a, b, c, d, f) {\n try {\n a.debug(c), b.onload = null, b.onerror = null, b.onabort = null, b.ontimeout = null, f(d);\n } catch (g) {\n a.cb(g);\n }\n}\n\nvar Sc = h.JSON.parse;\n\nfunction V(a) {\n H.call(this);\n this.headers = new S();\n this.Xa = a || null;\n this.ha = !1;\n this.mc = this.c = null;\n this.ge = this.Tb = \"\";\n this.Pa = 0;\n this.I = \"\";\n this.Aa = this.Lc = this.Qb = this.Ec = !1;\n this.vb = 0;\n this.hc = null;\n this.Ae = Tc;\n this.jc = this.lg = this.Ab = !1;\n}\n\nx(V, H);\nvar Tc = \"\";\nV.prototype.s = Vb(\"goog.net.XhrIo\");\nvar Uc = /^https?$/i,\n Vc = [\"POST\", \"PUT\"];\ne = V.prototype;\n\ne.Je = function (a) {\n this.Ab = a;\n};\n\ne.send = function (a, b, c, d) {\n if (this.c) throw Error(\"[goog.net.XhrIo] Object is active with another request=\" + this.Tb + \"; newUri=\" + a);\n b = b ? b.toUpperCase() : \"GET\";\n this.Tb = a;\n this.I = \"\";\n this.Pa = 0;\n this.ge = b;\n this.Ec = !1;\n this.ha = !0;\n this.c = this.df();\n this.mc = this.Xa ? this.Xa.Vd() : hc.Vd();\n this.c.onreadystatechange = u(this.te, this);\n this.lg && \"onprogress\" in this.c && (this.c.onprogress = u(function (a) {\n this.re(a, !0);\n }, this), this.c.upload && (this.c.upload.onprogress = u(this.re, this)));\n\n try {\n L(this.s, this.da(\"Opening Xhr\")), this.Lc = !0, this.c.open(b, String(a), !0), this.Lc = !1;\n } catch (g) {\n L(this.s, this.da(\"Error opening Xhr: \" + g.message));\n this.Ld(g);\n return;\n }\n\n a = c || \"\";\n var f = this.headers.clone();\n d && oc(d, function (a, b) {\n f.set(b, a);\n });\n d = pa(f.W());\n c = h.FormData && a instanceof h.FormData;\n !(0 <= la(Vc, b)) || d || c || f.set(\"Content-Type\", \"application/x-www-form-urlencoded;charset=utf-8\");\n f.forEach(function (a, b) {\n this.c.setRequestHeader(b, a);\n }, this);\n this.Ae && (this.c.responseType = this.Ae);\n \"withCredentials\" in this.c && this.c.withCredentials !== this.Ab && (this.c.withCredentials = this.Ab);\n\n try {\n this.yd(), 0 < this.vb && (this.jc = Wc(this.c), L(this.s, this.da(\"Will abort after \" + this.vb + \"ms if incomplete, xhr2 \" + this.jc)), this.jc ? (this.c.timeout = this.vb, this.c.ontimeout = u(this.Ua, this)) : this.hc = Hb(this.Ua, this.vb, this)), L(this.s, this.da(\"Sending request\")), this.Qb = !0, this.c.send(a), this.Qb = !1;\n } catch (g) {\n L(this.s, this.da(\"Send error: \" + g.message)), this.Ld(g);\n }\n};\n\nfunction Wc(a) {\n return C && Ta(9) && \"number\" == typeof a.timeout && void 0 !== a.ontimeout;\n}\n\nfunction qa(a) {\n return \"content-type\" == a.toLowerCase();\n}\n\ne.df = function () {\n return this.Xa ? this.Xa.Dd() : hc.Dd();\n};\n\ne.Ua = function () {\n \"undefined\" != typeof goog && this.c && (this.I = \"Timed out after \" + this.vb + \"ms, aborting\", this.Pa = 8, L(this.s, this.da(this.I)), this.dispatchEvent(\"timeout\"), this.abort(8));\n};\n\ne.Ld = function (a) {\n this.ha = !1;\n this.c && (this.Aa = !0, this.c.abort(), this.Aa = !1);\n this.I = a;\n this.Pa = 5;\n this.Jd();\n this.Gb();\n};\n\ne.Jd = function () {\n this.Ec || (this.Ec = !0, this.dispatchEvent(\"complete\"), this.dispatchEvent(\"error\"));\n};\n\ne.abort = function (a) {\n this.c && this.ha && (L(this.s, this.da(\"Aborting\")), this.ha = !1, this.Aa = !0, this.c.abort(), this.Aa = !1, this.Pa = a || 7, this.dispatchEvent(\"complete\"), this.dispatchEvent(\"abort\"), this.Gb());\n};\n\ne.F = function () {\n this.c && (this.ha && (this.ha = !1, this.Aa = !0, this.c.abort(), this.Aa = !1), this.Gb(!0));\n V.L.F.call(this);\n};\n\ne.te = function () {\n this.Ka || (this.Lc || this.Qb || this.Aa ? this.se() : this.eg());\n};\n\ne.eg = function () {\n this.se();\n};\n\ne.se = function () {\n if (this.ha && \"undefined\" != typeof goog) if (this.mc[1] && 4 == this.ma() && 2 == this.za()) L(this.s, this.da(\"Local request error detected and ignored\"));else if (this.Qb && 4 == this.ma()) Hb(this.te, 0, this);else if (this.dispatchEvent(\"readystatechange\"), this.Mc()) {\n L(this.s, this.da(\"Request complete\"));\n this.ha = !1;\n\n try {\n this.Rf() ? (this.dispatchEvent(\"complete\"), this.dispatchEvent(\"success\")) : (this.Pa = 6, this.I = this.Yd() + \" [\" + this.za() + \"]\", this.Jd());\n } finally {\n this.Gb();\n }\n }\n};\n\ne.re = function (a, b) {\n this.dispatchEvent(Xc(a, \"progress\"));\n this.dispatchEvent(Xc(a, b ? \"downloadprogress\" : \"uploadprogress\"));\n};\n\nfunction Xc(a, b) {\n return {\n type: b,\n lengthComputable: a.lengthComputable,\n loaded: a.loaded,\n total: a.total\n };\n}\n\ne.Gb = function (a) {\n if (this.c) {\n this.yd();\n var b = this.c,\n c = this.mc[0] ? aa : null;\n this.mc = this.c = null;\n a || this.dispatchEvent(\"ready\");\n\n try {\n b.onreadystatechange = c;\n } catch (d) {\n (a = this.s) && a.ca(\"Problem encountered resetting onreadystatechange: \" + d.message, void 0);\n }\n }\n};\n\ne.yd = function () {\n this.c && this.jc && (this.c.ontimeout = null);\n this.hc && (h.clearTimeout(this.hc), this.hc = null);\n};\n\ne.Ba = function () {\n return !!this.c;\n};\n\ne.Mc = function () {\n return 4 == this.ma();\n};\n\ne.Rf = function () {\n var a = this.za();\n\n a: switch (a) {\n case 200:\n case 201:\n case 202:\n case 204:\n case 206:\n case 304:\n case 1223:\n var b = !0;\n break a;\n\n default:\n b = !1;\n }\n\n return b || 0 === a && !this.Of();\n};\n\ne.Of = function () {\n var a = String(this.Tb).match(pc)[1] || null;\n !a && h.self && h.self.location && (a = h.self.location.protocol, a = a.substr(0, a.length - 1));\n return Uc.test(a ? a.toLowerCase() : \"\");\n};\n\ne.ma = function () {\n return this.c ? this.c.readyState : 0;\n};\n\ne.za = function () {\n try {\n return 2 < this.ma() ? this.c.status : -1;\n } catch (a) {\n return -1;\n }\n};\n\ne.Yd = function () {\n try {\n return 2 < this.ma() ? this.c.statusText : \"\";\n } catch (a) {\n return L(this.s, \"Can not get status: \" + a.message), \"\";\n }\n};\n\ne.ya = function () {\n try {\n return this.c ? this.c.responseText : \"\";\n } catch (a) {\n return L(this.s, \"Can not get responseText: \" + a.message), \"\";\n }\n};\n\ne.yf = function (a) {\n if (this.c) {\n var b = this.c.responseText;\n a && 0 == b.indexOf(a) && (b = b.substring(a.length));\n return Sc(b);\n }\n};\n\ne.getResponseHeader = function (a) {\n if (this.c && this.Mc()) return a = this.c.getResponseHeader(a), null === a ? void 0 : a;\n};\n\ne.getAllResponseHeaders = function () {\n return this.c && this.Mc() ? this.c.getAllResponseHeaders() || \"\" : \"\";\n};\n\ne.kb = function (a) {\n return this.c ? this.c.getResponseHeader(a) : null;\n};\n\ne.Ud = function () {\n return this.Pa;\n};\n\ne.Hc = function () {\n return l(this.I) ? this.I : String(this.I);\n};\n\ne.da = function (a) {\n return a + \" [\" + this.ge + \" \" + this.Tb + \" \" + this.za() + \"]\";\n};\n\nfunction Yc(a) {\n var b = \"\";\n Aa(a, function (a, d) {\n b += d;\n b += \":\";\n b += a;\n b += \"\\r\\n\";\n });\n return b;\n}\n\nfunction Zc(a, b, c) {\n a: {\n for (d in c) {\n var d = !1;\n break a;\n }\n\n d = !0;\n }\n\n if (d) return a;\n c = Yc(c);\n\n if (l(a)) {\n b = encodeURIComponent(String(b));\n c = null != c ? \"=\" + encodeURIComponent(String(c)) : \"\";\n\n if (b += c) {\n c = a.indexOf(\"#\");\n 0 > c && (c = a.length);\n d = a.indexOf(\"?\");\n\n if (0 > d || d > c) {\n d = c;\n var f = \"\";\n } else f = a.substring(d + 1, c);\n\n a = [a.substr(0, d), f, a.substr(c)];\n c = a[1];\n a[1] = b ? c ? c + \"&\" + b : b : c;\n a = a[0] + (a[1] ? \"?\" + a[1] : \"\") + a[2];\n }\n\n return a;\n }\n\n a.l(b, c);\n return a;\n}\n\nfunction $c(a) {\n this.Bd = 22;\n this.De = 0;\n this.M = [];\n this.a = new Xb();\n this.Ib = new Ic();\n this.na = this.md = this.hb = this.K = this.u = this.Kc = this.aa = this.gb = this.N = this.Rb = this.A = null;\n this.Te = !0;\n this.ag = this.Yb = 0;\n this.kf = !!m(\"internalChannelParams.failFast\", a);\n this.fd = this.Ja = this.wa = this.ia = this.ea = this.i = null;\n this.Se = !0;\n this.w = this.he = this.Sb = -1;\n this.rc = this.Ha = this.La = 0;\n this.Ve = m(\"internalChannelParams.baseRetryDelayMs\", a) || 5E3;\n this.vg = m(\"internalChannelParams.retryDelaySeedMs\", a) || 1E4;\n this.nf = m(\"internalChannelParams.forwardChannelMaxRetries\", a) || 2;\n this.Od = m(\"internalChannelParams.forwardChannelRequestTimeoutMs\", a) || 2E4;\n this.Xa = a && a.oh || void 0;\n this.Db = void 0;\n this.Ra = 0;\n this.gc = a && a.supportsCrossDomainXhr || !1;\n this.ra = \"\";\n this.G = new Mc(a && a.concurrentRequestLimit);\n this.kc = new Pc();\n this.ta = a && void 0 !== a.backgroundChannelTest ? a.backgroundChannelTest : !0;\n (this.Nd = a && a.fastHandshake || !1) && !this.ta && (this.a.T(\"Force backgroundChannelTest when fastHandshake is enabled.\"), this.ta = !0);\n a && a.Id && this.a.Id();\n}\n\ne = $c.prototype;\ne.tc = 8;\ne.g = 1;\n\ne.connect = function (a, b, c, d, f) {\n this.a.debug(\"connect()\");\n O(0);\n this.K = b;\n this.gb = c || {};\n d && void 0 !== f && (this.gb.OSID = d, this.gb.OAID = f);\n this.ta && (this.a.debug(\"connect() bypassed channel-test.\"), this.Ib.$d = [], this.Ib.od = !1);\n this.bf(a);\n};\n\ne.disconnect = function () {\n this.a.debug(\"disconnect()\");\n this.qd();\n\n if (3 == this.g) {\n var a = this.Yb++,\n b = this.hb.clone();\n b.l(\"SID\", this.ra);\n b.l(\"RID\", a);\n b.l(\"TYPE\", \"terminate\");\n this.Ya(b);\n new R(this, this.a, this.ra, a, void 0).yg(b);\n }\n\n this.qe();\n};\n\ne.bf = function (a) {\n this.a.debug(\"connectTest_()\");\n this.Ja = new Hc(this, this.a);\n null === this.N && this.Ja.ga(this.A);\n var b = a;\n this.N && this.A && (b = Zc(a, this.N, this.A));\n this.Ja.connect(b);\n};\n\ne.af = function () {\n this.a.debug(\"connectChannel_()\");\n this.hb = this.Sd(this.K);\n this.Dc();\n};\n\ne.qd = function () {\n this.Ja && (this.Ja.abort(), this.Ja = null);\n this.u && (this.u.cancel(), this.u = null);\n this.ia && (h.clearTimeout(this.ia), this.ia = null);\n this.Hb();\n this.G.cancel();\n this.ea && (h.clearTimeout(this.ea), this.ea = null);\n};\n\ne.ga = function (a) {\n this.A = a;\n};\n\ne.Eg = function (a) {\n this.Rb = a;\n};\n\ne.Cg = function (a) {\n this.N = a;\n};\n\ne.Dg = function (a) {\n this.aa = a;\n};\n\ne.Fe = function (a) {\n this.Kc = a;\n};\n\ne.He = function (a) {\n this.Ra = a;\n};\n\ne.Hg = function () {\n this.gc = !0;\n};\n\ne.Ee = function (a) {\n this.i = a;\n};\n\ne.Nf = function () {\n return !this.fd;\n};\n\ne.Zc = function (a) {\n 1E3 == this.M.length && this.a.ca(function () {\n return \"Already have 1000 queued maps upon queueing \" + ub(a);\n });\n this.M.push(new Lc(this.ag++, a));\n 3 == this.g && this.Dc();\n};\n\ne.qf = function () {\n return this.kf ? 0 : this.nf;\n};\n\ne.de = function () {\n return 0 == this.g;\n};\n\ne.getState = function () {\n return this.g;\n};\n\ne.Dc = function () {\n this.G.ee() || this.ea || (this.ea = P(u(this.we, this), 0), this.La = 0);\n};\n\ne.Yf = function (a) {\n if (this.G.xf() >= this.G.Xb - (this.ea ? 1 : 0)) return this.a.ca(\"Unexpected retry request is scheduled.\"), !1;\n if (this.ea) return this.a.debug(\"Use the retry request that is already scheduled.\"), this.M = a.la().concat(this.M), !0;\n if (1 == this.g || 2 == this.g || this.La >= this.qf()) return !1;\n this.a.debug(\"Going to retry POST\");\n this.ea = P(u(this.we, this, a), this.Xd(this.La));\n this.La++;\n return !0;\n};\n\ne.we = function (a) {\n this.ea = null;\n this.Mg(a);\n};\n\ne.Mg = function (a) {\n this.a.debug(\"startForwardChannel_\");\n 1 == this.g ? a ? this.a.ca(\"Not supposed to retry the open\") : (this.ig(), this.g = 2) : 3 == this.g && (a ? this.le(a) : 0 == this.M.length ? this.a.debug(\"startForwardChannel_ returned: nothing to send\") : this.G.ee() ? this.a.ca(\"startForwardChannel_ returned: connection already in progress\") : (this.le(), this.a.debug(\"startForwardChannel_ finished, sent request\")));\n};\n\ne.ig = function () {\n this.a.debug(\"open_()\");\n this.Yb = Math.floor(1E5 * Math.random());\n var a = this.Yb++,\n b = new R(this, this.a, \"\", a, void 0),\n c = this.A;\n this.Rb && (c ? (c = Da(c), Fa(c, this.Rb)) : c = this.Rb);\n null === this.N && b.ga(c);\n var d = this.Hd(b),\n f = this.hb.clone();\n f.l(\"RID\", a);\n 0 < this.Bd && f.l(\"CVER\", this.Bd);\n this.ta && this.aa && f.l(\"X-HTTP-Session-Id\", this.aa);\n this.Ya(f);\n this.N && c && Zc(f, this.N, c);\n this.G.oc(b);\n this.Nd ? (f.l(\"$req\", d), f.l(\"SID\", \"null\"), b.Ag(), b.kd(f, null)) : b.kd(f, d);\n};\n\ne.le = function (a) {\n var b = a ? a.R : this.Yb++;\n var c = this.hb.clone();\n c.l(\"SID\", this.ra);\n c.l(\"RID\", b);\n c.l(\"AID\", this.Sb);\n this.Ya(c);\n this.N && this.A && Zc(c, this.N, this.A);\n b = new R(this, this.a, this.ra, b, this.La + 1);\n null === this.N && b.ga(this.A);\n a && this.sg(a);\n a = this.Hd(b);\n b.setTimeout(Math.round(.5 * this.Od) + Math.round(.5 * this.Od * Math.random()));\n this.G.oc(b);\n b.kd(c, a);\n};\n\ne.Ya = function (a) {\n this.i && oc({}, function (b, c) {\n a.l(c, b);\n });\n};\n\ne.Hd = function (a) {\n var b = Math.min(this.M.length, 1E3),\n c = this.i ? u(this.i.Ue, this.i, this) : null;\n c = this.kc.jf(this.M, b, c);\n a.Gg(this.M.splice(0, b));\n return c;\n};\n\ne.sg = function (a) {\n this.M = a.la().concat(this.M);\n};\n\ne.Kd = function () {\n if (!this.u && !this.ia) {\n this.rc = 1;\n var a = this.ve;\n Bb || Cb();\n Eb || (Bb(), Eb = !0);\n Fb.add(a, this);\n this.Ha = 0;\n }\n};\n\ne.Qc = function () {\n if (this.u || this.ia) return this.a.ca(\"Request already in progress\"), !1;\n if (3 <= this.Ha) return !1;\n this.a.debug(\"Going to retry GET\");\n this.rc++;\n this.ia = P(u(this.ve, this), this.Xd(this.Ha));\n this.Ha++;\n return !0;\n};\n\ne.ve = function () {\n this.ia = null;\n this.Kg();\n};\n\ne.Kg = function () {\n this.a.debug(\"Creating new HttpRequest\");\n this.u = new R(this, this.a, this.ra, \"rpc\", this.rc);\n null === this.N && this.u.ga(this.A);\n this.u.He(this.Ra);\n var a = this.md.clone();\n a.l(\"RID\", \"rpc\");\n a.l(\"SID\", this.ra);\n a.l(\"CI\", this.fd ? \"0\" : \"1\");\n a.l(\"AID\", this.Sb);\n this.Ya(a);\n a.l(\"TYPE\", \"xmlhttp\");\n this.N && this.A && Zc(a, this.N, this.A);\n this.Db && this.u.setTimeout(this.Db);\n this.u.jd(a, !0, this.na);\n this.a.debug(\"New Request created\");\n};\n\ne.ub = function (a, b) {\n this.a.debug(\"Test Connection Finished\");\n var c = a.Ad;\n c && this.G.ld(c);\n this.fd = this.Se && b;\n this.w = a.w;\n this.af();\n};\n\ne.dd = function (a) {\n this.a.debug(\"Test Connection Failed\");\n this.w = a.w;\n this.sa(2);\n};\n\ne.ue = function (a, b) {\n if (0 != this.g && (this.u == a || this.G.Jc(a))) if (this.w = a.w, !a.lb && this.G.Jc(a) && 3 == this.g) {\n try {\n var c = this.kc.zc(b);\n } catch (d) {\n c = null;\n }\n\n n(c) && 3 == c.length ? this.Cf(c, a) : (this.a.debug(\"Bad POST response data returned\"), this.sa(11));\n } else (a.lb || this.u == a) && this.Hb(), va(b) || (c = this.kc.zc(b), this.dg(c, a));\n};\n\ne.Cf = function (a, b) {\n 0 == a[0] ? this.Bf(b) : (this.he = a[1], b = this.he - this.Sb, 0 < b && (a = a[2], this.a.debug(a + \" bytes (in \" + b + \" arrays) are outstanding on the BackChannel\"), this.Jg(a) && !this.wa && (this.wa = P(u(this.bg, this), 6E3))));\n};\n\ne.Bf = function (a) {\n this.a.debug(\"Server claims our backchannel is missing.\");\n if (this.ia) this.a.debug(\"But we are currently starting the request.\");else {\n if (this.u) {\n if (this.u.qb + 3E3 < a.qb) this.Hb(), this.u.cancel(), this.u = null;else return;\n } else this.a.T(\"We do not have a BackChannel established\");\n this.Qc();\n O(18);\n }\n};\n\ne.Jg = function (a) {\n return 37500 > a && !this.Nf() && 0 == this.Ha;\n};\n\ne.$a = function (a) {\n return this.Te ? this.i ? this.i.$a(a) : a : null;\n};\n\ne.bg = function () {\n null != this.wa && (this.wa = null, this.u.cancel(), this.u = null, this.Qc(), O(19));\n};\n\ne.Hb = function () {\n null != this.wa && (h.clearTimeout(this.wa), this.wa = null);\n};\n\ne.Tc = function (a) {\n this.a.debug(\"Request complete\");\n var b = null;\n\n if (this.u == a) {\n this.Hb();\n this.u = null;\n var c = 2;\n } else if (this.G.Jc(a)) b = a.la(), this.G.ze(a), c = 1;else return;\n\n this.w = a.w;\n if (0 != this.g) if (a.S) 1 == c ? (ac(a.Da ? a.Da.length : 0, w() - a.qb, this.La), this.Dc()) : this.Kd();else {\n var d = a.Hc();\n if (3 == d || 0 == d && 0 < this.w) this.a.debug(\"Not retrying due to error type\");else {\n var f = this;\n this.a.debug(function () {\n return \"Maybe retrying, last error: \" + kc(d, f.w);\n });\n if (1 == c && this.Yf(a) || 2 == c && this.Qc()) return;\n this.a.debug(\"Exceeded max number of retries\");\n }\n b && 0 < b.length && this.G.Re(b);\n this.a.debug(\"Error: HTTP request failed\");\n\n switch (d) {\n case 1:\n this.sa(5);\n break;\n\n case 4:\n this.sa(10);\n break;\n\n case 3:\n this.sa(6);\n break;\n\n default:\n this.sa(2);\n }\n }\n};\n\ne.Xd = function (a) {\n var b = this.Ve + Math.floor(Math.random() * this.vg);\n this.Ba() || (this.a.debug(\"Inactive channel\"), b *= 2);\n return b * a;\n};\n\ne.pc = function (a) {\n if (this.ta && (a = a.h)) {\n var b = a.kb(\"X-Client-Wire-Protocol\");\n b && this.G.ld(b);\n this.aa && ((a = a.kb(\"X-HTTP-Session-Id\")) ? (this.Fe(a), this.hb.l(this.aa, a)) : this.a.T(\"Missing X_HTTP_SESSION_ID in the handshake response\"));\n }\n};\n\ne.dg = function (a, b) {\n for (var c = this.i && this.i.sc ? [] : null, d = 0; d < a.length; d++) {\n var f = a[d];\n this.Sb = f[0];\n f = f[1];\n if (2 == this.g) {\n if (\"c\" == f[0]) {\n this.ra = f[1];\n this.na = this.$a(f[2]);\n var g = f[3];\n null != g && (this.tc = g, this.a.info(\"VER=\" + this.tc));\n g = f[4];\n null != g && (this.De = g, this.a.info(\"SVER=\" + this.De));\n f = f[5];\n null != f && \"number\" == typeof f && 0 < f && (this.Db = f *= 1.5, this.a.info(\"backChannelRequestTimeoutMs_=\" + f));\n this.pc(b);\n this.g = 3;\n this.i && this.i.wd();\n this.Lg(b);\n } else \"stop\" != f[0] && \"close\" != f[0] || this.sa(7);\n } else 3 == this.g && (\"stop\" == f[0] || \"close\" == f[0] ? (c && 0 != c.length && (this.i.sc(this, c), c.length = 0), \"stop\" == f[0] ? this.sa(7) : this.disconnect()) : \"noop\" != f[0] && (c ? c.push(f) : this.i && this.i.ud(f)), this.Ha = 0);\n }\n\n c && 0 != c.length && this.i.sc(this, c);\n};\n\ne.Lg = function (a) {\n this.md = this.Pd(this.na, this.K);\n a.lb ? (this.a.debug(\"Upgrade the handshake request to a backchannel.\"), this.G.ze(a), a.tg(this.Db), this.u = a) : this.Kd();\n};\n\ne.sa = function (a) {\n this.a.info(\"Error code \" + a);\n\n if (2 == a) {\n var b = null;\n this.i && (b = null);\n var c = u(this.Pg, this);\n b || (b = new U(\"//www.google.com/images/cleardot.gif\"), h.location && \"http\" == h.location.protocol || b.tb(\"https\"), b.Ub());\n Qc(b.toString(), c);\n } else O(2);\n\n this.cg(a);\n};\n\ne.Pg = function (a) {\n a ? (this.a.info(\"Successfully pinged google.com\"), O(2)) : (this.a.info(\"Failed to ping google.com\"), O(1));\n};\n\ne.cg = function (a) {\n this.a.debug(\"HttpChannel: error - \" + a);\n this.g = 0;\n this.i && this.i.td(a);\n this.qe();\n this.qd();\n};\n\ne.qe = function () {\n this.g = 0;\n this.w = -1;\n\n if (this.i) {\n var a = this.G.la();\n\n if (0 != a.length || 0 != this.M.length) {\n var b = this;\n this.a.debug(function () {\n return \"Number of undelivered maps, pending: \" + a.length + \", outgoing: \" + b.M.length;\n });\n this.G.$e();\n ua(this.M);\n this.M.length = 0;\n }\n\n this.i.sd();\n }\n};\n\ne.Sd = function (a) {\n a = this.Cd(null, a);\n this.a.debug(\"GetForwardChannelUri: \" + a);\n return a;\n};\n\ne.Pd = function (a, b) {\n a = this.Cd(this.fc() ? a : null, b);\n this.a.debug(\"GetBackChannelUri: \" + a);\n return a;\n};\n\ne.Cd = function (a, b) {\n var c = Ac(b);\n if (\"\" != c.xa) a && c.rb(a + \".\" + c.xa), c.sb(c.Ca);else {\n var d = h.location;\n c = Bc(d.protocol, a ? a + \".\" + d.hostname : d.hostname, +d.port, b);\n }\n this.gb && Aa(this.gb, function (a, b) {\n c.l(b, a);\n });\n a = this.aa;\n b = this.Kc;\n a && b && c.l(a, b);\n c.l(\"VER\", this.tc);\n this.Ya(c);\n return c;\n};\n\ne.Jb = function (a) {\n if (a && !this.gc) throw Error(\"Can't create secondary domain capable XhrIo object.\");\n a = new V(this.Xa);\n a.Je(this.gc);\n return a;\n};\n\ne.Ba = function () {\n return !!this.i && this.i.Ba();\n};\n\ne.fc = function () {\n return this.gc;\n};\n\nfunction ad() {}\n\ne = ad.prototype;\ne.sc = null;\n\ne.wd = function () {};\n\ne.ud = function () {};\n\ne.td = function () {};\n\ne.sd = function () {};\n\ne.Ba = function () {\n return !0;\n};\n\ne.Ue = function () {};\n\ne.$a = function (a) {\n return a;\n};\n\nfunction bd(a) {\n for (var b = arguments[0], c = 1; c < arguments.length; c++) {\n var d = arguments[c];\n if (0 == d.lastIndexOf(\"/\", 0)) b = d;else {\n var f;\n (f = \"\" == b) || (f = b.length - 1, f = 0 <= f && b.indexOf(\"/\", f) == f);\n b = f ? b + d : b + (\"/\" + d);\n }\n }\n\n return b;\n}\n\nfunction cd() {\n if (C && !(10 <= Number(Ua))) throw Error(\"Environmental error: no available transport.\");\n}\n\ncd.prototype.cf = function (a, b) {\n return new W(a, b);\n};\n\nfunction W(a, b) {\n H.call(this);\n this.b = new $c(b);\n this.yb = a;\n this.Qg = b && b.testUrl ? b.testUrl : bd(this.yb, \"test\");\n this.s = Vb(\"goog.labs.net.webChannel.WebChannelBaseTransport\");\n this.Rc = b && b.messageUrlParams || null;\n a = b && b.messageHeaders || null;\n b && b.clientProtocolHeaderRequired && (a ? a[\"X-Client-Protocol\"] = \"webchannel\" : a = {\n \"X-Client-Protocol\": \"webchannel\"\n });\n this.b.ga(a);\n a = b && b.initMessageHeaders || null;\n b && b.messageContentType && (a ? a[\"X-WebChannel-Content-Type\"] = b.messageContentType : a = {\n \"X-WebChannel-Content-Type\": b.messageContentType\n });\n b && b.zd && (a ? a[\"X-WebChannel-Client-Profile\"] = b.zd : a = {\n \"X-WebChannel-Client-Profile\": b.zd\n });\n this.b.Eg(a);\n (a = b && b.httpHeadersOverwriteParam) && !va(a) && this.b.Cg(a);\n this.Og = b && b.supportsCrossDomainXhr || !1;\n this.zg = b && b.sendRawJson || !1;\n (b = b && b.httpSessionIdParam) && !va(b) && (this.b.Dg(b), a = this.Rc, null !== a && b in a && (a = this.Rc, b in a && delete a[b], (a = this.s) && a.T(\"Ignore httpSessionIdParam also specified with messageUrlParams: \" + b, void 0)));\n this.vd = new X(this);\n}\n\nx(W, H);\ne = W.prototype;\n\ne.addEventListener = function (a, b, c, d) {\n W.L.addEventListener.call(this, a, b, c, d);\n};\n\ne.removeEventListener = function (a, b, c, d) {\n W.L.removeEventListener.call(this, a, b, c, d);\n};\n\ne.open = function () {\n this.b.Ee(this.vd);\n this.Og && this.b.Hg();\n this.b.connect(this.Qg, this.yb, this.Rc || void 0);\n};\n\ne.close = function () {\n this.b.disconnect();\n};\n\ne.send = function (a) {\n if (l(a)) {\n var b = {};\n b.__data__ = a;\n this.b.Zc(b);\n } else this.zg ? (b = {}, b.__data__ = ub(a), this.b.Zc(b)) : this.b.Zc(a);\n};\n\ne.F = function () {\n this.b.Ee(null);\n delete this.vd;\n this.b.disconnect();\n delete this.b;\n W.L.F.call(this);\n};\n\nfunction dd(a) {\n fc.call(this);\n var b = a.__sm__;\n\n if (b) {\n a: {\n for (var c in b) {\n a = c;\n break a;\n }\n\n a = void 0;\n }\n\n if (this.ne = a) a = this.ne, b = null !== b && a in b ? b[a] : void 0;\n this.data = b;\n } else this.data = a;\n}\n\nx(dd, fc);\n\nfunction ed(a) {\n gc.call(this);\n this.status = 1;\n this.errorCode = a;\n}\n\nx(ed, gc);\n\nfunction X(a) {\n this.b = a;\n}\n\nx(X, ad);\n\nX.prototype.wd = function () {\n Wb(this.b.s, \"WebChannel opened on \" + this.b.yb);\n this.b.dispatchEvent(\"a\");\n};\n\nX.prototype.ud = function (a) {\n this.b.dispatchEvent(new dd(a));\n};\n\nX.prototype.td = function (a) {\n Wb(this.b.s, \"WebChannel aborted on \" + this.b.yb + \" due to channel error: \" + a);\n this.b.dispatchEvent(new ed(a));\n};\n\nX.prototype.sd = function () {\n Wb(this.b.s, \"WebChannel closed on \" + this.b.yb);\n this.b.dispatchEvent(\"b\");\n};\n\nvar fd = v(function (a, b) {\n function c() {}\n\n c.prototype = a.prototype;\n var d = new c();\n a.apply(d, Array.prototype.slice.call(arguments, 1));\n return d;\n}, cd);\n\nfunction gd() {\n this.V = [];\n this.Z = [];\n}\n\ne = gd.prototype;\n\ne.Vf = function () {\n 0 == this.V.length && (this.V = this.Z, this.V.reverse(), this.Z = []);\n};\n\ne.enqueue = function (a) {\n this.Z.push(a);\n};\n\ne.ab = function () {\n this.Vf();\n return this.V.pop();\n};\n\ne.C = function () {\n return this.V.length + this.Z.length;\n};\n\ne.X = function () {\n return 0 == this.V.length && 0 == this.Z.length;\n};\n\ne.clear = function () {\n this.V = [];\n this.Z = [];\n};\n\ne.contains = function (a) {\n return 0 <= la(this.V, a) || 0 <= la(this.Z, a);\n};\n\ne.remove = function (a) {\n var b = this.V;\n var c = ma(b, a);\n 0 <= c ? (Array.prototype.splice.call(b, c, 1), b = !0) : b = !1;\n return b || sa(this.Z, a);\n};\n\ne.H = function () {\n for (var a = [], b = this.V.length - 1; 0 <= b; --b) {\n a.push(this.V[b]);\n }\n\n var c = this.Z.length;\n\n for (b = 0; b < c; ++b) {\n a.push(this.Z[b]);\n }\n\n return a;\n};\n\nfunction hd(a, b) {\n z.call(this);\n this.oe = a || 0;\n this.Wb = b || 10;\n if (this.oe > this.Wb) throw Error(id);\n this.fa = new gd();\n this.oa = new Jc();\n this.Ac = 0;\n this.Nc = null;\n this.Cb();\n}\n\nx(hd, z);\nvar id = \"[goog.structs.Pool] Min can not be greater than max\";\ne = hd.prototype;\n\ne.Mb = function () {\n var a = w();\n\n if (!(null != this.Nc && a - this.Nc < this.Ac)) {\n var b = this.qg();\n b && (this.Nc = a, this.oa.add(b));\n return b;\n }\n};\n\ne.og = function (a) {\n return this.oa.remove(a) ? (this.nc(a), !0) : !1;\n};\n\ne.qg = function () {\n for (var a; 0 < this.Td() && (a = this.fa.ab(), !this.Sc(a));) {\n this.Cb();\n }\n\n !a && this.C() < this.Wb && (a = this.xc());\n return a;\n};\n\ne.nc = function (a) {\n this.oa.remove(a);\n this.Sc(a) && this.C() < this.Wb ? this.fa.enqueue(a) : this.Bc(a);\n};\n\ne.Cb = function () {\n for (var a = this.fa; this.C() < this.oe;) {\n a.enqueue(this.xc());\n }\n\n for (; this.C() > this.Wb && 0 < this.Td();) {\n this.Bc(a.ab());\n }\n};\n\ne.xc = function () {\n return {};\n};\n\ne.Bc = function (a) {\n if (\"function\" == typeof a.bb) a.bb();else for (var b in a) {\n a[b] = null;\n }\n};\n\ne.Sc = function (a) {\n return \"function\" == typeof a.Ye ? a.Ye() : !0;\n};\n\ne.contains = function (a) {\n return this.fa.contains(a) || this.oa.contains(a);\n};\n\ne.C = function () {\n return this.fa.C() + this.oa.C();\n};\n\ne.rf = function () {\n return this.oa.C();\n};\n\ne.Td = function () {\n return this.fa.C();\n};\n\ne.X = function () {\n return this.fa.X() && this.oa.X();\n};\n\ne.F = function () {\n hd.L.F.call(this);\n if (0 < this.rf()) throw Error(\"[goog.structs.Pool] Objects not released\");\n delete this.oa;\n\n for (var a = this.fa; !a.X();) {\n this.Bc(a.ab());\n }\n\n delete this.fa;\n};\n\nfunction jd(a, b) {\n this.fe = a;\n this.gd = b;\n}\n\njd.prototype.getKey = function () {\n return this.fe;\n};\n\njd.prototype.clone = function () {\n return new jd(this.fe, this.gd);\n};\n\nfunction kd(a) {\n this.Y = [];\n a && this.Lf(a);\n}\n\ne = kd.prototype;\n\ne.ce = function (a, b) {\n var c = this.Y;\n c.push(new jd(a, b));\n this.$f(c.length - 1);\n};\n\ne.Lf = function (a) {\n if (a instanceof kd) {\n var b = a.W();\n a = a.H();\n\n if (0 >= this.C()) {\n for (var c = this.Y, d = 0; d < b.length; d++) {\n c.push(new jd(b[d], a[d]));\n }\n\n return;\n }\n } else b = Ca(a), a = Ba(a);\n\n for (d = 0; d < b.length; d++) {\n this.ce(b[d], a[d]);\n }\n};\n\ne.remove = function () {\n var a = this.Y,\n b = a.length,\n c = a[0];\n if (!(0 >= b)) return 1 == b ? ra(a) : (a[0] = a.pop(), this.Zf()), c.gd;\n};\n\ne.Zf = function () {\n for (var a = 0, b = this.Y, c = b.length, d = b[a]; a < c >> 1;) {\n var f = this.tf(a),\n g = this.zf(a);\n f = g < c && b[g].getKey() < b[f].getKey() ? g : f;\n if (b[f].getKey() > d.getKey()) break;\n b[a] = b[f];\n a = f;\n }\n\n b[a] = d;\n};\n\ne.$f = function (a) {\n for (var b = this.Y, c = b[a]; 0 < a;) {\n var d = this.wf(a);\n if (b[d].getKey() > c.getKey()) b[a] = b[d], a = d;else break;\n }\n\n b[a] = c;\n};\n\ne.tf = function (a) {\n return 2 * a + 1;\n};\n\ne.zf = function (a) {\n return 2 * a + 2;\n};\n\ne.wf = function (a) {\n return a - 1 >> 1;\n};\n\ne.H = function () {\n for (var a = this.Y, b = [], c = a.length, d = 0; d < c; d++) {\n b.push(a[d].gd);\n }\n\n return b;\n};\n\ne.W = function () {\n for (var a = this.Y, b = [], c = a.length, d = 0; d < c; d++) {\n b.push(a[d].getKey());\n }\n\n return b;\n};\n\ne.va = function (a) {\n return oa(this.Y, function (b) {\n return b.getKey() == a;\n });\n};\n\ne.clone = function () {\n return new kd(this);\n};\n\ne.C = function () {\n return this.Y.length;\n};\n\ne.X = function () {\n return 0 == this.Y.length;\n};\n\ne.clear = function () {\n ra(this.Y);\n};\n\nfunction ld() {\n kd.call(this);\n}\n\nx(ld, kd);\n\nld.prototype.enqueue = function (a, b) {\n this.ce(a, b);\n};\n\nld.prototype.ab = function () {\n return this.remove();\n};\n\nfunction Y(a, b) {\n this.Gd = void 0;\n this.cc = new ld();\n hd.call(this, a, b);\n}\n\nx(Y, hd);\ne = Y.prototype;\n\ne.Mb = function (a, b) {\n if (!a) return (a = Y.L.Mb.call(this)) && this.Ac && (this.Gd = h.setTimeout(u(this.Nb, this), this.Ac)), a;\n this.cc.enqueue(void 0 !== b ? b : 100, a);\n this.Nb();\n};\n\ne.Nb = function () {\n for (var a = this.cc; 0 < a.C();) {\n var b = this.Mb();\n if (b) a.ab().apply(this, [b]);else break;\n }\n};\n\ne.nc = function (a) {\n Y.L.nc.call(this, a);\n this.Nb();\n};\n\ne.Cb = function () {\n Y.L.Cb.call(this);\n this.Nb();\n};\n\ne.F = function () {\n Y.L.F.call(this);\n h.clearTimeout(this.Gd);\n this.cc.clear();\n this.cc = null;\n};\n\nfunction Z(a, b, c, d) {\n this.Jf = a;\n this.Ab = !!d;\n Y.call(this, b, c);\n}\n\nx(Z, Y);\n\nZ.prototype.xc = function () {\n var a = new V(),\n b = this.Jf;\n b && b.forEach(function (b, d) {\n a.headers.set(d, b);\n });\n this.Ab && a.Je(!0);\n return a;\n};\n\nZ.prototype.Sc = function (a) {\n return !a.Ka && !a.Ba();\n};\n\ncd.prototype.createWebChannel = cd.prototype.cf;\nW.prototype.send = W.prototype.send;\nW.prototype.open = W.prototype.open;\nW.prototype.close = W.prototype.close;\nbc.NO_ERROR = 0;\nbc.TIMEOUT = 8;\nbc.HTTP_ERROR = 6;\ncc.COMPLETE = \"complete\";\nec.EventType = Q;\nQ.OPEN = \"a\";\nQ.CLOSE = \"b\";\nQ.ERROR = \"c\";\nQ.MESSAGE = \"d\";\nH.prototype.listen = H.prototype.nb;\nZ.prototype.getObject = Z.prototype.Mb;\nZ.prototype.releaseObject = Z.prototype.og;\nV.prototype.listenOnce = V.prototype.Oc;\nV.prototype.getLastError = V.prototype.Hc;\nV.prototype.getLastErrorCode = V.prototype.Ud;\nV.prototype.getStatus = V.prototype.za;\nV.prototype.getStatusText = V.prototype.Yd;\nV.prototype.getResponseJson = V.prototype.yf;\nV.prototype.getResponseText = V.prototype.ya;\nV.prototype.getResponseText = V.prototype.ya;\nV.prototype.send = V.prototype.send;\nvar src = {\n createWebChannelTransport: fd,\n ErrorCode: bc,\n EventType: cc,\n WebChannel: ec,\n XhrIoPool: Z\n};\nvar src_1 = src.createWebChannelTransport;\nvar src_2 = src.ErrorCode;\nvar src_3 = src.EventType;\nvar src_4 = src.WebChannel;\nvar src_5 = src.XhrIoPool;\nexport default src;\nexport { src_1 as createWebChannelTransport, src_2 as ErrorCode, src_3 as EventType, src_4 as WebChannel, src_5 as XhrIoPool };","'use strict';\n\nObject.defineProperty(exports, '__esModule', {\n value: true\n});\n\nfunction _interopDefault(ex) {\n return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex;\n}\n\nvar tslib_1 = require('tslib');\n\nvar firebase = _interopDefault(require('@firebase/app'));\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Standard error codes for different ways a request can fail, as defined by:\r\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n *\r\n * This map is used primarily to convert from a backend error code string to\r\n * a client SDK error code string, and make sure it's in the supported set.\r\n */\n\n\nvar errorCodeMap = {\n OK: 'ok',\n CANCELLED: 'cancelled',\n UNKNOWN: 'unknown',\n INVALID_ARGUMENT: 'invalid-argument',\n DEADLINE_EXCEEDED: 'deadline-exceeded',\n NOT_FOUND: 'not-found',\n ALREADY_EXISTS: 'already-exists',\n PERMISSION_DENIED: 'permission-denied',\n UNAUTHENTICATED: 'unauthenticated',\n RESOURCE_EXHAUSTED: 'resource-exhausted',\n FAILED_PRECONDITION: 'failed-precondition',\n ABORTED: 'aborted',\n OUT_OF_RANGE: 'out-of-range',\n UNIMPLEMENTED: 'unimplemented',\n INTERNAL: 'internal',\n UNAVAILABLE: 'unavailable',\n DATA_LOSS: 'data-loss'\n};\n/**\r\n * An explicit error that can be thrown from a handler to send an error to the\r\n * client that called the function.\r\n */\n\nvar HttpsErrorImpl =\n/** @class */\nfunction (_super) {\n tslib_1.__extends(HttpsErrorImpl, _super);\n\n function HttpsErrorImpl(code, message, details) {\n var _this = _super.call(this, message) || this; // This is a workaround for a bug in TypeScript when extending Error:\n // tslint:disable-next-line\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\n\n Object.setPrototypeOf(_this, HttpsErrorImpl.prototype);\n _this.code = code;\n _this.details = details;\n return _this;\n }\n\n return HttpsErrorImpl;\n}(Error);\n/**\r\n * Takes an HTTP status code and returns the corresponding ErrorCode.\r\n * This is the standard HTTP status code -> error mapping defined in:\r\n * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto\r\n *\r\n * @param status An HTTP status code.\r\n * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.\r\n */\n\n\nfunction codeForHTTPStatus(status) {\n // Make sure any successful status is OK.\n if (status >= 200 && status < 300) {\n return 'ok';\n }\n\n switch (status) {\n case 0:\n // This can happen if the server returns 500.\n return 'internal';\n\n case 400:\n return 'invalid-argument';\n\n case 401:\n return 'unauthenticated';\n\n case 403:\n return 'permission-denied';\n\n case 404:\n return 'not-found';\n\n case 409:\n return 'aborted';\n\n case 429:\n return 'resource-exhausted';\n\n case 499:\n return 'cancelled';\n\n case 500:\n return 'internal';\n\n case 501:\n return 'unimplemented';\n\n case 503:\n return 'unavailable';\n\n case 504:\n return 'deadline-exceeded';\n }\n\n return 'unknown';\n}\n/**\r\n * Takes an HTTP response and returns the corresponding Error, if any.\r\n */\n\n\nfunction _errorForResponse(status, bodyJSON, serializer) {\n var code = codeForHTTPStatus(status); // Start with reasonable defaults from the status code.\n\n var description = code;\n var details = undefined; // Then look through the body for explicit details.\n\n try {\n var errorJSON = bodyJSON.error;\n\n if (errorJSON) {\n var status_1 = errorJSON.status;\n\n if (typeof status_1 === 'string') {\n if (!errorCodeMap[status_1]) {\n // They must've included an unknown error code in the body.\n return new HttpsErrorImpl('internal', 'internal');\n }\n\n code = errorCodeMap[status_1];\n } // TODO(klimt): Add better default descriptions for error enums.\n // The default description needs to be updated for the new code.\n\n\n description = status_1;\n var message = errorJSON.message;\n\n if (typeof message === 'string') {\n description = message;\n }\n\n details = errorJSON.details;\n\n if (details !== undefined) {\n details = serializer.decode(details);\n }\n }\n } catch (e) {// If we couldn't parse explicit error data, that's fine.\n }\n\n if (code === 'ok') {\n // Technically, there's an edge case where a developer could explicitly\n // return an error code of OK, and we will treat it as success, but that\n // seems reasonable.\n return null;\n }\n\n return new HttpsErrorImpl(code, description, details);\n}\n/**\r\n * Helper class to get metadata that should be included with a function call.\r\n */\n\n\nvar ContextProvider =\n/** @class */\nfunction () {\n function ContextProvider(app) {\n this.app = app;\n }\n\n ContextProvider.prototype.getAuthToken = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var token, e_1;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2,, 3]);\n\n return [4\n /*yield*/\n , this.app.INTERNAL.getToken()];\n\n case 1:\n token = _a.sent();\n\n if (!token) {\n return [2\n /*return*/\n , undefined];\n }\n\n return [2\n /*return*/\n , token.accessToken];\n\n case 2:\n e_1 = _a.sent(); // If there's any error when trying to get the auth token, leave it off.\n\n return [2\n /*return*/\n , undefined];\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n ContextProvider.prototype.getInstanceIdToken = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var messaging, token, e_2;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2,, 3]); // HACK: Until we have a separate instanceId package, this is a quick way\n // to load in the messaging instance for this app.\n\n\n if (!this.app.messaging) {\n return [2\n /*return*/\n , undefined];\n }\n\n messaging = this.app.messaging();\n return [4\n /*yield*/\n , messaging.getToken()];\n\n case 1:\n token = _a.sent();\n\n if (!token) {\n return [2\n /*return*/\n , undefined];\n }\n\n return [2\n /*return*/\n , token];\n\n case 2:\n e_2 = _a.sent(); // We don't warn on this, because it usually means messaging isn't set up.\n // console.warn('Failed to retrieve instance id token.', e);\n // If there's any error when trying to get the token, leave it off.\n\n return [2\n /*return*/\n , undefined];\n\n case 3:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n ContextProvider.prototype.getContext = function () {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var authToken, instanceIdToken;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , this.getAuthToken()];\n\n case 1:\n authToken = _a.sent();\n return [4\n /*yield*/\n , this.getInstanceIdToken()];\n\n case 2:\n instanceIdToken = _a.sent();\n return [2\n /*return*/\n , {\n authToken: authToken,\n instanceIdToken: instanceIdToken\n }];\n }\n });\n });\n };\n\n return ContextProvider;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';\nvar UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';\n\nfunction mapValues(o, f) {\n var result = {};\n\n for (var key in o) {\n if (o.hasOwnProperty(key)) {\n result[key] = f(o[key]);\n }\n }\n\n return result;\n}\n\nvar Serializer =\n/** @class */\nfunction () {\n function Serializer() {} // Takes data and encodes it in a JSON-friendly way, such that types such as\n // Date are preserved.\n\n\n Serializer.prototype.encode = function (data) {\n var _this = this;\n\n if (data === null || data === undefined) {\n return null;\n }\n\n if (data instanceof Number) {\n data = data.valueOf();\n }\n\n if (typeof data === 'number' && isFinite(data)) {\n // Any number in JS is safe to put directly in JSON and parse as a double\n // without any loss of precision.\n return data;\n }\n\n if (data === true || data === false) {\n return data;\n }\n\n if (Object.prototype.toString.call(data) === '[object String]') {\n return data;\n }\n\n if (Array.isArray(data)) {\n return data.map(function (x) {\n return _this.encode(x);\n });\n }\n\n if (typeof data === 'function' || typeof data === 'object') {\n return mapValues(data, function (x) {\n return _this.encode(x);\n });\n } // If we got this far, the data is not encodable.\n\n\n throw new Error('Data cannot be encoded in JSON: ' + data);\n }; // Takes data that's been encoded in a JSON-friendly form and returns a form\n // with richer datatypes, such as Dates, etc.\n\n\n Serializer.prototype.decode = function (json) {\n var _this = this;\n\n if (json === null) {\n return json;\n }\n\n if (json['@type']) {\n switch (json['@type']) {\n case LONG_TYPE: // Fall through and handle this the same as unsigned.\n\n case UNSIGNED_LONG_TYPE:\n {\n // Technically, this could work return a valid number for malformed\n // data if there was a number followed by garbage. But it's just not\n // worth all the extra code to detect that case.\n var value = parseFloat(json.value);\n\n if (isNaN(value)) {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n\n return value;\n }\n\n default:\n {\n throw new Error('Data cannot be decoded from JSON: ' + json);\n }\n }\n }\n\n if (Array.isArray(json)) {\n return json.map(function (x) {\n return _this.decode(x);\n });\n }\n\n if (typeof json === 'function' || typeof json === 'object') {\n return mapValues(json, function (x) {\n return _this.decode(x);\n });\n } // Anything else is safe to return.\n\n\n return json;\n };\n\n return Serializer;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * The main class for the Firebase Functions SDK.\r\n */\n\n\nvar Service =\n/** @class */\nfunction () {\n /**\r\n * Creates a new Functions service for the given app and (optional) region.\r\n * @param app_ The FirebaseApp to use.\r\n * @param region_ The region to call functions in.\r\n */\n function Service(app_, region_) {\n if (region_ === void 0) {\n region_ = 'us-central1';\n }\n\n this.app_ = app_;\n this.region_ = region_;\n this.serializer = new Serializer();\n this.emulatorOrigin = null;\n this.contextProvider = new ContextProvider(app_);\n }\n\n Object.defineProperty(Service.prototype, \"app\", {\n get: function get() {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Returns the URL for a callable with the given name.\r\n * @param name The name of the callable.\r\n */\n\n Service.prototype._url = function (name) {\n var projectId = this.app_.options.projectId;\n var region = this.region_;\n\n if (this.emulatorOrigin !== null) {\n var origin = this.emulatorOrigin;\n return origin + \"/\" + projectId + \"/\" + region + \"/\" + name;\n }\n\n return \"https://\" + region + \"-\" + projectId + \".cloudfunctions.net/\" + name;\n };\n /**\r\n * Changes this instance to point to a Cloud Functions emulator running\r\n * locally. See https://firebase.google.com/docs/functions/local-emulator\r\n *\r\n * @param origin The origin of the local emulator, such as\r\n * \"http://localhost:5005\".\r\n */\n\n\n Service.prototype.useFunctionsEmulator = function (origin) {\n this.emulatorOrigin = origin;\n };\n /**\r\n * Returns a reference to the callable https trigger with the given name.\r\n * @param name The name of the trigger.\r\n */\n\n\n Service.prototype.httpsCallable = function (name) {\n var _this = this;\n\n var callable = function callable(data) {\n return _this.call(name, data);\n };\n\n return callable;\n };\n /**\r\n * Does an HTTP POST and returns the completed response.\r\n * @param url The url to post to.\r\n * @param body The JSON body of the post.\r\n * @param headers The HTTP headers to include in the request.\r\n * @return A Promise that will succeed when the request finishes.\r\n */\n\n\n Service.prototype.postJSON = function (url, body, headers) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var response, e_1, json, e_2;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n headers.append('Content-Type', 'application/json');\n _a.label = 1;\n\n case 1:\n _a.trys.push([1, 3,, 4]);\n\n return [4\n /*yield*/\n , fetch(url, {\n method: 'POST',\n body: JSON.stringify(body),\n headers: headers\n })];\n\n case 2:\n response = _a.sent();\n return [3\n /*break*/\n , 4];\n\n case 3:\n e_1 = _a.sent(); // This could be an unhandled error on the backend, or it could be a\n // network error. There's no way to no, since an unhandled error on the\n // backend will fail to set the proper CORS header, and thus will be\n // treated as a network error by fetch.\n\n return [2\n /*return*/\n , {\n status: 0,\n json: null\n }];\n\n case 4:\n json = null;\n _a.label = 5;\n\n case 5:\n _a.trys.push([5, 7,, 8]);\n\n return [4\n /*yield*/\n , response.json()];\n\n case 6:\n json = _a.sent();\n return [3\n /*break*/\n , 8];\n\n case 7:\n e_2 = _a.sent();\n return [3\n /*break*/\n , 8];\n\n case 8:\n return [2\n /*return*/\n , {\n status: response.status,\n json: json\n }];\n }\n });\n });\n };\n /**\r\n * Calls a callable function asynchronously and returns the result.\r\n * @param name The name of the callable trigger.\r\n * @param data The data to pass as params to the function.s\r\n */\n\n\n Service.prototype.call = function (name, data) {\n return tslib_1.__awaiter(this, void 0, void 0, function () {\n var url, body, headers, context, response, error, responseData, decodedData;\n return tslib_1.__generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n url = this._url(name); // Encode any special types, such as dates, in the input data.\n\n data = this.serializer.encode(data);\n body = {\n data: data\n };\n headers = new Headers();\n return [4\n /*yield*/\n , this.contextProvider.getContext()];\n\n case 1:\n context = _a.sent();\n\n if (context.authToken) {\n headers.append('Authorization', 'Bearer ' + context.authToken);\n }\n\n if (context.instanceIdToken) {\n headers.append('Firebase-Instance-ID-Token', context.instanceIdToken);\n }\n\n return [4\n /*yield*/\n , this.postJSON(url, body, headers)];\n\n case 2:\n response = _a.sent();\n error = _errorForResponse(response.status, response.json, this.serializer);\n\n if (error) {\n throw error;\n }\n\n if (!response.json) {\n throw new HttpsErrorImpl('internal', 'Response is not valid JSON object.');\n }\n\n responseData = response.json.data; // TODO(klimt): For right now, allow \"result\" instead of \"data\", for\n // backwards compatibility.\n\n if (typeof responseData === 'undefined') {\n responseData = response.json.result;\n }\n\n if (typeof responseData === 'undefined') {\n // Consider the response malformed.\n throw new HttpsErrorImpl('internal', 'Response is missing data field.');\n }\n\n decodedData = this.serializer.decode(responseData);\n return [2\n /*return*/\n , {\n data: decodedData\n }];\n }\n });\n });\n };\n\n return Service;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Type constant for Firebase Functions.\r\n */\n\n\nvar FUNCTIONS_TYPE = 'functions';\n\nfunction factory(app, unused, region) {\n return new Service(app, region);\n}\n\nfunction registerFunctions(instance) {\n var namespaceExports = {\n // no-inline\n Functions: Service\n };\n instance.INTERNAL.registerService(FUNCTIONS_TYPE, factory, namespaceExports, // We don't need to wait on any AppHooks.\n undefined, // Allow multiple functions instances per app.\n true);\n}\n\nregisterFunctions(firebase);\nexports.registerFunctions = registerFunctions;","import { ErrorFactory, createSubscribe } from '@firebase/util';\nimport { __extends, __awaiter, __generator, __assign } from 'tslib';\nimport firebase from '@firebase/app';\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar ERROR_CODES = {\n AVAILABLE_IN_WINDOW: 'only-available-in-window',\n AVAILABLE_IN_SW: 'only-available-in-sw',\n SHOULD_BE_INHERITED: 'should-be-overriden',\n BAD_SENDER_ID: 'bad-sender-id',\n INCORRECT_GCM_SENDER_ID: 'incorrect-gcm-sender-id',\n PERMISSION_DEFAULT: 'permission-default',\n PERMISSION_BLOCKED: 'permission-blocked',\n UNSUPPORTED_BROWSER: 'unsupported-browser',\n NOTIFICATIONS_BLOCKED: 'notifications-blocked',\n FAILED_DEFAULT_REGISTRATION: 'failed-serviceworker-registration',\n SW_REGISTRATION_EXPECTED: 'sw-registration-expected',\n GET_SUBSCRIPTION_FAILED: 'get-subscription-failed',\n INVALID_SAVED_TOKEN: 'invalid-saved-token',\n SW_REG_REDUNDANT: 'sw-reg-redundant',\n TOKEN_SUBSCRIBE_FAILED: 'token-subscribe-failed',\n TOKEN_SUBSCRIBE_NO_TOKEN: 'token-subscribe-no-token',\n TOKEN_SUBSCRIBE_NO_PUSH_SET: 'token-subscribe-no-push-set',\n TOKEN_UNSUBSCRIBE_FAILED: 'token-unsubscribe-failed',\n TOKEN_UPDATE_FAILED: 'token-update-failed',\n TOKEN_UPDATE_NO_TOKEN: 'token-update-no-token',\n USE_SW_BEFORE_GET_TOKEN: 'use-sw-before-get-token',\n INVALID_DELETE_TOKEN: 'invalid-delete-token',\n DELETE_TOKEN_NOT_FOUND: 'delete-token-not-found',\n DELETE_SCOPE_NOT_FOUND: 'delete-scope-not-found',\n BG_HANDLER_FUNCTION_EXPECTED: 'bg-handler-function-expected',\n NO_WINDOW_CLIENT_TO_MSG: 'no-window-client-to-msg',\n UNABLE_TO_RESUBSCRIBE: 'unable-to-resubscribe',\n NO_FCM_TOKEN_FOR_RESUBSCRIBE: 'no-fcm-token-for-resubscribe',\n FAILED_TO_DELETE_TOKEN: 'failed-to-delete-token',\n NO_SW_IN_REG: 'no-sw-in-reg',\n BAD_SCOPE: 'bad-scope',\n BAD_VAPID_KEY: 'bad-vapid-key',\n BAD_SUBSCRIPTION: 'bad-subscription',\n BAD_TOKEN: 'bad-token',\n BAD_PUSH_SET: 'bad-push-set',\n FAILED_DELETE_VAPID_KEY: 'failed-delete-vapid-key',\n INVALID_PUBLIC_VAPID_KEY: 'invalid-public-vapid-key',\n USE_PUBLIC_KEY_BEFORE_GET_TOKEN: 'use-public-key-before-get-token',\n PUBLIC_KEY_DECRYPTION_FAILED: 'public-vapid-key-decryption-failed'\n};\nvar ERROR_MAP = (_a = {}, _a[ERROR_CODES.AVAILABLE_IN_WINDOW] = 'This method is available in a Window context.', _a[ERROR_CODES.AVAILABLE_IN_SW] = 'This method is available in a service worker ' + 'context.', _a[ERROR_CODES.SHOULD_BE_INHERITED] = 'This method should be overriden by ' + 'extended classes.', _a[ERROR_CODES.BAD_SENDER_ID] = \"Please ensure that 'messagingSenderId' is set \" + 'correctly in the options passed into firebase.initializeApp().', _a[ERROR_CODES.PERMISSION_DEFAULT] = 'The required permissions were not granted and ' + 'dismissed instead.', _a[ERROR_CODES.PERMISSION_BLOCKED] = 'The required permissions were not granted and ' + 'blocked instead.', _a[ERROR_CODES.UNSUPPORTED_BROWSER] = \"This browser doesn't support the API's \" + 'required to use the firebase SDK.', _a[ERROR_CODES.NOTIFICATIONS_BLOCKED] = 'Notifications have been blocked.', _a[ERROR_CODES.FAILED_DEFAULT_REGISTRATION] = 'We are unable to register the ' + 'default service worker. {$browserErrorMessage}', _a[ERROR_CODES.SW_REGISTRATION_EXPECTED] = 'A service worker registration was the ' + 'expected input.', _a[ERROR_CODES.GET_SUBSCRIPTION_FAILED] = 'There was an error when trying to get ' + 'any existing Push Subscriptions.', _a[ERROR_CODES.INVALID_SAVED_TOKEN] = 'Unable to access details of the saved token.', _a[ERROR_CODES.SW_REG_REDUNDANT] = 'The service worker being used for push was made ' + 'redundant.', _a[ERROR_CODES.TOKEN_SUBSCRIBE_FAILED] = 'A problem occured while subscribing the ' + 'user to FCM: {$message}', _a[ERROR_CODES.TOKEN_SUBSCRIBE_NO_TOKEN] = 'FCM returned no token when subscribing ' + 'the user to push.', _a[ERROR_CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET] = 'FCM returned an invalid response ' + 'when getting an FCM token.', _a[ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED] = 'A problem occured while unsubscribing the ' + 'user from FCM: {$message}', _a[ERROR_CODES.TOKEN_UPDATE_FAILED] = 'A problem occured while updating the ' + 'user from FCM: {$message}', _a[ERROR_CODES.TOKEN_UPDATE_NO_TOKEN] = 'FCM returned no token when updating ' + 'the user to push.', _a[ERROR_CODES.USE_SW_BEFORE_GET_TOKEN] = 'The useServiceWorker() method may only be called once and must be ' + 'called before calling getToken() to ensure your service worker is used.', _a[ERROR_CODES.INVALID_DELETE_TOKEN] = 'You must pass a valid token into ' + 'deleteToken(), i.e. the token from getToken().', _a[ERROR_CODES.DELETE_TOKEN_NOT_FOUND] = 'The deletion attempt for token could not ' + 'be performed as the token was not found.', _a[ERROR_CODES.DELETE_SCOPE_NOT_FOUND] = 'The deletion attempt for service worker ' + 'scope could not be performed as the scope was not found.', _a[ERROR_CODES.BG_HANDLER_FUNCTION_EXPECTED] = 'The input to ' + 'setBackgroundMessageHandler() must be a function.', _a[ERROR_CODES.NO_WINDOW_CLIENT_TO_MSG] = 'An attempt was made to message a ' + 'non-existant window client.', _a[ERROR_CODES.UNABLE_TO_RESUBSCRIBE] = 'There was an error while re-subscribing ' + 'the FCM token for push messaging. Will have to resubscribe the ' + 'user on next visit. {$message}', _a[ERROR_CODES.NO_FCM_TOKEN_FOR_RESUBSCRIBE] = 'Could not find an FCM token ' + 'and as a result, unable to resubscribe. Will have to resubscribe the ' + 'user on next visit.', _a[ERROR_CODES.FAILED_TO_DELETE_TOKEN] = 'Unable to delete the currently saved token.', _a[ERROR_CODES.NO_SW_IN_REG] = 'Even though the service worker registration was ' + 'successful, there was a problem accessing the service worker itself.', _a[ERROR_CODES.INCORRECT_GCM_SENDER_ID] = \"Please change your web app manifest's \" + \"'gcm_sender_id' value to '103953800507' to use Firebase messaging.\", _a[ERROR_CODES.BAD_SCOPE] = 'The service worker scope must be a string with at ' + 'least one character.', _a[ERROR_CODES.BAD_VAPID_KEY] = 'The public VAPID key is not a Uint8Array with 65 bytes.', _a[ERROR_CODES.BAD_SUBSCRIPTION] = 'The subscription must be a valid ' + 'PushSubscription.', _a[ERROR_CODES.BAD_TOKEN] = 'The FCM Token used for storage / lookup was not ' + 'a valid token string.', _a[ERROR_CODES.BAD_PUSH_SET] = 'The FCM push set used for storage / lookup was not ' + 'not a valid push set string.', _a[ERROR_CODES.FAILED_DELETE_VAPID_KEY] = 'The VAPID key could not be deleted.', _a[ERROR_CODES.INVALID_PUBLIC_VAPID_KEY] = 'The public VAPID key must be a string.', _a[ERROR_CODES.PUBLIC_KEY_DECRYPTION_FAILED] = 'The public VAPID key did not equal ' + '65 bytes when decrypted.', _a);\nvar errorFactory = new ErrorFactory('messaging', 'Messaging', ERROR_MAP);\n\nvar _a;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar DEFAULT_PUBLIC_VAPID_KEY = new Uint8Array([0x04, 0x33, 0x94, 0xf7, 0xdf, 0xa1, 0xeb, 0xb1, 0xdc, 0x03, 0xa2, 0x5e, 0x15, 0x71, 0xdb, 0x48, 0xd3, 0x2e, 0xed, 0xed, 0xb2, 0x34, 0xdb, 0xb7, 0x47, 0x3a, 0x0c, 0x8f, 0xc4, 0xcc, 0xe1, 0x6f, 0x3c, 0x8c, 0x84, 0xdf, 0xab, 0xb6, 0x66, 0x3e, 0xf2, 0x0c, 0xd4, 0x8b, 0xfe, 0xe3, 0xf9, 0x76, 0x2f, 0x14, 0x1c, 0x63, 0x08, 0x6a, 0x6f, 0x2d, 0xb1, 0x1a, 0x95, 0xb0, 0xce, 0x37, 0xc0, 0x9c, 0x6e]);\nvar ENDPOINT = 'https://fcm.googleapis.com';\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar MessageParameter;\n\n(function (MessageParameter) {\n MessageParameter[\"TYPE_OF_MSG\"] = \"firebase-messaging-msg-type\";\n MessageParameter[\"DATA\"] = \"firebase-messaging-msg-data\";\n})(MessageParameter || (MessageParameter = {}));\n\nvar MessageType;\n\n(function (MessageType) {\n MessageType[\"PUSH_MSG_RECEIVED\"] = \"push-msg-received\";\n MessageType[\"NOTIFICATION_CLICKED\"] = \"notification-clicked\";\n})(MessageType || (MessageType = {}));\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction isArrayBufferEqual(a, b) {\n if (a == null || b == null) {\n return false;\n }\n\n if (a === b) {\n return true;\n }\n\n if (a.byteLength !== b.byteLength) {\n return false;\n }\n\n var viewA = new DataView(a);\n var viewB = new DataView(b);\n\n for (var i = 0; i < a.byteLength; i++) {\n if (viewA.getUint8(i) !== viewB.getUint8(i)) {\n return false;\n }\n }\n\n return true;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction toBase64(arrayBuffer) {\n var uint8Version = new Uint8Array(arrayBuffer);\n return btoa(String.fromCharCode.apply(null, uint8Version));\n}\n\nfunction arrayBufferToBase64(arrayBuffer) {\n var base64String = toBase64(arrayBuffer);\n return base64String.replace(/=/g, '').replace(/\\+/g, '-').replace(/\\//g, '_');\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar IidModel =\n/** @class */\nfunction () {\n function IidModel() {}\n\n IidModel.prototype.getToken = function (senderId, subscription, publicVapidKey) {\n return __awaiter(this, void 0, void 0, function () {\n var p256dh, auth, fcmSubscribeBody, applicationPubKey, headers, subscribeOptions, responseData, response, err_1, message;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n p256dh = arrayBufferToBase64(subscription.getKey('p256dh'));\n auth = arrayBufferToBase64(subscription.getKey('auth'));\n fcmSubscribeBody = \"authorized_entity=\" + senderId + \"&\" + (\"endpoint=\" + subscription.endpoint + \"&\") + (\"encryption_key=\" + p256dh + \"&\") + (\"encryption_auth=\" + auth);\n\n if (!isArrayBufferEqual(publicVapidKey.buffer, DEFAULT_PUBLIC_VAPID_KEY.buffer)) {\n applicationPubKey = arrayBufferToBase64(publicVapidKey);\n fcmSubscribeBody += \"&application_pub_key=\" + applicationPubKey;\n }\n\n headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n subscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmSubscribeBody\n };\n _a.label = 1;\n\n case 1:\n _a.trys.push([1, 4,, 5]);\n\n return [4\n /*yield*/\n , fetch(ENDPOINT + '/fcm/connect/subscribe', subscribeOptions)];\n\n case 2:\n response = _a.sent();\n return [4\n /*yield*/\n , response.json()];\n\n case 3:\n responseData = _a.sent();\n return [3\n /*break*/\n , 5];\n\n case 4:\n err_1 = _a.sent();\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_FAILED);\n\n case 5:\n if (responseData.error) {\n message = responseData.error.message;\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_FAILED, {\n message: message\n });\n }\n\n if (!responseData.token) {\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_NO_TOKEN);\n }\n\n if (!responseData.pushSet) {\n throw errorFactory.create(ERROR_CODES.TOKEN_SUBSCRIBE_NO_PUSH_SET);\n }\n\n return [2\n /*return*/\n , {\n token: responseData.token,\n pushSet: responseData.pushSet\n }];\n }\n });\n });\n };\n /**\r\n * Update the underlying token details for fcmToken.\r\n */\n\n\n IidModel.prototype.updateToken = function (senderId, fcmToken, fcmPushSet, subscription, publicVapidKey) {\n return __awaiter(this, void 0, void 0, function () {\n var p256dh, auth, fcmUpdateBody, applicationPubKey, headers, updateOptions, responseData, response, err_2, message;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n p256dh = arrayBufferToBase64(subscription.getKey('p256dh'));\n auth = arrayBufferToBase64(subscription.getKey('auth'));\n fcmUpdateBody = \"push_set=\" + fcmPushSet + \"&\" + (\"token=\" + fcmToken + \"&\") + (\"authorized_entity=\" + senderId + \"&\") + (\"endpoint=\" + subscription.endpoint + \"&\") + (\"encryption_key=\" + p256dh + \"&\") + (\"encryption_auth=\" + auth);\n\n if (!isArrayBufferEqual(publicVapidKey.buffer, DEFAULT_PUBLIC_VAPID_KEY.buffer)) {\n applicationPubKey = arrayBufferToBase64(publicVapidKey);\n fcmUpdateBody += \"&application_pub_key=\" + applicationPubKey;\n }\n\n headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n updateOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUpdateBody\n };\n _a.label = 1;\n\n case 1:\n _a.trys.push([1, 4,, 5]);\n\n return [4\n /*yield*/\n , fetch(ENDPOINT + '/fcm/connect/subscribe', updateOptions)];\n\n case 2:\n response = _a.sent();\n return [4\n /*yield*/\n , response.json()];\n\n case 3:\n responseData = _a.sent();\n return [3\n /*break*/\n , 5];\n\n case 4:\n err_2 = _a.sent();\n throw errorFactory.create(ERROR_CODES.TOKEN_UPDATE_FAILED);\n\n case 5:\n if (responseData.error) {\n message = responseData.error.message;\n throw errorFactory.create(ERROR_CODES.TOKEN_UPDATE_FAILED, {\n message: message\n });\n }\n\n if (!responseData.token) {\n throw errorFactory.create(ERROR_CODES.TOKEN_UPDATE_NO_TOKEN);\n }\n\n return [2\n /*return*/\n , responseData.token];\n }\n });\n });\n };\n /**\r\n * Given a fcmToken, pushSet and messagingSenderId, delete an FCM token.\r\n */\n\n\n IidModel.prototype.deleteToken = function (senderId, fcmToken, fcmPushSet) {\n return __awaiter(this, void 0, void 0, function () {\n var fcmUnsubscribeBody, headers, unsubscribeOptions, response, responseData, message, err_3;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n fcmUnsubscribeBody = \"authorized_entity=\" + senderId + \"&\" + (\"token=\" + fcmToken + \"&\") + (\"pushSet=\" + fcmPushSet);\n headers = new Headers();\n headers.append('Content-Type', 'application/x-www-form-urlencoded');\n unsubscribeOptions = {\n method: 'POST',\n headers: headers,\n body: fcmUnsubscribeBody\n };\n _a.label = 1;\n\n case 1:\n _a.trys.push([1, 4,, 5]);\n\n return [4\n /*yield*/\n , fetch(ENDPOINT + '/fcm/connect/unsubscribe', unsubscribeOptions)];\n\n case 2:\n response = _a.sent();\n return [4\n /*yield*/\n , response.json()];\n\n case 3:\n responseData = _a.sent();\n\n if (responseData.error) {\n message = responseData.error.message;\n throw errorFactory.create(ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED, {\n message: message\n });\n }\n\n return [3\n /*break*/\n , 5];\n\n case 4:\n err_3 = _a.sent();\n throw errorFactory.create(ERROR_CODES.TOKEN_UNSUBSCRIBE_FAILED);\n\n case 5:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n return IidModel;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction base64ToArrayBuffer(base64String) {\n var padding = '='.repeat((4 - base64String.length % 4) % 4);\n var base64 = (base64String + padding).replace(/\\-/g, '+').replace(/_/g, '/');\n var rawData = atob(base64);\n var outputArray = new Uint8Array(rawData.length);\n\n for (var i = 0; i < rawData.length; ++i) {\n outputArray[i] = rawData.charCodeAt(i);\n }\n\n return outputArray;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar OLD_DB_NAME = 'undefined';\nvar OLD_OBJECT_STORE_NAME = 'fcm_token_object_Store';\n\nfunction handleDb(db) {\n if (!db.objectStoreNames.contains(OLD_OBJECT_STORE_NAME)) {\n // We found a database with the name 'undefined', but our expected object\n // store isn't defined.\n return;\n }\n\n var transaction = db.transaction(OLD_OBJECT_STORE_NAME);\n var objectStore = transaction.objectStore(OLD_OBJECT_STORE_NAME);\n var iidModel = new IidModel();\n var openCursorRequest = objectStore.openCursor();\n\n openCursorRequest.onerror = function (event) {\n // NOOP - Nothing we can do.\n console.warn('Unable to cleanup old IDB.', event);\n };\n\n openCursorRequest.onsuccess = function () {\n var cursor = openCursorRequest.result;\n\n if (cursor) {\n // cursor.value contains the current record being iterated through\n // this is where you'd do something with the result\n var tokenDetails = cursor.value;\n iidModel.deleteToken(tokenDetails.fcmSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet);\n cursor.continue();\n } else {\n db.close();\n indexedDB.deleteDatabase(OLD_DB_NAME);\n }\n };\n}\n\nfunction cleanV1() {\n var request = indexedDB.open(OLD_DB_NAME);\n\n request.onerror = function (event) {// NOOP - Nothing we can do.\n };\n\n request.onsuccess = function (event) {\n var db = request.result;\n handleDb(db);\n };\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar DbInterface =\n/** @class */\nfunction () {\n function DbInterface() {\n this.dbPromise = null;\n }\n /** Gets record(s) from the objectStore that match the given key. */\n\n\n DbInterface.prototype.get = function (key) {\n return this.createTransaction(function (objectStore) {\n return objectStore.get(key);\n });\n };\n /** Gets record(s) from the objectStore that match the given index. */\n\n\n DbInterface.prototype.getIndex = function (index, key) {\n function runRequest(objectStore) {\n var idbIndex = objectStore.index(index);\n return idbIndex.get(key);\n }\n\n return this.createTransaction(runRequest);\n };\n /** Assigns or overwrites the record for the given value. */\n // tslint:disable-next-line:no-any IndexedDB values are of type \"any\"\n\n\n DbInterface.prototype.put = function (value) {\n return this.createTransaction(function (objectStore) {\n return objectStore.put(value);\n }, 'readwrite');\n };\n /** Deletes record(s) from the objectStore that match the given key. */\n\n\n DbInterface.prototype.delete = function (key) {\n return this.createTransaction(function (objectStore) {\n return objectStore.delete(key);\n }, 'readwrite');\n };\n /**\r\n * Close the currently open database.\r\n */\n\n\n DbInterface.prototype.closeDatabase = function () {\n return __awaiter(this, void 0, void 0, function () {\n var db;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!this.dbPromise) return [3\n /*break*/\n , 2];\n return [4\n /*yield*/\n , this.dbPromise];\n\n case 1:\n db = _a.sent();\n db.close();\n this.dbPromise = null;\n _a.label = 2;\n\n case 2:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Creates an IndexedDB Transaction and passes its objectStore to the\r\n * runRequest function, which runs the database request.\r\n *\r\n * @return Promise that resolves with the result of the runRequest function\r\n */\n\n\n DbInterface.prototype.createTransaction = function (runRequest, mode) {\n if (mode === void 0) {\n mode = 'readonly';\n }\n\n return __awaiter(this, void 0, void 0, function () {\n var db, transaction, request, result;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , this.getDb()];\n\n case 1:\n db = _a.sent();\n transaction = db.transaction(this.objectStoreName, mode);\n request = transaction.objectStore(this.objectStoreName);\n return [4\n /*yield*/\n , promisify(runRequest(request))];\n\n case 2:\n result = _a.sent();\n return [2\n /*return*/\n , new Promise(function (resolve, reject) {\n transaction.oncomplete = function () {\n resolve(result);\n };\n\n transaction.onerror = function () {\n reject(transaction.error);\n };\n })];\n }\n });\n });\n };\n /** Gets the cached db connection or opens a new one. */\n\n\n DbInterface.prototype.getDb = function () {\n var _this = this;\n\n if (!this.dbPromise) {\n this.dbPromise = new Promise(function (resolve, reject) {\n var request = indexedDB.open(_this.dbName, _this.dbVersion);\n\n request.onsuccess = function () {\n resolve(request.result);\n };\n\n request.onerror = function () {\n _this.dbPromise = null;\n reject(request.error);\n };\n\n request.onupgradeneeded = function (event) {\n return _this.onDbUpgrade(request, event);\n };\n });\n }\n\n return this.dbPromise;\n };\n\n return DbInterface;\n}();\n/** Promisifies an IDBRequest. Resolves with the IDBRequest's result. */\n\n\nfunction promisify(request) {\n return new Promise(function (resolve, reject) {\n request.onsuccess = function () {\n resolve(request.result);\n };\n\n request.onerror = function () {\n reject(request.error);\n };\n });\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar TokenDetailsModel =\n/** @class */\nfunction (_super) {\n __extends(TokenDetailsModel, _super);\n\n function TokenDetailsModel() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n\n _this.dbName = 'fcm_token_details_db';\n _this.dbVersion = 3;\n _this.objectStoreName = 'fcm_token_object_Store';\n return _this;\n }\n\n TokenDetailsModel.prototype.onDbUpgrade = function (request, event) {\n var db = request.result; // Lack of 'break' statements is intentional.\n\n switch (event.oldVersion) {\n case 0:\n {\n // New IDB instance\n var objectStore = db.createObjectStore(this.objectStoreName, {\n keyPath: 'swScope'\n }); // Make sure the sender ID can be searched\n\n objectStore.createIndex('fcmSenderId', 'fcmSenderId', {\n unique: false\n });\n objectStore.createIndex('fcmToken', 'fcmToken', {\n unique: true\n });\n }\n\n case 1:\n {\n // Prior to version 2, we were using either 'fcm_token_details_db'\n // or 'undefined' as the database name due to bug in the SDK\n // So remove the old tokens and databases.\n cleanV1();\n }\n\n case 2:\n {\n var objectStore = request.transaction.objectStore(this.objectStoreName);\n var cursorRequest_1 = objectStore.openCursor();\n\n cursorRequest_1.onsuccess = function () {\n var cursor = cursorRequest_1.result;\n\n if (cursor) {\n var value = cursor.value;\n\n var newValue = __assign({}, value);\n\n if (!value.createTime) {\n newValue.createTime = Date.now();\n }\n\n if (typeof value.vapidKey === 'string') {\n newValue.vapidKey = base64ToArrayBuffer(value.vapidKey);\n }\n\n if (typeof value.auth === 'string') {\n newValue.auth = base64ToArrayBuffer(value.auth).buffer;\n }\n\n if (typeof value.auth === 'string') {\n newValue.p256dh = base64ToArrayBuffer(value.p256dh).buffer;\n }\n\n cursor.update(newValue);\n cursor.continue();\n }\n };\n }\n }\n };\n /**\r\n * Given a token, this method will look up the details in indexedDB.\r\n */\n\n\n TokenDetailsModel.prototype.getTokenDetailsFromToken = function (fcmToken) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (!fcmToken) {\n throw errorFactory.create(ERROR_CODES.BAD_TOKEN);\n }\n\n validateInputs({\n fcmToken: fcmToken\n });\n return [2\n /*return*/\n , this.getIndex('fcmToken', fcmToken)];\n });\n });\n };\n /**\r\n * Given a service worker scope, this method will look up the details in\r\n * indexedDB.\r\n * @return The details associated with that token.\r\n */\n\n\n TokenDetailsModel.prototype.getTokenDetailsFromSWScope = function (swScope) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (!swScope) {\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\n }\n\n validateInputs({\n swScope: swScope\n });\n return [2\n /*return*/\n , this.get(swScope)];\n });\n });\n };\n /**\r\n * Save the details for the fcm token for re-use at a later date.\r\n * @param input A plain js object containing args to save.\r\n */\n\n\n TokenDetailsModel.prototype.saveTokenDetails = function (tokenDetails) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (!tokenDetails.swScope) {\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\n }\n\n if (!tokenDetails.vapidKey) {\n throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);\n }\n\n if (!tokenDetails.endpoint || !tokenDetails.auth || !tokenDetails.p256dh) {\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\n }\n\n if (!tokenDetails.fcmSenderId) {\n throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);\n }\n\n if (!tokenDetails.fcmToken) {\n throw errorFactory.create(ERROR_CODES.BAD_TOKEN);\n }\n\n if (!tokenDetails.fcmPushSet) {\n throw errorFactory.create(ERROR_CODES.BAD_PUSH_SET);\n }\n\n validateInputs(tokenDetails);\n return [2\n /*return*/\n , this.put(tokenDetails)];\n });\n });\n };\n /**\r\n * This method deletes details of the current FCM token.\r\n * It's returning a promise in case we need to move to an async\r\n * method for deleting at a later date.\r\n *\r\n * @return Resolves once the FCM token details have been deleted and returns\r\n * the deleted details.\r\n */\n\n\n TokenDetailsModel.prototype.deleteToken = function (token) {\n return __awaiter(this, void 0, void 0, function () {\n var details;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (typeof token !== 'string' || token.length === 0) {\n return [2\n /*return*/\n , Promise.reject(errorFactory.create(ERROR_CODES.INVALID_DELETE_TOKEN))];\n }\n\n return [4\n /*yield*/\n , this.getTokenDetailsFromToken(token)];\n\n case 1:\n details = _a.sent();\n\n if (!details) {\n throw errorFactory.create(ERROR_CODES.DELETE_TOKEN_NOT_FOUND);\n }\n\n return [4\n /*yield*/\n , this.delete(details.swScope)];\n\n case 2:\n _a.sent();\n\n return [2\n /*return*/\n , details];\n }\n });\n });\n };\n\n return TokenDetailsModel;\n}(DbInterface);\n/**\r\n * This method takes an object and will check for known arguments and\r\n * validate the input.\r\n * @return Promise that resolves if input is valid, rejects otherwise.\r\n */\n\n\nfunction validateInputs(input) {\n if (input.fcmToken) {\n if (typeof input.fcmToken !== 'string' || input.fcmToken.length === 0) {\n throw errorFactory.create(ERROR_CODES.BAD_TOKEN);\n }\n }\n\n if (input.swScope) {\n if (typeof input.swScope !== 'string' || input.swScope.length === 0) {\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\n }\n }\n\n if (input.vapidKey) {\n if (!(input.vapidKey instanceof Uint8Array) || input.vapidKey.length !== 65) {\n throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);\n }\n }\n\n if (input.endpoint) {\n if (typeof input.endpoint !== 'string' || input.endpoint.length === 0) {\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\n }\n }\n\n if (input.auth) {\n if (!(input.auth instanceof ArrayBuffer)) {\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\n }\n }\n\n if (input.p256dh) {\n if (!(input.p256dh instanceof ArrayBuffer)) {\n throw errorFactory.create(ERROR_CODES.BAD_SUBSCRIPTION);\n }\n }\n\n if (input.fcmSenderId) {\n if (typeof input.fcmSenderId !== 'string' || input.fcmSenderId.length === 0) {\n throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);\n }\n }\n\n if (input.fcmPushSet) {\n if (typeof input.fcmPushSet !== 'string' || input.fcmPushSet.length === 0) {\n throw errorFactory.create(ERROR_CODES.BAD_PUSH_SET);\n }\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar UNCOMPRESSED_PUBLIC_KEY_SIZE = 65;\n\nvar VapidDetailsModel =\n/** @class */\nfunction (_super) {\n __extends(VapidDetailsModel, _super);\n\n function VapidDetailsModel() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n\n _this.dbName = 'fcm_vapid_details_db';\n _this.dbVersion = 1;\n _this.objectStoreName = 'fcm_vapid_object_Store';\n return _this;\n }\n\n VapidDetailsModel.prototype.onDbUpgrade = function (request) {\n var db = request.result;\n db.createObjectStore(this.objectStoreName, {\n keyPath: 'swScope'\n });\n };\n /**\r\n * Given a service worker scope, this method will look up the vapid key\r\n * in indexedDB.\r\n */\n\n\n VapidDetailsModel.prototype.getVapidFromSWScope = function (swScope) {\n return __awaiter(this, void 0, void 0, function () {\n var result;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (typeof swScope !== 'string' || swScope.length === 0) {\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\n }\n\n return [4\n /*yield*/\n , this.get(swScope)];\n\n case 1:\n result = _a.sent();\n return [2\n /*return*/\n , result ? result.vapidKey : undefined];\n }\n });\n });\n };\n /**\r\n * Save a vapid key against a swScope for later date.\r\n */\n\n\n VapidDetailsModel.prototype.saveVapidDetails = function (swScope, vapidKey) {\n return __awaiter(this, void 0, void 0, function () {\n var details;\n return __generator(this, function (_a) {\n if (typeof swScope !== 'string' || swScope.length === 0) {\n throw errorFactory.create(ERROR_CODES.BAD_SCOPE);\n }\n\n if (vapidKey === null || vapidKey.length !== UNCOMPRESSED_PUBLIC_KEY_SIZE) {\n throw errorFactory.create(ERROR_CODES.BAD_VAPID_KEY);\n }\n\n details = {\n swScope: swScope,\n vapidKey: vapidKey\n };\n return [2\n /*return*/\n , this.put(details)];\n });\n });\n };\n /**\r\n * This method deletes details of the current FCM VAPID key for a SW scope.\r\n * Resolves once the scope/vapid details have been deleted and returns the\r\n * deleted vapid key.\r\n */\n\n\n VapidDetailsModel.prototype.deleteVapidDetails = function (swScope) {\n return __awaiter(this, void 0, void 0, function () {\n var vapidKey;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , this.getVapidFromSWScope(swScope)];\n\n case 1:\n vapidKey = _a.sent();\n\n if (!vapidKey) {\n throw errorFactory.create(ERROR_CODES.DELETE_SCOPE_NOT_FOUND);\n }\n\n return [4\n /*yield*/\n , this.delete(swScope)];\n\n case 2:\n _a.sent();\n\n return [2\n /*return*/\n , vapidKey];\n }\n });\n });\n };\n\n return VapidDetailsModel;\n}(DbInterface);\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar SENDER_ID_OPTION_NAME = 'messagingSenderId'; // Database cache should be invalidated once a week.\n\nvar TOKEN_EXPIRATION_MILLIS = 7 * 24 * 60 * 60 * 1000; // 7 days\n\nvar BaseController =\n/** @class */\nfunction () {\n /**\r\n * An interface of the Messaging Service API\r\n */\n function BaseController(app) {\n var _this = this;\n\n if (!app.options[SENDER_ID_OPTION_NAME] || typeof app.options[SENDER_ID_OPTION_NAME] !== 'string') {\n throw errorFactory.create(ERROR_CODES.BAD_SENDER_ID);\n }\n\n this.messagingSenderId = app.options[SENDER_ID_OPTION_NAME];\n this.tokenDetailsModel = new TokenDetailsModel();\n this.vapidDetailsModel = new VapidDetailsModel();\n this.iidModel = new IidModel();\n this.app = app;\n this.INTERNAL = {\n delete: function _delete() {\n return _this.delete();\n }\n };\n }\n /**\r\n * @export\r\n */\n\n\n BaseController.prototype.getToken = function () {\n return __awaiter(this, void 0, void 0, function () {\n var currentPermission, swReg, publicVapidKey, pushSubscription, tokenDetails;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n currentPermission = this.getNotificationPermission_();\n\n if (currentPermission === 'denied') {\n throw errorFactory.create(ERROR_CODES.NOTIFICATIONS_BLOCKED);\n } else if (currentPermission !== 'granted') {\n // We must wait for permission to be granted\n return [2\n /*return*/\n , null];\n }\n\n return [4\n /*yield*/\n , this.getSWRegistration_()];\n\n case 1:\n swReg = _a.sent();\n return [4\n /*yield*/\n , this.getPublicVapidKey_()];\n\n case 2:\n publicVapidKey = _a.sent();\n return [4\n /*yield*/\n , this.getPushSubscription(swReg, publicVapidKey)];\n\n case 3:\n pushSubscription = _a.sent();\n return [4\n /*yield*/\n , this.tokenDetailsModel.getTokenDetailsFromSWScope(swReg.scope)];\n\n case 4:\n tokenDetails = _a.sent();\n\n if (tokenDetails) {\n return [2\n /*return*/\n , this.manageExistingToken(swReg, pushSubscription, publicVapidKey, tokenDetails)];\n }\n\n return [2\n /*return*/\n , this.getNewToken(swReg, pushSubscription, publicVapidKey)];\n }\n });\n });\n };\n /**\r\n * manageExistingToken is triggered if there's an existing FCM token in the\r\n * database and it can take 3 different actions:\r\n * 1) Retrieve the existing FCM token from the database.\r\n * 2) If VAPID details have changed: Delete the existing token and create a\r\n * new one with the new VAPID key.\r\n * 3) If the database cache is invalidated: Send a request to FCM to update\r\n * the token, and to check if the token is still valid on FCM-side.\r\n */\n\n\n BaseController.prototype.manageExistingToken = function (swReg, pushSubscription, publicVapidKey, tokenDetails) {\n return __awaiter(this, void 0, void 0, function () {\n var isTokenValid, now;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n isTokenValid = isTokenStillValid(pushSubscription, publicVapidKey, tokenDetails);\n\n if (isTokenValid) {\n now = Date.now();\n\n if (now < tokenDetails.createTime + TOKEN_EXPIRATION_MILLIS) {\n return [2\n /*return*/\n , tokenDetails.fcmToken];\n } else {\n return [2\n /*return*/\n , this.updateToken(swReg, pushSubscription, publicVapidKey, tokenDetails)];\n }\n } // If the token is no longer valid (for example if the VAPID details\n // have changed), delete the existing token from the FCM client and server\n // database. No need to unsubscribe from the Service Worker as we have a\n // good push subscription that we'd like to use in getNewToken.\n\n\n return [4\n /*yield*/\n , this.deleteTokenFromDB(tokenDetails.fcmToken)];\n\n case 1:\n // If the token is no longer valid (for example if the VAPID details\n // have changed), delete the existing token from the FCM client and server\n // database. No need to unsubscribe from the Service Worker as we have a\n // good push subscription that we'd like to use in getNewToken.\n _a.sent();\n\n return [2\n /*return*/\n , this.getNewToken(swReg, pushSubscription, publicVapidKey)];\n }\n });\n });\n };\n\n BaseController.prototype.updateToken = function (swReg, pushSubscription, publicVapidKey, tokenDetails) {\n return __awaiter(this, void 0, void 0, function () {\n var updatedToken, allDetails, e_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 4,, 6]);\n\n return [4\n /*yield*/\n , this.iidModel.updateToken(this.messagingSenderId, tokenDetails.fcmToken, tokenDetails.fcmPushSet, pushSubscription, publicVapidKey)];\n\n case 1:\n updatedToken = _a.sent();\n allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n fcmSenderId: this.messagingSenderId,\n fcmToken: updatedToken,\n fcmPushSet: tokenDetails.fcmPushSet,\n createTime: Date.now(),\n endpoint: pushSubscription.endpoint,\n auth: pushSubscription.getKey('auth'),\n p256dh: pushSubscription.getKey('p256dh')\n };\n return [4\n /*yield*/\n , this.tokenDetailsModel.saveTokenDetails(allDetails)];\n\n case 2:\n _a.sent();\n\n return [4\n /*yield*/\n , this.vapidDetailsModel.saveVapidDetails(swReg.scope, publicVapidKey)];\n\n case 3:\n _a.sent();\n\n return [2\n /*return*/\n , updatedToken];\n\n case 4:\n e_1 = _a.sent();\n return [4\n /*yield*/\n , this.deleteToken(tokenDetails.fcmToken)];\n\n case 5:\n _a.sent();\n\n throw e_1;\n\n case 6:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n BaseController.prototype.getNewToken = function (swReg, pushSubscription, publicVapidKey) {\n return __awaiter(this, void 0, void 0, function () {\n var tokenDetails, allDetails;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , this.iidModel.getToken(this.messagingSenderId, pushSubscription, publicVapidKey)];\n\n case 1:\n tokenDetails = _a.sent();\n allDetails = {\n swScope: swReg.scope,\n vapidKey: publicVapidKey,\n fcmSenderId: this.messagingSenderId,\n fcmToken: tokenDetails.token,\n fcmPushSet: tokenDetails.pushSet,\n createTime: Date.now(),\n endpoint: pushSubscription.endpoint,\n auth: pushSubscription.getKey('auth'),\n p256dh: pushSubscription.getKey('p256dh')\n };\n return [4\n /*yield*/\n , this.tokenDetailsModel.saveTokenDetails(allDetails)];\n\n case 2:\n _a.sent();\n\n return [4\n /*yield*/\n , this.vapidDetailsModel.saveVapidDetails(swReg.scope, publicVapidKey)];\n\n case 3:\n _a.sent();\n\n return [2\n /*return*/\n , tokenDetails.token];\n }\n });\n });\n };\n /**\r\n * This method deletes tokens that the token manager looks after,\r\n * unsubscribes the token from FCM and then unregisters the push\r\n * subscription if it exists. It returns a promise that indicates\r\n * whether or not the unsubscribe request was processed successfully.\r\n */\n\n\n BaseController.prototype.deleteToken = function (token) {\n return __awaiter(this, void 0, void 0, function () {\n var registration, pushSubscription;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n // Delete the token details from the database.\n return [4\n /*yield*/\n , this.deleteTokenFromDB(token)];\n\n case 1:\n // Delete the token details from the database.\n _a.sent();\n\n return [4\n /*yield*/\n , this.getSWRegistration_()];\n\n case 2:\n registration = _a.sent();\n if (!registration) return [3\n /*break*/\n , 4];\n return [4\n /*yield*/\n , registration.pushManager.getSubscription()];\n\n case 3:\n pushSubscription = _a.sent();\n\n if (pushSubscription) {\n return [2\n /*return*/\n , pushSubscription.unsubscribe()];\n }\n\n _a.label = 4;\n\n case 4:\n // If there's no SW, consider it a success.\n return [2\n /*return*/\n , true];\n }\n });\n });\n };\n /**\r\n * This method will delete the token from the client database, and make a\r\n * call to FCM to remove it from the server DB. Does not temper with the\r\n * push subscription.\r\n */\n\n\n BaseController.prototype.deleteTokenFromDB = function (token) {\n return __awaiter(this, void 0, void 0, function () {\n var details;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , this.tokenDetailsModel.deleteToken(token)];\n\n case 1:\n details = _a.sent();\n return [4\n /*yield*/\n , this.iidModel.deleteToken(details.fcmSenderId, details.fcmToken, details.fcmPushSet)];\n\n case 2:\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Gets a PushSubscription for the current user.\r\n */\n\n\n BaseController.prototype.getPushSubscription = function (swRegistration, publicVapidKey) {\n return swRegistration.pushManager.getSubscription().then(function (subscription) {\n if (subscription) {\n return subscription;\n }\n\n return swRegistration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: publicVapidKey\n });\n });\n }; //\n // The following methods should only be available in the window.\n //\n\n\n BaseController.prototype.requestPermission = function () {\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\n };\n\n BaseController.prototype.useServiceWorker = function (registration) {\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\n };\n\n BaseController.prototype.usePublicVapidKey = function (b64PublicKey) {\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\n };\n\n BaseController.prototype.onMessage = function (nextOrObserver, error, completed) {\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\n };\n\n BaseController.prototype.onTokenRefresh = function (nextOrObserver, error, completed) {\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_WINDOW);\n }; //\n // The following methods are used by the service worker only.\n //\n\n\n BaseController.prototype.setBackgroundMessageHandler = function (callback) {\n throw errorFactory.create(ERROR_CODES.AVAILABLE_IN_SW);\n }; //\n // The following methods are used by the service themselves and not exposed\n // publicly or not expected to be used by developers.\n //\n\n /**\r\n * This method is required to adhere to the Firebase interface.\r\n * It closes any currently open indexdb database connections.\r\n */\n\n\n BaseController.prototype.delete = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , Promise.all([this.tokenDetailsModel.closeDatabase(), this.vapidDetailsModel.closeDatabase()])];\n\n case 1:\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * Returns the current Notification Permission state.\r\n */\n\n\n BaseController.prototype.getNotificationPermission_ = function () {\n // TODO: Remove the cast when this issue is fixed:\n // https://github.com/Microsoft/TypeScript/issues/14701\n // tslint:disable-next-line no-any\n return Notification.permission;\n };\n\n BaseController.prototype.getTokenDetailsModel = function () {\n return this.tokenDetailsModel;\n };\n\n BaseController.prototype.getVapidDetailsModel = function () {\n return this.vapidDetailsModel;\n }; // Visible for testing\n // TODO: make protected\n\n\n BaseController.prototype.getIidModel = function () {\n return this.iidModel;\n };\n\n return BaseController;\n}();\n/**\r\n * Checks if the tokenDetails match the details provided in the clients.\r\n */\n\n\nfunction isTokenStillValid(pushSubscription, publicVapidKey, tokenDetails) {\n if (!tokenDetails.vapidKey || !isArrayBufferEqual(publicVapidKey.buffer, tokenDetails.vapidKey.buffer)) {\n return false;\n }\n\n var isEndpointEqual = pushSubscription.endpoint === tokenDetails.endpoint;\n var isAuthEqual = isArrayBufferEqual(pushSubscription.getKey('auth'), tokenDetails.auth);\n var isP256dhEqual = isArrayBufferEqual(pushSubscription.getKey('p256dh'), tokenDetails.p256dh);\n return isEndpointEqual && isAuthEqual && isP256dhEqual;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar FCM_MSG = 'FCM_MSG';\n\nvar SwController =\n/** @class */\nfunction (_super) {\n __extends(SwController, _super);\n\n function SwController(app) {\n var _this = _super.call(this, app) || this;\n\n _this.bgMessageHandler = null;\n self.addEventListener('push', function (e) {\n _this.onPush(e);\n });\n self.addEventListener('pushsubscriptionchange', function (e) {\n _this.onSubChange(e);\n });\n self.addEventListener('notificationclick', function (e) {\n _this.onNotificationClick(e);\n });\n return _this;\n } // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.onPush = function (event) {\n event.waitUntil(this.onPush_(event));\n }; // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.onSubChange = function (event) {\n event.waitUntil(this.onSubChange_(event));\n }; // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.onNotificationClick = function (event) {\n event.waitUntil(this.onNotificationClick_(event));\n };\n /**\r\n * A handler for push events that shows notifications based on the content of\r\n * the payload.\r\n *\r\n * The payload must be a JSON-encoded Object with a `notification` key. The\r\n * value of the `notification` property will be used as the NotificationOptions\r\n * object passed to showNotification. Additionally, the `title` property of the\r\n * notification object will be used as the title.\r\n *\r\n * If there is no notification data in the payload then no notification will be\r\n * shown.\r\n */\n\n\n SwController.prototype.onPush_ = function (event) {\n return __awaiter(this, void 0, void 0, function () {\n var msgPayload, hasVisibleClients, notificationDetails, notificationTitle, reg, actions, maxActions;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!event.data) {\n return [2\n /*return*/\n ];\n }\n\n try {\n msgPayload = event.data.json();\n } catch (err) {\n // Not JSON so not an FCM message\n return [2\n /*return*/\n ];\n }\n\n return [4\n /*yield*/\n , this.hasVisibleClients_()];\n\n case 1:\n hasVisibleClients = _a.sent();\n\n if (hasVisibleClients) {\n // App in foreground. Send to page.\n return [2\n /*return*/\n , this.sendMessageToWindowClients_(msgPayload)];\n }\n\n notificationDetails = this.getNotificationData_(msgPayload);\n if (!notificationDetails) return [3\n /*break*/\n , 3];\n notificationTitle = notificationDetails.title || '';\n return [4\n /*yield*/\n , this.getSWRegistration_()];\n\n case 2:\n reg = _a.sent();\n actions = notificationDetails.actions;\n maxActions = Notification.maxActions; // tslint:enable no-any\n\n if (actions && maxActions && actions.length > maxActions) {\n console.warn(\"This browser only supports \" + maxActions + \" actions.\" + \"The remaining actions will not be displayed.\");\n }\n\n return [2\n /*return*/\n , reg.showNotification(notificationTitle, notificationDetails)];\n\n case 3:\n if (!this.bgMessageHandler) return [3\n /*break*/\n , 5];\n return [4\n /*yield*/\n , this.bgMessageHandler(msgPayload)];\n\n case 4:\n _a.sent();\n\n return [2\n /*return*/\n ];\n\n case 5:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n SwController.prototype.onSubChange_ = function (event) {\n return __awaiter(this, void 0, void 0, function () {\n var registration, err_1, err_2, tokenDetailsModel, tokenDetails;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n _a.trys.push([0, 2,, 3]);\n\n return [4\n /*yield*/\n , this.getSWRegistration_()];\n\n case 1:\n registration = _a.sent();\n return [3\n /*break*/\n , 3];\n\n case 2:\n err_1 = _a.sent();\n throw errorFactory.create(ERROR_CODES.UNABLE_TO_RESUBSCRIBE, {\n message: err_1\n });\n\n case 3:\n _a.trys.push([3, 5,, 8]);\n\n return [4\n /*yield*/\n , registration.pushManager.getSubscription()];\n\n case 4:\n _a.sent();\n\n return [3\n /*break*/\n , 8];\n\n case 5:\n err_2 = _a.sent();\n tokenDetailsModel = this.getTokenDetailsModel();\n return [4\n /*yield*/\n , tokenDetailsModel.getTokenDetailsFromSWScope(registration.scope)];\n\n case 6:\n tokenDetails = _a.sent();\n\n if (!tokenDetails) {\n // This should rarely occure, but could if indexedDB\n // is corrupted or wiped\n throw err_2;\n } // Attempt to delete the token if we know it's bad\n\n\n return [4\n /*yield*/\n , this.deleteToken(tokenDetails.fcmToken)];\n\n case 7:\n // Attempt to delete the token if we know it's bad\n _a.sent();\n\n throw err_2;\n\n case 8:\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n\n SwController.prototype.onNotificationClick_ = function (event) {\n return __awaiter(this, void 0, void 0, function () {\n var msgPayload, link, windowClient, internalMsg;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!event.notification || !event.notification.data || !event.notification.data[FCM_MSG]) {\n // Not an FCM notification, do nothing.\n return [2\n /*return*/\n ];\n } else if (event.action) {\n // User clicked on an action button.\n // This will allow devs to act on action button clicks by using a custom\n // onNotificationClick listener that they define.\n return [2\n /*return*/\n ];\n } // Prevent other listeners from receiving the event\n\n\n event.stopImmediatePropagation();\n event.notification.close();\n msgPayload = event.notification.data[FCM_MSG];\n\n if (!msgPayload.notification) {\n // Nothing to do.\n return [2\n /*return*/\n ];\n }\n\n link = msgPayload.fcmOptions && msgPayload.fcmOptions.link || msgPayload.notification.click_action;\n\n if (!link) {\n // Nothing to do.\n return [2\n /*return*/\n ];\n }\n\n return [4\n /*yield*/\n , this.getWindowClient_(link)];\n\n case 1:\n windowClient = _a.sent();\n if (!!windowClient) return [3\n /*break*/\n , 3];\n return [4\n /*yield*/\n , self.clients.openWindow(link)];\n\n case 2:\n // Unable to find window client so need to open one.\n windowClient = _a.sent();\n return [3\n /*break*/\n , 5];\n\n case 3:\n return [4\n /*yield*/\n , windowClient.focus()];\n\n case 4:\n windowClient = _a.sent();\n _a.label = 5;\n\n case 5:\n if (!windowClient) {\n // Window Client will not be returned if it's for a third party origin.\n return [2\n /*return*/\n ];\n } // Delete notification and fcmOptions data from payload before sending to\n // the page.\n\n\n delete msgPayload.notification;\n delete msgPayload.fcmOptions;\n internalMsg = createNewMsg(MessageType.NOTIFICATION_CLICKED, msgPayload); // Attempt to send a message to the client to handle the data\n // Is affected by: https://github.com/slightlyoff/ServiceWorker/issues/728\n\n return [2\n /*return*/\n , this.attemptToMessageClient_(windowClient, internalMsg)];\n }\n });\n });\n }; // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.getNotificationData_ = function (msgPayload) {\n if (!msgPayload) {\n return;\n }\n\n if (typeof msgPayload.notification !== 'object') {\n return;\n }\n\n var notificationInformation = __assign({}, msgPayload.notification); // Put the message payload under FCM_MSG name so we can identify the\n // notification as being an FCM notification vs a notification from\n // somewhere else (i.e. normal web push or developer generated\n // notification).\n\n\n notificationInformation.data = __assign({}, msgPayload.notification.data, (_a = {}, _a[FCM_MSG] = msgPayload, _a));\n return notificationInformation;\n\n var _a;\n };\n /**\r\n * Calling setBackgroundMessageHandler will opt in to some specific\r\n * behaviours.\r\n * 1.) If a notification doesn't need to be shown due to a window already\r\n * being visible, then push messages will be sent to the page.\r\n * 2.) If a notification needs to be shown, and the message contains no\r\n * notification data this method will be called\r\n * and the promise it returns will be passed to event.waitUntil.\r\n * If you do not set this callback then all push messages will let and the\r\n * developer can handle them in a their own 'push' event callback\r\n *\r\n * @param callback The callback to be called when a push message is received\r\n * and a notification must be shown. The callback will be given the data from\r\n * the push message.\r\n */\n\n\n SwController.prototype.setBackgroundMessageHandler = function (callback) {\n if (!callback || typeof callback !== 'function') {\n throw errorFactory.create(ERROR_CODES.BG_HANDLER_FUNCTION_EXPECTED);\n }\n\n this.bgMessageHandler = callback;\n };\n /**\r\n * @param url The URL to look for when focusing a client.\r\n * @return Returns an existing window client or a newly opened WindowClient.\r\n */\n // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.getWindowClient_ = function (url) {\n return __awaiter(this, void 0, void 0, function () {\n var parsedURL, clientList, suitableClient, i, parsedClientUrl;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n parsedURL = new URL(url, self.location.href).href;\n return [4\n /*yield*/\n , getClientList()];\n\n case 1:\n clientList = _a.sent();\n suitableClient = null;\n\n for (i = 0; i < clientList.length; i++) {\n parsedClientUrl = new URL(clientList[i].url, self.location.href).href;\n\n if (parsedClientUrl === parsedURL) {\n suitableClient = clientList[i];\n break;\n }\n }\n\n return [2\n /*return*/\n , suitableClient];\n }\n });\n });\n };\n /**\r\n * This message will attempt to send the message to a window client.\r\n * @param client The WindowClient to send the message to.\r\n * @param message The message to send to the client.\r\n * @returns Returns a promise that resolves after sending the message. This\r\n * does not guarantee that the message was successfully received.\r\n */\n // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.attemptToMessageClient_ = function (client, message) {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n // NOTE: This returns a promise in case this API is abstracted later on to\n // do additional work\n if (!client) {\n throw errorFactory.create(ERROR_CODES.NO_WINDOW_CLIENT_TO_MSG);\n }\n\n client.postMessage(message);\n return [2\n /*return*/\n ];\n });\n });\n };\n /**\r\n * @returns If there is currently a visible WindowClient, this method will\r\n * resolve to true, otherwise false.\r\n */\n // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.hasVisibleClients_ = function () {\n return __awaiter(this, void 0, void 0, function () {\n var clientList;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , getClientList()];\n\n case 1:\n clientList = _a.sent();\n return [2\n /*return*/\n , clientList.some(function (client) {\n return client.visibilityState === 'visible';\n })];\n }\n });\n });\n };\n /**\r\n * @param msgPayload The data from the push event that should be sent to all\r\n * available pages.\r\n * @returns Returns a promise that resolves once the message has been sent to\r\n * all WindowClients.\r\n */\n // Visible for testing\n // TODO: Make private\n\n\n SwController.prototype.sendMessageToWindowClients_ = function (msgPayload) {\n return __awaiter(this, void 0, void 0, function () {\n var _this = this;\n\n var clientList, internalMsg;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , getClientList()];\n\n case 1:\n clientList = _a.sent();\n internalMsg = createNewMsg(MessageType.PUSH_MSG_RECEIVED, msgPayload);\n return [4\n /*yield*/\n , Promise.all(clientList.map(function (client) {\n return _this.attemptToMessageClient_(client, internalMsg);\n }))];\n\n case 2:\n _a.sent();\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * This will register the default service worker and return the registration.\r\n * @return he service worker registration to be used for the push service.\r\n */\n\n\n SwController.prototype.getSWRegistration_ = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n return [2\n /*return*/\n , self.registration];\n });\n });\n };\n /**\r\n * This will return the default VAPID key or the uint8array version of the\r\n * public VAPID key provided by the developer.\r\n */\n\n\n SwController.prototype.getPublicVapidKey_ = function () {\n return __awaiter(this, void 0, void 0, function () {\n var swReg, vapidKeyFromDatabase;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n return [4\n /*yield*/\n , this.getSWRegistration_()];\n\n case 1:\n swReg = _a.sent();\n\n if (!swReg) {\n throw errorFactory.create(ERROR_CODES.SW_REGISTRATION_EXPECTED);\n }\n\n return [4\n /*yield*/\n , this.getVapidDetailsModel().getVapidFromSWScope(swReg.scope)];\n\n case 2:\n vapidKeyFromDatabase = _a.sent();\n\n if (vapidKeyFromDatabase == null) {\n return [2\n /*return*/\n , DEFAULT_PUBLIC_VAPID_KEY];\n }\n\n return [2\n /*return*/\n , vapidKeyFromDatabase];\n }\n });\n });\n };\n\n return SwController;\n}(BaseController);\n\nfunction getClientList() {\n return self.clients.matchAll({\n type: 'window',\n includeUncontrolled: true // TS doesn't know that \"type: 'window'\" means it'll return WindowClient[]\n\n });\n}\n\nfunction createNewMsg(msgType, msgData) {\n return _a = {}, _a[MessageParameter.TYPE_OF_MSG] = msgType, _a[MessageParameter.DATA] = msgData, _a;\n\n var _a;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar DEFAULT_SW_PATH = '/firebase-messaging-sw.js';\nvar DEFAULT_SW_SCOPE = '/firebase-cloud-messaging-push-scope';\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar WindowController =\n/** @class */\nfunction (_super) {\n __extends(WindowController, _super);\n /**\r\n * A service that provides a MessagingService instance.\r\n */\n\n\n function WindowController(app) {\n var _this = _super.call(this, app) || this;\n\n _this.registrationToUse = null;\n _this.publicVapidKeyToUse = null;\n _this.manifestCheckPromise = null;\n _this.messageObserver = null; // @ts-ignore: Unused variable error, this is not implemented yet.\n\n _this.tokenRefreshObserver = null;\n _this.onMessageInternal = createSubscribe(function (observer) {\n _this.messageObserver = observer;\n });\n _this.onTokenRefreshInternal = createSubscribe(function (observer) {\n _this.tokenRefreshObserver = observer;\n });\n\n _this.setupSWMessageListener_();\n\n return _this;\n }\n /**\r\n * This method returns an FCM token if it can be generated.\r\n * The return promise will reject if the browser doesn't support\r\n * FCM, if permission is denied for notifications or it's not\r\n * possible to generate a token.\r\n *\r\n * @return Returns a promise that resolves to an FCM token or null if\r\n * permission isn't granted.\r\n */\n\n\n WindowController.prototype.getToken = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (!this.manifestCheckPromise) {\n this.manifestCheckPromise = manifestCheck();\n }\n\n return [4\n /*yield*/\n , this.manifestCheckPromise];\n\n case 1:\n _a.sent();\n\n return [2\n /*return*/\n , _super.prototype.getToken.call(this)];\n }\n });\n });\n };\n /**\r\n * Request permission if it is not currently granted\r\n *\r\n * @return Resolves if the permission was granted, otherwise rejects\r\n */\n\n\n WindowController.prototype.requestPermission = function () {\n return __awaiter(this, void 0, void 0, function () {\n var permissionResult;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n if (this.getNotificationPermission_() === 'granted') {\n return [2\n /*return*/\n ];\n }\n\n return [4\n /*yield*/\n , Notification.requestPermission()];\n\n case 1:\n permissionResult = _a.sent();\n\n if (permissionResult === 'granted') {\n return [2\n /*return*/\n ];\n } else if (permissionResult === 'denied') {\n throw errorFactory.create(ERROR_CODES.PERMISSION_BLOCKED);\n } else {\n throw errorFactory.create(ERROR_CODES.PERMISSION_DEFAULT);\n }\n\n return [2\n /*return*/\n ];\n }\n });\n });\n };\n /**\r\n * This method allows a developer to override the default service worker and\r\n * instead use a custom service worker.\r\n *\r\n * @param registration The service worker registration that should be used to\r\n * receive the push messages.\r\n */\n\n\n WindowController.prototype.useServiceWorker = function (registration) {\n if (!(registration instanceof ServiceWorkerRegistration)) {\n throw errorFactory.create(ERROR_CODES.SW_REGISTRATION_EXPECTED);\n }\n\n if (this.registrationToUse != null) {\n throw errorFactory.create(ERROR_CODES.USE_SW_BEFORE_GET_TOKEN);\n }\n\n this.registrationToUse = registration;\n };\n /**\r\n * This method allows a developer to override the default vapid key\r\n * and instead use a custom VAPID public key.\r\n *\r\n * @param publicKey A URL safe base64 encoded string.\r\n */\n\n\n WindowController.prototype.usePublicVapidKey = function (publicKey) {\n if (typeof publicKey !== 'string') {\n throw errorFactory.create(ERROR_CODES.INVALID_PUBLIC_VAPID_KEY);\n }\n\n if (this.publicVapidKeyToUse != null) {\n throw errorFactory.create(ERROR_CODES.USE_PUBLIC_KEY_BEFORE_GET_TOKEN);\n }\n\n var parsedKey = base64ToArrayBuffer(publicKey);\n\n if (parsedKey.length !== 65) {\n throw errorFactory.create(ERROR_CODES.PUBLIC_KEY_DECRYPTION_FAILED);\n }\n\n this.publicVapidKeyToUse = parsedKey;\n };\n /**\r\n * @export\r\n * @param nextOrObserver An observer object or a function triggered on\r\n * message.\r\n * @param error A function triggered on message error.\r\n * @param completed function triggered when the observer is removed.\r\n * @return The unsubscribe function for the observer.\r\n */\n\n\n WindowController.prototype.onMessage = function (nextOrObserver, error, completed) {\n if (typeof nextOrObserver === 'function') {\n return this.onMessageInternal(nextOrObserver, error, completed);\n } else {\n return this.onMessageInternal(nextOrObserver);\n }\n };\n /**\r\n * @param nextOrObserver An observer object or a function triggered on token\r\n * refresh.\r\n * @param error A function triggered on token refresh error.\r\n * @param completed function triggered when the observer is removed.\r\n * @return The unsubscribe function for the observer.\r\n */\n\n\n WindowController.prototype.onTokenRefresh = function (nextOrObserver, error, completed) {\n if (typeof nextOrObserver === 'function') {\n return this.onTokenRefreshInternal(nextOrObserver, error, completed);\n } else {\n return this.onTokenRefreshInternal(nextOrObserver);\n }\n };\n /**\r\n * Given a registration, wait for the service worker it relates to\r\n * become activer\r\n * @param registration Registration to wait for service worker to become active\r\n * @return Wait for service worker registration to become active\r\n */\n // Visible for testing\n // TODO: Make private\n\n\n WindowController.prototype.waitForRegistrationToActivate_ = function (registration) {\n var serviceWorker = registration.installing || registration.waiting || registration.active;\n return new Promise(function (resolve, reject) {\n if (!serviceWorker) {\n // This is a rare scenario but has occured in firefox\n reject(errorFactory.create(ERROR_CODES.NO_SW_IN_REG));\n return;\n } // Because the Promise function is called on next tick there is a\n // small chance that the worker became active or redundant already.\n\n\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n return;\n }\n\n if (serviceWorker.state === 'redundant') {\n reject(errorFactory.create(ERROR_CODES.SW_REG_REDUNDANT));\n return;\n }\n\n var stateChangeListener = function stateChangeListener() {\n if (serviceWorker.state === 'activated') {\n resolve(registration);\n } else if (serviceWorker.state === 'redundant') {\n reject(errorFactory.create(ERROR_CODES.SW_REG_REDUNDANT));\n } else {\n // Return early and wait to next state change\n return;\n }\n\n serviceWorker.removeEventListener('statechange', stateChangeListener);\n };\n\n serviceWorker.addEventListener('statechange', stateChangeListener);\n });\n };\n /**\r\n * This will register the default service worker and return the registration\r\n * @return The service worker registration to be used for the push service.\r\n */\n\n\n WindowController.prototype.getSWRegistration_ = function () {\n var _this = this;\n\n if (this.registrationToUse) {\n return this.waitForRegistrationToActivate_(this.registrationToUse);\n } // Make the registration null so we know useServiceWorker will not\n // use a new service worker as registrationToUse is no longer undefined\n\n\n this.registrationToUse = null;\n return navigator.serviceWorker.register(DEFAULT_SW_PATH, {\n scope: DEFAULT_SW_SCOPE\n }).catch(function (err) {\n throw errorFactory.create(ERROR_CODES.FAILED_DEFAULT_REGISTRATION, {\n browserErrorMessage: err.message\n });\n }).then(function (registration) {\n return _this.waitForRegistrationToActivate_(registration).then(function () {\n _this.registrationToUse = registration; // We update after activation due to an issue with Firefox v49 where\n // a race condition occassionally causes the service work to not\n // install\n\n registration.update();\n return registration;\n });\n });\n };\n /**\r\n * This will return the default VAPID key or the uint8array version of the public VAPID key\r\n * provided by the developer.\r\n */\n\n\n WindowController.prototype.getPublicVapidKey_ = function () {\n return __awaiter(this, void 0, void 0, function () {\n return __generator(this, function (_a) {\n if (this.publicVapidKeyToUse) {\n return [2\n /*return*/\n , this.publicVapidKeyToUse];\n }\n\n return [2\n /*return*/\n , DEFAULT_PUBLIC_VAPID_KEY];\n });\n });\n };\n /**\r\n * This method will set up a message listener to handle\r\n * events from the service worker that should trigger\r\n * events in the page.\r\n */\n // Visible for testing\n // TODO: Make private\n\n\n WindowController.prototype.setupSWMessageListener_ = function () {\n var _this = this;\n\n navigator.serviceWorker.addEventListener('message', function (event) {\n if (!event.data || !event.data[MessageParameter.TYPE_OF_MSG]) {\n // Not a message from FCM\n return;\n }\n\n var workerPageMessage = event.data;\n\n switch (workerPageMessage[MessageParameter.TYPE_OF_MSG]) {\n case MessageType.PUSH_MSG_RECEIVED:\n case MessageType.NOTIFICATION_CLICKED:\n var pushMessage = workerPageMessage[MessageParameter.DATA];\n\n if (_this.messageObserver) {\n _this.messageObserver.next(pushMessage);\n }\n\n break;\n\n default:\n // Noop.\n break;\n }\n }, false);\n };\n\n return WindowController;\n}(BaseController);\n/**\r\n * The method checks that a manifest is defined and has the correct GCM\r\n * sender ID.\r\n * @return Returns a promise that resolves if the manifest matches\r\n * our required sender ID\r\n */\n// Exported for testing\n\n\nfunction manifestCheck() {\n return __awaiter(this, void 0, void 0, function () {\n var manifestTag, manifestContent, response, e_1;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n manifestTag = document.querySelector('link[rel=\"manifest\"]');\n\n if (!manifestTag) {\n return [2\n /*return*/\n ];\n }\n\n _a.label = 1;\n\n case 1:\n _a.trys.push([1, 4,, 5]);\n\n return [4\n /*yield*/\n , fetch(manifestTag.href)];\n\n case 2:\n response = _a.sent();\n return [4\n /*yield*/\n , response.json()];\n\n case 3:\n manifestContent = _a.sent();\n return [3\n /*break*/\n , 5];\n\n case 4:\n e_1 = _a.sent(); // If the download or parsing fails allow check.\n // We only want to error if we KNOW that the gcm_sender_id is incorrect.\n\n return [2\n /*return*/\n ];\n\n case 5:\n if (!manifestContent || !manifestContent.gcm_sender_id) {\n return [2\n /*return*/\n ];\n }\n\n if (manifestContent.gcm_sender_id !== '103953800507') {\n throw errorFactory.create(ERROR_CODES.INCORRECT_GCM_SENDER_ID);\n }\n\n return [2\n /*return*/\n ];\n }\n });\n });\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction registerMessaging(instance) {\n var messagingName = 'messaging';\n\n var factoryMethod = function factoryMethod(app) {\n if (!isSupported()) {\n throw errorFactory.create(ERROR_CODES.UNSUPPORTED_BROWSER);\n }\n\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // Running in ServiceWorker context\n return new SwController(app);\n } else {\n // Assume we are in the window context.\n return new WindowController(app);\n }\n };\n\n var namespaceExports = {\n isSupported: isSupported\n };\n instance.INTERNAL.registerService(messagingName, factoryMethod, namespaceExports);\n}\n\nregisterMessaging(firebase);\n\nfunction isSupported() {\n if (self && 'ServiceWorkerGlobalScope' in self) {\n // Running in ServiceWorker context\n return isSWControllerSupported();\n } else {\n // Assume we are in the window context.\n return isWindowControllerSupported();\n }\n}\n/**\r\n * Checks to see if the required APIs exist.\r\n */\n\n\nfunction isWindowControllerSupported() {\n return navigator.cookieEnabled && 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window && 'fetch' in window && ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') && PushSubscription.prototype.hasOwnProperty('getKey');\n}\n/**\r\n * Checks to see if the required APIs exist within SW Context.\r\n */\n\n\nfunction isSWControllerSupported() {\n return 'PushManager' in self && 'Notification' in self && ServiceWorkerRegistration.prototype.hasOwnProperty('showNotification') && PushSubscription.prototype.hasOwnProperty('getKey');\n}\n\nexport { registerMessaging, isSupported };","import firebase from '@firebase/app';\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @fileoverview Constants used in the Firebase Storage library.\r\n */\n\n/**\r\n * Domain and scheme for API calls.\r\n */\n\nvar domainBase = 'https://firebasestorage.googleapis.com';\n/**\r\n * Domain and scheme for object downloads.\r\n */\n\nvar downloadBase = 'https://firebasestorage.googleapis.com';\n/**\r\n * Base URL for non-upload calls to the API.\r\n */\n\nvar apiBaseUrl = '/v0';\n/**\r\n * Base URL for upload calls to the API.\r\n */\n\nvar apiUploadBaseUrl = '/v0';\nvar configOption = 'storageBucket';\n/**\r\n * 2 minutes\r\n */\n\nvar defaultMaxOperationRetryTime = 2 * 60 * 1000;\n/**\r\n * 10 minutes\r\n */\n\nvar defaultMaxUploadRetryTime = 10 * 60 * 100;\n/**\r\n * This is the value of Number.MIN_SAFE_INTEGER, which is not well supported\r\n * enough for us to use it directly.\r\n */\n\nvar minSafeInteger = -9007199254740991;\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\nvar FirebaseStorageError =\n/** @class */\nfunction () {\n function FirebaseStorageError(code, message) {\n this.code_ = prependCode(code);\n this.message_ = 'Firebase Storage: ' + message;\n this.serverResponse_ = null;\n this.name_ = 'FirebaseError';\n }\n\n FirebaseStorageError.prototype.codeProp = function () {\n return this.code;\n };\n\n FirebaseStorageError.prototype.codeEquals = function (code) {\n return prependCode(code) === this.codeProp();\n };\n\n FirebaseStorageError.prototype.serverResponseProp = function () {\n return this.serverResponse_;\n };\n\n FirebaseStorageError.prototype.setServerResponseProp = function (serverResponse) {\n this.serverResponse_ = serverResponse;\n };\n\n Object.defineProperty(FirebaseStorageError.prototype, \"name\", {\n get: function get() {\n return this.name_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"code\", {\n get: function get() {\n return this.code_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"message\", {\n get: function get() {\n return this.message_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(FirebaseStorageError.prototype, \"serverResponse\", {\n get: function get() {\n return this.serverResponse_;\n },\n enumerable: true,\n configurable: true\n });\n return FirebaseStorageError;\n}();\n\nvar Code = {\n // Shared between all platforms\n UNKNOWN: 'unknown',\n OBJECT_NOT_FOUND: 'object-not-found',\n BUCKET_NOT_FOUND: 'bucket-not-found',\n PROJECT_NOT_FOUND: 'project-not-found',\n QUOTA_EXCEEDED: 'quota-exceeded',\n UNAUTHENTICATED: 'unauthenticated',\n UNAUTHORIZED: 'unauthorized',\n RETRY_LIMIT_EXCEEDED: 'retry-limit-exceeded',\n INVALID_CHECKSUM: 'invalid-checksum',\n CANCELED: 'canceled',\n // JS specific\n INVALID_EVENT_NAME: 'invalid-event-name',\n INVALID_URL: 'invalid-url',\n INVALID_DEFAULT_BUCKET: 'invalid-default-bucket',\n NO_DEFAULT_BUCKET: 'no-default-bucket',\n CANNOT_SLICE_BLOB: 'cannot-slice-blob',\n SERVER_FILE_WRONG_SIZE: 'server-file-wrong-size',\n NO_DOWNLOAD_URL: 'no-download-url',\n INVALID_ARGUMENT: 'invalid-argument',\n INVALID_ARGUMENT_COUNT: 'invalid-argument-count',\n APP_DELETED: 'app-deleted',\n INVALID_ROOT_OPERATION: 'invalid-root-operation',\n INVALID_FORMAT: 'invalid-format',\n INTERNAL_ERROR: 'internal-error'\n};\n\nfunction prependCode(code) {\n return 'storage/' + code;\n}\n\nfunction unknown() {\n var message = 'An unknown error occurred, please check the error payload for ' + 'server response.';\n return new FirebaseStorageError(Code.UNKNOWN, message);\n}\n\nfunction objectNotFound(path) {\n return new FirebaseStorageError(Code.OBJECT_NOT_FOUND, \"Object '\" + path + \"' does not exist.\");\n}\n\nfunction quotaExceeded(bucket) {\n return new FirebaseStorageError(Code.QUOTA_EXCEEDED, \"Quota for bucket '\" + bucket + \"' exceeded, please view quota on \" + 'https://firebase.google.com/pricing/.');\n}\n\nfunction unauthenticated() {\n var message = 'User is not authenticated, please authenticate using Firebase ' + 'Authentication and try again.';\n return new FirebaseStorageError(Code.UNAUTHENTICATED, message);\n}\n\nfunction unauthorized(path) {\n return new FirebaseStorageError(Code.UNAUTHORIZED, \"User does not have permission to access '\" + path + \"'.\");\n}\n\nfunction retryLimitExceeded() {\n return new FirebaseStorageError(Code.RETRY_LIMIT_EXCEEDED, 'Max retry time for operation exceeded, please try again.');\n}\n\nfunction canceled() {\n return new FirebaseStorageError(Code.CANCELED, 'User canceled the upload/download.');\n}\n\nfunction invalidUrl(url) {\n return new FirebaseStorageError(Code.INVALID_URL, \"Invalid URL '\" + url + \"'.\");\n}\n\nfunction invalidDefaultBucket(bucket) {\n return new FirebaseStorageError(Code.INVALID_DEFAULT_BUCKET, \"Invalid default bucket '\" + bucket + \"'.\");\n}\n\nfunction cannotSliceBlob() {\n return new FirebaseStorageError(Code.CANNOT_SLICE_BLOB, 'Cannot slice blob for upload. Please retry the upload.');\n}\n\nfunction serverFileWrongSize() {\n return new FirebaseStorageError(Code.SERVER_FILE_WRONG_SIZE, 'Server recorded incorrect upload file size, please retry the upload.');\n}\n\nfunction noDownloadURL() {\n return new FirebaseStorageError(Code.NO_DOWNLOAD_URL, 'The given file does not have any download URLs.');\n}\n\nfunction invalidArgument(index, fnName, message) {\n return new FirebaseStorageError(Code.INVALID_ARGUMENT, 'Invalid argument in `' + fnName + '` at index ' + index + ': ' + message);\n}\n\nfunction invalidArgumentCount(argMin, argMax, fnName, real) {\n var countPart;\n var plural;\n\n if (argMin === argMax) {\n countPart = argMin;\n plural = argMin === 1 ? 'argument' : 'arguments';\n } else {\n countPart = 'between ' + argMin + ' and ' + argMax;\n plural = 'arguments';\n }\n\n return new FirebaseStorageError(Code.INVALID_ARGUMENT_COUNT, 'Invalid argument count in `' + fnName + '`: Expected ' + countPart + ' ' + plural + ', received ' + real + '.');\n}\n\nfunction appDeleted() {\n return new FirebaseStorageError(Code.APP_DELETED, 'The Firebase app was deleted.');\n}\n/**\r\n * @param name The name of the operation that was invalid.\r\n */\n\n\nfunction invalidRootOperation(name) {\n return new FirebaseStorageError(Code.INVALID_ROOT_OPERATION, \"The operation '\" + name + \"' cannot be performed on a root reference, create a non-root \" + \"reference using child, such as .child('file.png').\");\n}\n/**\r\n * @param format The format that was not valid.\r\n * @param message A message describing the format violation.\r\n */\n\n\nfunction invalidFormat(format, message) {\n return new FirebaseStorageError(Code.INVALID_FORMAT, \"String does not match format '\" + format + \"': \" + message);\n}\n/**\r\n * @param message A message describing the internal error.\r\n */\n\n\nfunction internalError(message) {\n throw new FirebaseStorageError(Code.INTERNAL_ERROR, 'Internal error: ' + message);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar StringFormat = {\n RAW: 'raw',\n BASE64: 'base64',\n BASE64URL: 'base64url',\n DATA_URL: 'data_url'\n};\n\nfunction formatValidator(stringFormat) {\n switch (stringFormat) {\n case StringFormat.RAW:\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n case StringFormat.DATA_URL:\n return;\n\n default:\n throw 'Expected one of the event types: [' + StringFormat.RAW + ', ' + StringFormat.BASE64 + ', ' + StringFormat.BASE64URL + ', ' + StringFormat.DATA_URL + '].';\n }\n}\n/**\r\n * @struct\r\n */\n\n\nvar StringData =\n/** @class */\nfunction () {\n function StringData(data, opt_contentType) {\n this.data = data;\n this.contentType = opt_contentType || null;\n }\n\n return StringData;\n}();\n\nfunction dataFromString(format, string) {\n switch (format) {\n case StringFormat.RAW:\n return new StringData(utf8Bytes_(string));\n\n case StringFormat.BASE64:\n case StringFormat.BASE64URL:\n return new StringData(base64Bytes_(format, string));\n\n case StringFormat.DATA_URL:\n return new StringData(dataURLBytes_(string), dataURLContentType_(string));\n } // assert(false);\n\n\n throw unknown();\n}\n\nfunction utf8Bytes_(string) {\n var b = [];\n\n for (var i = 0; i < string.length; i++) {\n var c = string.charCodeAt(i);\n\n if (c <= 127) {\n b.push(c);\n } else {\n if (c <= 2047) {\n b.push(192 | c >> 6, 128 | c & 63);\n } else {\n if ((c & 64512) == 55296) {\n // The start of a surrogate pair.\n var valid = i < string.length - 1 && (string.charCodeAt(i + 1) & 64512) == 56320;\n\n if (!valid) {\n // The second surrogate wasn't there.\n b.push(239, 191, 189);\n } else {\n var hi = c;\n var lo = string.charCodeAt(++i);\n c = 65536 | (hi & 1023) << 10 | lo & 1023;\n b.push(240 | c >> 18, 128 | c >> 12 & 63, 128 | c >> 6 & 63, 128 | c & 63);\n }\n } else {\n if ((c & 64512) == 56320) {\n // Invalid low surrogate.\n b.push(239, 191, 189);\n } else {\n b.push(224 | c >> 12, 128 | c >> 6 & 63, 128 | c & 63);\n }\n }\n }\n }\n }\n\n return new Uint8Array(b);\n}\n\nfunction percentEncodedBytes_(string) {\n var decoded;\n\n try {\n decoded = decodeURIComponent(string);\n } catch (e) {\n throw invalidFormat(StringFormat.DATA_URL, 'Malformed data URL.');\n }\n\n return utf8Bytes_(decoded);\n}\n\nfunction base64Bytes_(format, string) {\n switch (format) {\n case StringFormat.BASE64:\n {\n var hasMinus = string.indexOf('-') !== -1;\n var hasUnder = string.indexOf('_') !== -1;\n\n if (hasMinus || hasUnder) {\n var invalidChar = hasMinus ? '-' : '_';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64url encoded?\");\n }\n\n break;\n }\n\n case StringFormat.BASE64URL:\n {\n var hasPlus = string.indexOf('+') !== -1;\n var hasSlash = string.indexOf('/') !== -1;\n\n if (hasPlus || hasSlash) {\n var invalidChar = hasPlus ? '+' : '/';\n throw invalidFormat(format, \"Invalid character '\" + invalidChar + \"' found: is it base64 encoded?\");\n }\n\n string = string.replace(/-/g, '+').replace(/_/g, '/');\n break;\n }\n }\n\n var bytes;\n\n try {\n bytes = atob(string);\n } catch (e) {\n throw invalidFormat(format, 'Invalid character found');\n }\n\n var array = new Uint8Array(bytes.length);\n\n for (var i = 0; i < bytes.length; i++) {\n array[i] = bytes.charCodeAt(i);\n }\n\n return array;\n}\n/**\r\n * @struct\r\n */\n\n\nvar DataURLParts =\n/** @class */\nfunction () {\n function DataURLParts(dataURL) {\n this.base64 = false;\n this.contentType = null;\n var matches = dataURL.match(/^data:([^,]+)?,/);\n\n if (matches === null) {\n throw invalidFormat(StringFormat.DATA_URL, \"Must be formatted 'data:[][;base64],\");\n }\n\n var middle = matches[1] || null;\n\n if (middle != null) {\n this.base64 = endsWith(middle, ';base64');\n this.contentType = this.base64 ? middle.substring(0, middle.length - ';base64'.length) : middle;\n }\n\n this.rest = dataURL.substring(dataURL.indexOf(',') + 1);\n }\n\n return DataURLParts;\n}();\n\nfunction dataURLBytes_(string) {\n var parts = new DataURLParts(string);\n\n if (parts.base64) {\n return base64Bytes_(StringFormat.BASE64, parts.rest);\n } else {\n return percentEncodedBytes_(parts.rest);\n }\n}\n\nfunction dataURLContentType_(string) {\n var parts = new DataURLParts(string);\n return parts.contentType;\n}\n\nfunction endsWith(s, end) {\n var longEnough = s.length >= end.length;\n\n if (!longEnough) {\n return false;\n }\n\n return s.substring(s.length - end.length) === end;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nvar TaskEvent = {\n /** Triggered whenever the task changes or progress is updated. */\n STATE_CHANGED: 'state_changed'\n};\nvar InternalTaskState = {\n RUNNING: 'running',\n PAUSING: 'pausing',\n PAUSED: 'paused',\n SUCCESS: 'success',\n CANCELING: 'canceling',\n CANCELED: 'canceled',\n ERROR: 'error'\n};\nvar TaskState = {\n /** The task is currently transferring data. */\n RUNNING: 'running',\n\n /** The task was paused by the user. */\n PAUSED: 'paused',\n\n /** The task completed successfully. */\n SUCCESS: 'success',\n\n /** The task was canceled. */\n CANCELED: 'canceled',\n\n /** The task failed with an error. */\n ERROR: 'error'\n};\n\nfunction taskStateFromInternalTaskState(state) {\n switch (state) {\n case InternalTaskState.RUNNING:\n case InternalTaskState.PAUSING:\n case InternalTaskState.CANCELING:\n return TaskState.RUNNING;\n\n case InternalTaskState.PAUSED:\n return TaskState.PAUSED;\n\n case InternalTaskState.SUCCESS:\n return TaskState.SUCCESS;\n\n case InternalTaskState.CANCELED:\n return TaskState.CANCELED;\n\n case InternalTaskState.ERROR:\n return TaskState.ERROR;\n\n default:\n // TODO(andysoto): assert(false);\n return TaskState.ERROR;\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @fileoverview Contains methods for working with objects.\r\n */\n\n\nfunction contains(obj, prop) {\n return Object.prototype.hasOwnProperty.call(obj, prop);\n}\n\nfunction forEach(obj, f) {\n for (var key in obj) {\n if (contains(obj, key)) {\n f(key, obj[key]);\n }\n }\n}\n\nfunction clone(obj) {\n if (obj == null) {\n return {};\n }\n\n var c = {};\n forEach(obj, function (key, val) {\n c[key] = val;\n });\n return c;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @fileoverview Implements the promise abstraction interface for external\r\n * (public SDK) packaging, which just passes through to the firebase-app impl.\r\n */\n\n/**\r\n * @template T\r\n * @param {function((function(T): void),\r\n * (function(!Error): void))} resolver\r\n */\n\n\nfunction make(resolver) {\n return new Promise(resolver);\n}\n/**\r\n * @template T\r\n */\n\n\nfunction resolve(value) {\n return Promise.resolve(value);\n}\n\nfunction reject(error) {\n return Promise.reject(error);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @return False if the object is undefined or null, true otherwise.\r\n */\n\n\nfunction isDef(p) {\n return p != null;\n}\n\nfunction isJustDef(p) {\n return p !== void 0;\n}\n\nfunction isFunction(p) {\n return typeof p === 'function';\n}\n\nfunction isObject(p) {\n return typeof p === 'object';\n}\n\nfunction isNonNullObject(p) {\n return isObject(p) && p !== null;\n}\n\nfunction isNonArrayObject(p) {\n return isObject(p) && !Array.isArray(p);\n}\n\nfunction isString(p) {\n return typeof p === 'string' || p instanceof String;\n}\n\nfunction isNumber(p) {\n return typeof p === 'number' || p instanceof Number;\n}\n\nfunction isNativeBlob(p) {\n return isNativeBlobDefined() && p instanceof Blob;\n}\n\nfunction isNativeBlobDefined() {\n return typeof Blob !== 'undefined';\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @enum{number}\r\n */\n\n\nvar ErrorCode;\n\n(function (ErrorCode) {\n ErrorCode[ErrorCode[\"NO_ERROR\"] = 0] = \"NO_ERROR\";\n ErrorCode[ErrorCode[\"NETWORK_ERROR\"] = 1] = \"NETWORK_ERROR\";\n ErrorCode[ErrorCode[\"ABORT\"] = 2] = \"ABORT\";\n})(ErrorCode || (ErrorCode = {}));\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * We use this instead of goog.net.XhrIo because goog.net.XhrIo is hyuuuuge and\r\n * doesn't work in React Native on Android.\r\n */\n\n\nvar NetworkXhrIo =\n/** @class */\nfunction () {\n function NetworkXhrIo() {\n var _this = this;\n\n this.sent_ = false;\n this.xhr_ = new XMLHttpRequest();\n this.errorCode_ = ErrorCode.NO_ERROR;\n this.sendPromise_ = make(function (resolve$$1, reject$$1) {\n _this.xhr_.addEventListener('abort', function (event) {\n _this.errorCode_ = ErrorCode.ABORT;\n resolve$$1(_this);\n });\n\n _this.xhr_.addEventListener('error', function (event) {\n _this.errorCode_ = ErrorCode.NETWORK_ERROR;\n resolve$$1(_this);\n });\n\n _this.xhr_.addEventListener('load', function (event) {\n resolve$$1(_this);\n });\n });\n }\n /**\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.send = function (url, method, opt_body, opt_headers) {\n var _this = this;\n\n if (this.sent_) {\n throw internalError('cannot .send() more than once');\n }\n\n this.sent_ = true;\n this.xhr_.open(method, url, true);\n\n if (isDef(opt_headers)) {\n var headers = opt_headers;\n forEach(headers, function (key, val) {\n _this.xhr_.setRequestHeader(key, val.toString());\n });\n }\n\n if (isDef(opt_body)) {\n this.xhr_.send(opt_body);\n } else {\n this.xhr_.send();\n }\n\n return this.sendPromise_;\n };\n /**\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.getErrorCode = function () {\n if (!this.sent_) {\n throw internalError('cannot .getErrorCode() before sending');\n }\n\n return this.errorCode_;\n };\n /**\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.getStatus = function () {\n if (!this.sent_) {\n throw internalError('cannot .getStatus() before sending');\n }\n\n try {\n return this.xhr_.status;\n } catch (e) {\n return -1;\n }\n };\n /**\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.getResponseText = function () {\n if (!this.sent_) {\n throw internalError('cannot .getResponseText() before sending');\n }\n\n return this.xhr_.responseText;\n };\n /**\r\n * Aborts the request.\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.abort = function () {\n this.xhr_.abort();\n };\n /**\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.getResponseHeader = function (header) {\n return this.xhr_.getResponseHeader(header);\n };\n /**\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.addUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.addEventListener('progress', listener);\n }\n };\n /**\r\n * @override\r\n */\n\n\n NetworkXhrIo.prototype.removeUploadProgressListener = function (listener) {\n if (isDef(this.xhr_.upload)) {\n this.xhr_.upload.removeEventListener('progress', listener);\n }\n };\n\n return NetworkXhrIo;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Factory-like class for creating XhrIo instances.\r\n */\n\n\nvar XhrIoPool =\n/** @class */\nfunction () {\n function XhrIoPool() {}\n\n XhrIoPool.prototype.createXhrIo = function () {\n return new NetworkXhrIo();\n };\n\n return XhrIoPool;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Returns the Object resulting from parsing the given JSON, or null if the\r\n * given string does not represent a JSON object.\r\n */\n\n\nfunction jsonObjectOrNull(s) {\n var obj;\n\n try {\n obj = JSON.parse(s);\n } catch (e) {\n return null;\n }\n\n if (isNonArrayObject(obj)) {\n return obj;\n } else {\n return null;\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @struct\r\n */\n\n\nvar Location =\n/** @class */\nfunction () {\n function Location(bucket, path) {\n this.bucket = bucket;\n this.path_ = path;\n }\n\n Object.defineProperty(Location.prototype, \"path\", {\n get: function get() {\n return this.path_;\n },\n enumerable: true,\n configurable: true\n });\n\n Location.prototype.fullServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);\n };\n\n Location.prototype.bucketOnlyServerUrl = function () {\n var encode = encodeURIComponent;\n return '/b/' + encode(this.bucket) + '/o';\n };\n\n Location.makeFromBucketSpec = function (bucketString) {\n var bucketLocation;\n\n try {\n bucketLocation = Location.makeFromUrl(bucketString);\n } catch (e) {\n // Not valid URL, use as-is. This lets you put bare bucket names in\n // config.\n return new Location(bucketString, '');\n }\n\n if (bucketLocation.path === '') {\n return bucketLocation;\n } else {\n throw invalidDefaultBucket(bucketString);\n }\n };\n\n Location.makeFromUrl = function (url) {\n var location = null;\n var bucketDomain = '([A-Za-z0-9.\\\\-_]+)';\n\n function gsModify(loc) {\n if (loc.path.charAt(loc.path.length - 1) === '/') {\n loc.path_ = loc.path_.slice(0, -1);\n }\n }\n\n var gsPath = '(/(.*))?$';\n var path = '(/([^?#]*).*)?$';\n var gsRegex = new RegExp('^gs://' + bucketDomain + gsPath, 'i');\n var gsIndices = {\n bucket: 1,\n path: 3\n };\n\n function httpModify(loc) {\n loc.path_ = decodeURIComponent(loc.path);\n }\n\n var version = 'v[A-Za-z0-9_]+';\n var httpRegex = new RegExp('^https?://firebasestorage\\\\.googleapis\\\\.com/' + version + '/b/' + bucketDomain + '/o' + path, 'i');\n var httpIndices = {\n bucket: 1,\n path: 3\n };\n var groups = [{\n regex: gsRegex,\n indices: gsIndices,\n postModify: gsModify\n }, {\n regex: httpRegex,\n indices: httpIndices,\n postModify: httpModify\n }];\n\n for (var i = 0; i < groups.length; i++) {\n var group = groups[i];\n var captures = group.regex.exec(url);\n\n if (captures) {\n var bucketValue = captures[group.indices.bucket];\n var pathValue = captures[group.indices.path];\n\n if (!pathValue) {\n pathValue = '';\n }\n\n location = new Location(bucketValue, pathValue);\n group.postModify(location);\n break;\n }\n }\n\n if (location == null) {\n throw invalidUrl(url);\n }\n\n return location;\n };\n\n return Location;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @fileoverview Contains helper methods for manipulating paths.\r\n */\n\n/**\r\n * @return Null if the path is already at the root.\r\n */\n\n\nfunction parent(path) {\n if (path.length == 0) {\n return null;\n }\n\n var index = path.lastIndexOf('/');\n\n if (index === -1) {\n return '';\n }\n\n var newPath = path.slice(0, index);\n return newPath;\n}\n\nfunction child(path, childPath) {\n var canonicalChildPath = childPath.split('/').filter(function (component) {\n return component.length > 0;\n }).join('/');\n\n if (path.length === 0) {\n return canonicalChildPath;\n } else {\n return path + '/' + canonicalChildPath;\n }\n}\n/**\r\n * Returns the last component of a path.\r\n * '/foo/bar' -> 'bar'\r\n * '/foo/bar/baz/' -> 'baz/'\r\n * '/a' -> 'a'\r\n */\n\n\nfunction lastComponent(path) {\n var index = path.lastIndexOf('/', path.length - 2);\n\n if (index === -1) {\n return path;\n } else {\n return path.slice(index + 1);\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction makeNormalUrl(urlPart) {\n return domainBase + apiBaseUrl + urlPart;\n}\n\nfunction makeDownloadUrl(urlPart) {\n return downloadBase + apiBaseUrl + urlPart;\n}\n\nfunction makeUploadUrl(urlPart) {\n return domainBase + apiUploadBaseUrl + urlPart;\n}\n\nfunction makeQueryString(params) {\n var encode = encodeURIComponent;\n var queryPart = '?';\n forEach(params, function (key, val) {\n var nextPart = encode(key) + '=' + encode(val);\n queryPart = queryPart + nextPart + '&';\n }); // Chop off the extra '&' or '?' on the end\n\n queryPart = queryPart.slice(0, -1);\n return queryPart;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nfunction noXform_(metadata, value) {\n return value;\n}\n/**\r\n * @struct\r\n */\n\n\nvar Mapping =\n/** @class */\nfunction () {\n function Mapping(server, opt_local, opt_writable, opt_xform) {\n this.server = server;\n this.local = opt_local || server;\n this.writable = !!opt_writable;\n this.xform = opt_xform || noXform_;\n }\n\n return Mapping;\n}();\n\nvar mappings_ = null;\n\nfunction xformPath(fullPath) {\n var valid = isString(fullPath);\n\n if (!valid || fullPath.length < 2) {\n return fullPath;\n } else {\n fullPath = fullPath;\n return lastComponent(fullPath);\n }\n}\n\nfunction getMappings() {\n if (mappings_) {\n return mappings_;\n }\n\n var mappings = [];\n mappings.push(new Mapping('bucket'));\n mappings.push(new Mapping('generation'));\n mappings.push(new Mapping('metageneration'));\n mappings.push(new Mapping('name', 'fullPath', true));\n\n function mappingsXformPath(metadata, fullPath) {\n return xformPath(fullPath);\n }\n\n var nameMapping = new Mapping('name');\n nameMapping.xform = mappingsXformPath;\n mappings.push(nameMapping);\n /**\r\n * Coerces the second param to a number, if it is defined.\r\n */\n\n function xformSize(metadata, size) {\n if (isDef(size)) {\n return +size;\n } else {\n return size;\n }\n }\n\n var sizeMapping = new Mapping('size');\n sizeMapping.xform = xformSize;\n mappings.push(sizeMapping);\n mappings.push(new Mapping('timeCreated'));\n mappings.push(new Mapping('updated'));\n mappings.push(new Mapping('md5Hash', null, true));\n mappings.push(new Mapping('cacheControl', null, true));\n mappings.push(new Mapping('contentDisposition', null, true));\n mappings.push(new Mapping('contentEncoding', null, true));\n mappings.push(new Mapping('contentLanguage', null, true));\n mappings.push(new Mapping('contentType', null, true));\n mappings.push(new Mapping('metadata', 'customMetadata', true));\n mappings_ = mappings;\n return mappings_;\n}\n\nfunction addRef(metadata, authWrapper) {\n function generateRef() {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var loc = new Location(bucket, path);\n return authWrapper.makeStorageReference(loc);\n }\n\n Object.defineProperty(metadata, 'ref', {\n get: generateRef\n });\n}\n\nfunction fromResource(authWrapper, resource, mappings) {\n var metadata = {};\n metadata['type'] = 'file';\n var len = mappings.length;\n\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n metadata[mapping.local] = mapping.xform(metadata, resource[mapping.server]);\n }\n\n addRef(metadata, authWrapper);\n return metadata;\n}\n\nfunction fromResourceString(authWrapper, resourceString, mappings) {\n var obj = jsonObjectOrNull(resourceString);\n\n if (obj === null) {\n return null;\n }\n\n var resource = obj;\n return fromResource(authWrapper, resource, mappings);\n}\n\nfunction downloadUrlFromResourceString(metadata, resourceString) {\n var obj = jsonObjectOrNull(resourceString);\n\n if (obj === null) {\n return null;\n }\n\n if (!isString(obj['downloadTokens'])) {\n // This can happen if objects are uploaded through GCS and retrieved\n // through list, so we don't want to throw an Error.\n return null;\n }\n\n var tokens = obj['downloadTokens'];\n\n if (tokens.length === 0) {\n return null;\n }\n\n var encode = encodeURIComponent;\n var tokensList = tokens.split(',');\n var urls = tokensList.map(function (token) {\n var bucket = metadata['bucket'];\n var path = metadata['fullPath'];\n var urlPart = '/b/' + encode(bucket) + '/o/' + encode(path);\n var base = makeDownloadUrl(urlPart);\n var queryString = makeQueryString({\n alt: 'media',\n token: token\n });\n return base + queryString;\n });\n return urls[0];\n}\n\nfunction toResourceString(metadata, mappings) {\n var resource = {};\n var len = mappings.length;\n\n for (var i = 0; i < len; i++) {\n var mapping = mappings[i];\n\n if (mapping.writable) {\n resource[mapping.server] = metadata[mapping.local];\n }\n }\n\n return JSON.stringify(resource);\n}\n\nfunction metadataValidator(p) {\n var validType = p && isObject(p);\n\n if (!validType) {\n throw 'Expected Metadata object.';\n }\n\n for (var key in p) {\n var val = p[key];\n\n if (key === 'customMetadata') {\n if (!isObject(val)) {\n throw 'Expected object for \\'customMetadata\\' mapping.';\n }\n } else {\n if (isNonNullObject(val)) {\n throw \"Mapping for '\" + key + \"' cannot be an object.\";\n }\n }\n }\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @param name Name of the function.\r\n * @param specs Argument specs.\r\n * @param passed The actual arguments passed to the function.\r\n * @throws {fbs.Error} If the arguments are invalid.\r\n */\n\n\nfunction validate(name, specs, passed) {\n var minArgs = specs.length;\n var maxArgs = specs.length;\n\n for (var i = 0; i < specs.length; i++) {\n if (specs[i].optional) {\n minArgs = i;\n break;\n }\n }\n\n var validLength = minArgs <= passed.length && passed.length <= maxArgs;\n\n if (!validLength) {\n throw invalidArgumentCount(minArgs, maxArgs, name, passed.length);\n }\n\n for (var i = 0; i < passed.length; i++) {\n try {\n specs[i].validator(passed[i]);\n } catch (e) {\n if (e instanceof Error) {\n throw invalidArgument(i, name, e.message);\n } else {\n throw invalidArgument(i, name, e);\n }\n }\n }\n}\n/**\r\n * @struct\r\n */\n\n\nvar ArgSpec =\n/** @class */\nfunction () {\n function ArgSpec(validator, opt_optional) {\n var self = this;\n\n this.validator = function (p) {\n if (self.optional && !isJustDef(p)) {\n return;\n }\n\n validator(p);\n };\n\n this.optional = !!opt_optional;\n }\n\n return ArgSpec;\n}();\n\nfunction and_(v1, v2) {\n return function (p) {\n v1(p);\n v2(p);\n };\n}\n\nfunction stringSpec(opt_validator, opt_optional) {\n function stringValidator(p) {\n if (!isString(p)) {\n throw 'Expected string.';\n }\n }\n\n var validator;\n\n if (opt_validator) {\n validator = and_(stringValidator, opt_validator);\n } else {\n validator = stringValidator;\n }\n\n return new ArgSpec(validator, opt_optional);\n}\n\nfunction uploadDataSpec() {\n function validator(p) {\n var valid = p instanceof Uint8Array || p instanceof ArrayBuffer || isNativeBlobDefined() && p instanceof Blob;\n\n if (!valid) {\n throw 'Expected Blob or File.';\n }\n }\n\n return new ArgSpec(validator);\n}\n\nfunction metadataSpec(opt_optional) {\n return new ArgSpec(metadataValidator, opt_optional);\n}\n\nfunction nonNegativeNumberSpec() {\n function validator(p) {\n var valid = isNumber(p) && p >= 0;\n\n if (!valid) {\n throw 'Expected a number 0 or greater.';\n }\n }\n\n return new ArgSpec(validator);\n}\n\nfunction looseObjectSpec(opt_validator, opt_optional) {\n function validator(p) {\n var isLooseObject = p === null || isDef(p) && p instanceof Object;\n\n if (!isLooseObject) {\n throw 'Expected an Object.';\n }\n\n if (opt_validator !== undefined && opt_validator !== null) {\n opt_validator(p);\n }\n }\n\n return new ArgSpec(validator, opt_optional);\n}\n\nfunction nullFunctionSpec(opt_optional) {\n function validator(p) {\n var valid = p === null || isFunction(p);\n\n if (!valid) {\n throw 'Expected a Function.';\n }\n }\n\n return new ArgSpec(validator, opt_optional);\n}\n\nfunction getBlobBuilder() {\n if (typeof BlobBuilder !== 'undefined') {\n return BlobBuilder;\n } else if (typeof WebKitBlobBuilder !== 'undefined') {\n return WebKitBlobBuilder;\n } else {\n return undefined;\n }\n}\n/**\r\n * Concatenates one or more values together and converts them to a Blob.\r\n *\r\n * @param var_args The values that will make up the resulting blob.\r\n * @return The blob.\r\n */\n\n\nfunction getBlob() {\n var var_args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n\n var BlobBuilder = getBlobBuilder();\n\n if (BlobBuilder !== undefined) {\n var bb = new BlobBuilder();\n\n for (var i = 0; i < var_args.length; i++) {\n bb.append(var_args[i]);\n }\n\n return bb.getBlob();\n } else {\n if (isNativeBlobDefined()) {\n return new Blob(var_args);\n } else {\n throw Error(\"This browser doesn't seem to support creating Blobs\");\n }\n }\n}\n/**\r\n * Slices the blob. The returned blob contains data from the start byte\r\n * (inclusive) till the end byte (exclusive). Negative indices cannot be used.\r\n *\r\n * @param blob The blob to be sliced.\r\n * @param start Index of the starting byte.\r\n * @param end Index of the ending byte.\r\n * @return The blob slice or null if not supported.\r\n */\n\n\nfunction sliceBlob(blob, start, end) {\n if (blob.webkitSlice) {\n return blob.webkitSlice(start, end);\n } else if (blob.mozSlice) {\n return blob.mozSlice(start, end);\n } else if (blob.slice) {\n return blob.slice(start, end);\n }\n\n return null;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @param opt_elideCopy If true, doesn't copy mutable input data\r\n * (e.g. Uint8Arrays). Pass true only if you know the objects will not be\r\n * modified after this blob's construction.\r\n */\n\n\nvar FbsBlob =\n/** @class */\nfunction () {\n function FbsBlob(data, opt_elideCopy) {\n var size = 0;\n var blobType = '';\n\n if (isNativeBlob(data)) {\n this.data_ = data;\n size = data.size;\n blobType = data.type;\n } else if (data instanceof ArrayBuffer) {\n if (opt_elideCopy) {\n this.data_ = new Uint8Array(data);\n } else {\n this.data_ = new Uint8Array(data.byteLength);\n this.data_.set(new Uint8Array(data));\n }\n\n size = this.data_.length;\n } else if (data instanceof Uint8Array) {\n if (opt_elideCopy) {\n this.data_ = data;\n } else {\n this.data_ = new Uint8Array(data.length);\n this.data_.set(data);\n }\n\n size = data.length;\n }\n\n this.size_ = size;\n this.type_ = blobType;\n }\n\n FbsBlob.prototype.size = function () {\n return this.size_;\n };\n\n FbsBlob.prototype.type = function () {\n return this.type_;\n };\n\n FbsBlob.prototype.slice = function (startByte, endByte) {\n if (isNativeBlob(this.data_)) {\n var realBlob = this.data_;\n var sliced = sliceBlob(realBlob, startByte, endByte);\n\n if (sliced === null) {\n return null;\n }\n\n return new FbsBlob(sliced);\n } else {\n var slice = new Uint8Array(this.data_.buffer, startByte, endByte - startByte);\n return new FbsBlob(slice, true);\n }\n };\n\n FbsBlob.getBlob = function () {\n var var_args = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n var_args[_i] = arguments[_i];\n }\n\n if (isNativeBlobDefined()) {\n var blobby = var_args.map(function (val) {\n if (val instanceof FbsBlob) {\n return val.data_;\n } else {\n return val;\n }\n });\n return new FbsBlob(getBlob.apply(null, blobby));\n } else {\n var uint8Arrays = var_args.map(function (val) {\n if (isString(val)) {\n return dataFromString(StringFormat.RAW, val).data;\n } else {\n // Blobs don't exist, so this has to be a Uint8Array.\n return val.data_;\n }\n });\n var finalLength_1 = 0;\n uint8Arrays.forEach(function (array) {\n finalLength_1 += array.byteLength;\n });\n var merged_1 = new Uint8Array(finalLength_1);\n var index_1 = 0;\n uint8Arrays.forEach(function (array) {\n for (var i = 0; i < array.length; i++) {\n merged_1[index_1++] = array[i];\n }\n });\n return new FbsBlob(merged_1, true);\n }\n };\n\n FbsBlob.prototype.uploadData = function () {\n return this.data_;\n };\n\n return FbsBlob;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Returns true if the object is contained in the array (compared with ===).\r\n * @template T\r\n */\n\n\nfunction contains$1(array, elem) {\n return array.indexOf(elem) !== -1;\n}\n/**\r\n * Returns a shallow copy of the array or array-like object (e.g. arguments).\r\n * @template T\r\n */\n\n\nfunction clone$1(arraylike) {\n return Array.prototype.slice.call(arraylike);\n}\n/**\r\n * Removes the given element from the given array, if it is contained.\r\n * Directly modifies the passed-in array.\r\n * @template T\r\n */\n\n\nfunction remove(array, elem) {\n var i = array.indexOf(elem);\n\n if (i !== -1) {\n array.splice(i, 1);\n }\n}\n\nvar RequestInfo =\n/** @class */\nfunction () {\n function RequestInfo(url, method,\n /**\r\n * Returns the value with which to resolve the request's promise. Only called\r\n * if the request is successful. Throw from this function to reject the\r\n * returned Request's promise with the thrown error.\r\n * Note: The XhrIo passed to this function may be reused after this callback\r\n * returns. Do not keep a reference to it in any way.\r\n */\n handler, timeout) {\n this.url = url;\n this.method = method;\n this.handler = handler;\n this.timeout = timeout;\n this.urlParams = {};\n this.headers = {};\n this.body = null;\n this.errorHandler = null;\n /**\r\n * Called with the current number of bytes uploaded and total size (-1 if not\r\n * computable) of the request body (i.e. used to report upload progress).\r\n */\n\n this.progressCallback = null;\n this.successCodes = [200];\n this.additionalRetryCodes = [];\n }\n\n return RequestInfo;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Throws the UNKNOWN FirebaseStorageError if cndn is false.\r\n */\n\n\nfunction handlerCheck(cndn) {\n if (!cndn) {\n throw unknown();\n }\n}\n\nfunction metadataHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return metadata;\n }\n\n return handler;\n}\n\nfunction downloadUrlHandler(authWrapper, mappings) {\n function handler(xhr, text) {\n var metadata = fromResourceString(authWrapper, text, mappings);\n handlerCheck(metadata !== null);\n return downloadUrlFromResourceString(metadata, text);\n }\n\n return handler;\n}\n\nfunction sharedErrorHandler(location) {\n function errorHandler(xhr, err) {\n var newErr;\n\n if (xhr.getStatus() === 401) {\n newErr = unauthenticated();\n } else {\n if (xhr.getStatus() === 402) {\n newErr = quotaExceeded(location.bucket);\n } else {\n if (xhr.getStatus() === 403) {\n newErr = unauthorized(location.path);\n } else {\n newErr = err;\n }\n }\n }\n\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n\n return errorHandler;\n}\n\nfunction objectErrorHandler(location) {\n var shared = sharedErrorHandler(location);\n\n function errorHandler(xhr, err) {\n var newErr = shared(xhr, err);\n\n if (xhr.getStatus() === 404) {\n newErr = objectNotFound(location.path);\n }\n\n newErr.setServerResponseProp(err.serverResponseProp());\n return newErr;\n }\n\n return errorHandler;\n}\n\nfunction getMetadata(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nfunction getDownloadUrl(authWrapper, location, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'GET';\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, downloadUrlHandler(authWrapper, mappings), timeout);\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nfunction updateMetadata(authWrapper, location, metadata, mappings) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'PATCH';\n var body = toResourceString(metadata, mappings);\n var headers = {\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var timeout = authWrapper.maxOperationRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nfunction deleteObject(authWrapper, location) {\n var urlPart = location.fullServerUrl();\n var url = makeNormalUrl(urlPart);\n var method = 'DELETE';\n var timeout = authWrapper.maxOperationRetryTime();\n\n function handler(xhr, text) {}\n\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.successCodes = [200, 204];\n requestInfo.errorHandler = objectErrorHandler(location);\n return requestInfo;\n}\n\nfunction determineContentType_(metadata, blob) {\n return metadata && metadata['contentType'] || blob && blob.type() || 'application/octet-stream';\n}\n\nfunction metadataForUpload_(location, blob, opt_metadata) {\n var metadata = clone(opt_metadata);\n metadata['fullPath'] = location.path;\n metadata['size'] = blob.size();\n\n if (!metadata['contentType']) {\n metadata['contentType'] = determineContentType_(null, blob);\n }\n\n return metadata;\n}\n\nfunction multipartUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var headers = {\n 'X-Goog-Upload-Protocol': 'multipart'\n };\n\n function genBoundary() {\n var str = '';\n\n for (var i = 0; i < 2; i++) {\n str = str + Math.random().toString().slice(2);\n }\n\n return str;\n }\n\n var boundary = genBoundary();\n headers['Content-Type'] = 'multipart/related; boundary=' + boundary;\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var metadataString = toResourceString(metadata, mappings);\n var preBlobPart = '--' + boundary + '\\r\\n' + 'Content-Type: application/json; charset=utf-8\\r\\n\\r\\n' + metadataString + '\\r\\n--' + boundary + '\\r\\n' + 'Content-Type: ' + metadata['contentType'] + '\\r\\n\\r\\n';\n var postBlobPart = '\\r\\n--' + boundary + '--';\n var body = FbsBlob.getBlob(preBlobPart, blob, postBlobPart);\n\n if (body === null) {\n throw cannotSliceBlob();\n }\n\n var urlParams = {\n name: metadata['fullPath']\n };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, metadataHandler(authWrapper, mappings), timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\r\n * @param current The number of bytes that have been uploaded so far.\r\n * @param total The total number of bytes in the upload.\r\n * @param opt_finalized True if the server has finished the upload.\r\n * @param opt_metadata The upload metadata, should\r\n * only be passed if opt_finalized is true.\r\n * @struct\r\n */\n\n\nvar ResumableUploadStatus =\n/** @class */\nfunction () {\n function ResumableUploadStatus(current, total, finalized, metadata) {\n this.current = current;\n this.total = total;\n this.finalized = !!finalized;\n this.metadata = metadata || null;\n }\n\n return ResumableUploadStatus;\n}();\n\nfunction checkResumeHeader_(xhr, opt_allowed) {\n var status;\n\n try {\n status = xhr.getResponseHeader('X-Goog-Upload-Status');\n } catch (e) {\n handlerCheck(false);\n }\n\n var allowed = opt_allowed || ['active'];\n handlerCheck(contains$1(allowed, status));\n return status;\n}\n\nfunction createResumableUpload(authWrapper, location, mappings, blob, opt_metadata) {\n var urlPart = location.bucketOnlyServerUrl();\n var metadata = metadataForUpload_(location, blob, opt_metadata);\n var urlParams = {\n name: metadata['fullPath']\n };\n var url = makeUploadUrl(urlPart);\n var method = 'POST';\n var headers = {\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': blob.size(),\n 'X-Goog-Upload-Header-Content-Type': metadata['contentType'],\n 'Content-Type': 'application/json; charset=utf-8'\n };\n var body = toResourceString(metadata, mappings);\n var timeout = authWrapper.maxUploadRetryTime();\n\n function handler(xhr, text) {\n checkResumeHeader_(xhr);\n var url;\n\n try {\n url = xhr.getResponseHeader('X-Goog-Upload-URL');\n } catch (e) {\n handlerCheck(false);\n }\n\n handlerCheck(isString(url));\n return url;\n }\n\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.urlParams = urlParams;\n requestInfo.headers = headers;\n requestInfo.body = body;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n */\n\n\nfunction getResumableUploadStatus(authWrapper, location, url, blob) {\n var headers = {\n 'X-Goog-Upload-Command': 'query'\n };\n\n function handler(xhr, text) {\n var status = checkResumeHeader_(xhr, ['active', 'final']);\n var sizeString;\n\n try {\n sizeString = xhr.getResponseHeader('X-Goog-Upload-Size-Received');\n } catch (e) {\n handlerCheck(false);\n }\n\n var size = parseInt(sizeString, 10);\n handlerCheck(!isNaN(size));\n return new ResumableUploadStatus(size, blob.size(), status === 'final');\n }\n\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\r\n * Any uploads via the resumable upload API must transfer a number of bytes\r\n * that is a multiple of this number.\r\n */\n\n\nvar resumableUploadChunkSize = 256 * 1024;\n/**\r\n * @param url From a call to fbs.requests.createResumableUpload.\r\n * @param chunkSize Number of bytes to upload.\r\n * @param opt_status The previous status.\r\n * If not passed or null, we start from the beginning.\r\n * @throws fbs.Error If the upload is already complete, the passed in status\r\n * has a final size inconsistent with the blob, or the blob cannot be sliced\r\n * for upload.\r\n */\n\nfunction continueResumableUpload(location, authWrapper, url, blob, chunkSize, mappings, opt_status, opt_progressCallback) {\n // TODO(andysoto): standardize on internal asserts\n // assert(!(opt_status && opt_status.finalized));\n var status = new ResumableUploadStatus(0, 0);\n\n if (opt_status) {\n status.current = opt_status.current;\n status.total = opt_status.total;\n } else {\n status.current = 0;\n status.total = blob.size();\n }\n\n if (blob.size() !== status.total) {\n throw serverFileWrongSize();\n }\n\n var bytesLeft = status.total - status.current;\n var bytesToUpload = bytesLeft;\n\n if (chunkSize > 0) {\n bytesToUpload = Math.min(bytesToUpload, chunkSize);\n }\n\n var startByte = status.current;\n var endByte = startByte + bytesToUpload;\n var uploadCommand = bytesToUpload === bytesLeft ? 'upload, finalize' : 'upload';\n var headers = {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': status.current\n };\n var body = blob.slice(startByte, endByte);\n\n if (body === null) {\n throw cannotSliceBlob();\n }\n\n function handler(xhr, text) {\n // TODO(andysoto): Verify the MD5 of each uploaded range:\n // the 'x-range-md5' header comes back with status code 308 responses.\n // We'll only be able to bail out though, because you can't re-upload a\n // range that you previously uploaded.\n var uploadStatus = checkResumeHeader_(xhr, ['active', 'final']);\n var newCurrent = status.current + bytesToUpload;\n var size = blob.size();\n var metadata;\n\n if (uploadStatus === 'final') {\n metadata = metadataHandler(authWrapper, mappings)(xhr, text);\n } else {\n metadata = null;\n }\n\n return new ResumableUploadStatus(newCurrent, size, uploadStatus === 'final', metadata);\n }\n\n var method = 'POST';\n var timeout = authWrapper.maxUploadRetryTime();\n var requestInfo = new RequestInfo(url, method, handler, timeout);\n requestInfo.headers = headers;\n requestInfo.body = body.uploadData();\n requestInfo.progressCallback = opt_progressCallback || null;\n requestInfo.errorHandler = sharedErrorHandler(location);\n return requestInfo;\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @struct\r\n */\n\n\nvar Observer =\n/** @class */\nfunction () {\n function Observer(nextOrObserver, opt_error, opt_complete) {\n var asFunctions = isFunction(nextOrObserver) || isDef(opt_error) || isDef(opt_complete);\n\n if (asFunctions) {\n this.next = nextOrObserver;\n this.error = opt_error || null;\n this.complete = opt_complete || null;\n } else {\n var observer = nextOrObserver;\n this.next = observer.next || null;\n this.error = observer.error || null;\n this.complete = observer.complete || null;\n }\n }\n\n return Observer;\n}();\n\nvar UploadTaskSnapshot =\n/** @class */\nfunction () {\n function UploadTaskSnapshot(bytesTransferred, totalBytes, state, metadata, task, ref) {\n this.bytesTransferred = bytesTransferred;\n this.totalBytes = totalBytes;\n this.state = state;\n this.metadata = metadata;\n this.task = task;\n this.ref = ref;\n }\n\n return UploadTaskSnapshot;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Returns a function that invokes f with its arguments asynchronously as a\r\n * microtask, i.e. as soon as possible after the current script returns back\r\n * into browser code.\r\n */\n\n\nfunction async(f) {\n return function () {\n var argsToForward = [];\n\n for (var _i = 0; _i < arguments.length; _i++) {\n argsToForward[_i] = arguments[_i];\n }\n\n resolve(true).then(function () {\n f.apply(null, argsToForward);\n });\n };\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Represents a blob being uploaded. Can be used to pause/resume/cancel the\r\n * upload and manage callbacks for various events.\r\n */\n\n\nvar UploadTask =\n/** @class */\nfunction () {\n /**\r\n * @param ref The firebaseStorage.Reference object this task came\r\n * from, untyped to avoid cyclic dependencies.\r\n * @param blob The blob to upload.\r\n */\n function UploadTask(ref, authWrapper, location, mappings, blob, metadata) {\n if (metadata === void 0) {\n metadata = null;\n }\n\n var _this = this;\n\n this.transferred_ = 0;\n this.needToFetchStatus_ = false;\n this.needToFetchMetadata_ = false;\n this.observers_ = [];\n this.error_ = null;\n this.uploadUrl_ = null;\n this.request_ = null;\n this.chunkMultiplier_ = 1;\n this.resolve_ = null;\n this.reject_ = null;\n this.ref_ = ref;\n this.authWrapper_ = authWrapper;\n this.location_ = location;\n this.blob_ = blob;\n this.metadata_ = metadata;\n this.mappings_ = mappings;\n this.resumable_ = this.shouldDoResumable_(this.blob_);\n this.state_ = InternalTaskState.RUNNING;\n\n this.errorHandler_ = function (error) {\n _this.request_ = null;\n _this.chunkMultiplier_ = 1;\n\n if (error.codeEquals(Code.CANCELED)) {\n _this.needToFetchStatus_ = true;\n\n _this.completeTransitions_();\n } else {\n _this.error_ = error;\n\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n\n this.metadataErrorHandler_ = function (error) {\n _this.request_ = null;\n\n if (error.codeEquals(Code.CANCELED)) {\n _this.completeTransitions_();\n } else {\n _this.error_ = error;\n\n _this.transition_(InternalTaskState.ERROR);\n }\n };\n\n this.promise_ = make(function (resolve$$1, reject$$1) {\n _this.resolve_ = resolve$$1;\n _this.reject_ = reject$$1;\n\n _this.start_();\n }); // Prevent uncaught rejections on the internal promise from bubbling out\n // to the top level with a dummy handler.\n\n this.promise_.then(null, function () {});\n }\n\n UploadTask.prototype.makeProgressCallback_ = function () {\n var _this = this;\n\n var sizeBefore = this.transferred_;\n return function (loaded, total) {\n _this.updateProgress_(sizeBefore + loaded);\n };\n };\n\n UploadTask.prototype.shouldDoResumable_ = function (blob) {\n return blob.size() > 256 * 1024;\n };\n\n UploadTask.prototype.start_ = function () {\n if (this.state_ !== InternalTaskState.RUNNING) {\n // This can happen if someone pauses us in a resume callback, for example.\n return;\n }\n\n if (this.request_ !== null) {\n return;\n }\n\n if (this.resumable_) {\n if (this.uploadUrl_ === null) {\n this.createResumable_();\n } else {\n if (this.needToFetchStatus_) {\n this.fetchStatus_();\n } else {\n if (this.needToFetchMetadata_) {\n // Happens if we miss the metadata on upload completion.\n this.fetchMetadata_();\n } else {\n this.continueUpload_();\n }\n }\n }\n } else {\n this.oneShotUpload_();\n }\n };\n\n UploadTask.prototype.resolveToken_ = function (callback) {\n var _this = this;\n\n this.authWrapper_.getAuthToken().then(function (authToken) {\n switch (_this.state_) {\n case InternalTaskState.RUNNING:\n callback(authToken);\n break;\n\n case InternalTaskState.CANCELING:\n _this.transition_(InternalTaskState.CANCELED);\n\n break;\n\n case InternalTaskState.PAUSING:\n _this.transition_(InternalTaskState.PAUSED);\n\n break;\n\n default:\n }\n });\n }; // TODO(andysoto): assert false\n\n\n UploadTask.prototype.createResumable_ = function () {\n var _this = this;\n\n this.resolveToken_(function (authToken) {\n var requestInfo = createResumableUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n\n var createRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n\n _this.request_ = createRequest;\n createRequest.getPromise().then(function (url) {\n _this.request_ = null;\n _this.uploadUrl_ = url;\n _this.needToFetchStatus_ = false;\n\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n\n UploadTask.prototype.fetchStatus_ = function () {\n var _this = this; // TODO(andysoto): assert(this.uploadUrl_ !== null);\n\n\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo = getResumableUploadStatus(_this.authWrapper_, _this.location_, url, _this.blob_);\n\n var statusRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n\n _this.request_ = statusRequest;\n statusRequest.getPromise().then(function (status) {\n status = status;\n _this.request_ = null;\n\n _this.updateProgress_(status.current);\n\n _this.needToFetchStatus_ = false;\n\n if (status.finalized) {\n _this.needToFetchMetadata_ = true;\n }\n\n _this.completeTransitions_();\n }, _this.errorHandler_);\n });\n };\n\n UploadTask.prototype.continueUpload_ = function () {\n var _this = this;\n\n var chunkSize = resumableUploadChunkSize * this.chunkMultiplier_;\n var status = new ResumableUploadStatus(this.transferred_, this.blob_.size()); // TODO(andysoto): assert(this.uploadUrl_ !== null);\n\n var url = this.uploadUrl_;\n this.resolveToken_(function (authToken) {\n var requestInfo;\n\n try {\n requestInfo = continueResumableUpload(_this.location_, _this.authWrapper_, url, _this.blob_, chunkSize, _this.mappings_, status, _this.makeProgressCallback_());\n } catch (e) {\n _this.error_ = e;\n\n _this.transition_(InternalTaskState.ERROR);\n\n return;\n }\n\n var uploadRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n\n _this.request_ = uploadRequest;\n uploadRequest.getPromise().then(function (newStatus) {\n _this.increaseMultiplier_();\n\n _this.request_ = null;\n\n _this.updateProgress_(newStatus.current);\n\n if (newStatus.finalized) {\n _this.metadata_ = newStatus.metadata;\n\n _this.transition_(InternalTaskState.SUCCESS);\n } else {\n _this.completeTransitions_();\n }\n }, _this.errorHandler_);\n });\n };\n\n UploadTask.prototype.increaseMultiplier_ = function () {\n var currentSize = resumableUploadChunkSize * this.chunkMultiplier_; // Max chunk size is 32M.\n\n if (currentSize < 32 * 1024 * 1024) {\n this.chunkMultiplier_ *= 2;\n }\n };\n\n UploadTask.prototype.fetchMetadata_ = function () {\n var _this = this;\n\n this.resolveToken_(function (authToken) {\n var requestInfo = getMetadata(_this.authWrapper_, _this.location_, _this.mappings_);\n\n var metadataRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n\n _this.request_ = metadataRequest;\n metadataRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.metadataErrorHandler_);\n });\n };\n\n UploadTask.prototype.oneShotUpload_ = function () {\n var _this = this;\n\n this.resolveToken_(function (authToken) {\n var requestInfo = multipartUpload(_this.authWrapper_, _this.location_, _this.mappings_, _this.blob_, _this.metadata_);\n\n var multipartRequest = _this.authWrapper_.makeRequest(requestInfo, authToken);\n\n _this.request_ = multipartRequest;\n multipartRequest.getPromise().then(function (metadata) {\n _this.request_ = null;\n _this.metadata_ = metadata;\n\n _this.updateProgress_(_this.blob_.size());\n\n _this.transition_(InternalTaskState.SUCCESS);\n }, _this.errorHandler_);\n });\n };\n\n UploadTask.prototype.updateProgress_ = function (transferred) {\n var old = this.transferred_;\n this.transferred_ = transferred; // A progress update can make the \"transferred\" value smaller (e.g. a\n // partial upload not completed by server, after which the \"transferred\"\n // value may reset to the value at the beginning of the request).\n\n if (this.transferred_ !== old) {\n this.notifyObservers_();\n }\n };\n\n UploadTask.prototype.transition_ = function (state) {\n if (this.state_ === state) {\n return;\n }\n\n switch (state) {\n case InternalTaskState.CANCELING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n\n break;\n\n case InternalTaskState.PAUSING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING);\n this.state_ = state;\n\n if (this.request_ !== null) {\n this.request_.cancel();\n }\n\n break;\n\n case InternalTaskState.RUNNING:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.PAUSING);\n var wasPaused = this.state_ === InternalTaskState.PAUSED;\n this.state_ = state;\n\n if (wasPaused) {\n this.notifyObservers_();\n this.start_();\n }\n\n break;\n\n case InternalTaskState.PAUSED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n\n case InternalTaskState.CANCELED:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.PAUSED ||\n // this.state_ === InternalTaskState.CANCELING);\n this.error_ = canceled();\n this.state_ = state;\n this.notifyObservers_();\n break;\n\n case InternalTaskState.ERROR:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n\n case InternalTaskState.SUCCESS:\n // TODO(andysoto):\n // assert(this.state_ === InternalTaskState.RUNNING ||\n // this.state_ === InternalTaskState.PAUSING ||\n // this.state_ === InternalTaskState.CANCELING);\n this.state_ = state;\n this.notifyObservers_();\n break;\n }\n };\n\n UploadTask.prototype.completeTransitions_ = function () {\n switch (this.state_) {\n case InternalTaskState.PAUSING:\n this.transition_(InternalTaskState.PAUSED);\n break;\n\n case InternalTaskState.CANCELING:\n this.transition_(InternalTaskState.CANCELED);\n break;\n\n case InternalTaskState.RUNNING:\n this.start_();\n break;\n\n default:\n // TODO(andysoto): assert(false);\n break;\n }\n };\n\n Object.defineProperty(UploadTask.prototype, \"snapshot\", {\n get: function get() {\n var externalState = taskStateFromInternalTaskState(this.state_);\n return new UploadTaskSnapshot(this.transferred_, this.blob_.size(), externalState, this.metadata_, this, this.ref_);\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Adds a callback for an event.\r\n * @param type The type of event to listen for.\r\n */\n\n UploadTask.prototype.on = function (type, nextOrObserver, error, completed) {\n if (nextOrObserver === void 0) {\n nextOrObserver = undefined;\n }\n\n if (error === void 0) {\n error = undefined;\n }\n\n if (completed === void 0) {\n completed = undefined;\n }\n\n function typeValidator(_p) {\n if (type !== TaskEvent.STATE_CHANGED) {\n throw \"Expected one of the event types: [\" + TaskEvent.STATE_CHANGED + \"].\";\n }\n }\n\n var nextOrObserverMessage = 'Expected a function or an Object with one of ' + '`next`, `error`, `complete` properties.';\n var nextValidator = nullFunctionSpec(true).validator;\n var observerValidator = looseObjectSpec(null, true).validator;\n\n function nextOrObserverValidator(p) {\n try {\n nextValidator(p);\n return;\n } catch (e) {}\n\n try {\n observerValidator(p);\n var anyDefined = isJustDef(p['next']) || isJustDef(p['error']) || isJustDef(p['complete']);\n\n if (!anyDefined) {\n throw '';\n }\n\n return;\n } catch (e) {\n throw nextOrObserverMessage;\n }\n }\n\n var specs = [stringSpec(typeValidator), looseObjectSpec(nextOrObserverValidator, true), nullFunctionSpec(true), nullFunctionSpec(true)];\n validate('on', specs, arguments);\n var self = this;\n\n function makeBinder(specs) {\n function binder(nextOrObserver, error, opt_complete) {\n if (specs !== null) {\n validate('on', specs, arguments);\n }\n\n var observer = new Observer(nextOrObserver, error, completed);\n self.addObserver_(observer);\n return function () {\n self.removeObserver_(observer);\n };\n }\n\n return binder;\n }\n\n function binderNextOrObserverValidator(p) {\n if (p === null) {\n throw nextOrObserverMessage;\n }\n\n nextOrObserverValidator(p);\n }\n\n var binderSpecs = [looseObjectSpec(binderNextOrObserverValidator), nullFunctionSpec(true), nullFunctionSpec(true)];\n var typeOnly = !(isJustDef(nextOrObserver) || isJustDef(error) || isJustDef(completed));\n\n if (typeOnly) {\n return makeBinder(binderSpecs);\n } else {\n return makeBinder(null)(nextOrObserver, error, completed);\n }\n };\n /**\r\n * This object behaves like a Promise, and resolves with its snapshot data\r\n * when the upload completes.\r\n * @param onFulfilled The fulfillment callback. Promise chaining works as normal.\r\n * @param onRejected The rejection callback.\r\n */\n\n\n UploadTask.prototype.then = function (onFulfilled, onRejected) {\n // These casts are needed so that TypeScript can infer the types of the\n // resulting Promise.\n return this.promise_.then(onFulfilled, onRejected);\n };\n /**\r\n * Equivalent to calling `then(null, onRejected)`.\r\n */\n\n\n UploadTask.prototype.catch = function (onRejected) {\n return this.then(null, onRejected);\n };\n /**\r\n * Adds the given observer.\r\n */\n\n\n UploadTask.prototype.addObserver_ = function (observer) {\n this.observers_.push(observer);\n this.notifyObserver_(observer);\n };\n /**\r\n * Removes the given observer.\r\n */\n\n\n UploadTask.prototype.removeObserver_ = function (observer) {\n remove(this.observers_, observer);\n };\n\n UploadTask.prototype.notifyObservers_ = function () {\n var _this = this;\n\n this.finishPromise_();\n var observers = clone$1(this.observers_);\n observers.forEach(function (observer) {\n _this.notifyObserver_(observer);\n });\n };\n\n UploadTask.prototype.finishPromise_ = function () {\n if (this.resolve_ !== null) {\n var triggered = true;\n\n switch (taskStateFromInternalTaskState(this.state_)) {\n case TaskState.SUCCESS:\n async(this.resolve_.bind(null, this.snapshot))();\n break;\n\n case TaskState.CANCELED:\n case TaskState.ERROR:\n var toCall = this.reject_;\n async(toCall.bind(null, this.error_))();\n break;\n\n default:\n triggered = false;\n break;\n }\n\n if (triggered) {\n this.resolve_ = null;\n this.reject_ = null;\n }\n }\n };\n\n UploadTask.prototype.notifyObserver_ = function (observer) {\n var externalState = taskStateFromInternalTaskState(this.state_);\n\n switch (externalState) {\n case TaskState.RUNNING:\n case TaskState.PAUSED:\n if (observer.next !== null) {\n async(observer.next.bind(observer, this.snapshot))();\n }\n\n break;\n\n case TaskState.SUCCESS:\n if (observer.complete !== null) {\n async(observer.complete.bind(observer))();\n }\n\n break;\n\n case TaskState.CANCELED:\n case TaskState.ERROR:\n if (observer.error !== null) {\n async(observer.error.bind(observer, this.error_))();\n }\n\n break;\n\n default:\n // TODO(andysoto): assert(false);\n if (observer.error !== null) {\n async(observer.error.bind(observer, this.error_))();\n }\n\n }\n };\n /**\r\n * Resumes a paused task. Has no effect on a currently running or failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\n\n\n UploadTask.prototype.resume = function () {\n validate('resume', [], arguments);\n var valid = this.state_ === InternalTaskState.PAUSED || this.state_ === InternalTaskState.PAUSING;\n\n if (valid) {\n this.transition_(InternalTaskState.RUNNING);\n }\n\n return valid;\n };\n /**\r\n * Pauses a currently running task. Has no effect on a paused or failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\n\n\n UploadTask.prototype.pause = function () {\n validate('pause', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING;\n\n if (valid) {\n this.transition_(InternalTaskState.PAUSING);\n }\n\n return valid;\n };\n /**\r\n * Cancels a currently running or paused task. Has no effect on a complete or\r\n * failed task.\r\n * @return True if the operation took effect, false if ignored.\r\n */\n\n\n UploadTask.prototype.cancel = function () {\n validate('cancel', [], arguments);\n var valid = this.state_ === InternalTaskState.RUNNING || this.state_ === InternalTaskState.PAUSING;\n\n if (valid) {\n this.transition_(InternalTaskState.CANCELING);\n }\n\n return valid;\n };\n\n return UploadTask;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Provides methods to interact with a bucket in the Firebase Storage service.\r\n * @param location An fbs.location, or the URL at\r\n * which to base this object, in one of the following forms:\r\n * gs:///\r\n * http[s]://firebasestorage.googleapis.com/\r\n * /b//o/\r\n * Any query or fragment strings will be ignored in the http[s]\r\n * format. If no value is passed, the storage object will use a URL based on\r\n * the project ID of the base firebase.App instance.\r\n */\n\n\nvar Reference =\n/** @class */\nfunction () {\n function Reference(authWrapper, location) {\n this.authWrapper = authWrapper;\n\n if (location instanceof Location) {\n this.location = location;\n } else {\n this.location = Location.makeFromUrl(location);\n }\n }\n /**\r\n * @return The URL for the bucket and path this object references,\r\n * in the form gs:///\r\n * @override\r\n */\n\n\n Reference.prototype.toString = function () {\n validate('toString', [], arguments);\n return 'gs://' + this.location.bucket + '/' + this.location.path;\n };\n\n Reference.prototype.newRef = function (authWrapper, location) {\n return new Reference(authWrapper, location);\n };\n\n Reference.prototype.mappings = function () {\n return getMappings();\n };\n /**\r\n * @return A reference to the object obtained by\r\n * appending childPath, removing any duplicate, beginning, or trailing\r\n * slashes.\r\n */\n\n\n Reference.prototype.child = function (childPath) {\n validate('child', [stringSpec()], arguments);\n var newPath = child(this.location.path, childPath);\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n };\n\n Object.defineProperty(Reference.prototype, \"parent\", {\n /**\r\n * @return A reference to the parent of the\r\n * current object, or null if the current object is the root.\r\n */\n get: function get() {\n var newPath = parent(this.location.path);\n\n if (newPath === null) {\n return null;\n }\n\n var location = new Location(this.location.bucket, newPath);\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"root\", {\n /**\r\n * @return An reference to the root of this\r\n * object's bucket.\r\n */\n get: function get() {\n var location = new Location(this.location.bucket, '');\n return this.newRef(this.authWrapper, location);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"bucket\", {\n get: function get() {\n return this.location.bucket;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"fullPath\", {\n get: function get() {\n return this.location.path;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"name\", {\n get: function get() {\n return lastComponent(this.location.path);\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Reference.prototype, \"storage\", {\n get: function get() {\n return this.authWrapper.service();\n },\n enumerable: true,\n configurable: true\n });\n /**\r\n * Uploads a blob to this object's location.\r\n * @param data The blob to upload.\r\n * @return An UploadTask that lets you control and\r\n * observe the upload.\r\n */\n\n Reference.prototype.put = function (data, metadata) {\n if (metadata === void 0) {\n metadata = null;\n }\n\n validate('put', [uploadDataSpec(), metadataSpec(true)], arguments);\n this.throwIfRoot_('put');\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data), metadata);\n };\n /**\r\n * Uploads a string to this object's location.\r\n * @param string The string to upload.\r\n * @param opt_format The format of the string to upload.\r\n * @return An UploadTask that lets you control and\r\n * observe the upload.\r\n */\n\n\n Reference.prototype.putString = function (string, format, opt_metadata) {\n if (format === void 0) {\n format = StringFormat.RAW;\n }\n\n validate('putString', [stringSpec(), stringSpec(formatValidator, true), metadataSpec(true)], arguments);\n this.throwIfRoot_('putString');\n var data = dataFromString(format, string);\n var metadata = clone(opt_metadata);\n\n if (!isDef(metadata['contentType']) && isDef(data.contentType)) {\n metadata['contentType'] = data.contentType;\n }\n\n return new UploadTask(this, this.authWrapper, this.location, this.mappings(), new FbsBlob(data.data, true), metadata);\n };\n /**\r\n * Deletes the object at this location.\r\n * @return A promise that resolves if the deletion succeeds.\r\n */\n\n\n Reference.prototype.delete = function () {\n validate('delete', [], arguments);\n this.throwIfRoot_('delete');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = deleteObject(self.authWrapper, self.location);\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\r\n * A promise that resolves with the metadata for this object. If this\r\n * object doesn't exist or metadata cannot be retreived, the promise is\r\n * rejected.\r\n */\n\n\n Reference.prototype.getMetadata = function () {\n validate('getMetadata', [], arguments);\n this.throwIfRoot_('getMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = getMetadata(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\r\n * Updates the metadata for this object.\r\n * @param metadata The new metadata for the object.\r\n * Only values that have been explicitly set will be changed. Explicitly\r\n * setting a value to null will remove the metadata.\r\n * @return A promise that resolves\r\n * with the new metadata for this object.\r\n * @see firebaseStorage.Reference.prototype.getMetadata\r\n */\n\n\n Reference.prototype.updateMetadata = function (metadata) {\n validate('updateMetadata', [metadataSpec()], arguments);\n this.throwIfRoot_('updateMetadata');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = updateMetadata(self.authWrapper, self.location, metadata, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise();\n });\n };\n /**\r\n * @return A promise that resolves with the download\r\n * URL for this object.\r\n */\n\n\n Reference.prototype.getDownloadURL = function () {\n validate('getDownloadURL', [], arguments);\n this.throwIfRoot_('getDownloadURL');\n var self = this;\n return this.authWrapper.getAuthToken().then(function (authToken) {\n var requestInfo = getDownloadUrl(self.authWrapper, self.location, self.mappings());\n return self.authWrapper.makeRequest(requestInfo, authToken).getPromise().then(function (url) {\n if (url === null) {\n throw noDownloadURL();\n }\n\n return url;\n });\n });\n };\n\n Reference.prototype.throwIfRoot_ = function (name) {\n if (this.location.path === '') {\n throw invalidRootOperation(name);\n }\n };\n\n return Reference;\n}();\n/**\r\n * A request whose promise always fails.\r\n * @struct\r\n * @template T\r\n */\n\n\nvar FailRequest =\n/** @class */\nfunction () {\n function FailRequest(error) {\n this.promise_ = reject(error);\n }\n /** @inheritDoc */\n\n\n FailRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n\n\n FailRequest.prototype.cancel = function (appDelete) {\n if (appDelete === void 0) {\n appDelete = false;\n }\n };\n\n return FailRequest;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @struct\r\n */\n\n\nvar RequestMap =\n/** @class */\nfunction () {\n function RequestMap() {\n this.map_ = {};\n this.id_ = minSafeInteger;\n }\n /**\r\n * Registers the given request with this map.\r\n * The request is unregistered when it completes.\r\n * @param r The request to register.\r\n */\n\n\n RequestMap.prototype.addRequest = function (r) {\n var id = this.id_;\n this.id_++;\n this.map_[id] = r;\n var self = this;\n\n function unmap() {\n delete self.map_[id];\n }\n\n r.getPromise().then(unmap, unmap);\n };\n /**\r\n * Cancels all registered requests.\r\n */\n\n\n RequestMap.prototype.clear = function () {\n forEach(this.map_, function (key, val) {\n if (val) {\n val.cancel(true);\n }\n });\n this.map_ = {};\n };\n\n return RequestMap;\n}();\n/**\r\n * @param app If null, getAuthToken always resolves with null.\r\n * @param service The storage service associated with this auth wrapper.\r\n * Untyped to avoid circular type dependencies.\r\n * @struct\r\n */\n\n\nvar AuthWrapper =\n/** @class */\nfunction () {\n function AuthWrapper(app, maker, requestMaker, service, pool) {\n this.bucket_ = null;\n this.deleted_ = false;\n this.app_ = app;\n\n if (this.app_ !== null) {\n var options = this.app_.options;\n\n if (isDef(options)) {\n this.bucket_ = AuthWrapper.extractBucket_(options);\n }\n }\n\n this.storageRefMaker_ = maker;\n this.requestMaker_ = requestMaker;\n this.pool_ = pool;\n this.service_ = service;\n this.maxOperationRetryTime_ = defaultMaxOperationRetryTime;\n this.maxUploadRetryTime_ = defaultMaxUploadRetryTime;\n this.requestMap_ = new RequestMap();\n }\n\n AuthWrapper.extractBucket_ = function (config) {\n var bucketString = config[configOption] || null;\n\n if (bucketString == null) {\n return null;\n }\n\n var loc = Location.makeFromBucketSpec(bucketString);\n return loc.bucket;\n };\n\n AuthWrapper.prototype.getAuthToken = function () {\n // TODO(andysoto): remove ifDef checks after firebase-app implements stubs\n // (b/28673818).\n if (this.app_ !== null && isDef(this.app_.INTERNAL) && isDef(this.app_.INTERNAL.getToken)) {\n return this.app_.INTERNAL.getToken().then(function (response) {\n if (response !== null) {\n return response.accessToken;\n } else {\n return null;\n }\n }, function (_error) {\n return null;\n });\n } else {\n return resolve(null);\n }\n };\n\n AuthWrapper.prototype.bucket = function () {\n if (this.deleted_) {\n throw appDeleted();\n } else {\n return this.bucket_;\n }\n };\n /**\r\n * The service associated with this auth wrapper. Untyped to avoid circular\r\n * type dependencies.\r\n */\n\n\n AuthWrapper.prototype.service = function () {\n return this.service_;\n };\n /**\r\n * Returns a new firebaseStorage.Reference object referencing this AuthWrapper\r\n * at the given Location.\r\n * @param loc The Location.\r\n * @return Actually a firebaseStorage.Reference, typing not allowed\r\n * because of circular dependency problems.\r\n */\n\n\n AuthWrapper.prototype.makeStorageReference = function (loc) {\n return this.storageRefMaker_(this, loc);\n };\n\n AuthWrapper.prototype.makeRequest = function (requestInfo, authToken) {\n if (!this.deleted_) {\n var request = this.requestMaker_(requestInfo, authToken, this.pool_);\n this.requestMap_.addRequest(request);\n return request;\n } else {\n return new FailRequest(appDeleted());\n }\n };\n /**\r\n * Stop running requests and prevent more from being created.\r\n */\n\n\n AuthWrapper.prototype.deleteApp = function () {\n this.deleted_ = true;\n this.app_ = null;\n this.requestMap_.clear();\n };\n\n AuthWrapper.prototype.maxUploadRetryTime = function () {\n return this.maxUploadRetryTime_;\n };\n\n AuthWrapper.prototype.setMaxUploadRetryTime = function (time) {\n this.maxUploadRetryTime_ = time;\n };\n\n AuthWrapper.prototype.maxOperationRetryTime = function () {\n return this.maxOperationRetryTime_;\n };\n\n AuthWrapper.prototype.setMaxOperationRetryTime = function (time) {\n this.maxOperationRetryTime_ = time;\n };\n\n return AuthWrapper;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @param f May be invoked\r\n * before the function returns.\r\n * @param callback Get all the arguments passed to the function\r\n * passed to f, including the initial boolean.\r\n */\n\n\nfunction start(f, callback, timeout) {\n // TODO(andysoto): make this code cleaner (probably refactor into an actual\n // type instead of a bunch of functions with state shared in the closure)\n var waitSeconds = 1; // Would type this as \"number\" but that doesn't work for Node so ¯\\_(ツ)_/¯\n\n var timeoutId = null;\n var hitTimeout = false;\n var cancelState = 0;\n\n function canceled() {\n return cancelState === 2;\n }\n\n var triggeredCallback = false;\n\n function triggerCallback() {\n if (!triggeredCallback) {\n triggeredCallback = true;\n callback.apply(null, arguments);\n }\n }\n\n function callWithDelay(millis) {\n timeoutId = setTimeout(function () {\n timeoutId = null;\n f(handler, canceled());\n }, millis);\n }\n\n function handler(success) {\n var var_args = [];\n\n for (var _i = 1; _i < arguments.length; _i++) {\n var_args[_i - 1] = arguments[_i];\n }\n\n if (triggeredCallback) {\n return;\n }\n\n if (success) {\n triggerCallback.apply(null, arguments);\n return;\n }\n\n var mustStop = canceled() || hitTimeout;\n\n if (mustStop) {\n triggerCallback.apply(null, arguments);\n return;\n }\n\n if (waitSeconds < 64) {\n /* TODO(andysoto): don't back off so quickly if we know we're offline. */\n waitSeconds *= 2;\n }\n\n var waitMillis;\n\n if (cancelState === 1) {\n cancelState = 2;\n waitMillis = 0;\n } else {\n waitMillis = (waitSeconds + Math.random()) * 1000;\n }\n\n callWithDelay(waitMillis);\n }\n\n var stopped = false;\n\n function stop(wasTimeout) {\n if (stopped) {\n return;\n }\n\n stopped = true;\n\n if (triggeredCallback) {\n return;\n }\n\n if (timeoutId !== null) {\n if (!wasTimeout) {\n cancelState = 2;\n }\n\n clearTimeout(timeoutId);\n callWithDelay(0);\n } else {\n if (!wasTimeout) {\n cancelState = 1;\n }\n }\n }\n\n callWithDelay(0);\n setTimeout(function () {\n hitTimeout = true;\n stop(true);\n }, timeout);\n return stop;\n}\n/**\r\n * Stops the retry loop from repeating.\r\n * If the function is currently \"in between\" retries, it is invoked immediately\r\n * with the second parameter as \"true\". Otherwise, it will be invoked once more\r\n * after the current invocation finishes iff the current invocation would have\r\n * triggered another retry.\r\n */\n\n\nfunction stop(id) {\n id(false);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * @struct\r\n * @template T\r\n */\n\n\nvar NetworkRequest =\n/** @class */\nfunction () {\n function NetworkRequest(url, method, headers, body, successCodes, additionalRetryCodes, callback, errorCallback, timeout, progressCallback, pool) {\n this.pendingXhr_ = null;\n this.backoffId_ = null;\n this.resolve_ = null;\n this.reject_ = null;\n this.canceled_ = false;\n this.appDelete_ = false;\n this.url_ = url;\n this.method_ = method;\n this.headers_ = headers;\n this.body_ = body;\n this.successCodes_ = successCodes.slice();\n this.additionalRetryCodes_ = additionalRetryCodes.slice();\n this.callback_ = callback;\n this.errorCallback_ = errorCallback;\n this.progressCallback_ = progressCallback;\n this.timeout_ = timeout;\n this.pool_ = pool;\n var self = this;\n this.promise_ = make(function (resolve$$1, reject$$1) {\n self.resolve_ = resolve$$1;\n self.reject_ = reject$$1;\n self.start_();\n });\n }\n /**\r\n * Actually starts the retry loop.\r\n */\n\n\n NetworkRequest.prototype.start_ = function () {\n var self = this;\n\n function doTheRequest(backoffCallback, canceled$$1) {\n if (canceled$$1) {\n backoffCallback(false, new RequestEndStatus(false, null, true));\n return;\n }\n\n var xhr = self.pool_.createXhrIo();\n self.pendingXhr_ = xhr;\n\n function progressListener(progressEvent) {\n var loaded = progressEvent.loaded;\n var total = progressEvent.lengthComputable ? progressEvent.total : -1;\n\n if (self.progressCallback_ !== null) {\n self.progressCallback_(loaded, total);\n }\n }\n\n if (self.progressCallback_ !== null) {\n xhr.addUploadProgressListener(progressListener);\n }\n\n xhr.send(self.url_, self.method_, self.body_, self.headers_).then(function (xhr) {\n if (self.progressCallback_ !== null) {\n xhr.removeUploadProgressListener(progressListener);\n }\n\n self.pendingXhr_ = null;\n xhr = xhr;\n var hitServer = xhr.getErrorCode() === ErrorCode.NO_ERROR;\n var status = xhr.getStatus();\n\n if (!hitServer || self.isRetryStatusCode_(status)) {\n var wasCanceled = xhr.getErrorCode() === ErrorCode.ABORT;\n backoffCallback(false, new RequestEndStatus(false, null, wasCanceled));\n return;\n }\n\n var successCode = contains$1(self.successCodes_, status);\n backoffCallback(true, new RequestEndStatus(successCode, xhr));\n });\n }\n /**\r\n * @param requestWentThrough True if the request eventually went\r\n * through, false if it hit the retry limit or was canceled.\r\n */\n\n\n function backoffDone(requestWentThrough, status) {\n var resolve$$1 = self.resolve_;\n var reject$$1 = self.reject_;\n var xhr = status.xhr;\n\n if (status.wasSuccessCode) {\n try {\n var result = self.callback_(xhr, xhr.getResponseText());\n\n if (isJustDef(result)) {\n resolve$$1(result);\n } else {\n resolve$$1();\n }\n } catch (e) {\n reject$$1(e);\n }\n } else {\n if (xhr !== null) {\n var err = unknown();\n err.setServerResponseProp(xhr.getResponseText());\n\n if (self.errorCallback_) {\n reject$$1(self.errorCallback_(xhr, err));\n } else {\n reject$$1(err);\n }\n } else {\n if (status.canceled) {\n var err = self.appDelete_ ? appDeleted() : canceled();\n reject$$1(err);\n } else {\n var err = retryLimitExceeded();\n reject$$1(err);\n }\n }\n }\n }\n\n if (this.canceled_) {\n backoffDone(false, new RequestEndStatus(false, null, true));\n } else {\n this.backoffId_ = start(doTheRequest, backoffDone, this.timeout_);\n }\n };\n /** @inheritDoc */\n\n\n NetworkRequest.prototype.getPromise = function () {\n return this.promise_;\n };\n /** @inheritDoc */\n\n\n NetworkRequest.prototype.cancel = function (appDelete) {\n this.canceled_ = true;\n this.appDelete_ = appDelete || false;\n\n if (this.backoffId_ !== null) {\n stop(this.backoffId_);\n }\n\n if (this.pendingXhr_ !== null) {\n this.pendingXhr_.abort();\n }\n };\n\n NetworkRequest.prototype.isRetryStatusCode_ = function (status) {\n // The codes for which to retry came from this page:\n // https://cloud.google.com/storage/docs/exponential-backoff\n var isFiveHundredCode = status >= 500 && status < 600;\n var extraRetryCodes = [// Request Timeout: web server didn't receive full request in time.\n 408, // Too Many Requests: you're getting rate-limited, basically.\n 429];\n var isExtraRetryCode = contains$1(extraRetryCodes, status);\n var isRequestSpecificRetryCode = contains$1(this.additionalRetryCodes_, status);\n return isFiveHundredCode || isExtraRetryCode || isRequestSpecificRetryCode;\n };\n\n return NetworkRequest;\n}();\n/**\r\n * A collection of information about the result of a network request.\r\n * @param opt_canceled Defaults to false.\r\n * @struct\r\n */\n\n\nvar RequestEndStatus =\n/** @class */\nfunction () {\n function RequestEndStatus(wasSuccessCode, xhr, opt_canceled) {\n this.wasSuccessCode = wasSuccessCode;\n this.xhr = xhr;\n this.canceled = !!opt_canceled;\n }\n\n return RequestEndStatus;\n}();\n\nfunction addAuthHeader_(headers, authToken) {\n if (authToken !== null && authToken.length > 0) {\n headers['Authorization'] = 'Firebase ' + authToken;\n }\n}\n\nfunction addVersionHeader_(headers) {\n var number = typeof firebase !== 'undefined' ? firebase.SDK_VERSION : 'AppManager';\n headers['X-Firebase-Storage-Version'] = 'webjs/' + number;\n}\n/**\r\n * @template T\r\n */\n\n\nfunction makeRequest(requestInfo, authToken, pool) {\n var queryPart = makeQueryString(requestInfo.urlParams);\n var url = requestInfo.url + queryPart;\n var headers = clone(requestInfo.headers);\n addAuthHeader_(headers, authToken);\n addVersionHeader_(headers);\n return new NetworkRequest(url, requestInfo.method, headers, requestInfo.body, requestInfo.successCodes, requestInfo.additionalRetryCodes, requestInfo.handler, requestInfo.errorHandler, requestInfo.timeout, requestInfo.progressCallback, pool);\n}\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * A service that provides firebaseStorage.Reference instances.\r\n * @param opt_url gs:// url to a custom Storage Bucket\r\n *\r\n * @struct\r\n */\n\n\nvar Service =\n/** @class */\nfunction () {\n function Service(app, pool, url) {\n this.bucket_ = null;\n\n function maker(authWrapper, loc) {\n return new Reference(authWrapper, loc);\n }\n\n this.authWrapper_ = new AuthWrapper(app, maker, makeRequest, this, pool);\n this.app_ = app;\n\n if (url != null) {\n this.bucket_ = Location.makeFromBucketSpec(url);\n } else {\n var authWrapperBucket = this.authWrapper_.bucket();\n\n if (authWrapperBucket != null) {\n this.bucket_ = new Location(authWrapperBucket, '');\n }\n }\n\n this.internals_ = new ServiceInternals(this);\n }\n /**\r\n * Returns a firebaseStorage.Reference for the given path in the default\r\n * bucket.\r\n */\n\n\n Service.prototype.ref = function (path) {\n function validator(path) {\n if (/^[A-Za-z]+:\\/\\//.test(path)) {\n throw 'Expected child path but got a URL, use refFromURL instead.';\n }\n }\n\n validate('ref', [stringSpec(validator, true)], arguments);\n\n if (this.bucket_ == null) {\n throw new Error('No Storage Bucket defined in Firebase Options.');\n }\n\n var ref = new Reference(this.authWrapper_, this.bucket_);\n\n if (path != null) {\n return ref.child(path);\n } else {\n return ref;\n }\n };\n /**\r\n * Returns a firebaseStorage.Reference object for the given absolute URL,\r\n * which must be a gs:// or http[s]:// URL.\r\n */\n\n\n Service.prototype.refFromURL = function (url) {\n function validator(p) {\n if (!/^[A-Za-z]+:\\/\\//.test(p)) {\n throw 'Expected full URL but got a child path, use ref instead.';\n }\n\n try {\n Location.makeFromUrl(p);\n } catch (e) {\n throw 'Expected valid full URL but got an invalid one.';\n }\n }\n\n validate('refFromURL', [stringSpec(validator, false)], arguments);\n return new Reference(this.authWrapper_, url);\n };\n\n Object.defineProperty(Service.prototype, \"maxUploadRetryTime\", {\n get: function get() {\n return this.authWrapper_.maxUploadRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n\n Service.prototype.setMaxUploadRetryTime = function (time) {\n validate('setMaxUploadRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxUploadRetryTime(time);\n };\n\n Object.defineProperty(Service.prototype, \"maxOperationRetryTime\", {\n get: function get() {\n return this.authWrapper_.maxOperationRetryTime();\n },\n enumerable: true,\n configurable: true\n });\n\n Service.prototype.setMaxOperationRetryTime = function (time) {\n validate('setMaxOperationRetryTime', [nonNegativeNumberSpec()], arguments);\n this.authWrapper_.setMaxOperationRetryTime(time);\n };\n\n Object.defineProperty(Service.prototype, \"app\", {\n get: function get() {\n return this.app_;\n },\n enumerable: true,\n configurable: true\n });\n Object.defineProperty(Service.prototype, \"INTERNAL\", {\n get: function get() {\n return this.internals_;\n },\n enumerable: true,\n configurable: true\n });\n return Service;\n}();\n/**\r\n * @struct\r\n */\n\n\nvar ServiceInternals =\n/** @class */\nfunction () {\n function ServiceInternals(service) {\n this.service_ = service;\n }\n /**\r\n * Called when the associated app is deleted.\r\n * @see {!fbs.AuthWrapper.prototype.deleteApp}\r\n */\n\n\n ServiceInternals.prototype.delete = function () {\n this.service_.authWrapper_.deleteApp();\n return resolve(undefined);\n };\n\n return ServiceInternals;\n}();\n/**\r\n * Copyright 2017 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n/**\r\n * Type constant for Firebase Storage.\r\n */\n\n\nvar STORAGE_TYPE = 'storage';\n\nfunction factory(app, unused, opt_url) {\n return new Service(app, new XhrIoPool(), opt_url);\n}\n\nfunction registerStorage(instance) {\n var namespaceExports = {\n // no-inline\n TaskState: TaskState,\n TaskEvent: TaskEvent,\n StringFormat: StringFormat,\n Storage: Service,\n Reference: Reference\n };\n instance.INTERNAL.registerService(STORAGE_TYPE, factory, namespaceExports, undefined, // Allow multiple storage instances per app.\n true);\n}\n\nregisterStorage(firebase);\nexport { registerStorage };","(function webpackUniversalModuleDefinition(root, factory) {\n if (typeof exports === 'object' && typeof module === 'object') module.exports = factory(require(\"firebase/app\"));else if (typeof define === 'function' && define.amd) define([\"firebase/app\"], factory);else {\n var a = typeof exports === 'object' ? factory(require(\"firebase/app\")) : factory(root[\"firebase/app\"]);\n\n for (var i in a) {\n (typeof exports === 'object' ? exports : root)[i] = a[i];\n }\n }\n})(this, function (__WEBPACK_EXTERNAL_MODULE_6__) {\n return (\n /******/\n function (modules) {\n // webpackBootstrap\n\n /******/\n // The module cache\n\n /******/\n var installedModules = {};\n /******/\n // The require function\n\n /******/\n\n function __webpack_require__(moduleId) {\n /******/\n // Check if module is in cache\n\n /******/\n if (installedModules[moduleId])\n /******/\n return installedModules[moduleId].exports;\n /******/\n // Create a new module (and put it into the cache)\n\n /******/\n\n var module = installedModules[moduleId] = {\n /******/\n exports: {},\n\n /******/\n id: moduleId,\n\n /******/\n loaded: false\n /******/\n\n };\n /******/\n // Execute the module function\n\n /******/\n\n modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n /******/\n // Flag the module as loaded\n\n /******/\n\n module.loaded = true;\n /******/\n // Return the exports of the module\n\n /******/\n\n return module.exports;\n /******/\n }\n /******/\n // expose the modules object (__webpack_modules__)\n\n /******/\n\n\n __webpack_require__.m = modules;\n /******/\n // expose the module cache\n\n /******/\n\n __webpack_require__.c = installedModules;\n /******/\n // __webpack_public_path__\n\n /******/\n\n __webpack_require__.p = \"\";\n /******/\n // Load entry module and return exports\n\n /******/\n\n return __webpack_require__(0);\n /******/\n }(\n /************************************************************************/\n\n /******/\n [\n /* 0 */\n\n /***/\n function (module, exports, __webpack_require__) {\n module.exports = __webpack_require__(1);\n /***/\n },\n /* 1 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n var _utils = __webpack_require__(2);\n\n var _validators = __webpack_require__(5);\n\n var _app = __webpack_require__(6);\n\n var _app2 = _interopRequireDefault(_app);\n\n var _push2 = __webpack_require__(7);\n\n var _push3 = _interopRequireDefault(_push2);\n\n var _fetch2 = __webpack_require__(8);\n\n var _fetch3 = _interopRequireDefault(_fetch2);\n\n var _post2 = __webpack_require__(9);\n\n var _post3 = _interopRequireDefault(_post2);\n\n var _sync2 = __webpack_require__(10);\n\n var _sync3 = _interopRequireDefault(_sync2);\n\n var _bind2 = __webpack_require__(11);\n\n var _bind3 = _interopRequireDefault(_bind2);\n\n var _update2 = __webpack_require__(12);\n\n var _update3 = _interopRequireDefault(_update2);\n\n var _reset2 = __webpack_require__(13);\n\n var _reset3 = _interopRequireDefault(_reset2);\n\n var _removeBinding2 = __webpack_require__(3);\n\n var _removeBinding3 = _interopRequireDefault(_removeBinding2);\n\n var _remove2 = __webpack_require__(14);\n\n var _remove3 = _interopRequireDefault(_remove2);\n\n var _fsSync2 = __webpack_require__(15);\n\n var _fsSync3 = _interopRequireDefault(_fsSync2);\n\n var _fsRemoveBinding2 = __webpack_require__(4);\n\n var _fsRemoveBinding3 = _interopRequireDefault(_fsRemoveBinding2);\n\n var _fsBind2 = __webpack_require__(16);\n\n var _fsBind3 = _interopRequireDefault(_fsBind2);\n\n var _fsGet2 = __webpack_require__(17);\n\n var _fsGet3 = _interopRequireDefault(_fsGet2);\n\n var _fsRemoveDoc2 = __webpack_require__(18);\n\n var _fsRemoveDoc3 = _interopRequireDefault(_fsRemoveDoc2);\n\n var _fsAddToCollection2 = __webpack_require__(19);\n\n var _fsAddToCollection3 = _interopRequireDefault(_fsAddToCollection2);\n\n var _fsRemoveFromCollection2 = __webpack_require__(20);\n\n var _fsRemoveFromCollection3 = _interopRequireDefault(_fsRemoveFromCollection2);\n\n var _fsUpdateDoc2 = __webpack_require__(21);\n\n var _fsUpdateDoc3 = _interopRequireDefault(_fsUpdateDoc2);\n\n var _fsReset2 = __webpack_require__(22);\n\n var _fsReset3 = _interopRequireDefault(_fsReset2);\n\n function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n default: obj\n };\n } //database\n\n\n module.exports = function () {\n function init(db) {\n return function () {\n var refs = new Map();\n var listeners = new Map();\n var syncs = new WeakMap();\n\n if (typeof db.ref === 'function') {\n var rebase = {\n initializedApp: db.app,\n timestamp: _app2.default.database.ServerValue.TIMESTAMP,\n listenTo: function listenTo(endpoint, options) {\n return _bind3.default.call(this, endpoint, options, 'listenTo', {\n db: db,\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n },\n bindToState: function bindToState(endpoint, options) {\n return _bind3.default.call(this, endpoint, options, 'bindToState', {\n db: db,\n refs: refs,\n listeners: listeners\n });\n },\n syncState: function syncState(endpoint, options) {\n return _sync3.default.call(this, endpoint, options, {\n db: db,\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n },\n fetch: function fetch(endpoint, options) {\n return (0, _fetch3.default)(endpoint, options, db);\n },\n post: function post(endpoint, options) {\n return (0, _post3.default)(endpoint, options, db);\n },\n update: function update(endpoint, options) {\n return (0, _update3.default)(endpoint, options, {\n db: db\n });\n },\n push: function push(endpoint, options) {\n return (0, _push3.default)(endpoint, options, db);\n },\n removeBinding: function removeBinding(binding) {\n (0, _removeBinding3.default)(binding, {\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n },\n remove: function remove(endpoint, fn) {\n return (0, _remove3.default)(endpoint, db, fn);\n },\n reset: function reset() {\n return (0, _reset3.default)({\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n }\n };\n } else {\n var rebase = {\n initializedApp: db.app,\n timestamp: _app2.default.firestore.FieldValue.serverTimestamp(),\n bindDoc: function bindDoc(path, options) {\n return _fsBind3.default.call(this, path, options, 'bindDoc', {\n db: db,\n refs: refs,\n listeners: listeners\n });\n },\n bindCollection: function bindCollection(path, options) {\n return _fsBind3.default.call(this, path, options, 'bindCollection', {\n db: db,\n refs: refs,\n listeners: listeners\n });\n },\n syncDoc: function syncDoc(doc, options) {\n return _fsSync3.default.call(this, doc, options, {\n db: db,\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n },\n listenToDoc: function listenToDoc(doc, options) {\n return _fsBind3.default.call(this, doc, options, 'listenToDoc', {\n db: db,\n refs: refs,\n listeners: listeners\n });\n },\n listenToCollection: function listenToCollection(path, options) {\n return _fsBind3.default.call(this, path, options, 'listenToCollection', {\n db: db,\n refs: refs,\n listeners: listeners\n });\n },\n addToCollection: function addToCollection(path, doc, key) {\n return _fsAddToCollection3.default.call(this, path, doc, db, key);\n },\n updateDoc: function updateDoc(path, doc, options) {\n return _fsUpdateDoc3.default.call(this, path, doc, db);\n },\n get: function get(path, options) {\n return _fsGet3.default.call(this, path, options, db);\n },\n removeDoc: function removeDoc(path) {\n return (0, _fsRemoveDoc3.default)(path, db);\n },\n removeFromCollection: function removeFromCollection(path, options) {\n return (0, _fsRemoveFromCollection3.default)(path, db, options);\n },\n removeBinding: function removeBinding(binding) {\n (0, _fsRemoveBinding3.default)(binding, {\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n },\n reset: function reset() {\n return (0, _fsReset3.default)({\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n }\n };\n }\n\n return rebase;\n }();\n }\n\n return {\n createClass: function createClass(db) {\n (0, _validators._validateDatabase)(db);\n return init(db);\n }\n };\n }(); //firestore\n //helpers\n\n /***/\n\n },\n /* 2 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports._fsCreateRef = exports._fsSetUnmountHandler = exports._setData = exports._handleError = exports._createNestedObject = exports._setUnmountHandler = exports._addFirestoreListener = exports._addListener = exports._fsUpdateSyncState = exports._updateSyncState = exports._firebaseRefsMixin = exports._addSync = exports._hasOwnNestedProperty = exports._getSegmentCount = exports._getNestedObject = exports._isNestedPath = exports._isObject = exports._isValid = exports._toArray = exports._fsPrepareData = exports._prepareData = exports._throwError = exports._setState = exports._returnRef = exports._addFirestoreQuery = exports._addQueries = exports._createHash = undefined;\n\n var _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n\n var _removeBinding2 = __webpack_require__(3);\n\n var _removeBinding3 = _interopRequireDefault(_removeBinding2);\n\n var _fsRemoveBinding2 = __webpack_require__(4);\n\n var _fsRemoveBinding3 = _interopRequireDefault(_fsRemoveBinding2);\n\n function _interopRequireDefault(obj) {\n return obj && obj.__esModule ? obj : {\n default: obj\n };\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n var _isObject = function _isObject(obj) {\n return Object.prototype.toString.call(obj) === '[object Object]' ? true : false;\n };\n\n var _toArray = function _toArray(snapshot) {\n var arr = [];\n snapshot.forEach(function (childSnapshot) {\n var val = childSnapshot.val();\n\n if (_isObject(val)) {\n val.key = childSnapshot.key;\n }\n\n arr.push(val);\n });\n return arr;\n };\n\n var _isValid = function _isValid(value) {\n return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' ? true : false;\n };\n\n var _isNestedPath = function _isNestedPath(path) {\n return path.split('.').length > 1 ? true : false;\n };\n\n var _createNestedObject = function _createNestedObject(path, value) {\n var obj = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n var keys = path.split('.');\n var lastKey = value === undefined ? false : keys.pop();\n var root = obj;\n var _iteratorNormalCompletion = true;\n var _didIteratorError = false;\n var _iteratorError = undefined;\n\n try {\n for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {\n var key = _step.value;\n obj = obj[key] = obj[key] || {};\n }\n } catch (err) {\n _didIteratorError = true;\n _iteratorError = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion && _iterator.return) {\n _iterator.return();\n }\n } finally {\n if (_didIteratorError) {\n throw _iteratorError;\n }\n }\n }\n\n if (lastKey) obj[lastKey] = value;\n return root;\n };\n\n var _getNestedObject = function _getNestedObject(obj, path) {\n if (_isNestedPath(path) === false) return;\n var keys = path.split('.');\n var _iteratorNormalCompletion2 = true;\n var _didIteratorError2 = false;\n var _iteratorError2 = undefined;\n\n try {\n for (var _iterator2 = keys[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {\n var key = _step2.value;\n if (!obj || (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object') return;\n obj = obj[key];\n }\n } catch (err) {\n _didIteratorError2 = true;\n _iteratorError2 = err;\n } finally {\n try {\n if (!_iteratorNormalCompletion2 && _iterator2.return) {\n _iterator2.return();\n }\n } finally {\n if (_didIteratorError2) {\n throw _iteratorError2;\n }\n }\n }\n\n return obj;\n };\n\n var _hasOwnNestedProperty = function _hasOwnNestedProperty(obj, path) {\n return _getNestedObject(obj, path) === undefined ? false : true;\n };\n\n var _prepareData = function _prepareData(snapshot) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var defaultValue = options.defaultValue,\n asArray = options.asArray;\n var data = snapshot.val();\n if (data === null && _isValid(defaultValue)) return defaultValue;\n if (asArray === true) return _toArray(snapshot);\n return data === null ? {} : data;\n };\n\n var _addSync = function _addSync(context, sync, syncs) {\n var existingSyncs = syncs.get(context) || [];\n existingSyncs.push(sync);\n syncs.set(context, existingSyncs);\n };\n\n var _throwError = function _throwError(msg, code) {\n var err = new Error('REBASE: ' + msg);\n err.code = code;\n throw err;\n };\n\n var _setState = function _setState(newState) {\n this.setState(newState);\n };\n\n var _returnRef = function _returnRef(endpoint, method, id, context) {\n return {\n endpoint: endpoint,\n method: method,\n id: id,\n context: context\n };\n };\n\n var _addQueries = function _addQueries(ref, queries) {\n var needArgs = {\n limitToFirst: true,\n limitToLast: true,\n orderByChild: true,\n startAt: true,\n endAt: true,\n equalTo: true\n };\n\n for (var key in queries) {\n /* istanbul ignore else */\n if (queries.hasOwnProperty(key)) {\n if (needArgs[key]) {\n ref = ref[key](queries[key]);\n } else {\n ref = ref[key]();\n }\n }\n }\n\n return ref;\n };\n\n var _addFirestoreQuery = function _addFirestoreQuery(ref, query) {\n if (query) {\n return query(ref);\n }\n\n return ref;\n };\n\n var _createHash = function _createHash(endpoint, invoker) {\n var hash = 0;\n var str = endpoint + invoker + Math.random();\n\n for (var i = 0; i < str.length; i++) {\n var char = str.charCodeAt(i);\n hash = (hash << 5) - hash + char;\n hash = hash & hash;\n }\n\n return hash;\n };\n\n var _firebaseRefsMixin = function _firebaseRefsMixin(id, ref, refs) {\n refs.set(id, ref);\n };\n\n var _handleError = function _handleError(onFailure, err) {\n if (err && typeof onFailure === 'function') {\n onFailure(err);\n }\n };\n\n var _setUnmountHandler = function _setUnmountHandler(context, id, refs, listeners, syncs) {\n var removeListeners = function removeListeners() {\n (0, _removeBinding3.default)({\n context: context,\n id: id\n }, {\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n };\n\n if (typeof context.componentWillUnmount === 'function') {\n var unmount = context.componentWillUnmount;\n }\n\n context.componentWillUnmount = function () {\n removeListeners();\n if (unmount) unmount.call(context);\n };\n };\n\n var _fsSetUnmountHandler = function _fsSetUnmountHandler(context, id, refs, listeners, syncs) {\n var removeListeners = function removeListeners() {\n (0, _fsRemoveBinding3.default)({\n context: context,\n id: id\n }, {\n refs: refs,\n listeners: listeners,\n syncs: syncs\n });\n };\n\n if (typeof context.componentWillUnmount === 'function') {\n var unmount = context.componentWillUnmount;\n }\n\n context.componentWillUnmount = function () {\n removeListeners();\n if (unmount) unmount.call(context);\n };\n };\n\n var _setData = function _setData(ref, data, handleError, keepKeys) {\n if (Array.isArray(data) && keepKeys) {\n var shouldConvertToObject = data.reduce(function (acc, curr) {\n return acc ? acc : _isObject(curr) && curr.hasOwnProperty('key');\n }, false);\n\n if (shouldConvertToObject) {\n data = data.reduce(function (acc, item) {\n acc[item.key] = item;\n return acc;\n }, {});\n }\n }\n\n ref.set(data, handleError);\n };\n\n var _updateSyncState = function _updateSyncState(ref, onFailure, keepKeys, data) {\n if (_isObject(data)) {\n for (var prop in data) {\n //allow timestamps to be set\n if (prop !== '.sv') {\n _updateSyncState(ref.child(prop), onFailure, keepKeys, data[prop]);\n } else {\n _setData(ref, data, _handleError.bind(null, onFailure), keepKeys);\n }\n }\n } else {\n _setData(ref, data, _handleError.bind(null, onFailure), keepKeys);\n }\n };\n\n var _fsUpdateSyncState = function _fsUpdateSyncState(ref, data) {\n ref.set(data);\n };\n\n var _addListener = function _addListener(id, invoker, options, ref, listeners) {\n ref = _addQueries(ref, options.queries);\n var boundOnFailure = typeof options.onFailure === 'function' ? options.onFailure.bind(options.context) : null;\n listeners.set(id, ref.on('value', function (snapshot) {\n var data = _prepareData(snapshot, options);\n\n if (invoker === 'listenTo') {\n options.then.call(options.context, data);\n } else {\n var newState = _defineProperty({}, options.state, data);\n\n if (_isNestedPath(options.state)) {\n var root = options.state.split('.')[0]; // Merge the previous state with the new one\n\n var prevState = _defineProperty({}, root, options.context.state[root]);\n\n newState = _createNestedObject(options.state, data, prevState);\n }\n\n if (invoker === 'syncState') {\n options.reactSetState.call(options.context, newState);\n\n if (options.then && options.then.called === false) {\n options.then.call(options.context);\n options.then.called = true;\n }\n } else if (invoker === 'bindToState') {\n _setState.call(options.context, newState);\n\n if (options.then && options.then.called === false) {\n options.then.call(options.context);\n options.then.called = true;\n }\n }\n }\n }, boundOnFailure));\n };\n\n var _addFirestoreListener = function _addFirestoreListener(id, invoker, options, ref, listeners) {\n ref = _addFirestoreQuery(ref, options.query);\n var boundOnFailure = typeof options.onFailure === 'function' ? options.onFailure.bind(options.context) : undefined;\n listeners.set(id, ref.onSnapshot(function (snapshot) {\n if (invoker.match(/^listenTo/)) {\n if (invoker === 'listenToDoc') {\n var newState = _fsPrepareData(snapshot, options);\n\n return options.then.call(options.context, newState);\n }\n\n if (invoker === 'listenToCollection') {\n var _newState2 = _fsPrepareData(snapshot, options, true);\n\n return options.then.call(options.context, _newState2);\n }\n } else {\n if (invoker === 'syncDoc') {\n var _newState3 = _fsPrepareData(snapshot, options);\n\n options.reactSetState.call(options.context, function (currentState) {\n return Object.assign(currentState, _newState3);\n });\n } else if (invoker === 'bindDoc') {\n var _newState4 = _fsPrepareData(snapshot, options);\n\n _setState.call(options.context, function (currentState) {\n return Object.assign(currentState, _newState4);\n });\n } else if (invoker === 'bindCollection') {\n var _newState5 = _fsPrepareData(snapshot, options, true);\n\n _setState.call(options.context, function (currentState) {\n return Object.assign(currentState, _newState5);\n });\n }\n\n if (options.then && options.then.called === false) {\n options.then.call(options.context);\n options.then.called = true;\n }\n }\n }, boundOnFailure));\n };\n\n var _getSegmentCount = function _getSegmentCount(path) {\n return path.match(/^\\//) ? path.split('/').slice(1).length : path.split('/').length;\n };\n\n var _fsPrepareData = function _fsPrepareData(snapshot, options) {\n var isCollection = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;\n var meta = {};\n\n if (!isCollection) {\n var data = {};\n\n if (snapshot.exists) {\n if (options.withRefs) meta.ref = snapshot.ref;\n if (options.withIds) meta.id = snapshot.id;\n data = snapshot.data();\n } else {\n data = {};\n }\n\n return options.state ? _defineProperty({}, options.state, Object.assign({}, data, meta)) : Object.assign({}, data, meta);\n }\n\n var collection = [];\n\n if (!snapshot.empty) {\n snapshot.forEach(function (doc) {\n if (options.withRefs) meta.ref = doc.ref;\n if (options.withIds) meta.id = doc.id;\n collection.push(Object.assign({}, doc.data(), meta));\n });\n }\n\n return options.state ? _defineProperty({}, options.state, collection) : collection;\n };\n\n var _fsCreateRef = function _fsCreateRef(pathOrRef, db) {\n if ((typeof pathOrRef === 'undefined' ? 'undefined' : _typeof(pathOrRef)) === 'object') {\n return pathOrRef;\n }\n\n var segmentCount = _getSegmentCount(pathOrRef);\n\n var ref;\n\n if (segmentCount % 2 === 0) {\n ref = db.doc(pathOrRef);\n } else {\n ref = db.collection(pathOrRef);\n }\n\n return ref;\n };\n\n exports._createHash = _createHash;\n exports._addQueries = _addQueries;\n exports._addFirestoreQuery = _addFirestoreQuery;\n exports._returnRef = _returnRef;\n exports._setState = _setState;\n exports._throwError = _throwError;\n exports._prepareData = _prepareData;\n exports._fsPrepareData = _fsPrepareData;\n exports._toArray = _toArray;\n exports._isValid = _isValid;\n exports._isObject = _isObject;\n exports._isNestedPath = _isNestedPath;\n exports._getNestedObject = _getNestedObject;\n exports._getSegmentCount = _getSegmentCount;\n exports._hasOwnNestedProperty = _hasOwnNestedProperty;\n exports._addSync = _addSync;\n exports._firebaseRefsMixin = _firebaseRefsMixin;\n exports._updateSyncState = _updateSyncState;\n exports._fsUpdateSyncState = _fsUpdateSyncState;\n exports._addListener = _addListener;\n exports._addFirestoreListener = _addFirestoreListener;\n exports._setUnmountHandler = _setUnmountHandler;\n exports._createNestedObject = _createNestedObject;\n exports._handleError = _handleError;\n exports._setData = _setData;\n exports._fsSetUnmountHandler = _fsSetUnmountHandler;\n exports._fsCreateRef = _fsCreateRef;\n /***/\n },\n /* 3 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _removeBinding;\n\n var _utils = __webpack_require__(2);\n\n function _removeBinding(_ref, _ref2) {\n var id = _ref.id,\n context = _ref.context;\n var refs = _ref2.refs,\n listeners = _ref2.listeners,\n syncs = _ref2.syncs;\n var ref = refs.get(id);\n var listener = listeners.get(id);\n\n if (typeof ref !== 'undefined') {\n ref.off('value', listener);\n refs.delete(id);\n listeners.delete(id);\n\n if (syncs) {\n var currentSyncs = syncs.get(context);\n\n if (currentSyncs && currentSyncs.length > 0) {\n var idx = currentSyncs.findIndex(function (item, index) {\n return item.id === id;\n });\n /*istanbul ignore else */\n\n if (idx !== -1) {\n currentSyncs.splice(idx, 1);\n syncs.set(context, currentSyncs);\n }\n }\n }\n }\n }\n /***/\n\n },\n /* 4 */\n\n /***/\n function (module, exports) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsRemoveBinding;\n\n function _fsRemoveBinding(_ref, _ref2) {\n var id = _ref.id,\n context = _ref.context;\n var refs = _ref2.refs,\n listeners = _ref2.listeners,\n syncs = _ref2.syncs;\n var unsubscribe = listeners.get(id);\n\n if (typeof unsubscribe === 'function') {\n unsubscribe();\n refs.delete(id);\n listeners.delete(id);\n\n if (syncs) {\n var currentSyncs = syncs.get(context);\n\n if (currentSyncs && currentSyncs.length > 0) {\n var idx = currentSyncs.findIndex(function (item, index) {\n return item.id === id;\n });\n /*istanbul ignore else */\n\n if (idx !== -1) {\n currentSyncs.splice(idx, 1);\n syncs.set(context, currentSyncs);\n }\n }\n }\n }\n }\n /***/\n\n },\n /* 5 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports._validateCollectionPath = exports._validateDocumentPath = exports._validateEndpoint = exports._validateDatabase = exports.optionValidators = undefined;\n\n var _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n } : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n\n var _utils = __webpack_require__(2);\n\n var optionValidators = {\n notObject: function notObject(options) {\n if (!(0, _utils._isObject)(options)) {\n (0, _utils._throwError)('The options argument must be an object. Instead, got ' + options, 'INVALID_OPTIONS');\n }\n },\n context: function context(options) {\n this.notObject(options);\n\n if (!options.context || !(0, _utils._isObject)(options.context)) {\n this.makeError('context', 'object', options.context);\n }\n },\n state: function state(options) {\n this.notObject(options);\n\n if (!options.state || typeof options.state !== 'string') {\n this.makeError('state', 'string', options.state);\n }\n },\n then: function then(options) {\n this.notObject(options);\n\n if (typeof options.then === 'undefined' || typeof options.then !== 'function') {\n this.makeError('then', 'function', options.then);\n }\n },\n data: function data(options) {\n this.notObject(options);\n\n if (typeof options.data === 'undefined') {\n this.makeError('data', 'ANY', options.data);\n }\n },\n query: function query(options) {\n this.notObject(options);\n var validQueries = ['limitToFirst', 'limitToLast', 'orderByChild', 'orderByValue', 'orderByKey', 'orderByPriority', 'startAt', 'endAt', 'equalTo'];\n var queries = options.queries;\n\n for (var key in queries) {\n if (queries.hasOwnProperty(key) && validQueries.indexOf(key) === -1) {\n (0, _utils._throwError)('The query field must contain valid Firebase queries. Expected one of [' + validQueries.join(', ') + ']. Instead, got ' + key, 'INVALID_OPTIONS');\n }\n }\n },\n defaultValue: function defaultValue(options) {\n this.notObject(options);\n\n if (options.hasOwnProperty('defaultValue')) {\n if (!(0, _utils._isValid)(options.defaultValue)) {\n (0, _utils._throwError)('The typeof defaultValue must be one of string, number, boolean, object.', 'INVALID_OPTIONS');\n }\n }\n },\n makeError: function makeError(prop, type, actual) {\n (0, _utils._throwError)('The options argument must contain a ' + prop + ' property of type ' + type + '. Instead, got ' + actual, 'INVALID_OPTIONS');\n }\n };\n\n var _validateEndpoint = function _validateEndpoint(endpoint) {\n if ((typeof endpoint === 'undefined' ? 'undefined' : _typeof(endpoint)) === 'object') {\n if (endpoint.hasOwnProperty('firestore')) {\n return;\n }\n }\n\n var defaultError = 'The Firebase endpoint you are trying to listen to';\n var errorMsg;\n\n if (typeof endpoint !== 'string') {\n errorMsg = defaultError + ' must be a string. Instead, got ' + endpoint;\n } else if (endpoint.length === 0) {\n errorMsg = defaultError + ' must be a non-empty string. Instead, got ' + endpoint;\n } else if (endpoint.length > 768) {\n errorMsg = defaultError + ' is too long to be stored in Firebase. It must be less than 768 characters.';\n } else if (/^$|[\\[\\]\\#\\$]|.{1}[\\.]/.test(endpoint)) {\n errorMsg = defaultError + ' in invalid. Paths must be non-empty strings and can\\'t contain \".\", \"#\", \"$\", \"[\", or \"]\".';\n }\n\n if (typeof errorMsg !== 'undefined') {\n (0, _utils._throwError)(errorMsg, 'INVALID_ENDPOINT');\n }\n };\n\n var _validateDatabase = function _validateDatabase(db) {\n var defaultError = 'Rebase.createClass failed.';\n var errorMsg;\n\n if ((typeof db === 'undefined' ? 'undefined' : _typeof(db)) !== 'object' || !db.ref && !db.collection) {\n errorMsg = defaultError + ' Expected an initialized firebase or firestore database object.';\n }\n\n if (typeof errorMsg !== 'undefined') {\n (0, _utils._throwError)(errorMsg, 'INVALID_CONFIG');\n }\n };\n\n var _validateDocumentPath = function _validateDocumentPath(path) {\n if ((typeof path === 'undefined' ? 'undefined' : _typeof(path)) === 'object' && path.hasOwnProperty('firestore')) return;\n var defaultError = 'Invalid document path or reference.';\n if (typeof path !== 'string') (0, _utils._throwError)(defaultError, 'INVALID_ENDPOINT');\n var segmentCount = (0, _utils._getSegmentCount)(path);\n if (segmentCount % 2 !== 0) (0, _utils._throwError)(defaultError, 'INVALID_ENDPOINT');\n };\n\n var _validateCollectionPath = function _validateCollectionPath(path) {\n if ((typeof path === 'undefined' ? 'undefined' : _typeof(path)) === 'object' && path.hasOwnProperty('firestore')) return;\n var defaultError = 'Invalid collection path or reference.';\n if (typeof path !== 'string') (0, _utils._throwError)(defaultError, 'INVALID_ENDPOINT');\n var segmentCount = (0, _utils._getSegmentCount)(path);\n if (segmentCount % 2 === 0) (0, _utils._throwError)(defaultError, 'INVALID_ENDPOINT');\n };\n\n exports.optionValidators = optionValidators;\n exports._validateDatabase = _validateDatabase;\n exports._validateEndpoint = _validateEndpoint;\n exports._validateDocumentPath = _validateDocumentPath;\n exports._validateCollectionPath = _validateCollectionPath;\n /***/\n },\n /* 6 */\n\n /***/\n function (module, exports) {\n module.exports = __WEBPACK_EXTERNAL_MODULE_6__;\n /***/\n },\n /* 7 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _push;\n\n var _validators = __webpack_require__(5);\n\n function _push(endpoint, options, db) {\n (0, _validators._validateEndpoint)(endpoint);\n\n _validators.optionValidators.data(options);\n\n var ref = db.ref(endpoint);\n var returnEndpoint;\n\n if (options.then) {\n returnEndpoint = ref.push(options.data, options.then);\n } else {\n returnEndpoint = ref.push(options.data);\n }\n\n return returnEndpoint;\n }\n /***/\n\n },\n /* 8 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fetch;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _fetch(endpoint, options, db) {\n (0, _validators._validateEndpoint)(endpoint);\n\n _validators.optionValidators.defaultValue(options);\n\n options.queries && _validators.optionValidators.query(options);\n var ref = db.ref(endpoint);\n ref = (0, _utils._addQueries)(ref, options.queries);\n return ref.once('value').then(function (snapshot) {\n var data = (0, _utils._prepareData)(snapshot, options);\n\n if (options.then) {\n options.then.call(options.context, data);\n }\n\n return data;\n }).catch(function (err) {\n //call onFailure callback if it exists otherwise rethrow error\n if (options.onFailure && typeof options.onFailure === 'function') {\n options.onFailure.call(options.context, err);\n } else {\n throw err;\n }\n });\n }\n /***/\n\n },\n /* 9 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _post;\n\n var _validators = __webpack_require__(5);\n\n function _post(endpoint, options, db) {\n (0, _validators._validateEndpoint)(endpoint);\n\n _validators.optionValidators.data(options);\n\n var ref = db.ref(endpoint);\n\n if (options.then) {\n return ref.set(options.data, options.then);\n } else {\n return ref.set(options.data);\n }\n }\n /***/\n\n },\n /* 10 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _sync;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _sync(endpoint, options, state) {\n (0, _validators._validateEndpoint)(endpoint);\n\n _validators.optionValidators.context(options);\n\n _validators.optionValidators.state(options);\n\n _validators.optionValidators.defaultValue(options);\n\n options.queries && _validators.optionValidators.query(options);\n options.then && (options.then.called = false);\n options.onFailure = options.onFailure ? options.onFailure.bind(options.context) : null;\n options.keepKeys = options.keepKeys && options.asArray; //store reference to react's setState\n\n if (_sync.called !== true) {\n _sync.reactSetState = options.context.setState;\n _sync.called = true;\n }\n\n options.reactSetState = _sync.reactSetState;\n var ref = state.db.ref(endpoint);\n var id = (0, _utils._createHash)(endpoint, 'syncState');\n (0, _utils._firebaseRefsMixin)(id, ref, state.refs);\n (0, _utils._addListener)(id, 'syncState', options, ref, state.listeners);\n (0, _utils._setUnmountHandler)(options.context, id, state.refs, state.listeners, state.syncs);\n var sync = {\n id: id,\n updateFirebase: _utils._updateSyncState.bind(null, ref, options.onFailure, options.keepKeys),\n stateKey: options.state\n };\n (0, _utils._addSync)(options.context, sync, state.syncs);\n\n options.context.setState = function (data, cb) {\n //if setState is a function, call it first before syncing to fb\n if (typeof data === 'function') {\n return _sync.reactSetState.call(options.context, data, function () {\n if (cb) cb.call(options.context);\n return options.context.setState.call(options.context, options.context.state);\n });\n } //if callback is supplied, call setState first before syncing to fb\n\n\n if (typeof cb === 'function') {\n return _sync.reactSetState.call(options.context, data, function () {\n cb();\n return options.context.setState.call(options.context, data);\n });\n }\n\n var syncsToCall = state.syncs.get(this); //if sync does not exist, call original Component.setState\n\n if (!syncsToCall || syncsToCall.length === 0) {\n return _sync.reactSetState.call(this, data, cb);\n }\n\n var syncedKeys = syncsToCall.map(function (sync) {\n return {\n key: sync.stateKey,\n update: sync.updateFirebase,\n nested: (0, _utils._isNestedPath)(sync.stateKey)\n };\n });\n syncedKeys.forEach(function (syncedKey) {\n if (syncedKey.nested === true) {\n if ((0, _utils._hasOwnNestedProperty)(data, syncedKey.key)) {\n var datum = (0, _utils._getNestedObject)(data, syncedKey.key);\n syncedKey.update(datum);\n }\n } else if (data.hasOwnProperty(syncedKey.key)) {\n syncedKey.update(data[syncedKey.key]);\n }\n });\n var allKeys = Object.keys(data);\n allKeys.forEach(function (key) {\n var absent = !syncedKeys.find(function (syncedKey) {\n var k = syncedKey.key;\n\n if (syncedKey.nested === true) {\n // Check with the root\n k = syncedKey.key.split('.')[0];\n }\n\n return k === key;\n });\n\n if (absent) {\n var update = {};\n update[key] = data[key];\n\n _sync.reactSetState.call(options.context, update, cb);\n }\n });\n };\n\n return (0, _utils._returnRef)(endpoint, 'syncState', id, options.context);\n }\n /***/\n\n },\n /* 11 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _bind;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _bind(endpoint, options, invoker, state) {\n (0, _validators._validateEndpoint)(endpoint);\n\n _validators.optionValidators.context(options);\n\n _validators.optionValidators.defaultValue(options);\n\n invoker === 'listenTo' && _validators.optionValidators.then(options);\n invoker === 'bindToState' && _validators.optionValidators.state(options);\n options.queries && _validators.optionValidators.query(options);\n options.then && (options.then.called = false);\n var id = (0, _utils._createHash)(endpoint, invoker);\n var ref = state.db.ref(endpoint);\n (0, _utils._firebaseRefsMixin)(id, ref, state.refs);\n (0, _utils._addListener)(id, invoker, options, ref, state.listeners);\n (0, _utils._setUnmountHandler)(options.context, id, state.refs, state.listeners, state.syncs);\n return (0, _utils._returnRef)(endpoint, invoker, id, options.context);\n }\n /***/\n\n },\n /* 12 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _update;\n\n var _validators = __webpack_require__(5);\n\n function _update(endpoint, options, state) {\n (0, _validators._validateEndpoint)(endpoint);\n\n _validators.optionValidators.data(options);\n\n var ref = state.db.ref(endpoint);\n\n if (options.then) {\n return ref.update(options.data, options.then);\n } else {\n return ref.update(options.data);\n }\n }\n /***/\n\n },\n /* 13 */\n\n /***/\n function (module, exports) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _reset;\n\n function _reset(state) {\n state.refs.forEach(function (ref, id) {\n ref.off('value', state.listeners.get(id));\n });\n state.listeners = new Map();\n state.refs = new Map();\n state.syncs = new WeakMap();\n return null;\n }\n /***/\n\n },\n /* 14 */\n\n /***/\n function (module, exports) {\n \"use strict\";\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n\n exports.default = function (endpoint, db, fn) {\n return db.ref().child(endpoint).remove(fn);\n };\n /***/\n\n },\n /* 15 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsSync;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _fsSync(document, options, state) {\n //validate arguments\n (0, _validators._validateDocumentPath)(document);\n\n _validators.optionValidators.context(options);\n\n _validators.optionValidators.state(options);\n\n options.then && (options.then.called = false); //store reference to react's setState\n\n if (_fsSync.called !== true) {\n _fsSync.reactSetState = options.context.setState;\n _fsSync.called = true;\n }\n\n options.reactSetState = _fsSync.reactSetState;\n var id = (0, _utils._createHash)(document, 'syncDoc');\n var ref = (0, _utils._fsCreateRef)(document, state.db);\n (0, _utils._firebaseRefsMixin)(id, ref, state.refs);\n (0, _utils._addFirestoreListener)(id, 'syncDoc', options, ref, state.listeners);\n (0, _utils._fsSetUnmountHandler)(options.context, id, state.refs, state.listeners, state.syncs);\n var sync = {\n id: id,\n updateFirebase: _utils._fsUpdateSyncState.bind(null, ref),\n stateKey: options.state\n };\n (0, _utils._addSync)(options.context, sync, state.syncs);\n\n options.context.setState = function (data, cb) {\n //if setState is a function, call it first before syncing to fb\n if (typeof data === 'function') {\n return _fsSync.reactSetState.call(options.context, data, function () {\n if (cb) cb.call(options.context);\n return options.context.setState.call(options.context, options.context.state);\n });\n } //if callback is supplied, call setState first before syncing to fb\n\n\n if (typeof cb === 'function') {\n return _fsSync.reactSetState.call(options.context, data, function () {\n cb();\n return options.context.setState.call(options.context, data);\n });\n }\n\n var syncsToCall = state.syncs.get(this); //if sync does not exist, call original Component.setState\n\n if (!syncsToCall || syncsToCall.length === 0) {\n return _fsSync.reactSetState.call(this, data, cb);\n } //send the update of synced keys to firestore\n\n\n var syncedKeys = syncsToCall.map(function (sync) {\n return {\n key: sync.stateKey,\n update: sync.updateFirebase\n };\n });\n syncedKeys.forEach(function (syncedKey) {\n if (data[syncedKey.key]) {\n syncedKey.update(data[syncedKey.key]);\n }\n }); //send the update of all other keys through setState\n\n var allKeys = Object.keys(data);\n allKeys.forEach(function (key) {\n var absent = !syncedKeys.find(function (syncedKey) {\n return syncedKey.key === key;\n });\n\n if (absent) {\n var update = {};\n update[key] = data[key];\n\n _fsSync.reactSetState.call(options.context, function (currentState) {\n return Object.assign(currentState, update);\n }, cb);\n }\n });\n };\n\n return (0, _utils._returnRef)(document, 'syncDoc', id, options.context);\n }\n /***/\n\n },\n /* 16 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsBind;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _fsBind(path, options, invoker, state) {\n _validators.optionValidators.context(options);\n\n options.then && (options.then.called = false);\n\n if (invoker === 'bindDoc') {\n (0, _validators._validateDocumentPath)(path);\n }\n\n if (invoker === 'bindCollection') {\n _validators.optionValidators.state(options);\n\n (0, _validators._validateCollectionPath)(path);\n }\n\n if (invoker === 'listenToDoc') {\n (0, _validators._validateDocumentPath)(path);\n\n _validators.optionValidators.then(options);\n }\n\n if (invoker === 'listenToCollection') {\n (0, _validators._validateCollectionPath)(path);\n\n _validators.optionValidators.then(options);\n }\n\n var ref = (0, _utils._fsCreateRef)(path, state.db);\n var id = (0, _utils._createHash)(path, invoker);\n (0, _utils._firebaseRefsMixin)(id, ref, state.refs);\n (0, _utils._addFirestoreListener)(id, invoker, options, ref, state.listeners);\n (0, _utils._fsSetUnmountHandler)(options.context, id, state.refs, state.listeners, state.syncs);\n return (0, _utils._returnRef)(path, invoker, id, options.context);\n }\n /***/\n\n },\n /* 17 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsGet;\n\n var _utils = __webpack_require__(2);\n\n var _validators = __webpack_require__(5);\n\n function _fsGet(endpoint) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n var db = arguments[2];\n (0, _validators._validateEndpoint)(endpoint);\n var ref = (0, _utils._fsCreateRef)(endpoint, db); //check if ref is a collection\n\n var isCollection = !!ref.add;\n ref = (0, _utils._addFirestoreQuery)(ref, options.query);\n return ref.get().then(function (snapshot) {\n if (isCollection && !snapshot.empty || !isCollection && snapshot.exists) {\n return (0, _utils._fsPrepareData)(snapshot, options, isCollection);\n } else {\n return Promise.reject(new Error('No Result'));\n }\n });\n }\n /***/\n\n },\n /* 18 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsRemoveDoc;\n\n var _utils = __webpack_require__(2);\n\n function _fsRemoveDoc(path, db) {\n var ref = (0, _utils._fsCreateRef)(path, db);\n return ref.delete();\n }\n /***/\n\n },\n /* 19 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsAddToCollection;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _fsAddToCollection(path, doc, db, key) {\n (0, _validators._validateCollectionPath)(path);\n var ref = (0, _utils._fsCreateRef)(path, db);\n\n if (key) {\n return ref.doc(key).set(doc);\n }\n\n return ref.add(doc);\n }\n /***/\n\n },\n /* 20 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsRemoveFromCollection;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _fsRemoveFromCollection(path, db) {\n var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};\n (0, _validators._validateCollectionPath)(path);\n var ref = (0, _utils._fsCreateRef)(path, db);\n ref = (0, _utils._addFirestoreQuery)(ref, options.query);\n return ref.get().then(function (snapshot) {\n if (!snapshot.empty) {\n var batch = db.batch();\n snapshot.forEach(function (doc) {\n batch.delete(doc.ref);\n });\n return batch.commit();\n }\n });\n }\n /***/\n\n },\n /* 21 */\n\n /***/\n function (module, exports, __webpack_require__) {\n 'use strict';\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsUpdateDoc;\n\n var _validators = __webpack_require__(5);\n\n var _utils = __webpack_require__(2);\n\n function _fsUpdateDoc(document, data, db) {\n (0, _validators._validateDocumentPath)(document);\n var ref = (0, _utils._fsCreateRef)(document, db);\n return ref.update(data);\n }\n /***/\n\n },\n /* 22 */\n\n /***/\n function (module, exports) {\n \"use strict\";\n\n Object.defineProperty(exports, \"__esModule\", {\n value: true\n });\n exports.default = _fsReset;\n\n function _fsReset(state) {\n state.listeners.forEach(function (unsubscribe, id) {\n unsubscribe();\n });\n state.listeners = new Map();\n state.refs = new Map();\n state.syncs = new WeakMap();\n return null;\n }\n /***/\n\n }])\n );\n});\n\n;","'use strict';\n\nfunction _interopDefault(ex) {\n return ex && typeof ex === 'object' && 'default' in ex ? ex['default'] : ex;\n}\n\nrequire('@firebase/polyfill');\n\nvar firebase = _interopDefault(require('@firebase/app'));\n/**\r\n * Copyright 2018 Google Inc.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\");\r\n * you may not use this file except in compliance with the License.\r\n * You may obtain a copy of the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS,\r\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n * See the License for the specific language governing permissions and\r\n * limitations under the License.\r\n */\n\n\nmodule.exports = firebase;","module.exports = Array.isArray || function (arr) {\n return Object.prototype.toString.call(arr) == '[object Array]';\n};","function isAbsolute(pathname) {\n return pathname.charAt(0) === '/';\n} // About 1.5x faster than the two-arg version of Array#splice()\n\n\nfunction spliceOne(list, index) {\n for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) {\n list[i] = list[k];\n }\n\n list.pop();\n} // This implementation is based heavily on node's url.parse\n\n\nfunction resolvePathname(to) {\n var from = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';\n var toParts = to && to.split('/') || [];\n var fromParts = from && from.split('/') || [];\n var isToAbs = to && isAbsolute(to);\n var isFromAbs = from && isAbsolute(from);\n var mustEndAbs = isToAbs || isFromAbs;\n\n if (to && isAbsolute(to)) {\n // to is absolute\n fromParts = toParts;\n } else if (toParts.length) {\n // to is relative, drop the filename\n fromParts.pop();\n fromParts = fromParts.concat(toParts);\n }\n\n if (!fromParts.length) return '/';\n var hasTrailingSlash = void 0;\n\n if (fromParts.length) {\n var last = fromParts[fromParts.length - 1];\n hasTrailingSlash = last === '.' || last === '..' || last === '';\n } else {\n hasTrailingSlash = false;\n }\n\n var up = 0;\n\n for (var i = fromParts.length; i >= 0; i--) {\n var part = fromParts[i];\n\n if (part === '.') {\n spliceOne(fromParts, i);\n } else if (part === '..') {\n spliceOne(fromParts, i);\n up++;\n } else if (up) {\n spliceOne(fromParts, i);\n up--;\n }\n }\n\n if (!mustEndAbs) for (; up--; up) {\n fromParts.unshift('..');\n }\n if (mustEndAbs && fromParts[0] !== '' && (!fromParts[0] || !isAbsolute(fromParts[0]))) fromParts.unshift('');\n var result = fromParts.join('/');\n if (hasTrailingSlash && result.substr(-1) !== '/') result += '/';\n return result;\n}\n\nexport default resolvePathname;","var _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n} : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nfunction valueEqual(a, b) {\n if (a === b) return true;\n if (a == null || b == null) return false;\n\n if (Array.isArray(a)) {\n return Array.isArray(b) && a.length === b.length && a.every(function (item, index) {\n return valueEqual(item, b[index]);\n });\n }\n\n var aType = typeof a === 'undefined' ? 'undefined' : _typeof(a);\n var bType = typeof b === 'undefined' ? 'undefined' : _typeof(b);\n if (aType !== bType) return false;\n\n if (aType === 'object') {\n var aValue = a.valueOf();\n var bValue = b.valueOf();\n if (aValue !== a || bValue !== b) return valueEqual(aValue, bValue);\n var aKeys = Object.keys(a);\n var bKeys = Object.keys(b);\n if (aKeys.length !== bKeys.length) return false;\n return aKeys.every(function (key) {\n return valueEqual(a[key], b[key]);\n });\n }\n\n return false;\n}\n\nexport default valueEqual;","export var addLeadingSlash = function addLeadingSlash(path) {\n return path.charAt(0) === '/' ? path : '/' + path;\n};\nexport var stripLeadingSlash = function stripLeadingSlash(path) {\n return path.charAt(0) === '/' ? path.substr(1) : path;\n};\nexport var hasBasename = function hasBasename(path, prefix) {\n return new RegExp('^' + prefix + '(\\\\/|\\\\?|#|$)', 'i').test(path);\n};\nexport var stripBasename = function stripBasename(path, prefix) {\n return hasBasename(path, prefix) ? path.substr(prefix.length) : path;\n};\nexport var stripTrailingSlash = function stripTrailingSlash(path) {\n return path.charAt(path.length - 1) === '/' ? path.slice(0, -1) : path;\n};\nexport var parsePath = function parsePath(path) {\n var pathname = path || '/';\n var search = '';\n var hash = '';\n var hashIndex = pathname.indexOf('#');\n\n if (hashIndex !== -1) {\n hash = pathname.substr(hashIndex);\n pathname = pathname.substr(0, hashIndex);\n }\n\n var searchIndex = pathname.indexOf('?');\n\n if (searchIndex !== -1) {\n search = pathname.substr(searchIndex);\n pathname = pathname.substr(0, searchIndex);\n }\n\n return {\n pathname: pathname,\n search: search === '?' ? '' : search,\n hash: hash === '#' ? '' : hash\n };\n};\nexport var createPath = function createPath(location) {\n var pathname = location.pathname,\n search = location.search,\n hash = location.hash;\n var path = pathname || '/';\n if (search && search !== '?') path += search.charAt(0) === '?' ? search : '?' + search;\n if (hash && hash !== '#') path += hash.charAt(0) === '#' ? hash : '#' + hash;\n return path;\n};","var _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nimport resolvePathname from 'resolve-pathname';\nimport valueEqual from 'value-equal';\nimport { parsePath } from './PathUtils';\nexport var createLocation = function createLocation(path, state, key, currentLocation) {\n var location = void 0;\n\n if (typeof path === 'string') {\n // Two-arg form: push(path, state)\n location = parsePath(path);\n location.state = state;\n } else {\n // One-arg form: push(location)\n location = _extends({}, path);\n if (location.pathname === undefined) location.pathname = '';\n\n if (location.search) {\n if (location.search.charAt(0) !== '?') location.search = '?' + location.search;\n } else {\n location.search = '';\n }\n\n if (location.hash) {\n if (location.hash.charAt(0) !== '#') location.hash = '#' + location.hash;\n } else {\n location.hash = '';\n }\n\n if (state !== undefined && location.state === undefined) location.state = state;\n }\n\n try {\n location.pathname = decodeURI(location.pathname);\n } catch (e) {\n if (e instanceof URIError) {\n throw new URIError('Pathname \"' + location.pathname + '\" could not be decoded. ' + 'This is likely caused by an invalid percent-encoding.');\n } else {\n throw e;\n }\n }\n\n if (key) location.key = key;\n\n if (currentLocation) {\n // Resolve incomplete/relative pathname relative to current location.\n if (!location.pathname) {\n location.pathname = currentLocation.pathname;\n } else if (location.pathname.charAt(0) !== '/') {\n location.pathname = resolvePathname(location.pathname, currentLocation.pathname);\n }\n } else {\n // When there is no prior location and pathname is empty, set it to /\n if (!location.pathname) {\n location.pathname = '/';\n }\n }\n\n return location;\n};\nexport var locationsAreEqual = function locationsAreEqual(a, b) {\n return a.pathname === b.pathname && a.search === b.search && a.hash === b.hash && a.key === b.key && valueEqual(a.state, b.state);\n};","import warning from 'warning';\n\nvar createTransitionManager = function createTransitionManager() {\n var prompt = null;\n\n var setPrompt = function setPrompt(nextPrompt) {\n warning(prompt == null, 'A history supports only one prompt at a time');\n prompt = nextPrompt;\n return function () {\n if (prompt === nextPrompt) prompt = null;\n };\n };\n\n var confirmTransitionTo = function confirmTransitionTo(location, action, getUserConfirmation, callback) {\n // TODO: If another transition starts while we're still confirming\n // the previous one, we may end up in a weird state. Figure out the\n // best way to handle this.\n if (prompt != null) {\n var result = typeof prompt === 'function' ? prompt(location, action) : prompt;\n\n if (typeof result === 'string') {\n if (typeof getUserConfirmation === 'function') {\n getUserConfirmation(result, callback);\n } else {\n warning(false, 'A history needs a getUserConfirmation function in order to use a prompt message');\n callback(true);\n }\n } else {\n // Return false from a transition hook to cancel the transition.\n callback(result !== false);\n }\n } else {\n callback(true);\n }\n };\n\n var listeners = [];\n\n var appendListener = function appendListener(fn) {\n var isActive = true;\n\n var listener = function listener() {\n if (isActive) fn.apply(undefined, arguments);\n };\n\n listeners.push(listener);\n return function () {\n isActive = false;\n listeners = listeners.filter(function (item) {\n return item !== listener;\n });\n };\n };\n\n var notifyListeners = function notifyListeners() {\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n listeners.forEach(function (listener) {\n return listener.apply(undefined, args);\n });\n };\n\n return {\n setPrompt: setPrompt,\n confirmTransitionTo: confirmTransitionTo,\n appendListener: appendListener,\n notifyListeners: notifyListeners\n };\n};\n\nexport default createTransitionManager;","export var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);\nexport var addEventListener = function addEventListener(node, event, listener) {\n return node.addEventListener ? node.addEventListener(event, listener, false) : node.attachEvent('on' + event, listener);\n};\nexport var removeEventListener = function removeEventListener(node, event, listener) {\n return node.removeEventListener ? node.removeEventListener(event, listener, false) : node.detachEvent('on' + event, listener);\n};\nexport var getConfirmation = function getConfirmation(message, callback) {\n return callback(window.confirm(message));\n}; // eslint-disable-line no-alert\n\n/**\n * Returns true if the HTML5 history API is supported. Taken from Modernizr.\n *\n * https://github.com/Modernizr/Modernizr/blob/master/LICENSE\n * https://github.com/Modernizr/Modernizr/blob/master/feature-detects/history.js\n * changed to avoid false negatives for Windows Phones: https://github.com/reactjs/react-router/issues/586\n */\n\nexport var supportsHistory = function supportsHistory() {\n var ua = window.navigator.userAgent;\n if ((ua.indexOf('Android 2.') !== -1 || ua.indexOf('Android 4.0') !== -1) && ua.indexOf('Mobile Safari') !== -1 && ua.indexOf('Chrome') === -1 && ua.indexOf('Windows Phone') === -1) return false;\n return window.history && 'pushState' in window.history;\n};\n/**\n * Returns true if browser fires popstate on hash change.\n * IE10 and IE11 do not.\n */\n\nexport var supportsPopStateOnHashChange = function supportsPopStateOnHashChange() {\n return window.navigator.userAgent.indexOf('Trident') === -1;\n};\n/**\n * Returns false if using go(n) with hash history causes a full page reload.\n */\n\nexport var supportsGoWithoutReloadUsingHash = function supportsGoWithoutReloadUsingHash() {\n return window.navigator.userAgent.indexOf('Firefox') === -1;\n};\n/**\n * Returns true if a given popstate event is an extraneous WebKit event.\n * Accounts for the fact that Chrome on iOS fires real popstate events\n * containing undefined state when pressing the back button.\n */\n\nexport var isExtraneousPopstateEvent = function isExtraneousPopstateEvent(event) {\n return event.state === undefined && navigator.userAgent.indexOf('CriOS') === -1;\n};","var _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n} : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nvar _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nimport warning from 'warning';\nimport invariant from 'invariant';\nimport { createLocation } from './LocationUtils';\nimport { addLeadingSlash, stripTrailingSlash, hasBasename, stripBasename, createPath } from './PathUtils';\nimport createTransitionManager from './createTransitionManager';\nimport { canUseDOM, addEventListener, removeEventListener, getConfirmation, supportsHistory, supportsPopStateOnHashChange, isExtraneousPopstateEvent } from './DOMUtils';\nvar PopStateEvent = 'popstate';\nvar HashChangeEvent = 'hashchange';\n\nvar getHistoryState = function getHistoryState() {\n try {\n return window.history.state || {};\n } catch (e) {\n // IE 11 sometimes throws when accessing window.history.state\n // See https://github.com/ReactTraining/history/pull/289\n return {};\n }\n};\n/**\n * Creates a history object that uses the HTML5 history API including\n * pushState, replaceState, and the popstate event.\n */\n\n\nvar createBrowserHistory = function createBrowserHistory() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n invariant(canUseDOM, 'Browser history needs a DOM');\n var globalHistory = window.history;\n var canUseHistory = supportsHistory();\n var needsHashChangeListener = !supportsPopStateOnHashChange();\n var _props$forceRefresh = props.forceRefresh,\n forceRefresh = _props$forceRefresh === undefined ? false : _props$forceRefresh,\n _props$getUserConfirm = props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === undefined ? getConfirmation : _props$getUserConfirm,\n _props$keyLength = props.keyLength,\n keyLength = _props$keyLength === undefined ? 6 : _props$keyLength;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n\n var getDOMLocation = function getDOMLocation(historyState) {\n var _ref = historyState || {},\n key = _ref.key,\n state = _ref.state;\n\n var _window$location = window.location,\n pathname = _window$location.pathname,\n search = _window$location.search,\n hash = _window$location.hash;\n var path = pathname + search + hash;\n warning(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".');\n if (basename) path = stripBasename(path, basename);\n return createLocation(path, state, key);\n };\n\n var createKey = function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n };\n\n var transitionManager = createTransitionManager();\n\n var setState = function setState(nextState) {\n _extends(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n };\n\n var handlePopState = function handlePopState(event) {\n // Ignore extraneous popstate events in WebKit.\n if (isExtraneousPopstateEvent(event)) return;\n handlePop(getDOMLocation(event.state));\n };\n\n var handleHashChange = function handleHashChange() {\n handlePop(getDOMLocation(getHistoryState()));\n };\n\n var forceNextPop = false;\n\n var handlePop = function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n };\n\n var revertPop = function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of keys we've seen in sessionStorage.\n // Instead, we just default to 0 for keys we don't know.\n\n var toIndex = allKeys.indexOf(toLocation.key);\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allKeys.indexOf(fromLocation.key);\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n };\n\n var initialLocation = getDOMLocation(getHistoryState());\n var allKeys = [initialLocation.key]; // Public interface\n\n var createHref = function createHref(location) {\n return basename + createPath(location);\n };\n\n var push = function push(path, state) {\n warning(!((typeof path === 'undefined' ? 'undefined' : _typeof(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored');\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.pushState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.href = href;\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n var nextKeys = allKeys.slice(0, prevIndex === -1 ? 0 : prevIndex + 1);\n nextKeys.push(location.key);\n allKeys = nextKeys;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n warning(state === undefined, 'Browser history cannot push state in browsers that do not support HTML5 history');\n window.location.href = href;\n }\n });\n };\n\n var replace = function replace(path, state) {\n warning(!((typeof path === 'undefined' ? 'undefined' : _typeof(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored');\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var href = createHref(location);\n var key = location.key,\n state = location.state;\n\n if (canUseHistory) {\n globalHistory.replaceState({\n key: key,\n state: state\n }, null, href);\n\n if (forceRefresh) {\n window.location.replace(href);\n } else {\n var prevIndex = allKeys.indexOf(history.location.key);\n if (prevIndex !== -1) allKeys[prevIndex] = location.key;\n setState({\n action: action,\n location: location\n });\n }\n } else {\n warning(state === undefined, 'Browser history cannot replace state in browsers that do not support HTML5 history');\n window.location.replace(href);\n }\n });\n };\n\n var go = function go(n) {\n globalHistory.go(n);\n };\n\n var goBack = function goBack() {\n return go(-1);\n };\n\n var goForward = function goForward() {\n return go(1);\n };\n\n var listenerCount = 0;\n\n var checkDOMListeners = function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1) {\n addEventListener(window, PopStateEvent, handlePopState);\n if (needsHashChangeListener) addEventListener(window, HashChangeEvent, handleHashChange);\n } else if (listenerCount === 0) {\n removeEventListener(window, PopStateEvent, handlePopState);\n if (needsHashChangeListener) removeEventListener(window, HashChangeEvent, handleHashChange);\n }\n };\n\n var isBlocked = false;\n\n var block = function block() {\n var prompt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n };\n\n var listen = function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n };\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n};\n\nexport default createBrowserHistory;","var _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _possibleConstructorReturn(self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n}\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n}\n\nimport warning from \"warning\";\nimport invariant from \"invariant\";\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\n/**\n * The public API for putting history on context.\n */\n\nvar Router = function (_React$Component) {\n _inherits(Router, _React$Component);\n\n function Router() {\n var _temp, _this, _ret;\n\n _classCallCheck(this, Router);\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {\n match: _this.computeMatch(_this.props.history.location.pathname)\n }, _temp), _possibleConstructorReturn(_this, _ret);\n }\n\n Router.prototype.getChildContext = function getChildContext() {\n return {\n router: _extends({}, this.context.router, {\n history: this.props.history,\n route: {\n location: this.props.history.location,\n match: this.state.match\n }\n })\n };\n };\n\n Router.prototype.computeMatch = function computeMatch(pathname) {\n return {\n path: \"/\",\n url: \"/\",\n params: {},\n isExact: pathname === \"/\"\n };\n };\n\n Router.prototype.componentWillMount = function componentWillMount() {\n var _this2 = this;\n\n var _props = this.props,\n children = _props.children,\n history = _props.history;\n invariant(children == null || React.Children.count(children) === 1, \"A may have only one child element\"); // Do this here so we can setState when a changes the\n // location in componentWillMount. This happens e.g. when doing\n // server rendering using a .\n\n this.unlisten = history.listen(function () {\n _this2.setState({\n match: _this2.computeMatch(history.location.pathname)\n });\n });\n };\n\n Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n warning(this.props.history === nextProps.history, \"You cannot change \");\n };\n\n Router.prototype.componentWillUnmount = function componentWillUnmount() {\n this.unlisten();\n };\n\n Router.prototype.render = function render() {\n var children = this.props.children;\n return children ? React.Children.only(children) : null;\n };\n\n return Router;\n}(React.Component);\n\nRouter.propTypes = {\n history: PropTypes.object.isRequired,\n children: PropTypes.node\n};\nRouter.contextTypes = {\n router: PropTypes.object\n};\nRouter.childContextTypes = {\n router: PropTypes.object.isRequired\n};\nexport default Router;","var _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nimport warning from 'warning';\nimport invariant from 'invariant';\nimport { createLocation, locationsAreEqual } from './LocationUtils';\nimport { addLeadingSlash, stripLeadingSlash, stripTrailingSlash, hasBasename, stripBasename, createPath } from './PathUtils';\nimport createTransitionManager from './createTransitionManager';\nimport { canUseDOM, addEventListener, removeEventListener, getConfirmation, supportsGoWithoutReloadUsingHash } from './DOMUtils';\nvar HashChangeEvent = 'hashchange';\nvar HashPathCoders = {\n hashbang: {\n encodePath: function encodePath(path) {\n return path.charAt(0) === '!' ? path : '!/' + stripLeadingSlash(path);\n },\n decodePath: function decodePath(path) {\n return path.charAt(0) === '!' ? path.substr(1) : path;\n }\n },\n noslash: {\n encodePath: stripLeadingSlash,\n decodePath: addLeadingSlash\n },\n slash: {\n encodePath: addLeadingSlash,\n decodePath: addLeadingSlash\n }\n};\n\nvar getHashPath = function getHashPath() {\n // We can't use window.location.hash here because it's not\n // consistent across browsers - Firefox will pre-decode it!\n var href = window.location.href;\n var hashIndex = href.indexOf('#');\n return hashIndex === -1 ? '' : href.substring(hashIndex + 1);\n};\n\nvar pushHashPath = function pushHashPath(path) {\n return window.location.hash = path;\n};\n\nvar replaceHashPath = function replaceHashPath(path) {\n var hashIndex = window.location.href.indexOf('#');\n window.location.replace(window.location.href.slice(0, hashIndex >= 0 ? hashIndex : 0) + '#' + path);\n};\n\nvar createHashHistory = function createHashHistory() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n invariant(canUseDOM, 'Hash history needs a DOM');\n var globalHistory = window.history;\n var canGoWithoutReload = supportsGoWithoutReloadUsingHash();\n var _props$getUserConfirm = props.getUserConfirmation,\n getUserConfirmation = _props$getUserConfirm === undefined ? getConfirmation : _props$getUserConfirm,\n _props$hashType = props.hashType,\n hashType = _props$hashType === undefined ? 'slash' : _props$hashType;\n var basename = props.basename ? stripTrailingSlash(addLeadingSlash(props.basename)) : '';\n var _HashPathCoders$hashT = HashPathCoders[hashType],\n encodePath = _HashPathCoders$hashT.encodePath,\n decodePath = _HashPathCoders$hashT.decodePath;\n\n var getDOMLocation = function getDOMLocation() {\n var path = decodePath(getHashPath());\n warning(!basename || hasBasename(path, basename), 'You are attempting to use a basename on a page whose URL path does not begin ' + 'with the basename. Expected path \"' + path + '\" to begin with \"' + basename + '\".');\n if (basename) path = stripBasename(path, basename);\n return createLocation(path);\n };\n\n var transitionManager = createTransitionManager();\n\n var setState = function setState(nextState) {\n _extends(history, nextState);\n\n history.length = globalHistory.length;\n transitionManager.notifyListeners(history.location, history.action);\n };\n\n var forceNextPop = false;\n var ignorePath = null;\n\n var handleHashChange = function handleHashChange() {\n var path = getHashPath();\n var encodedPath = encodePath(path);\n\n if (path !== encodedPath) {\n // Ensure we always have a properly-encoded hash.\n replaceHashPath(encodedPath);\n } else {\n var location = getDOMLocation();\n var prevLocation = history.location;\n if (!forceNextPop && locationsAreEqual(prevLocation, location)) return; // A hashchange doesn't always == location change.\n\n if (ignorePath === createPath(location)) return; // Ignore this change; we already setState in push/replace.\n\n ignorePath = null;\n handlePop(location);\n }\n };\n\n var handlePop = function handlePop(location) {\n if (forceNextPop) {\n forceNextPop = false;\n setState();\n } else {\n var action = 'POP';\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location\n });\n } else {\n revertPop(location);\n }\n });\n }\n };\n\n var revertPop = function revertPop(fromLocation) {\n var toLocation = history.location; // TODO: We could probably make this more reliable by\n // keeping a list of paths we've seen in sessionStorage.\n // Instead, we just default to 0 for paths we don't know.\n\n var toIndex = allPaths.lastIndexOf(createPath(toLocation));\n if (toIndex === -1) toIndex = 0;\n var fromIndex = allPaths.lastIndexOf(createPath(fromLocation));\n if (fromIndex === -1) fromIndex = 0;\n var delta = toIndex - fromIndex;\n\n if (delta) {\n forceNextPop = true;\n go(delta);\n }\n }; // Ensure the hash is encoded properly before doing anything else.\n\n\n var path = getHashPath();\n var encodedPath = encodePath(path);\n if (path !== encodedPath) replaceHashPath(encodedPath);\n var initialLocation = getDOMLocation();\n var allPaths = [createPath(initialLocation)]; // Public interface\n\n var createHref = function createHref(location) {\n return '#' + encodePath(basename + createPath(location));\n };\n\n var push = function push(path, state) {\n warning(state === undefined, 'Hash history cannot push state; it is ignored');\n var action = 'PUSH';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a PUSH, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n pushHashPath(encodedPath);\n var prevIndex = allPaths.lastIndexOf(createPath(history.location));\n var nextPaths = allPaths.slice(0, prevIndex === -1 ? 0 : prevIndex + 1);\n nextPaths.push(path);\n allPaths = nextPaths;\n setState({\n action: action,\n location: location\n });\n } else {\n warning(false, 'Hash history cannot PUSH the same path; a new entry will not be added to the history stack');\n setState();\n }\n });\n };\n\n var replace = function replace(path, state) {\n warning(state === undefined, 'Hash history cannot replace state; it is ignored');\n var action = 'REPLACE';\n var location = createLocation(path, undefined, undefined, history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var path = createPath(location);\n var encodedPath = encodePath(basename + path);\n var hashChanged = getHashPath() !== encodedPath;\n\n if (hashChanged) {\n // We cannot tell if a hashchange was caused by a REPLACE, so we'd\n // rather setState here and ignore the hashchange. The caveat here\n // is that other hash histories in the page will consider it a POP.\n ignorePath = path;\n replaceHashPath(encodedPath);\n }\n\n var prevIndex = allPaths.indexOf(createPath(history.location));\n if (prevIndex !== -1) allPaths[prevIndex] = path;\n setState({\n action: action,\n location: location\n });\n });\n };\n\n var go = function go(n) {\n warning(canGoWithoutReload, 'Hash history go(n) causes a full page reload in this browser');\n globalHistory.go(n);\n };\n\n var goBack = function goBack() {\n return go(-1);\n };\n\n var goForward = function goForward() {\n return go(1);\n };\n\n var listenerCount = 0;\n\n var checkDOMListeners = function checkDOMListeners(delta) {\n listenerCount += delta;\n\n if (listenerCount === 1) {\n addEventListener(window, HashChangeEvent, handleHashChange);\n } else if (listenerCount === 0) {\n removeEventListener(window, HashChangeEvent, handleHashChange);\n }\n };\n\n var isBlocked = false;\n\n var block = function block() {\n var prompt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var unblock = transitionManager.setPrompt(prompt);\n\n if (!isBlocked) {\n checkDOMListeners(1);\n isBlocked = true;\n }\n\n return function () {\n if (isBlocked) {\n isBlocked = false;\n checkDOMListeners(-1);\n }\n\n return unblock();\n };\n };\n\n var listen = function listen(listener) {\n var unlisten = transitionManager.appendListener(listener);\n checkDOMListeners(1);\n return function () {\n checkDOMListeners(-1);\n unlisten();\n };\n };\n\n var history = {\n length: globalHistory.length,\n action: 'POP',\n location: initialLocation,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n block: block,\n listen: listen\n };\n return history;\n};\n\nexport default createHashHistory;","var _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) {\n return typeof obj;\n} : function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n};\n\nvar _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nimport warning from 'warning';\nimport { createPath } from './PathUtils';\nimport { createLocation } from './LocationUtils';\nimport createTransitionManager from './createTransitionManager';\n\nvar clamp = function clamp(n, lowerBound, upperBound) {\n return Math.min(Math.max(n, lowerBound), upperBound);\n};\n/**\n * Creates a history object that stores locations in memory.\n */\n\n\nvar createMemoryHistory = function createMemoryHistory() {\n var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n var getUserConfirmation = props.getUserConfirmation,\n _props$initialEntries = props.initialEntries,\n initialEntries = _props$initialEntries === undefined ? ['/'] : _props$initialEntries,\n _props$initialIndex = props.initialIndex,\n initialIndex = _props$initialIndex === undefined ? 0 : _props$initialIndex,\n _props$keyLength = props.keyLength,\n keyLength = _props$keyLength === undefined ? 6 : _props$keyLength;\n var transitionManager = createTransitionManager();\n\n var setState = function setState(nextState) {\n _extends(history, nextState);\n\n history.length = history.entries.length;\n transitionManager.notifyListeners(history.location, history.action);\n };\n\n var createKey = function createKey() {\n return Math.random().toString(36).substr(2, keyLength);\n };\n\n var index = clamp(initialIndex, 0, initialEntries.length - 1);\n var entries = initialEntries.map(function (entry) {\n return typeof entry === 'string' ? createLocation(entry, undefined, createKey()) : createLocation(entry, undefined, entry.key || createKey());\n }); // Public interface\n\n var createHref = createPath;\n\n var push = function push(path, state) {\n warning(!((typeof path === 'undefined' ? 'undefined' : _typeof(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to push when the 1st ' + 'argument is a location-like object that already has state; it is ignored');\n var action = 'PUSH';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n var prevIndex = history.index;\n var nextIndex = prevIndex + 1;\n var nextEntries = history.entries.slice(0);\n\n if (nextEntries.length > nextIndex) {\n nextEntries.splice(nextIndex, nextEntries.length - nextIndex, location);\n } else {\n nextEntries.push(location);\n }\n\n setState({\n action: action,\n location: location,\n index: nextIndex,\n entries: nextEntries\n });\n });\n };\n\n var replace = function replace(path, state) {\n warning(!((typeof path === 'undefined' ? 'undefined' : _typeof(path)) === 'object' && path.state !== undefined && state !== undefined), 'You should avoid providing a 2nd state argument to replace when the 1st ' + 'argument is a location-like object that already has state; it is ignored');\n var action = 'REPLACE';\n var location = createLocation(path, state, createKey(), history.location);\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (!ok) return;\n history.entries[history.index] = location;\n setState({\n action: action,\n location: location\n });\n });\n };\n\n var go = function go(n) {\n var nextIndex = clamp(history.index + n, 0, history.entries.length - 1);\n var action = 'POP';\n var location = history.entries[nextIndex];\n transitionManager.confirmTransitionTo(location, action, getUserConfirmation, function (ok) {\n if (ok) {\n setState({\n action: action,\n location: location,\n index: nextIndex\n });\n } else {\n // Mimic the behavior of DOM histories by\n // causing a render after a cancelled POP.\n setState();\n }\n });\n };\n\n var goBack = function goBack() {\n return go(-1);\n };\n\n var goForward = function goForward() {\n return go(1);\n };\n\n var canGo = function canGo(n) {\n var nextIndex = history.index + n;\n return nextIndex >= 0 && nextIndex < history.entries.length;\n };\n\n var block = function block() {\n var prompt = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n return transitionManager.setPrompt(prompt);\n };\n\n var listen = function listen(listener) {\n return transitionManager.appendListener(listener);\n };\n\n var history = {\n length: entries.length,\n action: 'POP',\n location: entries[index],\n index: index,\n entries: entries,\n createHref: createHref,\n push: push,\n replace: replace,\n go: go,\n goBack: goBack,\n goForward: goForward,\n canGo: canGo,\n block: block,\n listen: listen\n };\n return history;\n};\n\nexport default createMemoryHistory;","// Written in this round about way for babel-transform-imports\nimport Router from \"react-router/es/Router\";\nexport default Router;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _possibleConstructorReturn(self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n}\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n}\n\nimport warning from \"warning\";\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\nimport { createBrowserHistory as createHistory } from \"history\";\nimport Router from \"./Router\";\n/**\n * The public API for a that uses HTML5 history.\n */\n\nvar BrowserRouter = function (_React$Component) {\n _inherits(BrowserRouter, _React$Component);\n\n function BrowserRouter() {\n var _temp, _this, _ret;\n\n _classCallCheck(this, BrowserRouter);\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret);\n }\n\n BrowserRouter.prototype.componentWillMount = function componentWillMount() {\n warning(!this.props.history, \" ignores the history prop. To use a custom history, \" + \"use `import { Router }` instead of `import { BrowserRouter as Router }`.\");\n };\n\n BrowserRouter.prototype.render = function render() {\n return React.createElement(Router, {\n history: this.history,\n children: this.props.children\n });\n };\n\n return BrowserRouter;\n}(React.Component);\n\nBrowserRouter.propTypes = {\n basename: PropTypes.string,\n forceRefresh: PropTypes.bool,\n getUserConfirmation: PropTypes.func,\n keyLength: PropTypes.number,\n children: PropTypes.node\n};\nexport default BrowserRouter;","var _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n};\n\nfunction _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _possibleConstructorReturn(self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n}\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n}\n\nimport warning from \"warning\";\nimport invariant from \"invariant\";\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\nimport matchPath from \"./matchPath\";\n\nvar isEmptyChildren = function isEmptyChildren(children) {\n return React.Children.count(children) === 0;\n};\n/**\n * The public API for matching a single path and rendering.\n */\n\n\nvar Route = function (_React$Component) {\n _inherits(Route, _React$Component);\n\n function Route() {\n var _temp, _this, _ret;\n\n _classCallCheck(this, Route);\n\n for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {\n args[_key] = arguments[_key];\n }\n\n return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {\n match: _this.computeMatch(_this.props, _this.context.router)\n }, _temp), _possibleConstructorReturn(_this, _ret);\n }\n\n Route.prototype.getChildContext = function getChildContext() {\n return {\n router: _extends({}, this.context.router, {\n route: {\n location: this.props.location || this.context.router.route.location,\n match: this.state.match\n }\n })\n };\n };\n\n Route.prototype.computeMatch = function computeMatch(_ref, router) {\n var computedMatch = _ref.computedMatch,\n location = _ref.location,\n path = _ref.path,\n strict = _ref.strict,\n exact = _ref.exact,\n sensitive = _ref.sensitive;\n if (computedMatch) return computedMatch; // already computed the match for us\n\n invariant(router, \"You should not use or withRouter() outside a \");\n var route = router.route;\n var pathname = (location || route.location).pathname;\n return matchPath(pathname, {\n path: path,\n strict: strict,\n exact: exact,\n sensitive: sensitive\n }, route.match);\n };\n\n Route.prototype.componentWillMount = function componentWillMount() {\n warning(!(this.props.component && this.props.render), \"You should not use and in the same route; will be ignored\");\n warning(!(this.props.component && this.props.children && !isEmptyChildren(this.props.children)), \"You should not use and in the same route; will be ignored\");\n warning(!(this.props.render && this.props.children && !isEmptyChildren(this.props.children)), \"You should not use and in the same route; will be ignored\");\n };\n\n Route.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps, nextContext) {\n warning(!(nextProps.location && !this.props.location), ' elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.');\n warning(!(!nextProps.location && this.props.location), ' elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.');\n this.setState({\n match: this.computeMatch(nextProps, nextContext.router)\n });\n };\n\n Route.prototype.render = function render() {\n var match = this.state.match;\n var _props = this.props,\n children = _props.children,\n component = _props.component,\n render = _props.render;\n var _context$router = this.context.router,\n history = _context$router.history,\n route = _context$router.route,\n staticContext = _context$router.staticContext;\n var location = this.props.location || route.location;\n var props = {\n match: match,\n location: location,\n history: history,\n staticContext: staticContext\n };\n if (component) return match ? React.createElement(component, props) : null;\n if (render) return match ? render(props) : null;\n if (typeof children === \"function\") return children(props);\n if (children && !isEmptyChildren(children)) return React.Children.only(children);\n return null;\n };\n\n return Route;\n}(React.Component);\n\nRoute.propTypes = {\n computedMatch: PropTypes.object,\n // private, from \n path: PropTypes.string,\n exact: PropTypes.bool,\n strict: PropTypes.bool,\n sensitive: PropTypes.bool,\n component: PropTypes.func,\n render: PropTypes.func,\n children: PropTypes.oneOfType([PropTypes.func, PropTypes.node]),\n location: PropTypes.object\n};\nRoute.contextTypes = {\n router: PropTypes.shape({\n history: PropTypes.object.isRequired,\n route: PropTypes.object.isRequired,\n staticContext: PropTypes.object\n })\n};\nRoute.childContextTypes = {\n router: PropTypes.object.isRequired\n};\nexport default Route;","// Written in this round about way for babel-transform-imports\nimport Route from \"react-router/es/Route\";\nexport default Route;","function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n}\n\nfunction _possibleConstructorReturn(self, call) {\n if (!self) {\n throw new ReferenceError(\"this hasn't been initialised - super() hasn't been called\");\n }\n\n return call && (typeof call === \"object\" || typeof call === \"function\") ? call : self;\n}\n\nfunction _inherits(subClass, superClass) {\n if (typeof superClass !== \"function\" && superClass !== null) {\n throw new TypeError(\"Super expression must either be null or a function, not \" + typeof superClass);\n }\n\n subClass.prototype = Object.create(superClass && superClass.prototype, {\n constructor: {\n value: subClass,\n enumerable: false,\n writable: true,\n configurable: true\n }\n });\n if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;\n}\n\nimport React from \"react\";\nimport PropTypes from \"prop-types\";\nimport warning from \"warning\";\nimport invariant from \"invariant\";\nimport matchPath from \"./matchPath\";\n/**\n * The public API for rendering the first that matches.\n */\n\nvar Switch = function (_React$Component) {\n _inherits(Switch, _React$Component);\n\n function Switch() {\n _classCallCheck(this, Switch);\n\n return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));\n }\n\n Switch.prototype.componentWillMount = function componentWillMount() {\n invariant(this.context.router, \"You should not use outside a \");\n };\n\n Switch.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {\n warning(!(nextProps.location && !this.props.location), ' elements should not change from uncontrolled to controlled (or vice versa). You initially used no \"location\" prop and then provided one on a subsequent render.');\n warning(!(!nextProps.location && this.props.location), ' elements should not change from controlled to uncontrolled (or vice versa). You provided a \"location\" prop initially but omitted it on a subsequent render.');\n };\n\n Switch.prototype.render = function render() {\n var route = this.context.router.route;\n var children = this.props.children;\n var location = this.props.location || route.location;\n var match = void 0,\n child = void 0;\n React.Children.forEach(children, function (element) {\n if (match == null && React.isValidElement(element)) {\n var _element$props = element.props,\n pathProp = _element$props.path,\n exact = _element$props.exact,\n strict = _element$props.strict,\n sensitive = _element$props.sensitive,\n from = _element$props.from;\n var path = pathProp || from;\n child = element;\n match = matchPath(location.pathname, {\n path: path,\n exact: exact,\n strict: strict,\n sensitive: sensitive\n }, route.match);\n }\n });\n return match ? React.cloneElement(child, {\n location: location,\n computedMatch: match\n }) : null;\n };\n\n return Switch;\n}(React.Component);\n\nSwitch.contextTypes = {\n router: PropTypes.shape({\n route: PropTypes.object.isRequired\n }).isRequired\n};\nSwitch.propTypes = {\n children: PropTypes.node,\n location: PropTypes.object\n};\nexport default Switch;","// Written in this round about way for babel-transform-imports\nimport Switch from \"react-router/es/Switch\";\nexport default Switch;"],"sourceRoot":""} \ No newline at end of file diff --git a/build/static/js/main.40d8c8fe.chunk.js b/build/static/js/main.40d8c8fe.chunk.js new file mode 100644 index 00000000..470fc7e0 --- /dev/null +++ b/build/static/js/main.40d8c8fe.chunk.js @@ -0,0 +1,2 @@ +(window.webpackJsonp=window.webpackJsonp||[]).push([[0],{33:function(e,t,a){e.exports=a(63)},62:function(e,t,a){},63:function(e,t,a){"use strict";a.r(t);var n=a(0),r=a.n(n),s=a(19),i=a(65),c=a(67),o=a(66),l=a(5),u=a(6),h=a(8),m=a(7),p=a(9);function d(e){return(e/100).toLocaleString("en-US",{style:"currency",currency:"USD"})}function f(e){return e[Math.floor(Math.random()*e.length)]}function b(){var e=["adorable","beautiful","clean","drab","elegant","fancy","glamorous","handsome","long","magnificent","old-fashioned","plain","quaint","sparkling","ugliest","unsightly","angry","bewildered","clumsy","defeated","embarrassed","fierce","grumpy","helpless","itchy","jealous","lazy","mysterious","nervous","obnoxious","panicky","repulsive","scary","thoughtless","uptight","worried"];return"".concat(f(e),"-").concat(f(e),"-").concat(f(["women","men","children","teeth","feet","people","leaves","mice","geese","halves","knives","wives","lives","elves","loaves","potatoes","tomatoes","cacti","foci","fungi","nuclei","syllabuses","analyses","diagnoses","oases","theses","crises","phenomena","criteria","data"]))}var v=function(e){function t(){var e,a;Object(l.a)(this,t);for(var n=arguments.length,s=new Array(n),i=0;i {\n // 1. Stop the form from reloading on submit\n event.preventDefault();\n // 2. get the text from that input\n const storeName = this.myInput.current.value;\n // 3. Change the page to /store/name-of-the-store\n this.props.history.push(`/store/${storeName}`);\n };\n\n render() {\n return (\n
\n

Enter a Store name

\n \n \n \n );\n }\n}\n\nexport default StorePicker;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\n\nconst Header = props => (\n /*stateless functional component*/\n
\n

\n Catch\n \n of\n the\n \n Day\n

\n

\n {props.tagline}\n

\n
\n);\n\nHeader.propTypes = {\n tagline: PropTypes.string.isRequired\n};\n\nexport default Header;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\nimport { formatPrice } from \"../helpers\";\nimport { TransitionGroup, CSSTransition } from \"react-transition-group\";\n\nclass Order extends React.Component {\n static propTypes = {\n fishes: PropTypes.object.isRequired,\n order: PropTypes.object.isRequired,\n removeFromOrder: PropTypes.func.isRequired\n };\n\n renderOrder = key => {\n const fish = this.props.fishes[key];\n const count = this.props.order[key];\n const isAvailable = fish && fish.status === \"available\";\n const transitionOptions = {\n classNames: \"order\",\n key,\n timeout: { enter: 500, exit: 500 }\n };\n\n if (!fish) return null;\n\n if (!isAvailable) {\n return (\n \n
  • \n Sorry {fish ? fish.name : \"fish\"} is no longer available{\" \"}\n {/*if fish is deleted, name will not be available */}\n
  • \n
    \n );\n }\n return (\n \n
  • \n \n \n \n {count}\n \n \n lbs {fish.name}\n {formatPrice(count * fish.price)}\n \n \n
  • \n
    \n );\n };\n\n render() {\n const orderIds = Object.keys(this.props.order);\n const total = orderIds.reduce((prevTotal, key) => {\n const fish = this.props.fishes[key];\n const count = this.props.order[key];\n const isAvailable = fish && fish.status === \"available\";\n\n if (isAvailable) {\n return prevTotal + count * fish.price;\n }\n return prevTotal;\n }, 0);\n return (\n
    \n

    Order

    \n \n {orderIds.map(this.renderOrder)}\n \n
    \n Total:\n {formatPrice(total)}\n
    \n
    \n );\n }\n}\n\nexport default Order;\n","import React from \"react\";\nimport PropTypes from \"prop-types\";\n\nclass AddFish extends React.Component {\n nameRef = React.createRef();\n priceRef = React.createRef();\n statusRef = React.createRef();\n descRef = React.createRef();\n imageRef = React.createRef();\n\n static propTypes = {\n addFish: PropTypes.func.isRequired\n };\n\n createFish = event => {\n // stop the form from submitting & reloading\n event.preventDefault();\n const fish = {\n name: this.nameRef.current.value,\n price: parseFloat(this.priceRef.current.value),\n status: this.statusRef.current.value,\n desc: this.descRef.current.value,\n image: this.imageRef.current.value\n };\n // calls the custom method in App through props\n this.props.addFish(fish);\n // empties the form for new fish to be added\n event.currentTarget.reset();\n };\n render() {\n return (\n
    \n \n \n \n\n