/*! For license information please see background.js.LICENSE.txt */ (()=>{var e,t,i,r,n,a={30(e,t,i){"use strict";var r=i(6893),n=i(3315),a=i(4466),s=i(3770),o=i(380),l=i(7137);t.f=r&&!n?Object.defineProperties:function(e,t){s(e);for(var i,r=o(t),n=l(t),c=n.length,u=0;c>u;)a.f(e,i=n[u++],r[i]);return e}},81(e,t,i){var r=i(4643);i(9679),i(8550),(e.exports=r.hmac=r.hmac||{}).create=function(){var e=null,t=null,i=null,n=null,a={start:function(a,s){if(null!==a)if("string"==typeof a){if(!((a=a.toLowerCase())in r.md.algorithms))throw new Error('Unknown hash algorithm "'+a+'"');t=r.md.algorithms[a].create()}else t=a;if(null===s)s=e;else{if("string"==typeof s)s=r.util.createBuffer(s);else if(r.util.isArray(s)){var o=s;s=r.util.createBuffer();for(var l=0;lt.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),i=r.util.createBuffer(),n=r.util.createBuffer(),c=s.length(),l=0;l>14;--a>=0;){var l=16383&this.data[e],c=this.data[e++]>>14,u=o*l+c*s;n=((l=s*l+((16383&u)<<14)+i.data[r]+n)>>28)+(u>>14)+o*c,i.data[r++]=268435455&l}return n}e.exports=n.jsbn=n.jsbn||{},n.jsbn.BigInteger=a,"undefined"==typeof navigator?(a.prototype.am=o,r=28):"Microsoft Internet Explorer"==navigator.appName?(a.prototype.am=function(e,t,i,r,n,a){for(var s=32767&t,o=t>>15;--a>=0;){var l=32767&this.data[e],c=this.data[e++]>>15,u=o*l+c*s;n=((l=s*l+((32767&u)<<15)+i.data[r]+(1073741823&n))>>>30)+(u>>>15)+o*c+(n>>>30),i.data[r++]=1073741823&l}return n},r=30):"Netscape"!=navigator.appName?(a.prototype.am=function(e,t,i,r,n,a){for(;--a>=0;){var s=t*this.data[e++]+i.data[r]+n;n=Math.floor(s/67108864),i.data[r++]=67108863&s}return n},r=26):(a.prototype.am=o,r=28),a.prototype.DB=r,a.prototype.DM=(1<>>16)&&(e=t,i+=16),0!=(t=e>>8)&&(e=t,i+=8),0!=(t=e>>4)&&(e=t,i+=4),0!=(t=e>>2)&&(e=t,i+=2),0!=(t=e>>1)&&(e=t,i+=1),i}function g(e){this.m=e}function f(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<>=16,t+=16),255&e||(e>>=8,t+=8),15&e||(e>>=4,t+=4),3&e||(e>>=2,t+=2),1&e||++t,t}function S(e){for(var t=0;0!=e;)e&=e-1,++t;return t}function _(){}function x(e){return e}function C(e){this.r2=s(),this.q3=s(),a.ONE.dlShiftTo(2*e.t,this.r2),this.mu=this.r2.divide(e),this.m=e}g.prototype.convert=function(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e},g.prototype.revert=function(e){return e},g.prototype.reduce=function(e){e.divRemTo(this.m,null,e)},g.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},g.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},f.prototype.convert=function(e){var t=s();return e.abs().dlShiftTo(this.m.t,t),t.divRemTo(this.m,null,t),e.s<0&&t.compareTo(a.ZERO)>0&&this.m.subTo(t,t),t},f.prototype.revert=function(e){var t=s();return e.copyTo(t),this.reduce(t),t},f.prototype.reduce=function(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(i=t+this.m.t,e.data[i]+=this.m.am(0,r,e,t,0,this.m.t);e.data[i]>=e.DV;)e.data[i]-=e.DV,e.data[++i]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)},f.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},f.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)},a.prototype.copyTo=function(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s},a.prototype.fromInt=function(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0},a.prototype.fromString=function(e,t){var i;if(16==t)i=4;else if(8==t)i=3;else if(256==t)i=8;else if(2==t)i=1;else if(32==t)i=5;else{if(4!=t)return void this.fromRadix(e,t);i=2}this.t=0,this.s=0;for(var r=e.length,n=!1,s=0;--r>=0;){var o=8==i?255&e[r]:h(e,r);o<0?"-"==e.charAt(r)&&(n=!0):(n=!1,0==s?this.data[this.t++]=o:s+i>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB))}8==i&&128&e[0]&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t},a.prototype.dlShiftTo=function(e,t){var i;for(i=this.t-1;i>=0;--i)t.data[i+e]=this.data[i];for(i=e-1;i>=0;--i)t.data[i]=0;t.t=this.t+e,t.s=this.s},a.prototype.drShiftTo=function(e,t){for(var i=e;i=0;--i)t.data[i+s+1]=this.data[i]>>n|o,o=(this.data[i]&a)<=0;--i)t.data[i]=0;t.data[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()},a.prototype.rShiftTo=function(e,t){t.s=this.s;var i=Math.floor(e/this.DB);if(i>=this.t)t.t=0;else{var r=e%this.DB,n=this.DB-r,a=(1<>r;for(var s=i+1;s>r;r>0&&(t.data[this.t-i-1]|=(this.s&a)<>=this.DB;if(e.t>=this.DB;r+=this.s}else{for(r+=this.s;i>=this.DB;r-=e.s}t.s=r<0?-1:0,r<-1?t.data[i++]=this.DV+r:r>0&&(t.data[i++]=r),t.t=i,t.clamp()},a.prototype.multiplyTo=function(e,t){var i=this.abs(),r=e.abs(),n=i.t;for(t.t=n+r.t;--n>=0;)t.data[n]=0;for(n=0;n=0;)e.data[i]=0;for(i=0;i=t.DV&&(e.data[i+t.t]-=t.DV,e.data[i+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(i,t.data[i],e,2*i,0,1)),e.s=0,e.clamp()},a.prototype.divRemTo=function(e,t,i){var r=e.abs();if(!(r.t<=0)){var n=this.abs();if(n.t0?(r.lShiftTo(u,o),n.lShiftTo(u,i)):(r.copyTo(o),n.copyTo(i));var d=o.t,h=o.data[d-1];if(0!=h){var p=h*(1<1?o.data[d-2]>>this.F2:0),g=this.FV/p,f=(1<=0&&(i.data[i.t++]=1,i.subTo(w,i)),a.ONE.dlShiftTo(d,w),w.subTo(o,o);o.t=0;){var k=i.data[--v]==h?this.DM:Math.floor(i.data[v]*g+(i.data[v-1]+y)*f);if((i.data[v]+=o.am(0,k,i,b,0,d))0&&i.rShiftTo(u,i),l<0&&a.ZERO.subTo(i,i)}}},a.prototype.invDigit=function(){if(this.t<1)return 0;var e=this.data[0];if(!(1&e))return 0;var t=3&e;return(t=(t=(t=(t=t*(2-(15&e)*t)&15)*(2-(255&e)*t)&255)*(2-((65535&e)*t&65535))&65535)*(2-e*t%this.DV)%this.DV)>0?this.DV-t:-t},a.prototype.isEven=function(){return 0==(this.t>0?1&this.data[0]:this.s)},a.prototype.exp=function(e,t){if(e>4294967295||e<1)return a.ONE;var i=s(),r=s(),n=t.convert(this),o=m(e)-1;for(n.copyTo(i);--o>=0;)if(t.sqrTo(i,r),(e&1<0)t.mulTo(r,n,i);else{var l=i;i=r,r=l}return t.revert(i)},a.prototype.toString=function(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var i,r=(1<0)for(o>o)>0&&(n=!0,a=d(i));s>=0;)o>(o+=this.DB-t)):(i=this.data[s]>>(o-=t)&r,o<=0&&(o+=this.DB,--s)),i>0&&(n=!0),n&&(a+=d(i));return n?a:"0"},a.prototype.negate=function(){var e=s();return a.ZERO.subTo(this,e),e},a.prototype.abs=function(){return this.s<0?this.negate():this},a.prototype.compareTo=function(e){var t=this.s-e.s;if(0!=t)return t;var i=this.t;if(0!=(t=i-e.t))return this.s<0?-t:t;for(;--i>=0;)if(0!=(t=this.data[i]-e.data[i]))return t;return 0},a.prototype.bitLength=function(){return this.t<=0?0:this.DB*(this.t-1)+m(this.data[this.t-1]^this.s&this.DM)},a.prototype.mod=function(e){var t=s();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(a.ZERO)>0&&e.subTo(t,t),t},a.prototype.modPowInt=function(e,t){var i;return i=e<256||t.isEven()?new g(t):new f(t),this.exp(e,i)},a.ZERO=p(0),a.ONE=p(1),_.prototype.convert=x,_.prototype.revert=x,_.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i)},_.prototype.sqrTo=function(e,t){e.squareTo(t)},C.prototype.convert=function(e){if(e.s<0||e.t>2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=s();return e.copyTo(t),this.reduce(t),t},C.prototype.revert=function(e){return e},C.prototype.reduce=function(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)},C.prototype.mulTo=function(e,t,i){e.multiplyTo(t,i),this.reduce(i)},C.prototype.sqrTo=function(e,t){e.squareTo(t),this.reduce(t)};var I=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509],E=(1<<26)/I[I.length-1];a.prototype.chunkSize=function(e){return Math.floor(Math.LN2*this.DB/Math.log(e))},a.prototype.toRadix=function(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),i=Math.pow(e,t),r=p(i),n=s(),a=s(),o="";for(this.divRemTo(r,n,a);n.signum()>0;)o=(i+a.intValue()).toString(e).substr(1)+o,n.divRemTo(r,n,a);return a.intValue().toString(e)+o},a.prototype.fromRadix=function(e,t){this.fromInt(0),null==t&&(t=10);for(var i=this.chunkSize(t),r=Math.pow(t,i),n=!1,s=0,o=0,l=0;l=i&&(this.dMultiply(r),this.dAddOffset(o,0),s=0,o=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,0)),n&&a.ZERO.subTo(this,this)},a.prototype.fromNumber=function(e,t,i){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,i),this.testBit(e-1)||this.bitwiseTo(a.ONE.shiftLeft(e-1),v,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(a.ONE.shiftLeft(e-1),this);else{var r=new Array,n=7&e;r.length=1+(e>>3),t.nextBytes(r),n>0?r[0]&=(1<>=this.DB;if(e.t>=this.DB;r+=this.s}else{for(r+=this.s;i>=this.DB;r+=e.s}t.s=r<0?-1:0,r>0?t.data[i++]=r:r<-1&&(t.data[i++]=this.DV+r),t.t=i,t.clamp()},a.prototype.dMultiply=function(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()},a.prototype.dAddOffset=function(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}},a.prototype.multiplyLowerTo=function(e,t,i){var r,n=Math.min(this.t+e.t,t);for(i.s=0,i.t=n;n>0;)i.data[--n]=0;for(r=i.t-this.t;n=0;)i.data[r]=0;for(r=Math.max(t-this.t,0);r0)if(0==t)i=this.data[0]%e;else for(var r=this.t-1;r>=0;--r)i=(t*i+this.data[r])%e;return i},a.prototype.millerRabin=function(e){var t=this.subtract(a.ONE),i=t.getLowestSetBit();if(i<=0)return!1;for(var r,n=t.shiftRight(i),s={nextBytes:function(e){for(var t=0;t=0);var l=r.modPow(n,this);if(0!=l.compareTo(a.ONE)&&0!=l.compareTo(t)){for(var c=1;c++>24},a.prototype.shortValue=function(){return 0==this.t?this.s:this.data[0]<<16>>16},a.prototype.signum=function(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1},a.prototype.toByteArray=function(){var e=this.t,t=new Array;t[0]=this.s;var i,r=this.DB-e*this.DB%8,n=0;if(e-- >0)for(r>r)!=(this.s&this.DM)>>r&&(t[n++]=i|this.s<=0;)r<8?(i=(this.data[e]&(1<>(r+=this.DB-8)):(i=this.data[e]>>(r-=8)&255,r<=0&&(r+=this.DB,--e)),128&i&&(i|=-256),0==n&&(128&this.s)!=(128&i)&&++n,(n>0||i!=this.s)&&(t[n++]=i);return t},a.prototype.equals=function(e){return 0==this.compareTo(e)},a.prototype.min=function(e){return this.compareTo(e)<0?this:e},a.prototype.max=function(e){return this.compareTo(e)>0?this:e},a.prototype.and=function(e){var t=s();return this.bitwiseTo(e,y,t),t},a.prototype.or=function(e){var t=s();return this.bitwiseTo(e,v,t),t},a.prototype.xor=function(e){var t=s();return this.bitwiseTo(e,b,t),t},a.prototype.andNot=function(e){var t=s();return this.bitwiseTo(e,w,t),t},a.prototype.not=function(){for(var e=s(),t=0;t=this.t?0!=this.s:!!(this.data[t]&1<1){var d=s();for(r.sqrTo(o[1],d);l<=u;)o[l]=s(),r.mulTo(d,o[l-2],o[l]),l+=2}var h,y,v=e.t-1,b=!0,w=s();for(n=m(e.data[v])-1;v>=0;){for(n>=c?h=e.data[v]>>n-c&u:(h=(e.data[v]&(1<0&&(h|=e.data[v-1]>>this.DB+n-c)),l=i;!(1&h);)h>>=1,--l;if((n-=l)<0&&(n+=this.DB,--v),b)o[h].copyTo(a),b=!1;else{for(;l>1;)r.sqrTo(a,w),r.sqrTo(w,a),l-=2;l>0?r.sqrTo(a,w):(y=a,a=w,w=y),r.mulTo(w,o[h],a)}for(;v>=0&&!(e.data[v]&1<=0?(i.subTo(r,i),t&&n.subTo(o,n),s.subTo(l,s)):(r.subTo(i,r),t&&o.subTo(n,o),l.subTo(s,l))}return 0!=r.compareTo(a.ONE)?a.ZERO:l.compareTo(e)>=0?l.subtract(e):l.signum()<0?(l.addTo(e,l),l.signum()<0?l.add(e):l):l},a.prototype.pow=function(e){return this.exp(e,new _)},a.prototype.gcd=function(e){var t=this.s<0?this.negate():this.clone(),i=e.s<0?e.negate():e.clone();if(t.compareTo(i)<0){var r=t;t=i,i=r}var n=t.getLowestSetBit(),a=i.getLowestSetBit();if(a<0)return t;for(n0&&(t.rShiftTo(a,t),i.rShiftTo(a,i));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=i.getLowestSetBit())>0&&i.rShiftTo(n,i),t.compareTo(i)>=0?(t.subTo(i,t),t.rShiftTo(1,t)):(i.subTo(t,i),i.rShiftTo(1,i));return a>0&&i.lShiftTo(a,i),i},a.prototype.isProbablePrime=function(e){var t,i=this.abs();if(1==i.t&&i.data[0]<=I[I.length-1]){for(t=0;t0?i:t)(r)}},156(e,t){"use strict";t.f=Object.getOwnPropertySymbols},168(e,t,i){"use strict";var r=i(746),n=i(6209),a=r("keys");e.exports=function(e){return a[e]||(a[e]=n(e))}},213(e){"use strict";var t=TypeError;e.exports=function(e){var i=e&&e.alphabet;if(void 0===i||"base64"===i||"base64url"===i)return i||"base64";throw new t("Incorrect `alphabet` option")}},260(e,t,i){var r=i(4643);i(9679),i(8550);var n=e.exports=r.sha512=r.sha512||{};r.md.sha512=r.md.algorithms.sha512=n;var a=r.sha384=r.sha512.sha384=r.sha512.sha384||{};a.create=function(){return n.create("SHA-384")},r.md.sha384=r.md.algorithms.sha384=a,r.sha512.sha256=r.sha512.sha256||{create:function(){return n.create("SHA-512/256")}},r.md["sha512/256"]=r.md.algorithms["sha512/256"]=r.sha512.sha256,r.sha512.sha224=r.sha512.sha224||{create:function(){return n.create("SHA-512/224")}},r.md["sha512/224"]=r.md.algorithms["sha512/224"]=r.sha512.sha224,n.create=function(e){if(o||(s=String.fromCharCode(128),s+=r.util.fillString(String.fromCharCode(0),128),l=[[1116352408,3609767458],[1899447441,602891725],[3049323471,3964484399],[3921009573,2173295548],[961987163,4081628472],[1508970993,3053834265],[2453635748,2937671579],[2870763221,3664609560],[3624381080,2734883394],[310598401,1164996542],[607225278,1323610764],[1426881987,3590304994],[1925078388,4068182383],[2162078206,991336113],[2614888103,633803317],[3248222580,3479774868],[3835390401,2666613458],[4022224774,944711139],[264347078,2341262773],[604807628,2007800933],[770255983,1495990901],[1249150122,1856431235],[1555081692,3175218132],[1996064986,2198950837],[2554220882,3999719339],[2821834349,766784016],[2952996808,2566594879],[3210313671,3203337956],[3336571891,1034457026],[3584528711,2466948901],[113926993,3758326383],[338241895,168717936],[666307205,1188179964],[773529912,1546045734],[1294757372,1522805485],[1396182291,2643833823],[1695183700,2343527390],[1986661051,1014477480],[2177026350,1206759142],[2456956037,344077627],[2730485921,1290863460],[2820302411,3158454273],[3259730800,3505952657],[3345764771,106217008],[3516065817,3606008344],[3600352804,1432725776],[4094571909,1467031594],[275423344,851169720],[430227734,3100823752],[506948616,1363258195],[659060556,3750685593],[883997877,3785050280],[958139571,3318307427],[1322822218,3812723403],[1537002063,2003034995],[1747873779,3602036899],[1955562222,1575990012],[2024104815,1125592928],[2227730452,2716904306],[2361852424,442776044],[2428436474,593698344],[2756734187,3733110249],[3204031479,2999351573],[3329325298,3815920427],[3391569614,3928383900],[3515267271,566280711],[3940187606,3454069534],[4118630271,4000239992],[116418474,1914138554],[174292421,2731055270],[289380356,3203993006],[460393269,320620315],[685471733,587496836],[852142971,1086792851],[1017036298,365543100],[1126000580,2618297676],[1288033470,3409855158],[1501505948,4234509866],[1607167915,987167468],[1816402316,1246189591]],(c={})["SHA-512"]=[[1779033703,4089235720],[3144134277,2227873595],[1013904242,4271175723],[2773480762,1595750129],[1359893119,2917565137],[2600822924,725511199],[528734635,4215389547],[1541459225,327033209]],c["SHA-384"]=[[3418070365,3238371032],[1654270250,914150663],[2438529370,812702999],[355462360,4144912697],[1731405415,4290775857],[2394180231,1750603025],[3675008525,1694076839],[1203062813,3204075428]],c["SHA-512/256"]=[[573645204,4230739756],[2673172387,3360449730],[596883563,1867755857],[2520282905,1497426621],[2519219938,2827943907],[3193839141,1401305490],[721525244,746961066],[246885852,2177182882]],c["SHA-512/224"]=[[2352822216,424955298],[1944164710,2312950998],[502970286,855612546],[1738396948,1479516111],[258812777,2077511080],[2011393907,79989058],[1067287976,1780299464],[286451373,2446758561]],o=!0),void 0===e&&(e="SHA-512"),!(e in c))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=c[e],i=null,n=r.util.createBuffer(),a=new Array(80),d=0;d<80;++d)a[d]=new Array(2);var h=64;switch(e){case"SHA-384":h=48;break;case"SHA-512/256":h=32;break;case"SHA-512/224":h=28}var p={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:h,messageLength:0,fullMessageLength:null,messageLengthSize:16,start:function(){p.messageLength=0,p.fullMessageLength=p.messageLength128=[];for(var e=p.messageLengthSize/4,a=0;a>>0,s>>>0];for(var o=p.fullMessageLength.length-1;o>=0;--o)p.fullMessageLength[o]+=s[1],s[1]=s[0]+(p.fullMessageLength[o]/4294967296>>>0),p.fullMessageLength[o]=p.fullMessageLength[o]>>>0,s[0]=s[1]/4294967296>>>0;return n.putBytes(e),u(i,a,n),(n.read>2048||0===n.length())&&n.compact(),p},p.digest=function(){var t=r.util.createBuffer();t.putBytes(n.bytes());var o,l=p.fullMessageLength[p.fullMessageLength.length-1]+p.messageLengthSize&p.blockLength-1;t.putBytes(s.substr(0,p.blockLength-l));for(var c=8*p.fullMessageLength[0],d=0;d>>0,t.putInt32(c>>>0),c=o>>>0;t.putInt32(c);var h=new Array(i.length);for(d=0;d=128;){for(A=0;A<16;++A)t[A][0]=i.getInt32()>>>0,t[A][1]=i.getInt32()>>>0;for(;A<80;++A)r=(((j=(D=t[A-2])[0])>>>19|(T=D[1])<<13)^(T>>>29|j<<3)^j>>>6)>>>0,n=((j<<13|T>>>19)^(T<<3|j>>>29)^(j<<26|T>>>6))>>>0,a=(((j=(N=t[A-15])[0])>>>1|(T=N[1])<<31)^(j>>>8|T<<24)^j>>>7)>>>0,s=((j<<31|T>>>1)^(j<<24|T>>>8)^(j<<25|T>>>7))>>>0,O=t[A-7],R=t[A-16],T=n+O[1]+s+R[1],t[A][0]=r+O[0]+a+R[0]+(T/4294967296>>>0)>>>0,t[A][1]=T>>>0;for(m=e[0][0],g=e[0][1],f=e[1][0],y=e[1][1],v=e[2][0],b=e[2][1],w=e[3][0],k=e[3][1],S=e[4][0],_=e[4][1],x=e[5][0],C=e[5][1],I=e[6][0],E=e[6][1],z=e[7][0],P=e[7][1],A=0;A<80;++A)u=((S>>>14|_<<18)^(S>>>18|_<<14)^(_>>>9|S<<23))>>>0,d=(I^S&(x^I))>>>0,o=((m>>>28|g<<4)^(g>>>2|m<<30)^(g>>>7|m<<25))>>>0,c=((m<<4|g>>>28)^(g<<30|m>>>2)^(g<<25|m>>>7))>>>0,h=(m&f|v&(m^f))>>>0,p=(g&y|b&(g^y))>>>0,T=P+(((S<<18|_>>>14)^(S<<14|_>>>18)^(_<<23|S>>>9))>>>0)+((E^_&(C^E))>>>0)+l[A][1]+t[A][1],r=z+u+d+l[A][0]+t[A][0]+(T/4294967296>>>0)>>>0,n=T>>>0,a=o+h+((T=c+p)/4294967296>>>0)>>>0,s=T>>>0,z=I,P=E,I=x,E=C,x=S,C=_,S=w+r+((T=k+n)/4294967296>>>0)>>>0,_=T>>>0,w=v,k=b,v=f,b=y,f=m,y=g,m=r+a+((T=n+s)/4294967296>>>0)>>>0,g=T>>>0;T=e[0][1]+g,e[0][0]=e[0][0]+m+(T/4294967296>>>0)>>>0,e[0][1]=T>>>0,T=e[1][1]+y,e[1][0]=e[1][0]+f+(T/4294967296>>>0)>>>0,e[1][1]=T>>>0,T=e[2][1]+b,e[2][0]=e[2][0]+v+(T/4294967296>>>0)>>>0,e[2][1]=T>>>0,T=e[3][1]+k,e[3][0]=e[3][0]+w+(T/4294967296>>>0)>>>0,e[3][1]=T>>>0,T=e[4][1]+_,e[4][0]=e[4][0]+S+(T/4294967296>>>0)>>>0,e[4][1]=T>>>0,T=e[5][1]+C,e[5][0]=e[5][0]+x+(T/4294967296>>>0)>>>0,e[5][1]=T>>>0,T=e[6][1]+E,e[6][0]=e[6][0]+I+(T/4294967296>>>0)>>>0,e[6][1]=T>>>0,T=e[7][1]+P,e[7][0]=e[7][0]+z+(T/4294967296>>>0)>>>0,e[7][1]=T>>>0,U-=128}}},286(e,t,i){"use strict";var r=i(4578),n=TypeError;e.exports=function(e,t){if(r(t,e))return e;throw new n("Incorrect invocation")}},290(e,t,i){"use strict";var r=i(9944),n=i(831),a=i(6032),s=i(2913),o=i(2287),l=i(4282),c=TypeError,u=l("toPrimitive");e.exports=function(e,t){if(!n(e)||a(e))return e;var i,l=s(e,u);if(l){if(void 0===t&&(t="default"),i=r(l,e,t),!n(i)||a(i))return i;throw new c("Can't convert object to primitive value")}return void 0===t&&(t="number"),o(e,t)}},339(e,t,i){var r=i(4643);i(8550),i(121),i(5417),function(){if(r.prime)e.exports=r.prime;else{var t=e.exports=r.prime=r.prime||{},i=r.jsbn.BigInteger,n=[6,4,2,4,2,4,6,2],a=new i(null);a.fromInt(30);var s=function(e,t){return e|t};t.generateProbablePrime=function(e,t,n){"function"==typeof t&&(n=t,t={});var a=(t=t||{}).algorithm||"PRIMEINC";"string"==typeof a&&(a={name:a}),a.options=a.options||{};var s=t.prng||r.random,l={nextBytes:function(e){for(var t=s.getBytesSync(e.length),i=0;ie&&(s=c(e,t));var p=s.toString(16);n.target.postMessage({hex:p,workLoad:u}),s.dAddOffset(d,0)}}}p()}(e,t,n,a):o(e,t,n,a)}(e,l,a.options,n);throw new Error("Invalid prime generation algorithm: "+a.name)}}function o(e,t,i,r){var n=c(e,t),a=function(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}(n.bitLength());"millerRabinTests"in i&&(a=i.millerRabinTests);var s=10;"maxBlockTime"in i&&(s=i.maxBlockTime),l(n,e,t,0,a,s,r)}function l(e,t,i,a,s,o,u){var d=+new Date;do{if(e.bitLength()>t&&(e=c(t,i)),e.isProbablePrime(s))return u(null,e);e.dAddOffset(n[a++%8],0)}while(o<0||+new Date-de)return 0;if(0===t)return 1;for(n=1,i=r=1,a=t;1<=a?r<=a:r>=a;i=1<=a?++r:--r)n*=e,n/=i,e-=1;return n},log10:function(e){return Math.log(e)/Math.log(10)},log2:function(e){return Math.log(e)/Math.log(2)},factorial:function(e){var t,i,r,n;if(e<2)return 1;for(t=1,i=r=2,n=e;2<=n?r<=n:r>=n;i=2<=n?++r:--r)t*=i;return t},most_guessable_match_sequence:function(e,t,i){var r,n,a,s,o,l,c,u,d,h,p,m,g,f,y,v,b,w,k,S,_,x,C;for(null==i&&(i=!1),p=e.length,h=function(){var e,t,i;for(i=[],e=0,t=p;0<=t?et;0<=t?++e:--e)i.push([]);return i}(),m=0,o=t.length;me;0<=e?++i:--i)t.push({});return t}(),pi:function(){var e,t,i;for(t=[],i=0,e=p;0<=e?ie;0<=e?++i:--i)t.push({});return t}(),g:function(){var e,t,i;for(t=[],i=0,e=p;0<=e?ie;0<=e?++i:--i)t.push({});return t}()},C=this,_=function(t,r){var n,a,s,o,l,c;for(a in o=t.j,l=C.estimate_guesses(t,e),r>1&&(l*=g.pi[t.i-1][r-1]),s=C.factorial(r)*l,i||(s+=Math.pow(1e4,r-1)),c=g.g[o])if(n=c[a],!(a>r)&&n<=s)return;return g.g[o][r]=s,g.m[o][r]=t,g.pi[o][r]=l},r=function(e){var t,i,r,n,a,s;for(u=d(0,e),_(u,1),a=[],t=s=1,n=e;1<=n?s<=n:s>=n;t=1<=n?++s:--s)u=d(t,e),a.push(function(){var e,n;for(i in n=[],e=g.m[t-1])r=e[i],i=parseInt(i),"bruteforce"!==r.pattern&&n.push(_(u,i+1));return n}());return a},d=function(t,i){return{pattern:"bruteforce",token:e.slice(t,+i+1||9e9),i:t,j:i}},S=function(e){var t,i,r,n,a,s,o;for(i in s=[],n=e-1,a=void 0,r=1/0,o=g.g[n])(t=o[i])=0;)u=g.m[n][a],s.unshift(u),n=u.i-1,a--;return s},a=k=0,b=p;0<=b?kb;a=0<=b?++k:--k){for(x=0,c=(w=h[a]).length;x0)for(s in g.m[u.i-1])s=parseInt(s),_(u,s+1);else _(u,1);r(a)}return f=(y=S(p)).length,n=0===e.length?1:g.g[p-1][f],{password:e,guesses:n,guesses_log10:this.log10(n),sequence:y}},estimate_guesses:function(e,t){var i,r;return null!=e.guesses||(r=1,e.token.length=d;s=2<=d?++l:--l)for(o=c=1,h=Math.min(f,s-1);1<=h?c<=h:c>=h;o=1<=h?++c:--c)a+=this.nCk(s-1,o-1)*m*Math.pow(n,o);if(e.shifted_count)if(i=e.shifted_count,r=e.token.length-e.shifted_count,0===i||0===r)a*=2;else{for(g=0,s=y=1,p=Math.min(i,r);1<=p?y<=p:y>=p;s=1<=p?++y:--y)g+=this.nCk(i+r,s);a*=g}return a},dictionary_guesses:function(e){var t;return e.base_guesses=e.rank,e.uppercase_variations=this.uppercase_variations(e),e.l33t_variations=this.l33t_variations(e),t=e.reversed?2:1,e.base_guesses*e.uppercase_variations*e.l33t_variations*t},START_UPPER:/^[A-Z][^A-Z]+$/,END_UPPER:/^[^A-Z]+[A-Z]$/,ALL_UPPER:/^[^a-z]+$/,ALL_LOWER:/^[^A-Z]+$/,uppercase_variations:function(e){var t,i,r,n,a,s,o,l,c,u,d,h;if((h=e.token).match(this.ALL_LOWER)||h.toLowerCase()===h)return 1;for(s=0,a=(l=[this.START_UPPER,this.END_UPPER,this.ALL_UPPER]).length;s=c;n=1<=c?++o:--o)d+=this.nCk(i+t,n);return d},l33t_variations:function(e){var t,i,r,n,a,s,o,l,c,u,d,h;if(!e.l33t)return 1;for(u in h=1,l=e.sub)if(d=l[u],n=e.token.toLowerCase().split(""),t=function(){var e,t,i;for(i=[],t=0,e=n.length;t=c;a=1<=c?++s:--s)o+=this.nCk(i+t,a);h*=o}return h}},e.exports=s},380(e,t,i){"use strict";var r=i(7568),n=i(9509);e.exports=function(e){return r(n(e))}},382(e,t,i){"use strict";i(2219)},503(e,t,i){"use strict";var r=i(831),n=String,a=TypeError;e.exports=function(e){if(void 0===e||r(e))return e;throw new a(n(e)+" is not an object or undefined")}},528(e,t,i){"use strict";var r,n=i(9629),a=i(9838),s=i(9110),o=i(1155),l=i(4943),c=i(5731),u=i(3468),d=i(2140),h=i(8479),p=i(8449),m=i(8129),g=i(2387),f=i(5865),y=i(1319),v=i(6882),b=Function,w=function(e){try{return b('"use strict"; return ('+e+").constructor;")()}catch(e){}},k=i(9336),S=i(4940),_=function(){throw new u},x=k?function(){try{return _}catch(e){try{return k(arguments,"callee").get}catch(e){return _}}}():_,C=i(3558)(),I=i(6369),E=i(7345),z=i(7859),P=i(6095),A=i(4531),j={},T="undefined"!=typeof Uint8Array&&I?I(Uint8Array):r,D={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?r:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?r:ArrayBuffer,"%ArrayIteratorPrototype%":C&&I?I([][Symbol.iterator]()):r,"%AsyncFromSyncIteratorPrototype%":r,"%AsyncFunction%":j,"%AsyncGenerator%":j,"%AsyncGeneratorFunction%":j,"%AsyncIteratorPrototype%":j,"%Atomics%":"undefined"==typeof Atomics?r:Atomics,"%BigInt%":"undefined"==typeof BigInt?r:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?r:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?r:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?r:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":a,"%eval%":eval,"%EvalError%":s,"%Float16Array%":"undefined"==typeof Float16Array?r:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?r:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?r:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?r:FinalizationRegistry,"%Function%":b,"%GeneratorFunction%":j,"%Int8Array%":"undefined"==typeof Int8Array?r:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?r:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?r:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":C&&I?I(I([][Symbol.iterator]())):r,"%JSON%":"object"==typeof JSON?JSON:r,"%Map%":"undefined"==typeof Map?r:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&C&&I?I((new Map)[Symbol.iterator]()):r,"%Math%":Math,"%Number%":Number,"%Object%":n,"%Object.getOwnPropertyDescriptor%":k,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?r:Promise,"%Proxy%":"undefined"==typeof Proxy?r:Proxy,"%RangeError%":o,"%ReferenceError%":l,"%Reflect%":"undefined"==typeof Reflect?r:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?r:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&C&&I?I((new Set)[Symbol.iterator]()):r,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?r:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":C&&I?I(""[Symbol.iterator]()):r,"%Symbol%":C?Symbol:r,"%SyntaxError%":c,"%ThrowTypeError%":x,"%TypedArray%":T,"%TypeError%":u,"%Uint8Array%":"undefined"==typeof Uint8Array?r:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?r:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?r:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?r:Uint32Array,"%URIError%":d,"%WeakMap%":"undefined"==typeof WeakMap?r:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?r:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?r:WeakSet,"%Function.prototype.call%":A,"%Function.prototype.apply%":P,"%Object.defineProperty%":S,"%Object.getPrototypeOf%":E,"%Math.abs%":h,"%Math.floor%":p,"%Math.max%":m,"%Math.min%":g,"%Math.pow%":f,"%Math.round%":y,"%Math.sign%":v,"%Reflect.getPrototypeOf%":z};if(I)try{null.error}catch(e){var O=I(I(e));D["%Error.prototype%"]=O}var N=function e(t){var i;if("%AsyncFunction%"===t)i=w("async function () {}");else if("%GeneratorFunction%"===t)i=w("function* () {}");else if("%AsyncGeneratorFunction%"===t)i=w("async function* () {}");else if("%AsyncGenerator%"===t){var r=e("%AsyncGeneratorFunction%");r&&(i=r.prototype)}else if("%AsyncIteratorPrototype%"===t){var n=e("%AsyncGenerator%");n&&I&&(i=I(n.prototype))}return D[t]=i,i},R={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},U=i(9138),F=i(8554),q=U.call(A,Array.prototype.concat),L=U.call(P,Array.prototype.splice),B=U.call(A,String.prototype.replace),M=U.call(A,String.prototype.slice),V=U.call(A,RegExp.prototype.exec),$=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,K=/\\(\\)?/g,W=function(e,t){var i,r=e;if(F(R,r)&&(r="%"+(i=R[r])[0]+"%"),F(D,r)){var n=D[r];if(n===j&&(n=N(r)),void 0===n&&!t)throw new u("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:r,value:n}}throw new c("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new u("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new u('"allowMissing" argument must be a boolean');if(null===V(/^%?[^%]*%?$/,e))throw new c("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function(e){var t=M(e,0,1),i=M(e,-1);if("%"===t&&"%"!==i)throw new c("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==t)throw new c("invalid intrinsic syntax, expected opening `%`");var r=[];return B(e,$,function(e,t,i,n){r[r.length]=i?B(n,K,"$1"):t||e}),r}(e),r=i.length>0?i[0]:"",n=W("%"+r+"%",t),a=n.name,s=n.value,o=!1,l=n.alias;l&&(r=l[0],L(i,q([0,1],l)));for(var d=1,h=!0;d=i.length){var f=k(s,p);s=(h=!!f)&&"get"in f&&!("originalValue"in f.get)?f.get:s[p]}else h=F(s,p),s=s[p];h&&!o&&(D[a]=s)}}return s}},583(e,t,i){"use strict";const r=i(7476),n=i(1565),{ANY:a}=n,s=i(7229),o=i(7851),l=[new n(">=0.0.0-0")],c=[new n(">=0.0.0")],u=(e,t,i)=>{if(e===t)return!0;if(1===e.length&&e[0].semver===a){if(1===t.length&&t[0].semver===a)return!0;e=i.includePrerelease?l:c}if(1===t.length&&t[0].semver===a){if(i.includePrerelease)return!0;t=c}const r=new Set;let n,u,p,m,g,f,y;for(const t of e)">"===t.operator||">="===t.operator?n=d(n,t,i):"<"===t.operator||"<="===t.operator?u=h(u,t,i):r.add(t.semver);if(r.size>1)return null;if(n&&u){if(p=o(n.semver,u.semver,i),p>0)return null;if(0===p&&(">="!==n.operator||"<="!==u.operator))return null}for(const e of r){if(n&&!s(e,String(n),i))return null;if(u&&!s(e,String(u),i))return null;for(const r of t)if(!s(e,String(r),i))return!1;return!0}let v=!(!u||i.includePrerelease||!u.semver.prerelease.length)&&u.semver,b=!(!n||i.includePrerelease||!n.semver.prerelease.length)&&n.semver;v&&1===v.prerelease.length&&"<"===u.operator&&0===v.prerelease[0]&&(v=!1);for(const e of t){if(y=y||">"===e.operator||">="===e.operator,f=f||"<"===e.operator||"<="===e.operator,n)if(b&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===b.major&&e.semver.minor===b.minor&&e.semver.patch===b.patch&&(b=!1),">"===e.operator||">="===e.operator){if(m=d(n,e,i),m===e&&m!==n)return!1}else if(">="===n.operator&&!s(n.semver,String(e),i))return!1;if(u)if(v&&e.semver.prerelease&&e.semver.prerelease.length&&e.semver.major===v.major&&e.semver.minor===v.minor&&e.semver.patch===v.patch&&(v=!1),"<"===e.operator||"<="===e.operator){if(g=h(u,e,i),g===e&&g!==u)return!1}else if("<="===u.operator&&!s(u.semver,String(e),i))return!1;if(!e.operator&&(u||n)&&0!==p)return!1}return!(n&&f&&!u&&0!==p||u&&y&&!n&&0!==p||b||v)},d=(e,t,i)=>{if(!e)return t;const r=o(e.semver,t.semver,i);return r>0?e:r<0||">"===t.operator&&">="===e.operator?t:e},h=(e,t,i)=>{if(!e)return t;const r=o(e.semver,t.semver,i);return r<0?e:r>0||"<"===t.operator&&"<="===e.operator?t:e};e.exports=(e,t,i={})=>{if(e===t)return!0;e=new r(e,i),t=new r(t,i);let n=!1;e:for(const r of e.set){for(const e of t.set){const t=u(r,e,i);if(n=n||null!==t,t)continue e}if(n)return!1}return!0}},597(e,t,i){var r=i(4643);i(8550),r.cipher=r.cipher||{};var n=e.exports=r.cipher.modes=r.cipher.modes||{};function a(e,t){if("string"==typeof e&&(e=r.util.createBuffer(e)),r.util.isArray(e)&&e.length>4){var i=e;e=r.util.createBuffer();for(var n=0;n0))return!0;for(var r=0;r0))return!0;for(var r=0;r0)return!1;var i=e.length(),r=e.at(i-1);return!(r>this.blockSize<<2||(e.truncate(r),0))},n.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},n.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},n.cbc.prototype.encrypt=function(e,t,i){if(e.length()0))return!0;for(var r=0;r0))return!0;for(var r=0;r0)return!1;var i=e.length(),r=e.at(i-1);return!(r>this.blockSize<<2||(e.truncate(r),0))},n.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=r.util.createBuffer(),this._partialBytes=0},n.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},n.cfb.prototype.encrypt=function(e,t,i){var r=e.length();if(0===r)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&r>=this.blockSize)for(var n=0;n0&&(a=this.blockSize-a),this._partialOutput.clear(),n=0;n0)e.read-=this.blockSize;else for(n=0;n0&&this._partialOutput.getBytes(this._partialBytes),a>0&&!i)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}},n.cfb.prototype.decrypt=function(e,t,i){var r=e.length();if(0===r)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&r>=this.blockSize)for(var n=0;n0&&(a=this.blockSize-a),this._partialOutput.clear(),n=0;n0)e.read-=this.blockSize;else for(n=0;n0&&this._partialOutput.getBytes(this._partialBytes),a>0&&!i)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}},n.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=r.util.createBuffer(),this._partialBytes=0},n.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},n.ofb.prototype.encrypt=function(e,t,i){var r=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&r>=this.blockSize)for(var n=0;n0&&(a=this.blockSize-a),this._partialOutput.clear(),n=0;n0)e.read-=this.blockSize;else for(n=0;n0&&this._partialOutput.getBytes(this._partialBytes),a>0&&!i)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}},n.ofb.prototype.decrypt=n.ofb.prototype.encrypt,n.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=r.util.createBuffer(),this._partialBytes=0},n.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},n.ctr.prototype.encrypt=function(e,t,i){var r=e.length();if(0===r)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&r>=this.blockSize)for(var n=0;n0&&(a=this.blockSize-a),this._partialOutput.clear(),n=0;n0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),a>0&&!i)return t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}s(this._inBlock)},n.ctr.prototype.decrypt=n.ctr.prototype.encrypt,n.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=r.util.createBuffer(),this._partialBytes=0,this._R=3774873600},n.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t,i=r.util.createBuffer(e.iv);if(this._cipherLength=0,t="additionalData"in e?r.util.createBuffer(e.additionalData):r.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=r.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=i.length();if(12===n)this._j0=[i.getInt32(),i.getInt32(),i.getInt32(),1];else{for(this._j0=[0,0,0,0];i.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[i.getInt32(),i.getInt32(),i.getInt32(),i.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(o(8*n)))}this._inBlock=this._j0.slice(0),s(this._inBlock),this._partialBytes=0,t=r.util.createBuffer(t),this._aDataLength=o(8*t.length());var a=t.length()%this.blockSize;for(a&&t.fillWithByte(0,this.blockSize-a),this._s=[0,0,0,0];t.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()])},n.gcm.prototype.encrypt=function(e,t,i){var r=e.length();if(0===r)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&r>=this.blockSize){for(var n=0;n0&&(a=this.blockSize-a),this._partialOutput.clear(),n=0;n0&&this._partialOutput.getBytes(this._partialBytes),a>0&&!i)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=a,!0;t.putBytes(this._partialOutput.getBytes(r-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),s(this._inBlock)},n.gcm.prototype.decrypt=function(e,t,i){var r=e.length();if(r0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),s(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var n=0;n0;--r)t[r]=e[r]>>>1|(1&e[r-1])<<31;t[0]=e[0]>>>1,i&&(t[0]^=this._R)},n.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],i=0;i<32;++i){var r=e[i/8|0]>>>4*(7-i%8)&15,n=this._m[i][r];t[0]^=n[0],t[1]^=n[1],t[2]^=n[2],t[3]^=n[3]}return t},n.gcm.prototype.ghash=function(e,t,i){return t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3],this.tableMultiply(t)},n.gcm.prototype.generateHashTable=function(e,t){for(var i=8/t,r=4*i,n=16*i,a=new Array(n),s=0;s>>1,n=new Array(i);n[r]=e.slice(0);for(var a=r>>>1;a>0;)this.pow(n[2*a],n[a]=[]),a>>=1;for(a=2;a=0;--i)F(r,r),1!==i&&q(r,r,t);for(i=0;i<16;++i)e[i]=r[i]}(i,i),q(i,i,n),q(i,i,a),q(i,i,a),q(e[0],i,a),F(r,e[0]),q(r,r,a),E(r,n)&&q(e[0],e[0],b),F(r,e[0]),q(r,r,a),E(r,n)?-1:(P(e[0])===t[31]>>7&&U(e[0],h,e[0]),q(e[3],e[0],e[1]),0)}(o,r))return-1;for(n=0;n=0};var h=N(),p=N([1]),m=N([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),g=N([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),f=N([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),y=N([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),v=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),b=N([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139]);function w(e,t){var i=r.md.sha512.create(),n=new l(e);i.update(n.getBytes(t),"binary");var a=i.digest().getBytes();if("undefined"!=typeof Buffer)return Buffer.from(a,"binary");for(var s=new c(u.constants.HASH_BYTE_LENGTH),o=0;o<64;++o)s[o]=a.charCodeAt(o);return s}function k(e,t){var i,r,n,a;for(r=63;r>=32;--r){for(i=0,n=r-32,a=r-12;n>8,t[n]-=256*i;t[n]+=i,t[r]=0}for(i=0,n=0;n<32;++n)t[n]+=i-(t[31]>>4)*v[n],i=t[n]>>8,t[n]&=255;for(n=0;n<32;++n)t[n]-=i*v[n];for(r=0;r<32;++r)t[r+1]+=t[r]>>8,e[r]=255&t[r]}function S(e){for(var t=new Float64Array(64),i=0;i<64;++i)t[i]=e[i],e[i]=0;k(e,t)}function _(e,t){var i=N(),r=N(),n=N(),a=N(),s=N(),o=N(),l=N(),c=N(),u=N();U(i,e[1],e[0]),U(u,t[1],t[0]),q(i,i,u),R(r,e[0],e[1]),R(u,t[0],t[1]),q(r,r,u),q(n,e[3],t[3]),q(n,n,g),q(a,e[2],t[2]),R(a,a,a),U(s,r,i),U(o,a,n),R(l,a,n),R(c,r,i),q(e[0],s,o),q(e[1],c,l),q(e[2],l,o),q(e[3],s,c)}function x(e,t,i){for(var r=0;r<4;++r)O(e[r],t[r],i)}function C(e,t){var i=N(),r=N(),n=N();!function(e,t){var i,r=N();for(i=0;i<16;++i)r[i]=t[i];for(i=253;i>=0;--i)F(r,r),2!==i&&4!==i&&q(r,r,t);for(i=0;i<16;++i)e[i]=r[i]}(n,t[2]),q(i,t[0],n),q(r,t[1],n),I(e,r),e[31]^=P(i)<<7}function I(e,t){var i,r,n,a=N(),s=N();for(i=0;i<16;++i)s[i]=t[i];for(D(s),D(s),D(s),r=0;r<2;++r){for(a[0]=s[0]-65517,i=1;i<15;++i)a[i]=s[i]-65535-(a[i-1]>>16&1),a[i-1]&=65535;a[15]=s[15]-32767-(a[14]>>16&1),n=a[15]>>16&1,a[14]&=65535,O(s,a,1-n)}for(i=0;i<16;i++)e[2*i]=255&s[i],e[2*i+1]=s[i]>>8}function E(e,t){var i=new c(32),r=new c(32);return I(i,e),I(r,t),z(i,0,r,0)}function z(e,t,i,r){return function(e,t,i,r){var n,a=0;for(n=0;n<32;++n)a|=e[t+n]^i[r+n];return(1&a-1>>>8)-1}(e,t,i,r)}function P(e){var t=new c(32);return I(t,e),1&t[0]}function A(e,t,i){var r,n;for(T(e[0],h),T(e[1],p),T(e[2],p),T(e[3],h),n=255;n>=0;--n)x(e,t,r=i[n/8|0]>>(7&n)&1),_(t,e),_(e,e),x(e,t,r)}function j(e,t){var i=[N(),N(),N(),N()];T(i[0],f),T(i[1],y),T(i[2],p),q(i[3],f,y),A(e,i,t)}function T(e,t){var i;for(i=0;i<16;i++)e[i]=0|t[i]}function D(e){var t,i,r=1;for(t=0;t<16;++t)i=e[t]+r+65535,r=Math.floor(i/65536),e[t]=i-65536*r;e[0]+=r-1+37*(r-1)}function O(e,t,i){for(var r,n=~(i-1),a=0;a<16;++a)r=n&(e[a]^t[a]),e[a]^=r,t[a]^=r}function N(e){var t,i=new Float64Array(16);if(e)for(t=0;t128)throw new Error('Invalid "nsComment" content.');e.value=n.create(n.Class.UNIVERSAL,n.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var p=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=p.toHex(),e.value=n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,p.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){if(e.value=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]),u=e.value.value,e.keyIdentifier){var m=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;u.push(n.create(n.Class.CONTEXT_SPECIFIC,0,!1,m))}if(e.authorityCertIssuer){var g=[n.create(n.Class.CONTEXT_SPECIFIC,4,!0,[y(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];u.push(n.create(n.Class.CONTEXT_SPECIFIC,1,!0,g))}if(e.serialNumber){var f=r.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);u.push(n.create(n.Class.CONTEXT_SPECIFIC,2,!1,f))}}else if("cRLDistributionPoints"===e.name){e.value=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]),u=e.value.value;var v,b=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]),w=n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[]);for(h=0;h2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(d.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(l.validity.notBefore=d[0],l.validity.notAfter=d[1],l.tbsCertificate=i.tbsCertificate,t){l.md=g({signatureOid:l.signatureOid,type:"certificate"});var h=n.toDer(l.tbsCertificate);l.md.update(h.getBytes())}var f=r.md.sha1.create(),y=n.toDer(i.certIssuer);f.update(y.getBytes()),l.issuer.getField=function(e){return p(l.issuer,e)},l.issuer.addField=function(e){v([e]),l.issuer.attributes.push(e)},l.issuer.attributes=a.RDNAttributesAsArray(i.certIssuer),i.certIssuerUniqueId&&(l.issuer.uniqueId=i.certIssuerUniqueId),l.issuer.hash=f.digest().toHex();var b=r.md.sha1.create(),w=n.toDer(i.certSubject);return b.update(w.getBytes()),l.subject.getField=function(e){return p(l.subject,e)},l.subject.addField=function(e){v([e]),l.subject.attributes.push(e)},l.subject.attributes=a.RDNAttributesAsArray(i.certSubject),i.certSubjectUniqueId&&(l.subject.uniqueId=i.certSubjectUniqueId),l.subject.hash=b.digest().toHex(),i.certExtensions?l.extensions=a.certificateExtensionsFromAsn1(i.certExtensions):l.extensions=[],l.publicKey=a.publicKeyFromAsn1(i.subjectPublicKeyInfo),l},a.certificateExtensionsFromAsn1=function(e){for(var t=[],i=0;i1&&(i=l.value.charCodeAt(1),a=l.value.length>2?l.value.charCodeAt(2):0),t.digitalSignature=!(128&~i),t.nonRepudiation=!(64&~i),t.keyEncipherment=!(32&~i),t.dataEncipherment=!(16&~i),t.keyAgreement=!(8&~i),t.keyCertSign=!(4&~i),t.cRLSign=!(2&~i),t.encipherOnly=!(1&~i),t.decipherOnly=!(128&~a)}else if("basicConstraints"===t.name){(l=n.fromDer(t.value)).value.length>0&&l.value[0].type===n.Type.BOOLEAN?t.cA=0!==l.value[0].value.charCodeAt(0):t.cA=!1;var o=null;l.value.length>0&&l.value[0].type===n.Type.INTEGER?o=l.value[0].value:l.value.length>1&&(o=l.value[1].value),null!==o&&(t.pathLenConstraint=n.derToInteger(o))}else if("extKeyUsage"===t.name)for(var l=n.fromDer(t.value),c=0;c1&&(i=l.value.charCodeAt(1)),t.client=!(128&~i),t.server=!(64&~i),t.email=!(32&~i),t.objsign=!(16&~i),t.reserved=!(8&~i),t.sslCA=!(4&~i),t.emailCA=!(2&~i),t.objCA=!(1&~i);else if("subjectAltName"===t.name||"issuerAltName"===t.name){var d;t.altNames=[],l=n.fromDer(t.value);for(var h=0;h=S&&e<_?n.create(n.Class.UNIVERSAL,n.Type.UTCTIME,!1,n.dateToUtcTime(e)):n.create(n.Class.UNIVERSAL,n.Type.GENERALIZEDTIME,!1,n.dateToGeneralizedTime(e))}a.getTBSCertificate=function(e){var t=x(e.validity.notBefore),i=x(e.validity.notAfter),s=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(e.version).getBytes())]),n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,r.util.hexToBytes(e.serialNumber)),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(e.siginfo.algorithmOid).getBytes()),w(e.siginfo.algorithmOid,e.siginfo.parameters)]),y(e.issuer),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[t,i]),y(e.subject),a.publicKeyToAsn1(e.publicKey)]);return e.issuer.uniqueId&&s.value.push(n.create(n.Class.CONTEXT_SPECIFIC,1,!0,[n.create(n.Class.UNIVERSAL,n.Type.BITSTRING,!1,String.fromCharCode(0)+e.issuer.uniqueId)])),e.subject.uniqueId&&s.value.push(n.create(n.Class.CONTEXT_SPECIFIC,2,!0,[n.create(n.Class.UNIVERSAL,n.Type.BITSTRING,!1,String.fromCharCode(0)+e.subject.uniqueId)])),e.extensions.length>0&&s.value.push(a.certificateExtensionsToAsn1(e.extensions)),s},a.getCertificationRequestInfo=function(e){return n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(e.version).getBytes()),y(e.subject),a.publicKeyToAsn1(e.publicKey),k(e)])},a.distinguishedNameToAsn1=function(e){return y(e)},a.certificateToAsn1=function(e){var t=e.tbsCertificate||a.getTBSCertificate(e);return n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[t,n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(e.signatureOid).getBytes()),w(e.signatureOid,e.signatureParameters)]),n.create(n.Class.UNIVERSAL,n.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},a.certificateExtensionsToAsn1=function(e){var t=n.create(n.Class.CONTEXT_SPECIFIC,3,!0,[]),i=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[]);t.value.push(i);for(var r=0;ru.validity.notAfter)&&(l={message:"Certificate is not valid yet or has expired.",error:a.certificateError.certificate_expired,notBefore:u.validity.notBefore,notAfter:u.validity.notAfter,now:s}),null===l){if(null===(d=t[0]||e.getIssuer(u))&&u.isIssuer(u)&&(h=!0,d=u),d){var p=d;r.util.isArray(p)||(p=[p]);for(var m=!1;!m&&p.length>0;){d=p.shift();try{m=d.verify(u)}catch(e){}}m||(l={message:"Certificate signature is invalid.",error:a.certificateError.bad_certificate})}null!==l||d&&!h||e.hasCertificate(u)||(l={message:"Certificate is not trusted.",error:a.certificateError.unknown_ca})}if(null===l&&d&&!u.isIssuer(d)&&(l={message:"Certificate issuer is invalid.",error:a.certificateError.bad_certificate}),null===l)for(var g={keyUsage:!0,basicConstraints:!0},f=0;null===l&&fv.pathLenConstraint&&(l={message:"Certificate basicConstraints pathLenConstraint violated.",error:a.certificateError.bad_certificate})}var w=null===l||l.error,k=i.verify?i.verify(w,c,n):w;if(!0!==k)throw!0===w&&(l={message:"The application rejected the certificate.",error:a.certificateError.bad_certificate}),(k||0===k)&&("object"!=typeof k||r.util.isArray(k)?"string"==typeof k&&(l.error=k):(k.message&&(l.message=k.message),k.error&&(l.error=k.error))),l;l=null,o=!1,++c}while(t.length>0);return!0}},943(e,t,i){var r=i(4643);i(9679),i(8550);var n=e.exports=r.sha1=r.sha1||{};r.md.sha1=r.md.algorithms.sha1=n,n.create=function(){s||(a=String.fromCharCode(128),a+=r.util.fillString(String.fromCharCode(0),64),s=!0);var e=null,t=r.util.createBuffer(),i=new Array(80),n={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,a=0;a>>0,l>>>0];for(var c=n.fullMessageLength.length-1;c>=0;--c)n.fullMessageLength[c]+=l[1],l[1]=l[0]+(n.fullMessageLength[c]/4294967296>>>0),n.fullMessageLength[c]=n.fullMessageLength[c]>>>0,l[0]=l[1]/4294967296>>>0;return t.putBytes(a),o(e,i,t),(t.read>2048||0===t.length())&&t.compact(),n},n.digest=function(){var s=r.util.createBuffer();s.putBytes(t.bytes());var l,c=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;s.putBytes(a.substr(0,n.blockLength-c));for(var u=8*n.fullMessageLength[0],d=0;d>>0,s.putInt32(u>>>0),u=l>>>0;s.putInt32(u);var h={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};o(h,i,s);var p=r.util.createBuffer();return p.putInt32(h.h0),p.putInt32(h.h1),p.putInt32(h.h2),p.putInt32(h.h3),p.putInt32(h.h4),p},n};var a=null,s=!1;function o(e,t,i){for(var r,n,a,s,o,l,c,u=i.length();u>=64;){for(n=e.h0,a=e.h1,s=e.h2,o=e.h3,l=e.h4,c=0;c<16;++c)r=i.getInt32(),t[c]=r,r=(n<<5|n>>>27)+(o^a&(s^o))+l+1518500249+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=n,n=r;for(;c<20;++c)r=(r=t[c-3]^t[c-8]^t[c-14]^t[c-16])<<1|r>>>31,t[c]=r,r=(n<<5|n>>>27)+(o^a&(s^o))+l+1518500249+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=n,n=r;for(;c<32;++c)r=(r=t[c-3]^t[c-8]^t[c-14]^t[c-16])<<1|r>>>31,t[c]=r,r=(n<<5|n>>>27)+(a^s^o)+l+1859775393+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=n,n=r;for(;c<40;++c)r=(r=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|r>>>30,t[c]=r,r=(n<<5|n>>>27)+(a^s^o)+l+1859775393+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=n,n=r;for(;c<60;++c)r=(r=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|r>>>30,t[c]=r,r=(n<<5|n>>>27)+(a&s|o&(a^s))+l+2400959708+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=n,n=r;for(;c<80;++c)r=(r=t[c-6]^t[c-16]^t[c-28]^t[c-32])<<2|r>>>30,t[c]=r,r=(n<<5|n>>>27)+(a^s^o)+l+3395469782+r,l=o,o=s,s=(a<<30|a>>>2)>>>0,a=n,n=r;e.h0=e.h0+n|0,e.h1=e.h1+a|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+l|0,u-=64}}},997(e,t,i){"use strict";var r=i(4530),n=i(4466);e.exports=function(e,t,i){return i.get&&r(i.get,t,{getter:!0}),i.set&&r(i.set,t,{setter:!0}),n.f(e,t,i)}},1025(e,t,i){"use strict";var r=i(6881),n=i(4977);e.exports=function(e,t,i){try{return r(n(Object.getOwnPropertyDescriptor(e,t)[i]))}catch(e){}}},1048(e,t,i){"use strict";const r=i(7991),n=i(9318),a="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.hp=l,t.IS=50;const s=2147483647;function o(e){if(e>s)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,i){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return d(e)}return c(e,t,i)}function c(e,t,i){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const i=0|g(e,t);let r=o(i);const n=r.write(e,t);return n!==i&&(r=r.slice(0,n)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(Q(e,Uint8Array)){const t=new Uint8Array(e);return p(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(Q(e,ArrayBuffer)||e&&Q(e.buffer,ArrayBuffer))return p(e,t,i);if("undefined"!=typeof SharedArrayBuffer&&(Q(e,SharedArrayBuffer)||e&&Q(e.buffer,SharedArrayBuffer)))return p(e,t,i);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return l.from(r,t,i);const n=function(e){if(l.isBuffer(e)){const t=0|m(e.length),i=o(t);return 0===i.length||e.copy(i,0,0,t),i}return void 0!==e.length?"number"!=typeof e.length||J(e.length)?o(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,i);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function u(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function d(e){return u(e),o(e<0?0:0|m(e))}function h(e){const t=e.length<0?0:0|m(e.length),i=o(t);for(let r=0;r=s)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+s.toString(16)+" bytes");return 0|e}function g(e,t){if(l.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||Q(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const i=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===i)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return i;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*i;case"hex":return i>>>1;case"base64":return H(e).length;default:if(n)return r?-1:W(e).length;t=(""+t).toLowerCase(),n=!0}}function f(e,t,i){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===i||i>this.length)&&(i=this.length),i<=0)return"";if((i>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,i);case"utf8":case"utf-8":return I(this,t,i);case"ascii":return z(this,t,i);case"latin1":case"binary":return P(this,t,i);case"base64":return C(this,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return j(this,t,i);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,i){const r=e[t];e[t]=e[i],e[i]=r}function v(e,t,i,r,n){if(0===e.length)return-1;if("string"==typeof i?(r=i,i=0):i>2147483647?i=2147483647:i<-2147483648&&(i=-2147483648),J(i=+i)&&(i=n?0:e.length-1),i<0&&(i=e.length+i),i>=e.length){if(n)return-1;i=e.length-1}else if(i<0){if(!n)return-1;i=0}if("string"==typeof t&&(t=l.from(t,r)),l.isBuffer(t))return 0===t.length?-1:b(e,t,i,r,n);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?n?Uint8Array.prototype.indexOf.call(e,t,i):Uint8Array.prototype.lastIndexOf.call(e,t,i):b(e,[t],i,r,n);throw new TypeError("val must be string, number or Buffer")}function b(e,t,i,r,n){let a,s=1,o=e.length,l=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;s=2,o/=2,l/=2,i/=2}function c(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){let r=-1;for(a=i;ao&&(i=o-l),a=i;a>=0;a--){let i=!0;for(let r=0;rn&&(r=n):r=n;const a=t.length;let s;for(r>a/2&&(r=a/2),s=0;s>8,n=i%256,a.push(n),a.push(r);return a}(t,e.length-i),e,i,r)}function C(e,t,i){return 0===t&&i===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,i))}function I(e,t,i){i=Math.min(e.length,i);const r=[];let n=t;for(;n239?4:t>223?3:t>191?2:1;if(n+s<=i){let i,r,o,l;switch(s){case 1:t<128&&(a=t);break;case 2:i=e[n+1],128==(192&i)&&(l=(31&t)<<6|63&i,l>127&&(a=l));break;case 3:i=e[n+1],r=e[n+2],128==(192&i)&&128==(192&r)&&(l=(15&t)<<12|(63&i)<<6|63&r,l>2047&&(l<55296||l>57343)&&(a=l));break;case 4:i=e[n+1],r=e[n+2],o=e[n+3],128==(192&i)&&128==(192&r)&&128==(192&o)&&(l=(15&t)<<18|(63&i)<<12|(63&r)<<6|63&o,l>65535&&l<1114112&&(a=l))}}null===a?(a=65533,s=1):a>65535&&(a-=65536,r.push(a>>>10&1023|55296),a=56320|1023&a),r.push(a),n+=s}return function(e){const t=e.length;if(t<=E)return String.fromCharCode.apply(String,e);let i="",r=0;for(;rr.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(r,n)):Uint8Array.prototype.set.call(r,t,n);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,n)}n+=t.length}return r},l.byteLength=g,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;ti&&(e+=" ... "),""},a&&(l.prototype[a]=l.prototype.inspect),l.prototype.compare=function(e,t,i,r,n){if(Q(e,Uint8Array)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===i&&(i=e?e.length:0),void 0===r&&(r=0),void 0===n&&(n=this.length),t<0||i>e.length||r<0||n>this.length)throw new RangeError("out of range index");if(r>=n&&t>=i)return 0;if(r>=n)return-1;if(t>=i)return 1;if(this===e)return 0;let a=(n>>>=0)-(r>>>=0),s=(i>>>=0)-(t>>>=0);const o=Math.min(a,s),c=this.slice(r,n),u=e.slice(t,i);for(let e=0;e>>=0,isFinite(i)?(i>>>=0,void 0===r&&(r="utf8")):(r=i,i=void 0)}const n=this.length-t;if((void 0===i||i>n)&&(i=n),e.length>0&&(i<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let a=!1;for(;;)switch(r){case"hex":return w(this,e,t,i);case"utf8":case"utf-8":return k(this,e,t,i);case"ascii":case"latin1":case"binary":return S(this,e,t,i);case"base64":return _(this,e,t,i);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return x(this,e,t,i);default:if(a)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),a=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const E=4096;function z(e,t,i){let r="";i=Math.min(e.length,i);for(let n=t;nr)&&(i=r);let n="";for(let r=t;ri)throw new RangeError("Trying to access beyond buffer length")}function D(e,t,i,r,n,a){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||te.length)throw new RangeError("Index out of range")}function O(e,t,i,r,n){M(t,r,n,e,i,7);let a=Number(t&BigInt(4294967295));e[i++]=a,a>>=8,e[i++]=a,a>>=8,e[i++]=a,a>>=8,e[i++]=a;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[i++]=s,s>>=8,e[i++]=s,s>>=8,e[i++]=s,s>>=8,e[i++]=s,i}function N(e,t,i,r,n){M(t,r,n,e,i,7);let a=Number(t&BigInt(4294967295));e[i+7]=a,a>>=8,e[i+6]=a,a>>=8,e[i+5]=a,a>>=8,e[i+4]=a;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[i+3]=s,s>>=8,e[i+2]=s,s>>=8,e[i+1]=s,s>>=8,e[i]=s,i+8}function R(e,t,i,r,n,a){if(i+r>e.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("Index out of range")}function U(e,t,i,r,a){return t=+t,i>>>=0,a||R(e,0,i,4),n.write(e,t,i,r,23,4),i+4}function F(e,t,i,r,a){return t=+t,i>>>=0,a||R(e,0,i,8),n.write(e,t,i,r,52,8),i+8}l.prototype.slice=function(e,t){const i=this.length;(e=~~e)<0?(e+=i)<0&&(e=0):e>i&&(e=i),(t=void 0===t?i:~~t)<0?(t+=i)<0&&(t=0):t>i&&(t=i),t>>=0,t>>>=0,i||T(e,t,this.length);let r=this[e],n=1,a=0;for(;++a>>=0,t>>>=0,i||T(e,t,this.length);let r=this[e+--t],n=1;for(;t>0&&(n*=256);)r+=this[e+--t]*n;return r},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||T(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||T(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=X(function(e){V(e>>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+i*2**24;return BigInt(r)+(BigInt(n)<>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+i;return(BigInt(r)<>>=0,t>>>=0,i||T(e,t,this.length);let r=this[e],n=1,a=0;for(;++a=n&&(r-=Math.pow(2,8*t)),r},l.prototype.readIntBE=function(e,t,i){e>>>=0,t>>>=0,i||T(e,t,this.length);let r=t,n=1,a=this[e+--r];for(;r>0&&(n*=256);)a+=this[e+--r]*n;return n*=128,a>=n&&(a-=Math.pow(2,8*t)),a},l.prototype.readInt8=function(e,t){return e>>>=0,t||T(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||T(e,2,this.length);const i=this[e]|this[e+1]<<8;return 32768&i?4294901760|i:i},l.prototype.readInt16BE=function(e,t){e>>>=0,t||T(e,2,this.length);const i=this[e+1]|this[e]<<8;return 32768&i?4294901760|i:i},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||T(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=X(function(e){V(e>>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(i<<24);return(BigInt(r)<>>=0,"offset");const t=this[e],i=this[e+7];void 0!==t&&void 0!==i||$(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<>>=0,t||T(e,4,this.length),n.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||T(e,4,this.length),n.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||T(e,8,this.length),n.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||T(e,8,this.length),n.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,i,r){e=+e,t>>>=0,i>>>=0,r||D(this,e,t,i,Math.pow(2,8*i)-1,0);let n=1,a=0;for(this[t]=255&e;++a>>=0,i>>>=0,r||D(this,e,t,i,Math.pow(2,8*i)-1,0);let n=i-1,a=1;for(this[t+n]=255&e;--n>=0&&(a*=256);)this[t+n]=e/a&255;return t+i},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=X(function(e,t=0){return O(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=X(function(e,t=0){return N(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,i,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*i-1);D(this,e,t,i,r-1,-r)}let n=0,a=1,s=0;for(this[t]=255&e;++n>>=0,!r){const r=Math.pow(2,8*i-1);D(this,e,t,i,r-1,-r)}let n=i-1,a=1,s=0;for(this[t+n]=255&e;--n>=0&&(a*=256);)e<0&&0===s&&0!==this[t+n+1]&&(s=1),this[t+n]=(e/a|0)-s&255;return t+i},l.prototype.writeInt8=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,i){return e=+e,t>>>=0,i||D(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=X(function(e,t=0){return O(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=X(function(e,t=0){return N(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,i){return U(this,e,t,!0,i)},l.prototype.writeFloatBE=function(e,t,i){return U(this,e,t,!1,i)},l.prototype.writeDoubleLE=function(e,t,i){return F(this,e,t,!0,i)},l.prototype.writeDoubleBE=function(e,t,i){return F(this,e,t,!1,i)},l.prototype.copy=function(e,t,i,r){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(i||(i=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t>>=0,i=void 0===i?this.length:i>>>0,e||(e=0),"number"==typeof e)for(n=t;n=r+4;i-=3)t=`_${e.slice(i-3,i)}${t}`;return`${e.slice(0,i)}${t}`}function M(e,t,i,r,n,a){if(e>i||e3?0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(a+1)}${r}`:`>= -(2${r} ** ${8*(a+1)-1}${r}) and < 2 ** ${8*(a+1)-1}${r}`:`>= ${t}${r} and <= ${i}${r}`,new q.ERR_OUT_OF_RANGE("value",n,e)}!function(e,t,i){V(t,"offset"),void 0!==e[t]&&void 0!==e[t+i]||$(t,e.length-(i+1))}(r,n,a)}function V(e,t){if("number"!=typeof e)throw new q.ERR_INVALID_ARG_TYPE(t,"number",e)}function $(e,t,i){if(Math.floor(e)!==e)throw V(e,i),new q.ERR_OUT_OF_RANGE(i||"offset","an integer",e);if(t<0)throw new q.ERR_BUFFER_OUT_OF_BOUNDS;throw new q.ERR_OUT_OF_RANGE(i||"offset",`>= ${i?1:0} and <= ${t}`,e)}L("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),L("ERR_OUT_OF_RANGE",function(e,t,i){let r=`The value of "${e}" is out of range.`,n=i;return Number.isInteger(i)&&Math.abs(i)>2**32?n=B(String(i)):"bigint"==typeof i&&(n=String(i),(i>BigInt(2)**BigInt(32)||i<-(BigInt(2)**BigInt(32)))&&(n=B(n)),n+="n"),r+=` It must be ${t}. Received ${n}`,r},RangeError);const K=/[^+/0-9A-Za-z-_]/g;function W(e,t){let i;t=t||1/0;const r=e.length;let n=null;const a=[];for(let s=0;s55295&&i<57344){if(!n){if(i>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(s+1===r){(t-=3)>-1&&a.push(239,191,189);continue}n=i;continue}if(i<56320){(t-=3)>-1&&a.push(239,191,189),n=i;continue}i=65536+(n-55296<<10|i-56320)}else n&&(t-=3)>-1&&a.push(239,191,189);if(n=null,i<128){if((t-=1)<0)break;a.push(i)}else if(i<2048){if((t-=2)<0)break;a.push(i>>6|192,63&i|128)}else if(i<65536){if((t-=3)<0)break;a.push(i>>12|224,i>>6&63|128,63&i|128)}else{if(!(i<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(i>>18|240,i>>12&63|128,i>>6&63|128,63&i|128)}}return a}function H(e){return r.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(K,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function G(e,t,i,r){let n;for(n=0;n=t.length||n>=e.length);++n)t[n+i]=e[n];return n}function Q(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const Y=function(){const e="0123456789abcdef",t=new Array(256);for(let i=0;i<16;++i){const r=16*i;for(let n=0;n<16;++n)t[r+n]=e[i]+e[n]}return t}();function X(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},1054(e,t,i){var r=i(4643);i(8550),i(5417),i(943);var n=e.exports=r.pkcs1=r.pkcs1||{};function a(e,t,i){i||(i=r.md.sha1.create());for(var n="",a=Math.ceil(t/i.digestLength),s=0;s>24&255,s>>16&255,s>>8&255,255&s);i.start(),i.update(e+o),n+=i.digest().getBytes()}return n.substring(0,t)}n.encode_rsa_oaep=function(e,t,i){var n,s,o,l;"string"==typeof i?(n=i,s=arguments[3]||void 0,o=arguments[4]||void 0):i&&(n=i.label||void 0,s=i.seed||void 0,o=i.md||void 0,i.mgf1&&i.mgf1.md&&(l=i.mgf1.md)),o?o.start():o=r.md.sha1.create(),l||(l=o);var c=Math.ceil(e.n.bitLength()/8),u=c-2*o.digestLength-2;if(t.length>u)throw(f=new Error("RSAES-OAEP input message length is too long.")).length=t.length,f.maxLength=u,f;n||(n=""),o.update(n,"raw");for(var d=o.digest(),h="",p=u-t.length,m=0;m1?arguments[1]:void 0,null,9007199254740991);return a(o,t.bytes)}})},1262(e,t,i){"use strict";const r=i(7851);e.exports=(e,t,i)=>r(e,t,i)<0},1264(e,t,i){var r=i(4643);i(7835),i(4467),i(4117),i(5206),i(3939),i(3574),i(5114),i(2374),i(8550),i(846);var n=r.asn1,a=e.exports=r.pki=r.pki||{};a.pemToDer=function(e){var t=r.pem.decode(e)[0];if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert PEM to DER; PEM is encrypted.");return r.util.createBuffer(t.body)},a.privateKeyFromPem=function(e){var t=r.pem.decode(e)[0];if("PRIVATE KEY"!==t.type&&"RSA PRIVATE KEY"!==t.type){var i=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw i.headerType=t.type,i}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert private key from PEM; PEM is encrypted.");var s=n.fromDer(t.body);return a.privateKeyFromAsn1(s)},a.privateKeyToPem=function(e,t){var i={type:"RSA PRIVATE KEY",body:n.toDer(a.privateKeyToAsn1(e)).getBytes()};return r.pem.encode(i,{maxline:t})},a.privateKeyInfoToPem=function(e,t){var i={type:"PRIVATE KEY",body:n.toDer(e).getBytes()};return r.pem.encode(i,{maxline:t})}},1274(e){"use strict";e.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},1280(e,t,i){"use strict";const r=i(4517),n=i(7476),a=i(9761);e.exports=(e,t)=>{e=new n(e,t);let i=new r("0.0.0");if(e.test(i))return i;if(i=new r("0.0.0-0"),e.test(i))return i;i=null;for(let t=0;t{const t=new r(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":s&&!a(t,s)||(s=t);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${e.operator}`)}}),!s||i&&!a(i,s)||(i=s)}return i&&e.test(i)?i:null}},1292(e){"use strict";e.exports=Object.getOwnPropertyDescriptor},1319(e){"use strict";e.exports=Math.round},1353(e,t,i){"use strict";const r=i(4517);e.exports=(e,t)=>new r(e,t).minor},1361(e){"use strict";const t="object"==typeof process&&{ENV:"production"}.NODE_DEBUG&&/\bsemver\b/i.test({ENV:"production"}.NODE_DEBUG)?(...e)=>console.error("SEMVER",...e):()=>{};e.exports=t},1457(e,t,i){var r=i(4643);i(8550),e.exports=r.cipher=r.cipher||{},r.cipher.algorithms=r.cipher.algorithms||{},r.cipher.createCipher=function(e,t){var i=e;if("string"==typeof i&&(i=r.cipher.getAlgorithm(i))&&(i=i()),!i)throw new Error("Unsupported algorithm: "+e);return new r.cipher.BlockCipher({algorithm:i,key:t,decrypt:!1})},r.cipher.createDecipher=function(e,t){var i=e;if("string"==typeof i&&(i=r.cipher.getAlgorithm(i))&&(i=i()),!i)throw new Error("Unsupported algorithm: "+e);return new r.cipher.BlockCipher({algorithm:i,key:t,decrypt:!0})},r.cipher.registerAlgorithm=function(e,t){e=e.toUpperCase(),r.cipher.algorithms[e]=t},r.cipher.getAlgorithm=function(e){return(e=e.toUpperCase())in r.cipher.algorithms?r.cipher.algorithms[e]:null};var n=r.cipher.BlockCipher=function(e){this.algorithm=e.algorithm,this.mode=this.algorithm.mode,this.blockSize=this.mode.blockSize,this._finish=!1,this._input=null,this.output=null,this._op=e.decrypt?this.mode.decrypt:this.mode.encrypt,this._decrypt=e.decrypt,this.algorithm.initialize(e)};n.prototype.start=function(e){e=e||{};var t={};for(var i in e)t[i]=e[i];t.decrypt=this._decrypt,this._finish=!1,this._input=r.util.createBuffer(),this.output=e.output||r.util.createBuffer(),this.mode.start(t)},n.prototype.update=function(e){for(e&&this._input.putBuffer(e);!this._op.call(this.mode,this._input,this.output,this._finish)&&!this._finish;);this._input.compact()},n.prototype.finish=function(e){!e||"ECB"!==this.mode.name&&"CBC"!==this.mode.name||(this.mode.pad=function(t){return e(this.blockSize,t,!1)},this.mode.unpad=function(t){return e(this.blockSize,t,!0)});var t={};return t.decrypt=this._decrypt,t.overflow=this._input.length()%this.blockSize,!(!this._decrypt&&this.mode.pad&&!this.mode.pad(this._input,t)||(this._finish=!0,this.update(),this._decrypt&&this.mode.unpad&&!this.mode.unpad(this.output,t)||this.mode.afterFinish&&!this.mode.afterFinish(this.output,t)))}},1458(e,t,i){"use strict";var r=i(380),n=i(675),a=i(9389),s=function(e){return function(t,i,s){var o=r(t),l=a(o);if(0===l)return!e&&-1;var c,u=n(s,l);if(e&&i!=i){for(;l>u;)if((c=o[u++])!=c)return!0}else for(;l>u;u++)if((e||u in o)&&o[u]===i)return e||u||0;return!e&&-1}};e.exports={includes:s(!0),indexOf:s(!1)}},1539(e,t,i){"use strict";var r=i(1830),n=Object.prototype.hasOwnProperty,a=Array.isArray,s=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),o=function(e,t){for(var i=t&&t.plainObjects?{__proto__:null}:{},r=0;r1;){var t=e.pop(),i=t.obj[t.prop];if(a(i)){for(var r=[],n=0;n=l?o.slice(u,u+l):o,h=[],p=0;p=48&&m<=57||m>=65&&m<=90||m>=97&&m<=122||a===r.RFC1738&&(40===m||41===m)?h[h.length]=d.charAt(p):m<128?h[h.length]=s[m]:m<2048?h[h.length]=s[192|m>>6]+s[128|63&m]:m<55296||m>=57344?h[h.length]=s[224|m>>12]+s[128|m>>6&63]+s[128|63&m]:(p+=1,m=65536+((1023&m)<<10|1023&d.charCodeAt(p)),h[h.length]=s[240|m>>18]+s[128|m>>12&63]+s[128|m>>6&63]+s[128|63&m])}c+=h.join("")}return c},isBuffer:function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(a(e)){for(var i=[],r=0;r")||!e.operator.startsWith(">"))&&(!this.operator.startsWith("<")||!e.operator.startsWith("<"))&&(this.semver.version!==e.semver.version||!this.operator.includes("=")||!e.operator.includes("="))&&!(l(this.semver,"<",e.semver,t)&&this.operator.startsWith(">")&&e.operator.startsWith("<"))&&!(l(this.semver,">",e.semver,t)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}}e.exports=n;const a=i(3990),{safeRe:s,t:o}=i(2841),l=i(4004),c=i(1361),u=i(4517),d=i(7476)},1617(e,t,i){"use strict";var r=i(9117),n=i(1025),a=i(8689),s=r.ArrayBuffer,o=r.TypeError;e.exports=s&&n(s.prototype,"byteLength","get")||function(e){if("ArrayBuffer"!==a(e))throw new o("ArrayBuffer expected");return e.byteLength}},1685(e,t,i){"use strict";var r=i(9117),n=i(2860),a=i(4466).f,s=i(9304).f,o=r.Symbol;if(n("dispose"),o){var l=s(o,"dispose");l.enumerable&&l.configurable&&l.writable&&a(o,"dispose",{value:l.value,enumerable:!1,configurable:!1,writable:!1})}},1730(e,t,i){"use strict";var r=i(9117),n=i(6881),a=i(503),s=i(7028),o=i(4418),l=i(6579),c=i(213),u=i(2676),d=l.c2i,h=l.c2iUrl,p=r.SyntaxError,m=r.TypeError,g=n("".charAt),f=function(e,t){for(var i=e.length;t>16&255,n>>8&255,255&n];if(2===r){if(i&&0!==a[1])throw new p("Extra bits");return[a[0]]}if(3===r){if(i&&0!==a[2])throw new p("Extra bits");return[a[0],a[1]]}return a},v=function(e,t,i){for(var r=t.length,n=0;n0){if("stop-before-partial"===l)break;if("loose"!==l)throw new p("Missing padding");if(1===_.length)throw new p("Malformed padding: exactly one additional character");k=v(w,y(_,n,!1),k)}S=b;break}var C=g(e,x);if(++x,"="===C){if(_.length<2)throw new p("Padding is too early");if(x=f(e,x),2===_.length){if(x===b){if("stop-before-partial"===l)break;throw new p("Malformed padding: only one =")}"="===g(e,x)&&(++x,x=f(e,x))}if(xc;)n(r,i=t[c++])&&(~s(u,i)||l(u,i));return u}},1880(e,t){var i,r;i=function e(){var t,i="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==i?i:{},r=!i.document&&!!i.postMessage,n=i.IS_PAPA_WORKER||!1,a={},s=0,o={};function l(e){this._handle=null,this._finished=!1,this._completed=!1,this._halted=!1,this._input=null,this._baseIndex=0,this._partialLine="",this._rowCount=0,this._start=0,this._nextChunk=null,this.isFirstChunk=!0,this._completeResults={data:[],errors:[],meta:{}},function(e){var t=b(e);t.chunkSize=parseInt(t.chunkSize),e.step||e.chunk||(t.chunkSize=null),this._handle=new p(t),(this._handle.streamer=this)._config=t}.call(this,e),this.parseChunk=function(e,t){var r=parseInt(this._config.skipFirstNLines)||0;if(this.isFirstChunk&&0=this._config.preview,n)i.postMessage({results:a,workerId:o.WORKER_ID,finished:r});else if(k(this._config.chunk)&&!t){if(this._config.chunk(a,this._handle),this._handle.paused()||this._handle.aborted())return void(this._halted=!0);this._completeResults=a=void 0}return this._config.step||this._config.chunk||(this._completeResults.data=this._completeResults.data.concat(a.data),this._completeResults.errors=this._completeResults.errors.concat(a.errors),this._completeResults.meta=a.meta),this._completed||!r||!k(this._config.complete)||a&&a.meta.aborted||(this._config.complete(this._completeResults,this._input),this._completed=!0),r||a&&a.meta.paused||this._nextChunk(),a}this._halted=!0},this._sendError=function(e){k(this._config.error)?this._config.error(e):n&&this._config.error&&i.postMessage({workerId:o.WORKER_ID,error:e,finished:!1})}}function c(e){var t;(e=e||{}).chunkSize||(e.chunkSize=o.RemoteChunkSize),l.call(this,e),this._nextChunk=r?function(){this._readChunk(),this._chunkLoaded()}:function(){this._readChunk()},this.stream=function(e){this._input=e,this._nextChunk()},this._readChunk=function(){if(this._finished)this._chunkLoaded();else{if(t=new XMLHttpRequest,this._config.withCredentials&&(t.withCredentials=this._config.withCredentials),r||(t.onload=w(this._chunkLoaded,this),t.onerror=w(this._chunkError,this)),t.open(this._config.downloadRequestBody?"POST":"GET",this._input,!r),this._config.downloadRequestHeaders){var e,i=this._config.downloadRequestHeaders;for(e in i)t.setRequestHeader(e,i[e])}var n;this._config.chunkSize&&(n=this._start+this._config.chunkSize-1,t.setRequestHeader("Range","bytes="+this._start+"-"+n));try{t.send(this._config.downloadRequestBody)}catch(e){this._chunkError(e.message)}r&&0===t.status&&this._chunkError()}},this._chunkLoaded=function(){4===t.readyState&&(t.status<200||400<=t.status?this._chunkError():(this._start+=this._config.chunkSize||t.responseText.length,this._finished=!this._config.chunkSize||this._start>=(e=>null!==(e=e.getResponseHeader("Content-Range"))?parseInt(e.substring(e.lastIndexOf("/")+1)):-1)(t),this.parseChunk(t.responseText)))},this._chunkError=function(e){e=t.statusText||e,this._sendError(new Error(e))}}function u(e){(e=e||{}).chunkSize||(e.chunkSize=o.LocalChunkSize),l.call(this,e);var t,i,r="undefined"!=typeof FileReader;this.stream=function(e){this._input=e,i=e.slice||e.webkitSlice||e.mozSlice,r?((t=new FileReader).onload=w(this._chunkLoaded,this),t.onerror=w(this._chunkError,this)):t=new FileReaderSync,this._nextChunk()},this._nextChunk=function(){this._finished||this._config.preview&&!(this._rowCount=this._input.size,this.parseChunk(e.target.result)},this._chunkError=function(){this._sendError(t.error)}}function d(e){var t;l.call(this,e=e||{}),this.stream=function(e){return t=e,this._nextChunk()},this._nextChunk=function(){var e,i;if(!this._finished)return e=this._config.chunkSize,t=e?(i=t.substring(0,e),t.substring(e)):(i=t,""),this._finished=!t,this.parseChunk(i)}}function h(e){l.call(this,e=e||{});var t=[],i=!0,r=!1;this.pause=function(){l.prototype.pause.apply(this,arguments),this._input.pause()},this.resume=function(){l.prototype.resume.apply(this,arguments),this._input.resume()},this.stream=function(e){this._input=e,this._input.on("data",this._streamData),this._input.on("end",this._streamEnd),this._input.on("error",this._streamError)},this._checkIsFinished=function(){r&&1===t.length&&(this._finished=!0)},this._nextChunk=function(){this._checkIsFinished(),t.length?this.parseChunk(t.shift()):i=!0},this._streamData=w(function(e){try{t.push("string"==typeof e?e:e.toString(this._config.encoding)),i&&(i=!1,this._checkIsFinished(),this.parseChunk(t.shift()))}catch(e){this._streamError(e)}},this),this._streamError=w(function(e){this._streamCleanUp(),this._sendError(e)},this),this._streamEnd=w(function(){this._streamCleanUp(),r=!0,this._streamData("")},this),this._streamCleanUp=w(function(){this._input.removeListener("data",this._streamData),this._input.removeListener("end",this._streamEnd),this._input.removeListener("error",this._streamError)},this)}function p(e){var t,i,r,n,a=Math.pow(2,53),s=-a,l=/^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/,c=/^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/,u=this,d=0,h=0,p=!1,f=!1,y=[],v={data:[],errors:[],meta:{}};function w(t){return"greedy"===e.skipEmptyLines?""===t.join("").trim():1===t.length&&0===t[0].length}function S(){if(v&&r&&(x("Delimiter","UndetectableDelimiter","Unable to auto-detect delimiting character; defaulted to '"+o.DefaultDelimiter+"'"),r=!1),e.skipEmptyLines&&(v.data=v.data.filter(function(e){return!w(e)})),_()){if(v)if(Array.isArray(v.data[0])){for(var t=0;_()&&t(t=>(e.dynamicTypingFunction&&void 0===e.dynamicTyping[t]&&(e.dynamicTyping[t]=e.dynamicTypingFunction(t)),!0===(e.dynamicTyping[t]||e.dynamicTyping)))(t)?"true"===i||"TRUE"===i||"false"!==i&&"FALSE"!==i&&((e=>{if(l.test(e)&&(e=parseFloat(e),s=y.length?"__parsed_extra":y[n]:o,u=e.transform?e.transform(u,o):u),"__parsed_extra"===o?(r[o]=r[o]||[],r[o].push(u)):r[o]=u}return e.header&&(n>y.length?x("FieldMismatch","TooManyFields","Too many fields: expected "+y.length+" fields but parsed "+n,h+i):ne.preview?i.abort():(v.data=v.data[0],n(v,u))))}),this.parse=function(n,a,s){var l=e.quoteChar||'"';return e.newline||(e.newline=this.guessLineEndings(n,l)),r=!1,e.delimiter?k(e.delimiter)&&(e.delimiter=e.delimiter(n),v.meta.delimiter=e.delimiter):((l=((t,i,r,n,a)=>{var s,l,c,u;a=a||[",","\t","|",";",o.RECORD_SEP,o.UNIT_SEP];for(var d=0;d=i.length/2?"\r\n":"\r"}}function m(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function g(e){var t=(e=e||{}).delimiter,i=e.newline,r=e.comments,n=e.step,a=e.preview,s=e.fastMode,l=null,c=!1,u=null==e.quoteChar?'"':e.quoteChar,d=u;if(void 0!==e.escapeChar&&(d=e.escapeChar),("string"!=typeof t||-1=a)return F(!0);break}x.push({type:"Quotes",code:"InvalidQuotes",message:"Trailing quote on quoted field is malformed",row:_.length,index:h}),T++}}else if(r&&0===C.length&&o.substring(h,h+w)===r){if(-1===A)return F();h=A+b,A=o.indexOf(i,h),P=o.indexOf(t,h)}else if(-1!==P&&(P=a)return F(!0)}return R();function O(e){_.push(e),I=h}function N(e){return-1!==e&&(e=o.substring(T+1,e))&&""===e.trim()?e.length:0}function R(e){return f||(void 0===e&&(e=o.substring(h)),C.push(e),h=y,O(C),S&&q()),F()}function U(e){h=e,O(C),C=[],A=o.indexOf(i,h)}function F(r){if(e.header&&!g&&_.length&&!c){var n=_[0],a=Object.create(null),s=new Set(n);let t=!1;for(let i=0;i65279!==e.charCodeAt(0)?e:e.slice(1))(t),n=new(r.download?c:d)(r)):!0===t.readable&&k(t.read)&&k(t.on)?n=new h(r):(i.File&&t instanceof File||t instanceof Object)&&(n=new u(r)),n.stream(t);(n=(()=>{var t;return!!o.WORKERS_SUPPORTED&&(t=(()=>{var t=i.URL||i.webkitURL||null,r=e.toString();return o.BLOB_URL||(o.BLOB_URL=t.createObjectURL(new Blob(["var global = (function() { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } return {}; })(); global.IS_PAPA_WORKER=true; ","(",r,")();"],{type:"text/javascript"})))})(),(t=new i.Worker(t)).onmessage=f,t.id=s++,a[t.id]=t)})()).userStep=r.step,n.userChunk=r.chunk,n.userComplete=r.complete,n.userError=r.error,r.step=k(r.step),r.chunk=k(r.chunk),r.complete=k(r.complete),r.error=k(r.error),delete r.worker,n.postMessage({input:t,config:r,workerId:n.id})},o.unparse=function(e,t){var i=!1,r=!0,n=",",a="\r\n",s='"',l=s+s,c=!1,u=null,d=!1,h=((()=>{if("object"==typeof t){if("string"!=typeof t.delimiter||o.BAD_DELIMITERS.filter(function(e){return-1!==t.delimiter.indexOf(e)}).length||(n=t.delimiter),"boolean"!=typeof t.quotes&&"function"!=typeof t.quotes&&!Array.isArray(t.quotes)||(i=t.quotes),"boolean"!=typeof t.skipEmptyLines&&"string"!=typeof t.skipEmptyLines||(c=t.skipEmptyLines),"string"==typeof t.newline&&(a=t.newline),"string"==typeof t.quoteChar&&(s=t.quoteChar),"boolean"==typeof t.header&&(r=t.header),Array.isArray(t.columns)){if(0===t.columns.length)throw new Error("Option columns is empty");u=t.columns}void 0!==t.escapeChar&&(l=t.escapeChar+s),t.escapeFormulae instanceof RegExp?d=t.escapeFormulae:"boolean"==typeof t.escapeFormulae&&t.escapeFormulae&&(d=/^[=+\-@\t\r].*$/)}})(),new RegExp(m(s),"g"));if("string"==typeof e&&(e=JSON.parse(e)),Array.isArray(e)){if(!e.length||Array.isArray(e[0]))return p(null,e,c);if("object"==typeof e[0])return p(u||Object.keys(e[0]),e,c)}else if("object"==typeof e)return"string"==typeof e.data&&(e.data=JSON.parse(e.data)),Array.isArray(e.data)&&(e.fields||(e.fields=e.meta&&e.meta.fields||u),e.fields||(e.fields=Array.isArray(e.data[0])?e.fields:"object"==typeof e.data[0]?Object.keys(e.data[0]):[]),Array.isArray(e.data[0])||"object"==typeof e.data[0]||(e.data=[e.data])),p(e.fields||[],e.data||[],c);throw new Error("Unable to serialize unrecognized input");function p(e,t,i){var s="",o=("string"==typeof e&&(e=JSON.parse(e)),"string"==typeof t&&(t=JSON.parse(t)),Array.isArray(e)&&0{for(var i=0;i0){var l=N.utils.clone(t)||{};l.position=[s,o],l.index=n.length,n.push(new N.Token(i.slice(s,a),l))}s=a+1}}return n},N.tokenizer.separator=/[\s\-]+/,N.Pipeline=function(){this._stack=[]},N.Pipeline.registeredFunctions=Object.create(null),N.Pipeline.registerFunction=function(e,t){t in this.registeredFunctions&&N.utils.warn("Overwriting existing registered function: "+t),e.label=t,N.Pipeline.registeredFunctions[e.label]=e},N.Pipeline.warnIfFunctionNotRegistered=function(e){e.label&&e.label in this.registeredFunctions||N.utils.warn("Function is not registered with pipeline. This may cause problems when serialising the index.\n",e)},N.Pipeline.load=function(e){var t=new N.Pipeline;return e.forEach(function(e){var i=N.Pipeline.registeredFunctions[e];if(!i)throw new Error("Cannot load unregistered function: "+e);t.add(i)}),t},N.Pipeline.prototype.add=function(){Array.prototype.slice.call(arguments).forEach(function(e){N.Pipeline.warnIfFunctionNotRegistered(e),this._stack.push(e)},this)},N.Pipeline.prototype.after=function(e,t){N.Pipeline.warnIfFunctionNotRegistered(t);var i=this._stack.indexOf(e);if(-1==i)throw new Error("Cannot find existingFn");i+=1,this._stack.splice(i,0,t)},N.Pipeline.prototype.before=function(e,t){N.Pipeline.warnIfFunctionNotRegistered(t);var i=this._stack.indexOf(e);if(-1==i)throw new Error("Cannot find existingFn");this._stack.splice(i,0,t)},N.Pipeline.prototype.remove=function(e){var t=this._stack.indexOf(e);-1!=t&&this._stack.splice(t,1)},N.Pipeline.prototype.run=function(e){for(var t=this._stack.length,i=0;i1&&(ae&&(i=n),a!=e);)r=i-t,n=t+Math.floor(r/2),a=this.elements[2*n];return a==e||a>e?2*n:ao?c+=2:s==o&&(t+=i[l+1]*r[c+1],l+=2,c+=2);return t},N.Vector.prototype.similarity=function(e){return this.dot(e)/this.magnitude()||0},N.Vector.prototype.toArray=function(){for(var e=new Array(this.elements.length/2),t=1,i=0;t0){var a,s=n.str.charAt(0);s in n.node.edges?a=n.node.edges[s]:(a=new N.TokenSet,n.node.edges[s]=a),1==n.str.length&&(a.final=!0),r.push({node:a,editsRemaining:n.editsRemaining,str:n.str.slice(1)})}if(0!=n.editsRemaining){if("*"in n.node.edges)var o=n.node.edges["*"];else o=new N.TokenSet,n.node.edges["*"]=o;if(0==n.str.length&&(o.final=!0),r.push({node:o,editsRemaining:n.editsRemaining-1,str:n.str}),n.str.length>1&&r.push({node:n.node,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)}),1==n.str.length&&(n.node.final=!0),n.str.length>=1){if("*"in n.node.edges)var l=n.node.edges["*"];else l=new N.TokenSet,n.node.edges["*"]=l;1==n.str.length&&(l.final=!0),r.push({node:l,editsRemaining:n.editsRemaining-1,str:n.str.slice(1)})}if(n.str.length>1){var c,u=n.str.charAt(0),d=n.str.charAt(1);d in n.node.edges?c=n.node.edges[d]:(c=new N.TokenSet,n.node.edges[d]=c),1==n.str.length&&(c.final=!0),r.push({node:c,editsRemaining:n.editsRemaining-1,str:u+n.str.slice(2)})}}}return i},N.TokenSet.fromString=function(e){for(var t=new N.TokenSet,i=t,r=0,n=e.length;r=e;t--){var i=this.uncheckedNodes[t],r=i.child.toString();r in this.minimizedNodes?i.parent.edges[i.char]=this.minimizedNodes[r]:(i.child._str=r,this.minimizedNodes[r]=i.child),this.uncheckedNodes.pop()}},N.Index=function(e){this.invertedIndex=e.invertedIndex,this.fieldVectors=e.fieldVectors,this.tokenSet=e.tokenSet,this.fields=e.fields,this.pipeline=e.pipeline},N.Index.prototype.search=function(e){return this.query(function(t){new N.QueryParser(e,t).parse()})},N.Index.prototype.query=function(e){for(var t=new N.Query(this.fields),i=Object.create(null),r=Object.create(null),n=Object.create(null),a=Object.create(null),s=Object.create(null),o=0;o1?1:e},N.Builder.prototype.k1=function(e){this._k1=e},N.Builder.prototype.add=function(e,t){var i=e[this._ref],r=Object.keys(this._fields);this._documents[i]=t||{},this.documentCount+=1;for(var n=0;n=this.length)return N.QueryLexer.EOS;var e=this.str.charAt(this.pos);return this.pos+=1,e},N.QueryLexer.prototype.width=function(){return this.pos-this.start},N.QueryLexer.prototype.ignore=function(){this.start==this.pos&&(this.pos+=1),this.start=this.pos},N.QueryLexer.prototype.backup=function(){this.pos-=1},N.QueryLexer.prototype.acceptDigitRun=function(){var e,t;do{t=(e=this.next()).charCodeAt(0)}while(t>47&&t<58);e!=N.QueryLexer.EOS&&this.backup()},N.QueryLexer.prototype.more=function(){return this.pos1&&(e.backup(),e.emit(N.QueryLexer.TERM)),e.ignore(),e.more())return N.QueryLexer.lexText},N.QueryLexer.lexEditDistance=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(N.QueryLexer.EDIT_DISTANCE),N.QueryLexer.lexText},N.QueryLexer.lexBoost=function(e){return e.ignore(),e.acceptDigitRun(),e.emit(N.QueryLexer.BOOST),N.QueryLexer.lexText},N.QueryLexer.lexEOS=function(e){e.width()>0&&e.emit(N.QueryLexer.TERM)},N.QueryLexer.termSeparator=N.tokenizer.separator,N.QueryLexer.lexText=function(e){for(;;){var t=e.next();if(t==N.QueryLexer.EOS)return N.QueryLexer.lexEOS;if(92!=t.charCodeAt(0)){if(":"==t)return N.QueryLexer.lexField;if("~"==t)return e.backup(),e.width()>0&&e.emit(N.QueryLexer.TERM),N.QueryLexer.lexEditDistance;if("^"==t)return e.backup(),e.width()>0&&e.emit(N.QueryLexer.TERM),N.QueryLexer.lexBoost;if("+"==t&&1===e.width())return e.emit(N.QueryLexer.PRESENCE),N.QueryLexer.lexText;if("-"==t&&1===e.width())return e.emit(N.QueryLexer.PRESENCE),N.QueryLexer.lexText;if(t.match(N.QueryLexer.termSeparator))return N.QueryLexer.lexTerm}else e.escapeCharacter()}},N.QueryParser=function(e,t){this.lexer=new N.QueryLexer(e),this.query=t,this.currentClause={},this.lexemeIdx=0},N.QueryParser.prototype.parse=function(){this.lexer.run(),this.lexemes=this.lexer.lexemes;for(var e=N.QueryParser.parseClause;e;)e=e(this);return this.query},N.QueryParser.prototype.peekLexeme=function(){return this.lexemes[this.lexemeIdx]},N.QueryParser.prototype.consumeLexeme=function(){var e=this.peekLexeme();return this.lexemeIdx+=1,e},N.QueryParser.prototype.nextClause=function(){var e=this.currentClause;this.query.clause(e),this.currentClause={}},N.QueryParser.parseClause=function(e){var t=e.peekLexeme();if(null!=t)switch(t.type){case N.QueryLexer.PRESENCE:return N.QueryParser.parsePresence;case N.QueryLexer.FIELD:return N.QueryParser.parseField;case N.QueryLexer.TERM:return N.QueryParser.parseTerm;default:var i="expected either a field or a term, found "+t.type;throw t.str.length>=1&&(i+=" with value '"+t.str+"'"),new N.QueryParseError(i,t.start,t.end)}},N.QueryParser.parsePresence=function(e){var t=e.consumeLexeme();if(null!=t){switch(t.str){case"-":e.currentClause.presence=N.Query.presence.PROHIBITED;break;case"+":e.currentClause.presence=N.Query.presence.REQUIRED;break;default:var i="unrecognised presence operator'"+t.str+"'";throw new N.QueryParseError(i,t.start,t.end)}var r=e.peekLexeme();if(null==r)throw i="expecting term or field, found nothing",new N.QueryParseError(i,t.start,t.end);switch(r.type){case N.QueryLexer.FIELD:return N.QueryParser.parseField;case N.QueryLexer.TERM:return N.QueryParser.parseTerm;default:throw i="expecting term or field, found '"+r.type+"'",new N.QueryParseError(i,r.start,r.end)}}},N.QueryParser.parseField=function(e){var t=e.consumeLexeme();if(null!=t){if(-1==e.query.allFields.indexOf(t.str)){var i=e.query.allFields.map(function(e){return"'"+e+"'"}).join(", "),r="unrecognised field '"+t.str+"', possible fields: "+i;throw new N.QueryParseError(r,t.start,t.end)}e.currentClause.fields=[t.str];var n=e.peekLexeme();if(null==n)throw r="expecting term, found nothing",new N.QueryParseError(r,t.start,t.end);if(n.type===N.QueryLexer.TERM)return N.QueryParser.parseTerm;throw r="expecting term, found '"+n.type+"'",new N.QueryParseError(r,n.start,n.end)}},N.QueryParser.parseTerm=function(e){var t=e.consumeLexeme();if(null!=t){e.currentClause.term=t.str.toLowerCase(),-1!=t.str.indexOf("*")&&(e.currentClause.usePipeline=!1);var i=e.peekLexeme();if(null!=i)switch(i.type){case N.QueryLexer.TERM:return e.nextClause(),N.QueryParser.parseTerm;case N.QueryLexer.FIELD:return e.nextClause(),N.QueryParser.parseField;case N.QueryLexer.EDIT_DISTANCE:return N.QueryParser.parseEditDistance;case N.QueryLexer.BOOST:return N.QueryParser.parseBoost;case N.QueryLexer.PRESENCE:return e.nextClause(),N.QueryParser.parsePresence;default:var r="Unexpected lexeme type '"+i.type+"'";throw new N.QueryParseError(r,i.start,i.end)}else e.nextClause()}},N.QueryParser.parseEditDistance=function(e){var t=e.consumeLexeme();if(null!=t){var i=parseInt(t.str,10);if(isNaN(i)){var r="edit distance must be numeric";throw new N.QueryParseError(r,t.start,t.end)}e.currentClause.editDistance=i;var n=e.peekLexeme();if(null!=n)switch(n.type){case N.QueryLexer.TERM:return e.nextClause(),N.QueryParser.parseTerm;case N.QueryLexer.FIELD:return e.nextClause(),N.QueryParser.parseField;case N.QueryLexer.EDIT_DISTANCE:return N.QueryParser.parseEditDistance;case N.QueryLexer.BOOST:return N.QueryParser.parseBoost;case N.QueryLexer.PRESENCE:return e.nextClause(),N.QueryParser.parsePresence;default:throw r="Unexpected lexeme type '"+n.type+"'",new N.QueryParseError(r,n.start,n.end)}else e.nextClause()}},N.QueryParser.parseBoost=function(e){var t=e.consumeLexeme();if(null!=t){var i=parseInt(t.str,10);if(isNaN(i)){var r="boost must be numeric";throw new N.QueryParseError(r,t.start,t.end)}e.currentClause.boost=i;var n=e.peekLexeme();if(null!=n)switch(n.type){case N.QueryLexer.TERM:return e.nextClause(),N.QueryParser.parseTerm;case N.QueryLexer.FIELD:return e.nextClause(),N.QueryParser.parseField;case N.QueryLexer.EDIT_DISTANCE:return N.QueryParser.parseEditDistance;case N.QueryLexer.BOOST:return N.QueryParser.parseBoost;case N.QueryLexer.PRESENCE:return e.nextClause(),N.QueryParser.parsePresence;default:throw r="Unexpected lexeme type '"+n.type+"'",new N.QueryParseError(r,n.start,n.end)}else e.nextClause()}},void 0===(n="function"==typeof(r=function(){return N})?r.call(t,i,t,e):r)||(e.exports=n)}()},2037(e,t,i){"use strict";var r,n,a,s=i(5234),o=i(4188),l=i(831),c=i(7065),u=i(1786),d=i(7509),h=i(4282),p=i(1942),m=h("iterator"),g=!1;[].keys&&("next"in(a=[].keys())?(n=u(u(a)))!==Object.prototype&&(r=n):g=!0),!l(r)||s(function(){var e={};return r[m].call(e)!==e})?r={}:p&&(r=c(r)),o(r[m])||d(r,m,function(){return this}),e.exports={IteratorPrototype:r,BUGGY_SAFARI_ITERATORS:g}},2046(e,t,i){var r=i(4643);i(6531),e.exports=r.mgf=r.mgf||{},r.mgf.mgf1=r.mgf1},2067(e,t,i){"use strict";var r=i(5613),n=i(6893),a=i(5604),s=i(4977),o=i(286),l=i(7509),c=i(4320),u=i(997),d=i(4282),h=i(3086),p=i(2712),m=a("SuppressedError"),g=ReferenceError,f=d("dispose"),y=d("toStringTag"),v="DisposableStack",b=h.set,w=h.getterFor(v),k="sync-dispose",S="disposed",_=function(e){var t=w(e);if(t.state===S)throw new g(v+" already disposed");return t},x=function(){b(o(this,C),{type:v,state:"pending",stack:[]}),n||(this.disposed=!1)},C=x.prototype;c(C,{dispose:function(){var e=w(this);if(e.state!==S){e.state=S,n||(this.disposed=!0);for(var t,i=e.stack,r=i.length,a=!1;r;){var s=i[--r];i[r]=null;try{s()}catch(e){a?t=new m(e,t):(a=!0,t=e)}}if(e.stack=null,a)throw t}},use:function(e){return p(_(this),e,k),e},adopt:function(e,t){var i=_(this);return s(t),p(i,void 0,k,function(){t(e)}),e},defer:function(e){var t=_(this);s(e),p(t,void 0,k,e)},move:function(){var e=_(this),t=new x;return w(t).stack=e.stack,e.stack=[],e.state=S,n||(this.disposed=!0),t}}),n&&u(C,"disposed",{configurable:!0,get:function(){return w(this).state===S}}),l(C,f,C.dispose,{name:"dispose"}),l(C,y,v,{nonWritable:!0}),r({global:!0,constructor:!0},{DisposableStack:x})},2089(e){var t={};e.exports=t;var i={};t.encode=function(e,t,i){if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==i&&"number"!=typeof i)throw new TypeError('"maxline" must be a number.');var r="";if(e instanceof Uint8Array){var n=0,a=t.length,s=t.charAt(0),o=[0];for(n=0;n0;)o.push(c%a),c=c/a|0}for(n=0;0===e[n]&&n=0;--n)r+=t[o[n]]}else r=function(e,t){var i=0,r=t.length,n=t.charAt(0),a=[0];for(i=0;i0;)a.push(o%r),o=o/r|0}var l="";for(i=0;0===e.at(i)&&i=0;--i)l+=t[a[i]];return l}(e,t);if(i){var u=new RegExp(".{1,"+i+"}","g");r=r.match(u).join("\r\n")}return r},t.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var r=i[t];if(!r){r=i[t]=[];for(var n=0;n>=8;for(;u>0;)o.push(255&u),u>>=8}for(var d=0;e[d]===s&&dr(e,t,!0)},2140(e){"use strict";e.exports=URIError},2152(e,t,i){"use strict";i(2067)},2219(e,t,i){"use strict";var r=i(5613),n=i(9117),a=i(1730),s=i(8529),o=n.Uint8Array,l=!o||!o.prototype.setFromBase64||!function(){var e=new o([255,255,255,255,255]);try{return void e.setFromBase64("",null)}catch(e){}try{return void e.setFromBase64("a")}catch(e){}try{e.setFromBase64("MjYyZg===")}catch(t){return 50===e[0]&&54===e[1]&&50===e[2]&&255===e[3]&&255===e[4]}}();o&&r({target:"Uint8Array",proto:!0,forced:l},{setFromBase64:function(e){s(this);var t=a(e,arguments.length>1?arguments[1]:void 0,this,this.length);return{read:t.read,written:t.written}}})},2281(e,t,i){"use strict";const r=i(3955);e.exports=(e,t)=>{const i=r(e.trim().replace(/^[=v]+/,""),t);return i?i.version:null}},2287(e,t,i){"use strict";var r=i(9944),n=i(4188),a=i(831),s=TypeError;e.exports=function(e,t){var i,o;if("string"===t&&n(i=e.toString)&&!a(o=r(i,e)))return o;if(n(i=e.valueOf)&&!a(o=r(i,e)))return o;if("string"!==t&&n(i=e.toString)&&!a(o=r(i,e)))return o;throw new s("Can't convert object to primitive value")}},2344(e,t,i){"use strict";var r=i(290),n=i(6032);e.exports=function(e){var t=r(e,"string");return n(t)?t:t+""}},2352(e,t,i){"use strict";var r=i(5613),n=i(6893),a=i(5604),s=i(4977),o=i(286),l=i(7509),c=i(4320),u=i(997),d=i(4282),h=i(3086),p=i(2712),m=i(3008),g=a("Promise"),f=a("SuppressedError"),y=ReferenceError,v=d("asyncDispose"),b=d("toStringTag"),w="AsyncDisposableStack",k=h.set,S=h.getterFor(w),_="async-dispose",x="disposed",C=function(e){var t=S(e);if(t.state===x)throw new y(w+" already disposed");return t},I=function(){k(o(this,E),{type:w,state:"pending",stack:[]}),n||(this.disposed=!1)},E=I.prototype;c(E,{disposeAsync:function(){var e=this;return new g(function(t,i){var r=S(e);if(r.state===x)return t(void 0);r.state=x,n||(e.disposed=!0);var a,s=r.stack,o=s.length,l=!1,c=function(e){l?a=new f(e,a):(l=!0,a=e),u()},u=function(){if(o){var e=s[--o];s[o]=null;try{g.resolve(e()).then(u,c)}catch(e){c(e)}}else r.stack=null,l?i(a):t(void 0)};u()})},use:function(e){return p(C(this),e,_),e},adopt:function(e,t){var i=C(this);return s(t),p(i,void 0,_,function(){return t(e)}),e},defer:function(e){var t=C(this);s(e),p(t,void 0,_,e)},move:function(){var e=C(this),t=new I;return S(t).stack=e.stack,e.stack=[],e.state=x,n||(this.disposed=!0),t}}),n&&u(E,"disposed",{configurable:!0,get:function(){return S(this).state===x}}),l(E,v,E.disposeAsync,{name:"disposeAsync"}),l(E,b,w,{nonWritable:!0}),r({global:!0,constructor:!0,forced:m&&m<136},{AsyncDisposableStack:I})},2374(e,t,i){var r=i(4643);if(i(7835),i(121),i(4467),i(1054),i(339),i(5417),i(8550),void 0===n)var n=r.jsbn.BigInteger;var a=r.util.isNodejs?i(9701):null,s=r.asn1,o=r.util;r.pki=r.pki||{},e.exports=r.pki.rsa=r.rsa=r.rsa||{};var l=r.pki,c=[6,4,2,4,2,4,6,2],u={name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},d={name:"RSAPrivateKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPrivateKey.version",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"RSAPrivateKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyModulus"},{name:"RSAPrivateKey.publicExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPublicExponent"},{name:"RSAPrivateKey.privateExponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrivateExponent"},{name:"RSAPrivateKey.prime1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime1"},{name:"RSAPrivateKey.prime2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyPrime2"},{name:"RSAPrivateKey.exponent1",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent1"},{name:"RSAPrivateKey.exponent2",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyExponent2"},{name:"RSAPrivateKey.coefficient",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"privateKeyCoefficient"}]},h={name:"RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"RSAPublicKey.modulus",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyModulus"},{name:"RSAPublicKey.exponent",tagClass:s.Class.UNIVERSAL,type:s.Type.INTEGER,constructed:!1,capture:"publicKeyExponent"}]},p=r.pki.rsa.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{name:"SubjectPublicKeyInfo.subjectPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.BITSTRING,constructed:!1,value:[{name:"SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"rsaPublicKey"}]}]},m={name:"DigestInfo",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm",tagClass:s.Class.UNIVERSAL,type:s.Type.SEQUENCE,constructed:!0,value:[{name:"DigestInfo.DigestAlgorithm.algorithmIdentifier",tagClass:s.Class.UNIVERSAL,type:s.Type.OID,constructed:!1,capture:"algorithmIdentifier"},{name:"DigestInfo.DigestAlgorithm.parameters",tagClass:s.Class.UNIVERSAL,type:s.Type.NULL,capture:"parameters",optional:!0,constructed:!1}]},{name:"DigestInfo.digest",tagClass:s.Class.UNIVERSAL,type:s.Type.OCTETSTRING,constructed:!1,capture:"digest"}]},g=function(e){var t;if(!(e.algorithm in l.oids)){var i=new Error("Unknown message digest algorithm.");throw i.algorithm=e.algorithm,i}t=l.oids[e.algorithm];var r=s.oidToDer(t).getBytes(),n=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]),a=s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[]);a.value.push(s.create(s.Class.UNIVERSAL,s.Type.OID,!1,r)),a.value.push(s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,""));var o=s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,e.digest().getBytes());return n.value.push(a),n.value.push(o),s.toDer(n).getBytes()},f=function(e,t,i){if(i)return e.modPow(t.e,t.n);if(!t.p||!t.q)return e.modPow(t.d,t.n);var a;t.dP||(t.dP=t.d.mod(t.p.subtract(n.ONE))),t.dQ||(t.dQ=t.d.mod(t.q.subtract(n.ONE))),t.qInv||(t.qInv=t.q.modInverse(t.p));do{a=new n(r.util.bytesToHex(r.random.getBytes(t.n.bitLength()/8)),16)}while(a.compareTo(t.n)>=0||!a.gcd(t.n).equals(n.ONE));for(var s=(e=e.multiply(a.modPow(t.e,t.n)).mod(t.n)).mod(t.p).modPow(t.dP,t.p),o=e.mod(t.q).modPow(t.dQ,t.q);s.compareTo(o)<0;)s=s.add(t.p);var l=s.subtract(o).multiply(t.qInv).mod(t.p).multiply(t.q).add(o);return l.multiply(a.modInverse(t.n)).mod(t.n)};function y(e,t,i){var n=r.util.createBuffer(),a=Math.ceil(t.n.bitLength()/8);if(e.length>a-11){var s=new Error("Message is too long for PKCS#1 v1.5 padding.");throw s.length=e.length,s.max=a-11,s}n.putByte(0),n.putByte(i);var o,l=a-3-e.length;if(0===i||1===i){o=0===i?0:255;for(var c=0;c0;){var u=0,d=r.random.getBytes(l);for(c=0;c1;){if(255!==s.getByte()){--s.read;break}++c}else if(2===l)for(c=0;s.length()>1;){if(0===s.getByte()){--s.read;break}++c}if(0!==s.getByte()||c!==a-3-s.length())throw new Error("Encryption block is invalid.");return s.getBytes()}function b(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var i=r.util.hexToBytes(t);return!(i.length>1)||(0!==i.charCodeAt(0)||128&i.charCodeAt(1))&&(255!==i.charCodeAt(0)||128&~i.charCodeAt(1))?i:i.substr(1)}function w(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function k(e){return r.util.isNodejs&&"function"==typeof a[e]}function S(e){return void 0!==o.globalScope&&"object"==typeof o.globalScope.crypto&&"object"==typeof o.globalScope.crypto.subtle&&"function"==typeof o.globalScope.crypto.subtle[e]}function _(e){return void 0!==o.globalScope&&"object"==typeof o.globalScope.msCrypto&&"object"==typeof o.globalScope.msCrypto.subtle&&"function"==typeof o.globalScope.msCrypto.subtle[e]}function x(e){for(var t=r.util.hexToBytes(e.toString(16)),i=new Uint8Array(t.length),n=0;n0;)u.putByte(0),--d;return u.putBytes(r.util.hexToBytes(c)),u.getBytes()},l.rsa.decrypt=function(e,t,i,a){var s=Math.ceil(t.n.bitLength()/8);if(e.length!==s){var o=new Error("Encrypted message length is invalid.");throw o.length=e.length,o.expected=s,o}var l=new n(r.util.createBuffer(e).toHex(),16);if(l.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var c=f(l,t,i).toString(16),u=r.util.createBuffer(),d=s-Math.ceil(c.length/2);d>0;)u.putByte(0),--d;return u.putBytes(r.util.hexToBytes(c)),!1!==a?v(u.getBytes(),t,i):u.getBytes()},l.rsa.createKeyPairGenerationState=function(e,t,i){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048;var a,s=(i=i||{}).prng||r.random,o={nextBytes:function(e){for(var t=s.getBytesSync(e.length),i=0;i>1,pBits:e-(e>>1),pqState:0,num:null,keys:null}).e.fromInt(a.eInt),a},l.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var i=new n(null);i.fromInt(30);for(var r,a=0,s=function(e,t){return e|t},o=+new Date,u=0;null===e.keys&&(t<=0||ud?e.pqState=0:e.num.isProbablePrime(w(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(c[a++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(n.ONE).gcd(e.e).compareTo(n.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(n.ONE),e.q1=e.q.subtract(n.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(n.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var p=e.e.modInverse(e.phi);e.keys={privateKey:l.rsa.setPrivateKey(e.n,e.e,p,e.p,e.q,p.mod(e.p1),p.mod(e.q1),e.q.modInverse(e.p)),publicKey:l.rsa.setPublicKey(e.n,e.e)}}u+=(r=+new Date)-o,o=r}return null!==e.keys},l.rsa.generateKeyPair=function(e,t,i,c){if(1===arguments.length?"object"==typeof e?(i=e,e=void 0):"function"==typeof e&&(c=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(c=t,t=void 0):"number"!=typeof t&&(i=t,t=void 0):(i=e,c=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof i&&(c=i,i=void 0):(c=i,i=t,t=void 0)),i=i||{},void 0===e&&(e=i.bits||2048),void 0===t&&(t=i.e||65537),!r.options.usePureJavaScript&&!i.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(c){if(k("generateKeyPair"))return a.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(e,t,i){if(e)return c(e);c(null,{privateKey:l.privateKeyFromPem(i),publicKey:l.publicKeyFromPem(t)})});if(S("generateKey")&&S("exportKey"))return o.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:x(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(e){return o.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)}).then(void 0,function(e){c(e)}).then(function(e){if(e){var t=l.privateKeyFromAsn1(s.fromDer(r.util.createBuffer(e)));c(null,{privateKey:t,publicKey:l.setRsaPublicKey(t.n,t.e)})}});if(_("generateKey")&&_("exportKey")){var u=o.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:x(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return u.oncomplete=function(e){var t=e.target.result,i=o.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);i.oncomplete=function(e){var t=e.target.result,i=l.privateKeyFromAsn1(s.fromDer(r.util.createBuffer(t)));c(null,{privateKey:i,publicKey:l.setRsaPublicKey(i.n,i.e)})},i.onerror=function(e){c(e)}},void(u.onerror=function(e){c(e)})}}else if(k("generateKeyPairSync")){var d=a.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:l.privateKeyFromPem(d.privateKey),publicKey:l.publicKeyFromPem(d.publicKey)}}var h=l.rsa.createKeyPairGenerationState(e,t,i);if(!c)return l.rsa.stepKeyPairGenerationState(h,0),h.keys;!function(e,t,i){"function"==typeof t&&(i=t,t={});var a={algorithm:{name:(t=t||{}).algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};function s(){o(e.pBits,function(t,r){return t?i(t):(e.p=r,null!==e.q?c(t,e.q):void o(e.qBits,c))})}function o(e,t){r.prime.generateProbablePrime(e,a,t)}function c(t,r){if(t)return i(t);if(e.q=r,e.p.compareTo(e.q)<0){var a=e.p;e.p=e.q,e.q=a}if(0!==e.p.subtract(n.ONE).gcd(e.e).compareTo(n.ONE))return e.p=null,void s();if(0!==e.q.subtract(n.ONE).gcd(e.e).compareTo(n.ONE))return e.q=null,void o(e.qBits,c);if(e.p1=e.p.subtract(n.ONE),e.q1=e.q.subtract(n.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(n.ONE))return e.p=e.q=null,void s();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void o(e.qBits,c);var u=e.e.modInverse(e.phi);e.keys={privateKey:l.rsa.setPrivateKey(e.n,e.e,u,e.p,e.q,u.mod(e.p1),u.mod(e.q1),e.q.modInverse(e.p)),publicKey:l.rsa.setPublicKey(e.n,e.e)},i(null,e.keys)}"prng"in t&&(a.prng=t.prng),s()}(h,i,c)},l.setRsaPublicKey=l.rsa.setPublicKey=function(e,t){var i={n:e,e:t,encrypt:function(e,t,n){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,i){return y(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return r.pkcs1.encode_rsa_oaep(t,e,n)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var a=t.encode(e,i,!0);return l.rsa.encrypt(a,i,!0)},verify:function(e,t,n,a){"string"==typeof n?n=n.toUpperCase():void 0===n&&(n="RSASSA-PKCS1-V1_5"),void 0===a&&(a={_parseAllDigestBytes:!0}),"_parseAllDigestBytes"in a||(a._parseAllDigestBytes=!0),"RSASSA-PKCS1-V1_5"===n?n={verify:function(e,t){t=v(t,i,!0);var n=s.fromDer(t,{parseAllBytes:a._parseAllDigestBytes}),o={},l=[];if(!s.validate(n,m,o,l))throw(c=new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value.")).errors=l,c;var c,u=s.derToOid(o.algorithmIdentifier);if(u!==r.oids.md2&&u!==r.oids.md5&&u!==r.oids.sha1&&u!==r.oids.sha224&&u!==r.oids.sha256&&u!==r.oids.sha384&&u!==r.oids.sha512&&u!==r.oids["sha512-224"]&&u!==r.oids["sha512-256"])throw(c=new Error("Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.")).oid=u,c;if((u===r.oids.md2||u===r.oids.md5)&&!("parameters"in o))throw new Error("ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 DigestInfo value. Missing algorithm identifier NULL parameters.");return e===o.digest}}:"NONE"!==n&&"NULL"!==n&&null!==n||(n={verify:function(e,t){return e===v(t,i,!0)}});var o=l.rsa.decrypt(t,i,!0,!1);return n.verify(e,o,i.n.bitLength())}};return i},l.setRsaPrivateKey=l.rsa.setPrivateKey=function(e,t,i,n,a,s,o,c){var u={n:e,e:t,d:i,p:n,q:a,dP:s,dQ:o,qInv:c,decrypt:function(e,t,i){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var n=l.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:v};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return r.pkcs1.decode_rsa_oaep(t,e,i)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(n,u,!1)},sign:function(e,t){var i=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:g},i=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},i=1);var r=t.encode(e,u.n.bitLength());return l.rsa.encrypt(r,u,i)}};return u},l.wrapRsaPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(l.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.OCTETSTRING,!1,s.toDer(e).getBytes())])},l.privateKeyFromAsn1=function(e){var t,i,a,o,c,h,p,m,g={},f=[];if(s.validate(e,u,g,f)&&(e=s.fromDer(r.util.createBuffer(g.privateKey))),g={},f=[],!s.validate(e,d,g,f)){var y=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw y.errors=f,y}return t=r.util.createBuffer(g.privateKeyModulus).toHex(),i=r.util.createBuffer(g.privateKeyPublicExponent).toHex(),a=r.util.createBuffer(g.privateKeyPrivateExponent).toHex(),o=r.util.createBuffer(g.privateKeyPrime1).toHex(),c=r.util.createBuffer(g.privateKeyPrime2).toHex(),h=r.util.createBuffer(g.privateKeyExponent1).toHex(),p=r.util.createBuffer(g.privateKeyExponent2).toHex(),m=r.util.createBuffer(g.privateKeyCoefficient).toHex(),l.setRsaPrivateKey(new n(t,16),new n(i,16),new n(a,16),new n(o,16),new n(c,16),new n(h,16),new n(p,16),new n(m,16))},l.privateKeyToAsn1=l.privateKeyToRSAPrivateKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,s.integerToDer(0).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.e)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.d)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.p)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.q)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.dP)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.dQ)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.qInv))])},l.publicKeyFromAsn1=function(e){var t={},i=[];if(s.validate(e,p,t,i)){var a,o=s.derToOid(t.publicKeyOid);if(o!==l.oids.rsaEncryption)throw(a=new Error("Cannot read public key. Unknown OID.")).oid=o,a;e=t.rsaPublicKey}if(i=[],!s.validate(e,h,t,i))throw(a=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.")).errors=i,a;var c=r.util.createBuffer(t.publicKeyModulus).toHex(),u=r.util.createBuffer(t.publicKeyExponent).toHex();return l.setRsaPublicKey(new n(c,16),new n(u,16))},l.publicKeyToAsn1=l.publicKeyToSubjectPublicKeyInfo=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.OID,!1,s.oidToDer(l.oids.rsaEncryption).getBytes()),s.create(s.Class.UNIVERSAL,s.Type.NULL,!1,"")]),s.create(s.Class.UNIVERSAL,s.Type.BITSTRING,!1,[l.publicKeyToRSAPublicKey(e)])])},l.publicKeyToRSAPublicKey=function(e){return s.create(s.Class.UNIVERSAL,s.Type.SEQUENCE,!0,[s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.n)),s.create(s.Class.UNIVERSAL,s.Type.INTEGER,!1,b(e.e))])}},2386(e,t,i){"use strict";const r=i(7851);e.exports=(e,t,i)=>r(e,t,i)>=0},2387(e){"use strict";e.exports=Math.min},2422(e){"use strict";e.exports=Number.isNaN||function(e){return e!=e}},2461(e,t,i){e.exports=function e(t,i,r){function n(s,o){if(!i[s]){if(!t[s]){if(a)return a(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[s]={exports:{}};t[s][0].call(c.exports,function(e){return n(t[s][1][e]||e)},c,c.exports,e,t,i,r)}return i[s].exports}for(var a=void 0,s=0;s>2,o=(3&t)<<4|i>>4,l=1>6:64,c=2>4,i=(15&s)<<4|(o=a.indexOf(e.charAt(c++)))>>2,r=(3&o)<<6|(l=a.indexOf(e.charAt(c++))),h[u++]=t,64!==o&&(h[u++]=i),64!==l&&(h[u++]=r);return h}},{"./support":30,"./utils":32}],2:[function(e,t,i){"use strict";var r=e("./external"),n=e("./stream/DataWorker"),a=e("./stream/Crc32Probe"),s=e("./stream/DataLengthProbe");function o(e,t,i,r,n){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=r,this.compressedContent=n}o.prototype={getContentWorker:function(){var e=new n(r.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new s("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new n(r.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(e,t,i){return e.pipe(new a).pipe(new s("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new s("compressedSize")).withStreamInfo("compression",t)},t.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,i){"use strict";var r=e("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new r("STORE compression")},uncompressWorker:function(){return new r("STORE decompression")}},i.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,i){"use strict";var r=e("./utils"),n=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==r.getTypeOf(e)?function(e,t,i){var r=n,a=0+i;e^=-1;for(var s=0;s>>8^r[255&(e^t[s])];return-1^e}(0|t,e,e.length):function(e,t,i){var r=n,a=0+i;e^=-1;for(var s=0;s>>8^r[255&(e^t.charCodeAt(s))];return-1^e}(0|t,e,e.length):0}},{"./utils":32}],5:[function(e,t,i){"use strict";i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(e,t,i){"use strict";var r;r="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:r}},{lie:37}],7:[function(e,t,i){"use strict";var r="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=e("pako"),a=e("./utils"),s=e("./stream/GenericWorker"),o=r?"uint8array":"array";function l(e,t){s.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}i.magic="\b\0",a.inherits(l,s),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(a.transformTo(o,e.data),!1)},l.prototype.flush=function(){s.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},i.compressWorker=function(e){return new l("Deflate",e)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,i){"use strict";function r(e,t){var i,r="";for(i=0;i>>=8;return r}function n(e,t,i,n,s,u){var d,h,p=e.file,m=e.compression,g=u!==o.utf8encode,f=a.transformTo("string",u(p.name)),y=a.transformTo("string",o.utf8encode(p.name)),v=p.comment,b=a.transformTo("string",u(v)),w=a.transformTo("string",o.utf8encode(v)),k=y.length!==p.name.length,S=w.length!==v.length,_="",x="",C="",I=p.dir,E=p.date,z={crc32:0,compressedSize:0,uncompressedSize:0};t&&!i||(z.crc32=e.crc32,z.compressedSize=e.compressedSize,z.uncompressedSize=e.uncompressedSize);var P=0;t&&(P|=8),g||!k&&!S||(P|=2048);var A=0,j=0;I&&(A|=16),"UNIX"===s?(j=798,A|=function(e,t){var i=e;return e||(i=t?16893:33204),(65535&i)<<16}(p.unixPermissions,I)):(j=20,A|=function(e){return 63&(e||0)}(p.dosPermissions)),d=E.getUTCHours(),d<<=6,d|=E.getUTCMinutes(),d<<=5,d|=E.getUTCSeconds()/2,h=E.getUTCFullYear()-1980,h<<=4,h|=E.getUTCMonth()+1,h<<=5,h|=E.getUTCDate(),k&&(x=r(1,1)+r(l(f),4)+y,_+="up"+r(x.length,2)+x),S&&(C=r(1,1)+r(l(b),4)+w,_+="uc"+r(C.length,2)+C);var T="";return T+="\n\0",T+=r(P,2),T+=m.magic,T+=r(d,2),T+=r(h,2),T+=r(z.crc32,4),T+=r(z.compressedSize,4),T+=r(z.uncompressedSize,4),T+=r(f.length,2),T+=r(_.length,2),{fileRecord:c.LOCAL_FILE_HEADER+T+f+_,dirRecord:c.CENTRAL_FILE_HEADER+r(j,2)+T+r(b.length,2)+"\0\0\0\0"+r(A,4)+r(n,4)+f+_+b}}var a=e("../utils"),s=e("../stream/GenericWorker"),o=e("../utf8"),l=e("../crc32"),c=e("../signature");function u(e,t,i,r){s.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=r,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}a.inherits(u,s),u.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,r=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,s.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-r-1))/i:100}}))},u.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=n(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},u.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,i=n(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(i.dirRecord),t)this.push({data:function(e){return c.DATA_DESCRIPTOR+r(e.crc32,4)+r(e.compressedSize,4)+r(e.uncompressedSize,4)}(e),meta:{percent:100}});else for(this.push({data:i.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},u.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t=this.index;t--)i=(i<<8)+this.byteAt(t);return this.index+=e,i},readString:function(e){return r.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=n},{"../utils":32}],19:[function(e,t,i){"use strict";var r=e("./Uint8ArrayReader");function n(e){r.call(this,e)}e("../utils").inherits(n,r),n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,i){"use strict";var r=e("./DataReader");function n(e){r.call(this,e)}e("../utils").inherits(n,r),n.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},n.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},n.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},n.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./DataReader":18}],21:[function(e,t,i){"use strict";var r=e("./ArrayReader");function n(e){r.call(this,e)}e("../utils").inherits(n,r),n.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=n},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,i){"use strict";var r=e("../utils"),n=e("../support"),a=e("./ArrayReader"),s=e("./StringReader"),o=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=r.getTypeOf(e);return r.checkSupport(t),"string"!==t||n.uint8array?"nodebuffer"===t?new o(e):n.uint8array?new l(r.transformTo("uint8array",e)):new a(r.transformTo("array",e)):new s(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,i){"use strict";i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,i){"use strict";var r=e("./GenericWorker"),n=e("../utils");function a(e){r.call(this,"ConvertWorker to "+e),this.destType=e}n.inherits(a,r),a.prototype.processChunk=function(e){this.push({data:n.transformTo(this.destType,e.data),meta:e.meta})},t.exports=a},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,i){"use strict";var r=e("./GenericWorker"),n=e("../crc32");function a(){r.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(a,r),a.prototype.processChunk=function(e){this.streamInfo.crc32=n(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=a},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,i){"use strict";var r=e("../utils"),n=e("./GenericWorker");function a(e){n.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}r.inherits(a,n),a.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}n.prototype.processChunk.call(this,e)},t.exports=a},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,i){"use strict";var r=e("../utils"),n=e("./GenericWorker");function a(e){n.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=r.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}r.inherits(a,n),a.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this.data=null},a.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,r.delay(this._tickAndRepeat,[],this)),!0)},a.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(r.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},a.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=a},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,i){"use strict";function r(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}r.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i "+e:e}},t.exports=r},{}],29:[function(e,t,i){"use strict";var r=e("../utils"),n=e("./ConvertWorker"),a=e("./GenericWorker"),s=e("../base64"),o=e("../support"),l=e("../external"),c=null;if(o.nodestream)try{c=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function u(e,t,i){var s=t;switch(t){case"blob":case"arraybuffer":s="uint8array";break;case"base64":s="string"}try{this._internalType=s,this._outputType=t,this._mimeType=i,r.checkSupport(s),this._worker=e.pipe(new n(s)),e.lock()}catch(e){this._worker=new a("error"),this._worker.error(e)}}u.prototype={accumulate:function(e){return function(e,t){return new l.Promise(function(i,n){var a=[],o=e._internalType,l=e._outputType,c=e._mimeType;e.on("data",function(e,i){a.push(e),t&&t(i)}).on("error",function(e){a=[],n(e)}).on("end",function(){try{var e=function(e,t,i){switch(e){case"blob":return r.newBlob(r.transformTo("arraybuffer",t),i);case"base64":return s.encode(t);default:return r.transformTo(e,t)}}(l,function(e,t){var i,r=0,n=null,a=0;for(i=0;i>>6:(i<65536?t[s++]=224|i>>>12:(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63),t[s++]=128|i>>>6&63),t[s++]=128|63&i);return t}(e)},i.utf8decode=function(e){return n.nodebuffer?r.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,i,n,a,s=e.length,l=new Array(2*s);for(t=i=0;t>10&1023,l[i++]=56320|1023&n)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),r.applyFromCharCode(l)}(e=r.transformTo(n.uint8array?"uint8array":"array",e))},r.inherits(c,s),c.prototype.processChunk=function(e){var t=r.transformTo(n.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(n.uint8array){var a=t;(t=new Uint8Array(a.length+this.leftOver.length)).set(this.leftOver,0),t.set(a,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var s=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+o[e[i]]>t?i:t}(t),l=t;s!==t.length&&(n.uint8array?(l=t.subarray(0,s),this.leftOver=t.subarray(s,t.length)):(l=t.slice(0,s),this.leftOver=t.slice(s,t.length))),this.push({data:i.utf8decode(l),meta:e.meta})},c.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=c,r.inherits(u,s),u.prototype.processChunk=function(e){this.push({data:i.utf8encode(e.data),meta:e.meta})},i.Utf8EncodeWorker=u},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,i){"use strict";var r=e("./support"),n=e("./base64"),a=e("./nodejsUtils"),s=e("./external");function o(e){return e}function l(e,t){for(var i=0;i>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=r(this.extraFields[1].value);this.uncompressedSize===n.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===n.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===n.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===n.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,i,r,n=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4>>6:(i<65536?t[s++]=224|i>>>12:(t[s++]=240|i>>>18,t[s++]=128|i>>>12&63),t[s++]=128|i>>>6&63),t[s++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new r.Buf8(e.length),i=0,n=t.length;i>10&1023,c[r++]=56320|1023&n)}return l(c,r)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+s[e[i]]>t?i:t}},{"./common":41}],43:[function(e,t,i){"use strict";t.exports=function(e,t,i,r){for(var n=65535&e,a=e>>>16&65535,s=0;0!==i;){for(i-=s=2e3>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,n){var a=r,s=n+i;e^=-1;for(var o=n;o>>8^a[255&(e^t[o])];return-1^e}},{}],46:[function(e,t,i){"use strict";var r,n=e("../utils/common"),a=e("./trees"),s=e("./adler32"),o=e("./crc32"),l=e("./messages"),c=-2,u=258,d=262,h=113;function p(e,t){return e.msg=l[t],t}function m(e){return(e<<1)-(4e.avail_out&&(i=e.avail_out),0!==i&&(n.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function y(e,t){a._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,f(e.strm)}function v(e,t){e.pending_buf[e.pending++]=t}function b(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function w(e,t){var i,r,n=e.max_chain_length,a=e.strstart,s=e.prev_length,o=e.nice_match,l=e.strstart>e.w_size-d?e.strstart-(e.w_size-d):0,c=e.window,h=e.w_mask,p=e.prev,m=e.strstart+u,g=c[a+s-1],f=c[a+s];e.prev_length>=e.good_match&&(n>>=2),o>e.lookahead&&(o=e.lookahead);do{if(c[(i=t)+s]===f&&c[i+s-1]===g&&c[i]===c[a]&&c[++i]===c[a+1]){a+=2,i++;do{}while(c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&c[++a]===c[++i]&&al&&0!=--n);return s<=e.lookahead?s:e.lookahead}function k(e){var t,i,r,a,l,c,u,h,p,m,g=e.w_size;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=g+(g-d)){for(n.arraySet(e.window,e.window,g,g,0),e.match_start-=g,e.strstart-=g,e.block_start-=g,t=i=e.hash_size;r=e.head[--t],e.head[t]=g<=r?r-g:0,--i;);for(t=i=g;r=e.prev[--t],e.prev[t]=g<=r?r-g:0,--i;);a+=g}if(0===e.strm.avail_in)break;if(c=e.strm,u=e.window,h=e.strstart+e.lookahead,m=void 0,(p=a)<(m=c.avail_in)&&(m=p),i=0===m?0:(c.avail_in-=m,n.arraySet(u,c.input,c.next_in,m,h),1===c.state.wrap?c.adler=s(c.adler,u,m,h):2===c.state.wrap&&(c.adler=o(c.adler,u,m,h)),c.next_in+=m,c.total_in+=m,m),e.lookahead+=i,e.lookahead+e.insert>=3)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<=3&&(e.ins_h=(e.ins_h<=3)if(r=a._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=3&&(e.ins_h=(e.ins_h<=3&&e.match_length<=e.prev_length){for(n=e.strstart+e.lookahead-3,r=a._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=n&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(k(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+i;if((0===e.strstart||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,y(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-d&&(y(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(y(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(y(e,!1),e.strm.avail_out),1)}),new x(4,4,8,4,S),new x(4,5,16,8,S),new x(4,6,32,32,S),new x(4,4,16,16,_),new x(8,16,32,32,_),new x(8,16,128,128,_),new x(8,32,128,256,_),new x(32,128,258,1024,_),new x(32,258,258,4096,_)],i.deflateInit=function(e,t){return z(e,t,8,15,8,0)},i.deflateInit2=z,i.deflateReset=E,i.deflateResetKeep=I,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?c:(e.state.gzhead=t,0):c},i.deflate=function(e,t){var i,n,s,l;if(!e||!e.state||5>8&255),v(n,n.gzhead.time>>16&255),v(n,n.gzhead.time>>24&255),v(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),v(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(v(n,255&n.gzhead.extra.length),v(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=o(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(v(n,0),v(n,0),v(n,0),v(n,0),v(n,0),v(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),v(n,3),n.status=h);else{var d=8+(n.w_bits-8<<4)<<8;d|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(d|=32),d+=31-d%31,n.status=h,b(n,d),0!==n.strstart&&(b(n,e.adler>>>16),b(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(s=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>s&&(e.adler=o(e.adler,n.pending_buf,n.pending-s,s)),f(e),s=n.pending,n.pending!==n.pending_buf_size));)v(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>s&&(e.adler=o(e.adler,n.pending_buf,n.pending-s,s)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=o(e.adler,n.pending_buf,n.pending-s,s)),f(e),s=n.pending,n.pending===n.pending_buf_size)){l=1;break}l=n.gzindexs&&(e.adler=o(e.adler,n.pending_buf,n.pending-s,s)),0===l&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){s=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>s&&(e.adler=o(e.adler,n.pending_buf,n.pending-s,s)),f(e),s=n.pending,n.pending===n.pending_buf_size)){l=1;break}l=n.gzindexs&&(e.adler=o(e.adler,n.pending_buf,n.pending-s,s)),0===l&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&f(e),n.pending+2<=n.pending_buf_size&&(v(n,255&e.adler),v(n,e.adler>>8&255),e.adler=0,n.status=h)):n.status=h),0!==n.pending){if(f(e),0===e.avail_out)return n.last_flush=-1,0}else if(0===e.avail_in&&m(t)<=m(i)&&4!==t)return p(e,-5);if(666===n.status&&0!==e.avail_in)return p(e,-5);if(0!==e.avail_in||0!==n.lookahead||0!==t&&666!==n.status){var w=2===n.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(k(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=a._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(y(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(y(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(y(e,!1),0===e.strm.avail_out)?1:2}(n,t):3===n.strategy?function(e,t){for(var i,r,n,s,o=e.window;;){if(e.lookahead<=u){if(k(e),e.lookahead<=u&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&0e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=a._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=a._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(y(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(y(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(y(e,!1),0===e.strm.avail_out)?1:2}(n,t):r[n.level].func(n,t);if(3!==w&&4!==w||(n.status=666),1===w||3===w)return 0===e.avail_out&&(n.last_flush=-1),0;if(2===w&&(1===t?a._tr_align(n):5!==t&&(a._tr_stored_block(n,0,0,!1),3===t&&(g(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),f(e),0===e.avail_out))return n.last_flush=-1,0}return 4!==t?0:n.wrap<=0?1:(2===n.wrap?(v(n,255&e.adler),v(n,e.adler>>8&255),v(n,e.adler>>16&255),v(n,e.adler>>24&255),v(n,255&e.total_in),v(n,e.total_in>>8&255),v(n,e.total_in>>16&255),v(n,e.total_in>>24&255)):(b(n,e.adler>>>16),b(n,65535&e.adler)),f(e),0=i.w_size&&(0===o&&(g(i.head),i.strstart=0,i.block_start=0,i.insert=0),h=new n.Buf8(i.w_size),n.arraySet(h,t,p-i.w_size,i.w_size,0),t=h,p=i.w_size),l=e.avail_in,u=e.next_in,d=e.input,e.avail_in=p,e.next_in=0,e.input=t,k(i);i.lookahead>=3;){for(r=i.strstart,a=i.lookahead-2;i.ins_h=(i.ins_h<>>=w=b>>>24,m-=w,0==(w=b>>>16&255))I[a++]=65535&b;else{if(!(16&w)){if(!(64&w)){b=g[(65535&b)+(p&(1<>>=w,m-=w),m<15&&(p+=C[r++]<>>=w=b>>>24,m-=w,!(16&(w=b>>>16&255))){if(!(64&w)){b=f[(65535&b)+(p&(1<>>=w,m-=w,(w=a-s)>3,p&=(1<<(m-=k<<3))-1,e.next_in=r,e.next_out=a,e.avail_in=r>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function d(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new r.Buf32(852),t.distcode=t.distdyn=new r.Buf32(592),t.sane=1,t.back=-1,0):l}function h(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,d(e)):l}function p(e,t){var i,r;return e&&e.state?(r=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=s.wsize?(r.arraySet(s.window,t,i-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n<(a=s.wsize-s.wnext)&&(a=n),r.arraySet(s.window,t,i-n,a,s.wnext),(n-=a)?(r.arraySet(s.window,t,i-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=a,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,i.check=a(i.check,R,2,0),y=f=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&f)<<8)+(f>>8))%31){e.msg="incorrect header check",i.mode=30;break}if(8!=(15&f)){e.msg="unknown compression method",i.mode=30;break}if(y-=4,j=8+(15&(f>>>=4)),0===i.wbits)i.wbits=j;else if(j>i.wbits){e.msg="invalid window size",i.mode=30;break}i.dmax=1<>8&1),512&i.flags&&(R[0]=255&f,R[1]=f>>>8&255,i.check=a(i.check,R,2,0)),y=f=0,i.mode=3;case 3:for(;y<32;){if(0===m)break e;m--,f+=u[h++]<>>8&255,R[2]=f>>>16&255,R[3]=f>>>24&255,i.check=a(i.check,R,4,0)),y=f=0,i.mode=4;case 4:for(;y<16;){if(0===m)break e;m--,f+=u[h++]<>8),512&i.flags&&(R[0]=255&f,R[1]=f>>>8&255,i.check=a(i.check,R,2,0)),y=f=0,i.mode=5;case 5:if(1024&i.flags){for(;y<16;){if(0===m)break e;m--,f+=u[h++]<>>8&255,i.check=a(i.check,R,2,0)),y=f=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(m<(S=i.length)&&(S=m),S&&(i.head&&(j=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),r.arraySet(i.head.extra,u,h,S,j)),512&i.flags&&(i.check=a(i.check,u,S,h)),m-=S,h+=S,i.length-=S),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===m)break e;for(S=0;j=u[h+S++],i.head&&j&&i.length<65536&&(i.head.name+=String.fromCharCode(j)),j&&S>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=12;break;case 10:for(;y<32;){if(0===m)break e;m--,f+=u[h++]<>>=7&y,y-=7&y,i.mode=27;break}for(;y<3;){if(0===m)break e;m--,f+=u[h++]<>>=1)){case 0:i.mode=14;break;case 1:if(v(i),i.mode=20,6!==t)break;f>>>=2,y-=2;break e;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=30}f>>>=2,y-=2;break;case 14:for(f>>>=7&y,y-=7&y;y<32;){if(0===m)break e;m--,f+=u[h++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&f,y=f=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(S=i.length){if(m>>=5,y-=5,i.ndist=1+(31&f),f>>>=5,y-=5,i.ncode=4+(15&f),f>>>=4,y-=4,286>>=3,y-=3}for(;i.have<19;)i.lens[U[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,D={bits:i.lenbits},T=o(0,i.lens,0,19,i.lencode,0,i.work,D),i.lenbits=D.bits,T){e.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have>>16&255,E=65535&N,!((C=N>>>24)<=y);){if(0===m)break e;m--,f+=u[h++]<>>=C,y-=C,i.lens[i.have++]=E;else{if(16===E){for(O=C+2;y>>=C,y-=C,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}j=i.lens[i.have-1],S=3+(3&f),f>>>=2,y-=2}else if(17===E){for(O=C+3;y>>=C)),f>>>=3,y-=3}else{for(O=C+7;y>>=C)),f>>>=7,y-=7}if(i.have+S>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;S--;)i.lens[i.have++]=j}}if(30===i.mode)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,D={bits:i.lenbits},T=o(1,i.lens,0,i.nlen,i.lencode,0,i.work,D),i.lenbits=D.bits,T){e.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,D={bits:i.distbits},T=o(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,D),i.distbits=D.bits,T){e.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(6<=m&&258<=g){e.next_out=p,e.avail_out=g,e.next_in=h,e.avail_in=m,i.hold=f,i.bits=y,s(e,k),p=e.next_out,d=e.output,g=e.avail_out,h=e.next_in,u=e.input,m=e.avail_in,f=i.hold,y=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;I=(N=i.lencode[f&(1<>>16&255,E=65535&N,!((C=N>>>24)<=y);){if(0===m)break e;m--,f+=u[h++]<>z)])>>>16&255,E=65535&N,!(z+(C=N>>>24)<=y);){if(0===m)break e;m--,f+=u[h++]<>>=z,y-=z,i.back+=z}if(f>>>=C,y-=C,i.back+=C,i.length=E,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){e.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(O=i.extra;y>>=i.extra,y-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;I=(N=i.distcode[f&(1<>>16&255,E=65535&N,!((C=N>>>24)<=y);){if(0===m)break e;m--,f+=u[h++]<>z)])>>>16&255,E=65535&N,!(z+(C=N>>>24)<=y);){if(0===m)break e;m--,f+=u[h++]<>>=z,y-=z,i.back+=z}if(f>>>=C,y-=C,i.back+=C,64&I){e.msg="invalid distance code",i.mode=30;break}i.offset=E,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(O=i.extra;y>>=i.extra,y-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===g)break e;if(S=k-g,i.offset>S){if((S=i.offset-S)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}_=S>i.wnext?(S-=i.wnext,i.wsize-S):i.wnext-S,S>i.length&&(S=i.length),x=i.window}else x=d,_=p-i.offset,S=i.length;for(gv?(w=U[F+d[x]],D[O+d[x]]):(w=96,0),p=1<<_-P,C=m=1<>P)+(m-=p)]=b<<24|w<<16|k,0!==m;);for(p=1<<_-1;T&p;)p>>=1;if(0!==p?(T&=p-1,T+=p):T=0,x++,0==--N[_]){if(_===I)break;_=t[i+d[x]]}if(E<_&&(T&f)!==g){for(0===P&&(P=E),y+=C,A=1<<(z=_-P);z+P>>7)]}function C(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function I(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<>>=1,i<<=1,0<--t;);return i>>>1}function P(e,t,i){var r,n,a=new Array(16),s=0;for(r=1;r<=l;r++)a[r]=s=s+i[r-1]<<1;for(n=0;n<=t;n++){var o=e[2*n+1];0!==o&&(e[2*n]=z(a[o]++,o))}}function A(e){var t;for(t=0;t>1;1<=i;i--)D(e,a,i);for(n=c;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],D(e,a,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,a[2*n]=a[2*i]+a[2*r],e.depth[n]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,a[2*i+1]=a[2*r+1]=n,e.heap[1]=n++,D(e,a,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,r,n,a,s,o,c=t.dyn_tree,u=t.max_code,d=t.stat_desc.static_tree,h=t.stat_desc.has_stree,p=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,g=t.stat_desc.max_length,f=0;for(a=0;a<=l;a++)e.bl_count[a]=0;for(c[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)g<(a=c[2*c[2*(r=e.heap[i])+1]+1]+1)&&(a=g,f++),c[2*r+1]=a,u>=7;r>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t>>3,(s=e.static_len+3+7>>>3)<=n&&(n=s)):n=s=i+5,i+4<=n&&-1!==t?q(e,t,i,r):4===e.strategy||s===n?(I(e,2+(r?1:0),3),O(e,p,m)):(I(e,4+(r?1:0),3),function(e,t,i,r){var n;for(I(e,t-257,5),I(e,i-1,5),I(e,r-4,4),n=0;n>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(f[i]+a+1)]++,e.dyn_dtree[2*x(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){I(e,2,3),E(e,256,p),function(e){16===e.bi_valid?(C(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":41}],53:[function(e,t,i){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,r){(function(e){!function(e){"use strict";if(!e.setImmediate){var t,i,r,n,a=1,s={},o=!1,l=e.document,c=Object.getPrototypeOf&&Object.getPrototypeOf(e);c=c&&c.setTimeout?c:e,t="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick(function(){d(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(n="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",h,!1):e.attachEvent("onmessage",h),function(t){e.postMessage(n+t,"*")}):e.MessageChannel?((r=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){r.port2.postMessage(e)}):l&&"onreadystatechange"in l.createElement("script")?(i=l.documentElement,function(e){var t=l.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):function(e){setTimeout(d,0,e)},c.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var i=new Array(arguments.length-1),r=0;r8?3:1,y=[],v=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],b=0,w=0;w>>4^S))<<4,k^=t=65535&((S^=t)>>>-16^k),k^=(t=858993459&(k>>>2^(S^=t<<-16)))<<2,k^=t=65535&((S^=t)>>>-16^k),k^=(t=1431655765&(k>>>1^(S^=t<<-16)))<<1,k^=t=16711935&((S^=t)>>>8^k),t=(k^=(t=1431655765&(k>>>1^(S^=t<<8)))<<1)<<8|(S^=t)>>>20&240,k=S<<24|S<<8&16711680|S>>>8&65280|S>>>24&240,S=t;for(var _=0;_>>26,S=S<<2|S>>>26):(k=k<<1|k>>>27,S=S<<1|S>>>27);var x=i[(k&=-15)>>>28]|r[k>>>24&15]|n[k>>>20&15]|a[k>>>16&15]|s[k>>>12&15]|o[k>>>8&15]|l[k>>>4&15],C=c[(S&=-15)>>>28]|u[S>>>24&15]|d[S>>>20&15]|h[S>>>16&15]|p[S>>>12&15]|m[S>>>8&15]|g[S>>>4&15];t=65535&(C>>>16^x),y[b++]=x^t,y[b++]=C^t<<16}}return y}(t),this._init=!0}},n("DES-ECB",r.cipher.modes.ecb),n("DES-CBC",r.cipher.modes.cbc),n("DES-CFB",r.cipher.modes.cfb),n("DES-OFB",r.cipher.modes.ofb),n("DES-CTR",r.cipher.modes.ctr),n("3DES-ECB",r.cipher.modes.ecb),n("3DES-CBC",r.cipher.modes.cbc),n("3DES-CFB",r.cipher.modes.cfb),n("3DES-OFB",r.cipher.modes.ofb),n("3DES-CTR",r.cipher.modes.ctr);var a=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],s=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],o=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],l=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],c=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],u=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],d=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],h=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696];function p(e,t,i,r){var n,p,m=32===e.length?3:9;n=3===m?r?[30,-2,-2]:[0,32,2]:r?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var g=t[0],f=t[1];g^=(p=252645135&(g>>>4^f))<<4,g^=(p=65535&(g>>>16^(f^=p)))<<16,g^=p=858993459&((f^=p)>>>2^g),g^=p=16711935&((f^=p<<2)>>>8^g),g=(g^=(p=1431655765&(g>>>1^(f^=p<<8)))<<1)<<1|g>>>31,f=(f^=p)<<1|f>>>31;for(var y=0;y>>4|f<<28)^e[w+1];p=g,g=f,f=p^(s[k>>>24&63]|l[k>>>16&63]|u[k>>>8&63]|h[63&k]|a[S>>>24&63]|o[S>>>16&63]|c[S>>>8&63]|d[63&S])}p=g,g=f,f=p}f=f>>>1|f<<31,f^=p=1431655765&((g=g>>>1|g<<31)>>>1^f),f^=(p=16711935&(f>>>8^(g^=p<<1)))<<8,f^=(p=858993459&(f>>>2^(g^=p)))<<2,f^=p=65535&((g^=p)>>>16^f),f^=p=252645135&((g^=p<<16)>>>4^f),g^=p<<4,i[0]=g,i[1]=f}function m(e){var t,i="DES-"+((e=e||{}).mode||"CBC").toUpperCase(),n=(t=e.decrypt?r.cipher.createDecipher(i,e.key):r.cipher.createCipher(i,e.key)).start;return t.start=function(e,i){var a=null;i instanceof r.util.ByteBuffer&&(a=i,i={}),(i=i||{}).output=a,i.iv=e,n.call(t,i)},t}},2694(e,t,i){"use strict";var r=i(1942),n=i(9117),a=i(4798),s="__core-js_shared__",o=e.exports=n[s]||a(s,{});(o.versions||(o.versions=[])).push({version:"3.48.0",mode:r?"pure":"global",copyright:"© 2013–2025 Denis Pushkarev (zloirock.ru), 2025–2026 CoreJS Company (core-js.io). All rights reserved.",license:"https://github.com/zloirock/core-js/blob/v3.48.0/LICENSE",source:"https://github.com/zloirock/core-js"})},2712(e,t,i){"use strict";var r=i(5604),n=i(9944),a=i(6881),s=i(5821),o=i(3770),l=i(4977),c=i(4318),u=i(2913),d=i(4282),h=d("asyncDispose"),p=d("dispose"),m=a([].push),g=function(e,t,i){return arguments.length<3&&!c(e)&&(i=l(function(e,t){if("async-dispose"===t){var i=u(e,h);return void 0!==i||void 0===(i=u(e,p))?i:function(){var e=this;return new(r("Promise"))(function(t){n(i,e),t(void 0)})}}return u(e,p)}(o(e),t))),void 0===i?function(){}:s(i,e)};e.exports=function(e,t,i,r){var n;if(arguments.length<4){if(c(t)&&"sync-dispose"===i)return;n=g(t,i)}else n=g(void 0,i,r);m(e.stack,n)}},2721(e,t,i){"use strict";var r=i(5613),n=i(9117),a=i(6881),s=i(503),o=i(8529),l=i(2676),c=i(6579),u=i(213),d=c.i2c,h=c.i2cUrl,p=a("".charAt),m=n.Uint8Array,g=!m||!m.prototype.toBase64||!function(){try{(new m).toBase64(null)}catch(e){return!0}}();m&&r({target:"Uint8Array",proto:!0,forced:g},{toBase64:function(){var e=o(this),t=arguments.length?s(arguments[0]):void 0,i="base64"===u(t)?d:h,r=!!t&&!!t.omitPadding;l(this.buffer);for(var n,a="",c=0,m=e.length,g=function(e){return p(i,n>>6*e&63)};c+2{const r=(e=>{for(const[t,i]of m)e=e.split(`${t}*`).join(`${t}{0,${i}}`).split(`${t}+`).join(`${t}{1,${i}}`);return e})(t),n=h++;s(e,n,t),d[e]=n,c[n]=t,u[n]=r,o[n]=new RegExp(t,i?"g":void 0),l[n]=new RegExp(r,i?"g":void 0)};g("NUMERICIDENTIFIER","0|[1-9]\\d*"),g("NUMERICIDENTIFIERLOOSE","\\d+"),g("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${p}*`),g("MAINVERSION",`(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})\\.(${c[d.NUMERICIDENTIFIER]})`),g("MAINVERSIONLOOSE",`(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})\\.(${c[d.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASEIDENTIFIER",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIER]})`),g("PRERELEASEIDENTIFIERLOOSE",`(?:${c[d.NONNUMERICIDENTIFIER]}|${c[d.NUMERICIDENTIFIERLOOSE]})`),g("PRERELEASE",`(?:-(${c[d.PRERELEASEIDENTIFIER]}(?:\\.${c[d.PRERELEASEIDENTIFIER]})*))`),g("PRERELEASELOOSE",`(?:-?(${c[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${c[d.PRERELEASEIDENTIFIERLOOSE]})*))`),g("BUILDIDENTIFIER",`${p}+`),g("BUILD",`(?:\\+(${c[d.BUILDIDENTIFIER]}(?:\\.${c[d.BUILDIDENTIFIER]})*))`),g("FULLPLAIN",`v?${c[d.MAINVERSION]}${c[d.PRERELEASE]}?${c[d.BUILD]}?`),g("FULL",`^${c[d.FULLPLAIN]}$`),g("LOOSEPLAIN",`[v=\\s]*${c[d.MAINVERSIONLOOSE]}${c[d.PRERELEASELOOSE]}?${c[d.BUILD]}?`),g("LOOSE",`^${c[d.LOOSEPLAIN]}$`),g("GTLT","((?:<|>)?=?)"),g("XRANGEIDENTIFIERLOOSE",`${c[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),g("XRANGEIDENTIFIER",`${c[d.NUMERICIDENTIFIER]}|x|X|\\*`),g("XRANGEPLAIN",`[v=\\s]*(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:\\.(${c[d.XRANGEIDENTIFIER]})(?:${c[d.PRERELEASE]})?${c[d.BUILD]}?)?)?`),g("XRANGEPLAINLOOSE",`[v=\\s]*(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${c[d.XRANGEIDENTIFIERLOOSE]})(?:${c[d.PRERELEASELOOSE]})?${c[d.BUILD]}?)?)?`),g("XRANGE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAIN]}$`),g("XRANGELOOSE",`^${c[d.GTLT]}\\s*${c[d.XRANGEPLAINLOOSE]}$`),g("COERCEPLAIN",`(^|[^\\d])(\\d{1,${r}})(?:\\.(\\d{1,${r}}))?(?:\\.(\\d{1,${r}}))?`),g("COERCE",`${c[d.COERCEPLAIN]}(?:$|[^\\d])`),g("COERCEFULL",c[d.COERCEPLAIN]+`(?:${c[d.PRERELEASE]})?`+`(?:${c[d.BUILD]})?(?:$|[^\\d])`),g("COERCERTL",c[d.COERCE],!0),g("COERCERTLFULL",c[d.COERCEFULL],!0),g("LONETILDE","(?:~>?)"),g("TILDETRIM",`(\\s*)${c[d.LONETILDE]}\\s+`,!0),t.tildeTrimReplace="$1~",g("TILDE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAIN]}$`),g("TILDELOOSE",`^${c[d.LONETILDE]}${c[d.XRANGEPLAINLOOSE]}$`),g("LONECARET","(?:\\^)"),g("CARETTRIM",`(\\s*)${c[d.LONECARET]}\\s+`,!0),t.caretTrimReplace="$1^",g("CARET",`^${c[d.LONECARET]}${c[d.XRANGEPLAIN]}$`),g("CARETLOOSE",`^${c[d.LONECARET]}${c[d.XRANGEPLAINLOOSE]}$`),g("COMPARATORLOOSE",`^${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]})$|^$`),g("COMPARATOR",`^${c[d.GTLT]}\\s*(${c[d.FULLPLAIN]})$|^$`),g("COMPARATORTRIM",`(\\s*)${c[d.GTLT]}\\s*(${c[d.LOOSEPLAIN]}|${c[d.XRANGEPLAIN]})`,!0),t.comparatorTrimReplace="$1$2$3",g("HYPHENRANGE",`^\\s*(${c[d.XRANGEPLAIN]})\\s+-\\s+(${c[d.XRANGEPLAIN]})\\s*$`),g("HYPHENRANGELOOSE",`^\\s*(${c[d.XRANGEPLAINLOOSE]})\\s+-\\s+(${c[d.XRANGEPLAINLOOSE]})\\s*$`),g("STAR","(<|>)?=?\\s*\\*"),g("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),g("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")},2860(e,t,i){"use strict";var r=i(9120),n=i(4418),a=i(346),s=i(4466).f;e.exports=function(e){var t=r.Symbol||(r.Symbol={});n(t,e)||s(t,e,{value:a.f(e)})}},2908(e){"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),i=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var r in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var n=Object.getOwnPropertySymbols(e);if(1!==n.length||n[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var a=Object.getOwnPropertyDescriptor(e,t);if(42!==a.value||!0!==a.enumerable)return!1}return!0}},2913(e,t,i){"use strict";var r=i(4977),n=i(4318);e.exports=function(e,t){var i=e[t];return n(i)?void 0:r(i)}},2954(e,t,i){"use strict";i(8001)},3008(e,t,i){"use strict";var r,n,a=i(9117),s=i(8060),o=a.process,l=a.Deno,c=o&&o.versions||l&&l.version,u=c&&c.v8;u&&(n=(r=u.split("."))[0]>0&&r[0]<4?1:+(r[0]+r[1])),!n&&s&&(!(r=s.match(/Edge\/(\d+)/))||r[1]>=74)&&(r=s.match(/Chrome\/(\d+)/))&&(n=+r[1]),e.exports=n},3029(e,t,i){"use strict";var r=i(6881),n=i(4188),a=i(2694),s=r(Function.toString);n(a.inspectSource)||(a.inspectSource=function(e){return s(e)}),e.exports=a.inspectSource},3086(e,t,i){"use strict";var r,n,a,s=i(5945),o=i(9117),l=i(831),c=i(8088),u=i(4418),d=i(2694),h=i(168),p=i(7588),m="Object already initialized",g=o.TypeError,f=o.WeakMap;if(s||d.state){var y=d.state||(d.state=new f);y.get=y.get,y.has=y.has,y.set=y.set,r=function(e,t){if(y.has(e))throw new g(m);return t.facade=e,y.set(e,t),t},n=function(e){return y.get(e)||{}},a=function(e){return y.has(e)}}else{var v=h("state");p[v]=!0,r=function(e,t){if(u(e,v))throw new g(m);return t.facade=e,c(e,v,t),t},n=function(e){return u(e,v)?e[v]:{}},a=function(e){return u(e,v)}}e.exports={set:r,get:n,has:a,enforce:function(e){return a(e)?n(e):r(e,{})},getterFor:function(e){return function(t){var i;if(!l(t)||(i=n(t)).type!==e)throw new g("Incompatible receiver, "+e+" required");return i}}}},3105(e,t,i){var r=i(4643);i(7835),i(81),i(4412),i(5206),i(1264),i(5417),i(943),i(8550);var n=function(e,t,i,n){var a=r.util.createBuffer(),s=e.length>>1,o=s+(1&e.length),l=e.substr(0,o),c=e.substr(s,o),u=r.util.createBuffer(),d=r.hmac.create();i=t+i;var h=Math.ceil(n/16),p=Math.ceil(n/20);d.start("MD5",l);var m=r.util.createBuffer();u.putBytes(i);for(var g=0;g0&&(c.queue(e,c.createAlert(e,{level:c.Alert.Level.warning,description:c.Alert.Description.no_renegotiation})),c.flush(e)),e.process()},c.parseHelloMessage=function(e,t,i){var n=null,a=e.entity===c.ConnectionEnd.client;if(i<38)e.error(e,{message:a?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.illegal_parameter}});else{var s=t.fragment,l=s.length();if(n={version:{major:s.getByte(),minor:s.getByte()},random:r.util.createBuffer(s.getBytes(32)),session_id:o(s,1),extensions:[]},a?(n.cipher_suite=s.getBytes(2),n.compression_method=s.getByte()):(n.cipher_suites=o(s,2),n.compression_methods=o(s,1)),(l=i-(l-s.length()))>0){for(var u=o(s,2);u.length()>0;)n.extensions.push({type:[u.getByte(),u.getByte()],data:o(u,2)});if(!a)for(var d=0;d0&&0===p.getByte();)e.session.extensions.server_name.serverNameList.push(o(p,2).getBytes())}}if(e.session.version&&(n.version.major!==e.session.version.major||n.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.protocol_version}});if(a)e.session.cipherSuite=c.getCipherSuite(n.cipher_suite);else for(var m=r.util.createBuffer(n.cipher_suites.bytes());m.length()>0&&(e.session.cipherSuite=c.getCipherSuite(m.getBytes(2)),null===e.session.cipherSuite););if(null===e.session.cipherSuite)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.handshake_failure},cipherSuite:r.util.bytesToHex(n.cipher_suite)});e.session.compressionMethod=a?n.compression_method:c.CompressionMethod.none}return n},c.createSecurityParameters=function(e,t){var i=e.entity===c.ConnectionEnd.client,r=t.random.bytes(),n=i?e.session.sp.client_random:r,a=i?r:c.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:c.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:n,server_random:a}},c.handleServerHello=function(e,t,i){var r=c.parseHelloMessage(e,t,i);if(!e.fail){if(!(r.version.minor<=e.version.minor))return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.protocol_version}});e.version.minor=r.version.minor,e.session.version=e.version;var n=r.session_id.bytes();n.length>0&&n===e.session.id?(e.expect=m,e.session.resuming=!0,e.session.sp.server_random=r.random.bytes()):(e.expect=u,e.session.resuming=!1,c.createSecurityParameters(e,r)),e.session.id=n,e.process()}},c.handleClientHello=function(e,t,i){var n=c.parseHelloMessage(e,t,i);if(!e.fail){var a=n.session_id.bytes(),s=null;if(e.sessionCache&&(null===(s=e.sessionCache.getSession(a))?a="":(s.version.major!==n.version.major||s.version.minor>n.version.minor)&&(s=null,a="")),0===a.length&&(a=r.random.getBytes(32)),e.session.id=a,e.session.clientHelloVersion=n.version,e.session.sp={},s)e.version=e.session.version=s.version,e.session.sp=s.sp;else{for(var o,l=1;l0;)n=o(l.certificate_list,3),a=r.asn1.fromDer(n),n=r.pki.certificateFromAsn1(a,!0),u.push(n)}catch(t){return e.error(e,{message:"Could not parse certificate list.",cause:t,send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.bad_certificate}})}var h=e.entity===c.ConnectionEnd.client;!h&&!0!==e.verifyClient||0!==u.length?0===u.length?e.expect=h?d:b:(h?e.session.serverCertificate=u[0]:e.session.clientCertificate=u[0],c.verifyCertificateChain(e,u)&&(e.expect=h?d:b)):e.error(e,{message:h?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.illegal_parameter}}),e.process()},c.handleServerKeyExchange=function(e,t,i){if(i>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.unsupported_certificate}});e.expect=h,e.process()},c.handleClientKeyExchange=function(e,t,i){if(i<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.unsupported_certificate}});var n=t.fragment,a={enc_pre_master_secret:o(n,2).getBytes()},s=null;if(e.getPrivateKey)try{s=e.getPrivateKey(e,e.session.serverCertificate),s=r.pki.privateKeyFromPem(s)}catch(t){e.error(e,{message:"Could not get private key.",cause:t,send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.internal_error}})}if(null===s)return e.error(e,{message:"No private key set.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.internal_error}});try{var l=e.session.sp;l.pre_master_secret=s.decrypt(a.enc_pre_master_secret);var u=e.session.clientHelloVersion;if(u.major!==l.pre_master_secret.charCodeAt(0)||u.minor!==l.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch(e){l.pre_master_secret=r.random.getBytes(48)}e.expect=k,null!==e.session.clientCertificate&&(e.expect=w),e.process()},c.handleCertificateRequest=function(e,t,i){if(i<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.illegal_parameter}});var r=t.fragment,n={certificate_types:o(r,1),certificate_authorities:o(r,2)};e.session.certificateRequest=n,e.expect=p,e.process()},c.handleCertificateVerify=function(e,t,i){if(i<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.illegal_parameter}});var n=t.fragment;n.read-=4;var a=n.bytes();n.read+=4;var s={signature:o(n,2).getBytes()},l=r.util.createBuffer();l.putBuffer(e.session.md5.digest()),l.putBuffer(e.session.sha1.digest()),l=l.getBytes();try{if(!e.session.clientCertificate.publicKey.verify(l,s.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(a),e.session.sha1.update(a)}catch(t){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.handshake_failure}})}e.expect=k,e.process()},c.handleServerHelloDone=function(e,t,i){if(i>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.record_overflow}});if(null===e.serverCertificate){var n={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.insufficient_security}},a=e.verify(e,n.alert.description,0,[]);if(!0!==a)return(a||0===a)&&("object"!=typeof a||r.util.isArray(a)?"number"==typeof a&&(n.alert.description=a):(a.message&&(n.message=a.message),a.alert&&(n.alert.description=a.alert))),e.error(e,n)}null!==e.session.certificateRequest&&(t=c.createRecord(e,{type:c.ContentType.handshake,data:c.createCertificate(e)}),c.queue(e,t)),t=c.createRecord(e,{type:c.ContentType.handshake,data:c.createClientKeyExchange(e)}),c.queue(e,t),e.expect=y;var s=function(e,t){null!==e.session.certificateRequest&&null!==e.session.clientCertificate&&c.queue(e,c.createRecord(e,{type:c.ContentType.handshake,data:c.createCertificateVerify(e,t)})),c.queue(e,c.createRecord(e,{type:c.ContentType.change_cipher_spec,data:c.createChangeCipherSpec()})),e.state.pending=c.createConnectionState(e),e.state.current.write=e.state.pending.write,c.queue(e,c.createRecord(e,{type:c.ContentType.handshake,data:c.createFinished(e)})),e.expect=m,c.flush(e),e.process()};if(null===e.session.certificateRequest||null===e.session.clientCertificate)return s(e,null);c.getClientSignature(e,s)},c.handleChangeCipherSpec=function(e,t){if(1!==t.fragment.getByte())return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.illegal_parameter}});var i=e.entity===c.ConnectionEnd.client;(e.session.resuming&&i||!e.session.resuming&&!i)&&(e.state.pending=c.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&i||e.session.resuming&&!i)&&(e.state.pending=null),e.expect=i?g:S,e.process()},c.handleFinished=function(e,t,i){var a=t.fragment;a.read-=4;var s=a.bytes();a.read+=4;var o=t.fragment.getBytes();(a=r.util.createBuffer()).putBuffer(e.session.md5.digest()),a.putBuffer(e.session.sha1.digest());var l=e.entity===c.ConnectionEnd.client,u=l?"server finished":"client finished",d=e.session.sp;if((a=n(d.master_secret,u,a.getBytes(),12)).getBytes()!==o)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.decrypt_error}});e.session.md5.update(s),e.session.sha1.update(s),(e.session.resuming&&l||!e.session.resuming&&!l)&&(c.queue(e,c.createRecord(e,{type:c.ContentType.change_cipher_spec,data:c.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,c.queue(e,c.createRecord(e,{type:c.ContentType.handshake,data:c.createFinished(e)}))),e.expect=l?f:_,e.handshaking=!1,++e.handshakes,e.peerCertificate=l?e.session.serverCertificate:e.session.clientCertificate,c.flush(e),e.isConnected=!0,e.connected(e),e.process()},c.handleAlert=function(e,t){var i,r=t.fragment,n={level:r.getByte(),description:r.getByte()};switch(n.description){case c.Alert.Description.close_notify:i="Connection closed.";break;case c.Alert.Description.unexpected_message:i="Unexpected message.";break;case c.Alert.Description.bad_record_mac:i="Bad record MAC.";break;case c.Alert.Description.decryption_failed:i="Decryption failed.";break;case c.Alert.Description.record_overflow:i="Record overflow.";break;case c.Alert.Description.decompression_failure:i="Decompression failed.";break;case c.Alert.Description.handshake_failure:i="Handshake failure.";break;case c.Alert.Description.bad_certificate:i="Bad certificate.";break;case c.Alert.Description.unsupported_certificate:i="Unsupported certificate.";break;case c.Alert.Description.certificate_revoked:i="Certificate revoked.";break;case c.Alert.Description.certificate_expired:i="Certificate expired.";break;case c.Alert.Description.certificate_unknown:i="Certificate unknown.";break;case c.Alert.Description.illegal_parameter:i="Illegal parameter.";break;case c.Alert.Description.unknown_ca:i="Unknown certificate authority.";break;case c.Alert.Description.access_denied:i="Access denied.";break;case c.Alert.Description.decode_error:i="Decode error.";break;case c.Alert.Description.decrypt_error:i="Decrypt error.";break;case c.Alert.Description.export_restriction:i="Export restriction.";break;case c.Alert.Description.protocol_version:i="Unsupported protocol version.";break;case c.Alert.Description.insufficient_security:i="Insufficient security.";break;case c.Alert.Description.internal_error:i="Internal error.";break;case c.Alert.Description.user_canceled:i="User canceled.";break;case c.Alert.Description.no_renegotiation:i="Renegotiation not supported.";break;default:i="Unknown error."}if(n.description===c.Alert.Description.close_notify)return e.close();e.error(e,{message:i,send:!1,origin:e.entity===c.ConnectionEnd.client?"server":"client",alert:n}),e.process()},c.handleHandshake=function(e,t){var i=t.fragment,n=i.getByte(),a=i.getInt24();if(a>i.length())return e.fragmented=t,t.fragment=r.util.createBuffer(),i.read-=4,e.process();e.fragmented=null,i.read-=4;var s=i.bytes(a+4);i.read+=4,n in F[e.entity][e.expect]?(e.entity!==c.ConnectionEnd.server||e.open||e.fail||(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:r.md.md5.create(),sha1:r.md.sha1.create()}),n!==c.HandshakeType.hello_request&&n!==c.HandshakeType.certificate_verify&&n!==c.HandshakeType.finished&&(e.session.md5.update(s),e.session.sha1.update(s)),F[e.entity][e.expect][n](e,t,a)):c.handleUnexpected(e,t)},c.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()},c.handleHeartbeat=function(e,t){var i=t.fragment,n=i.getByte(),a=i.getInt16(),s=i.getBytes(a);if(n===c.HeartbeatMessageType.heartbeat_request){if(e.handshaking||a>s.length)return e.process();c.queue(e,c.createRecord(e,{type:c.ContentType.heartbeat,data:c.createHeartbeat(c.HeartbeatMessageType.heartbeat_response,s)})),c.flush(e)}else if(n===c.HeartbeatMessageType.heartbeat_response){if(s!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,r.util.createBuffer(s))}e.process()};var u=1,d=2,h=3,p=4,m=5,g=6,f=7,y=8,v=1,b=2,w=3,k=4,S=5,_=6,x=c.handleUnexpected,C=c.handleChangeCipherSpec,I=c.handleAlert,E=c.handleHandshake,z=c.handleApplicationData,P=c.handleHeartbeat,A=[];A[c.ConnectionEnd.client]=[[x,I,E,x,P],[x,I,E,x,P],[x,I,E,x,P],[x,I,E,x,P],[x,I,E,x,P],[C,I,x,x,P],[x,I,E,x,P],[x,I,E,z,P],[x,I,E,x,P]],A[c.ConnectionEnd.server]=[[x,I,E,x,P],[x,I,E,x,P],[x,I,E,x,P],[x,I,E,x,P],[C,I,x,x,P],[x,I,E,x,P],[x,I,E,z,P],[x,I,E,x,P]];var j=c.handleHelloRequest,T=c.handleServerHello,D=c.handleCertificate,O=c.handleServerKeyExchange,N=c.handleCertificateRequest,R=c.handleServerHelloDone,U=c.handleFinished,F=[];F[c.ConnectionEnd.client]=[[x,x,T,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],[j,x,x,x,x,x,x,x,x,x,x,D,O,N,R,x,x,x,x,x,x],[j,x,x,x,x,x,x,x,x,x,x,x,O,N,R,x,x,x,x,x,x],[j,x,x,x,x,x,x,x,x,x,x,x,x,N,R,x,x,x,x,x,x],[j,x,x,x,x,x,x,x,x,x,x,x,x,x,R,x,x,x,x,x,x],[j,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],[j,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,U],[j,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],[j,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x]];var q=c.handleClientHello,L=c.handleClientKeyExchange,B=c.handleCertificateVerify;F[c.ConnectionEnd.server]=[[x,q,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],[x,x,x,x,x,x,x,x,x,x,x,D,x,x,x,x,x,x,x,x,x],[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,L,x,x,x,x],[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,B,x,x,x,x,x],[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,U],[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x],[x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x]],c.generateKeys=function(e,t){var i=n,r=t.client_random+t.server_random;e.session.resuming||(t.master_secret=i(t.pre_master_secret,"master secret",r,48).bytes(),t.pre_master_secret=null),r=t.server_random+t.client_random;var a=2*t.mac_key_length+2*t.enc_key_length,s=e.version.major===c.Versions.TLS_1_0.major&&e.version.minor===c.Versions.TLS_1_0.minor;s&&(a+=2*t.fixed_iv_length);var o=i(t.master_secret,"key expansion",r,a),l={client_write_MAC_key:o.getBytes(t.mac_key_length),server_write_MAC_key:o.getBytes(t.mac_key_length),client_write_key:o.getBytes(t.enc_key_length),server_write_key:o.getBytes(t.enc_key_length)};return s&&(l.client_write_IV=o.getBytes(t.fixed_iv_length),l.server_write_IV=o.getBytes(t.fixed_iv_length)),l},c.createConnectionState=function(e){var t=e.entity===c.ConnectionEnd.client,i=function(){var e={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(e){return!0},compressionState:null,compressFunction:function(e){return!0},updateSequenceNumber:function(){4294967295===e.sequenceNumber[1]?(e.sequenceNumber[1]=0,++e.sequenceNumber[0]):++e.sequenceNumber[1]}};return e},r={read:i(),write:i()};if(r.read.update=function(e,t){return r.read.cipherFunction(t,r.read)?r.read.compressFunction(e,t,r.read)||e.error(e,{message:"Could not decompress record.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.decompression_failure}}):e.error(e,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.bad_record_mac}}),!e.fail},r.write.update=function(e,t){return r.write.compressFunction(e,t,r.write)?r.write.cipherFunction(t,r.write)||e.error(e,{message:"Could not encrypt record.",send:!1,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.internal_error}}):e.error(e,{message:"Could not compress record.",send:!1,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.internal_error}}),!e.fail},e.session){var n=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(n),n.keys=c.generateKeys(e,n),r.read.macKey=t?n.keys.server_write_MAC_key:n.keys.client_write_MAC_key,r.write.macKey=t?n.keys.client_write_MAC_key:n.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(r,e,n),n.compression_algorithm){case c.CompressionMethod.none:break;case c.CompressionMethod.deflate:r.read.compressFunction=s,r.write.compressFunction=a;break;default:throw new Error("Unsupported compression algorithm.")}}return r},c.createRandom=function(){var e=new Date,t=+e+6e4*e.getTimezoneOffset(),i=r.util.createBuffer();return i.putInt32(t),i.putBytes(r.random.getBytes(28)),i},c.createRecord=function(e,t){return t.data?{type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data}:null},c.createAlert=function(e,t){var i=r.util.createBuffer();return i.putByte(t.level),i.putByte(t.description),c.createRecord(e,{type:c.ContentType.alert,data:i})},c.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=r.util.createBuffer(),i=0;i0&&(m+=2);var g=e.session.id,f=g.length+1+2+4+28+2+a+1+o+m,y=r.util.createBuffer();return y.putByte(c.HandshakeType.client_hello),y.putInt24(f),y.putByte(e.version.major),y.putByte(e.version.minor),y.putBytes(e.session.sp.client_random),l(y,1,r.util.createBuffer(g)),l(y,2,t),l(y,1,s),m>0&&l(y,2,u),y},c.createServerHello=function(e){var t=e.session.id,i=t.length+1+2+4+28+2+1,n=r.util.createBuffer();return n.putByte(c.HandshakeType.server_hello),n.putInt24(i),n.putByte(e.version.major),n.putByte(e.version.minor),n.putBytes(e.session.sp.server_random),l(n,1,r.util.createBuffer(t)),n.putByte(e.session.cipherSuite.id[0]),n.putByte(e.session.cipherSuite.id[1]),n.putByte(e.session.compressionMethod),n},c.createCertificate=function(e){var t,i=e.entity===c.ConnectionEnd.client,n=null;e.getCertificate&&(t=i?e.session.certificateRequest:e.session.extensions.server_name.serverNameList,n=e.getCertificate(e,t));var a=r.util.createBuffer();if(null!==n)try{r.util.isArray(n)||(n=[n]);for(var s=null,o=0;oc.MaxFragment;)n.push(c.createRecord(e,{type:t.type,data:r.util.createBuffer(a.slice(0,c.MaxFragment))})),a=a.slice(c.MaxFragment);a.length>0&&n.push(c.createRecord(e,{type:t.type,data:r.util.createBuffer(a)}))}for(var s=0;s0&&(n=i.order[0]),null!==n&&n in i.cache)for(var a in t=i.cache[n],delete i.cache[n],i.order)if(i.order[a]===n){i.order.splice(a,1);break}return t},i.setSession=function(e,t){if(i.order.length===i.capacity){var n=i.order.shift();delete i.cache[n]}n=r.util.bytesToHex(e),i.order.push(n),i.cache[n]=t}}return i},c.createConnection=function(e){var t;t=e.caStore?r.util.isArray(e.caStore)?r.pki.createCaStore(e.caStore):e.caStore:r.pki.createCaStore();var i=e.cipherSuites||null;if(null===i)for(var n in i=[],c.CipherSuites)i.push(c.CipherSuites[n]);var a=e.server?c.ConnectionEnd.server:c.ConnectionEnd.client,s=e.sessionCache?c.createSessionCache(e.sessionCache):null,o={version:{major:c.Version.major,minor:c.Version.minor},entity:a,sessionId:e.sessionId,caStore:t,sessionCache:s,cipherSuites:i,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(e,t,i,r){return t},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:r.util.createBuffer(),tlsData:r.util.createBuffer(),data:r.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(t,i){i.origin=i.origin||(t.entity===c.ConnectionEnd.client?"client":"server"),i.send&&(c.queue(t,c.createAlert(t,i.alert)),c.flush(t));var r=!1!==i.fatal;r&&(t.fail=!0),e.error(t,i),r&&t.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null,reset:function(e){o.version={major:c.Version.major,minor:c.Version.minor},o.record=null,o.session=null,o.peerCertificate=null,o.state={pending:null,current:null},o.expect=(o.entity,c.ConnectionEnd.client,0),o.fragmented=null,o.records=[],o.open=!1,o.handshakes=0,o.handshaking=!1,o.isConnected=!1,o.fail=!(e||void 0===e),o.input.clear(),o.tlsData.clear(),o.data.clear(),o.state.current=c.createConnectionState(o)}};return o.reset(),o.handshake=function(e){if(o.entity!==c.ConnectionEnd.client)o.error(o,{message:"Cannot initiate handshake as a server.",fatal:!1});else if(o.handshaking)o.error(o,{message:"Handshake already in progress.",fatal:!1});else{o.fail&&!o.open&&0===o.handshakes&&(o.fail=!1),o.handshaking=!0;var t=null;(e=e||"").length>0&&(o.sessionCache&&(t=o.sessionCache.getSession(e)),null===t&&(e="")),0===e.length&&o.sessionCache&&null!==(t=o.sessionCache.getSession())&&(e=t.id),o.session={id:e,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:r.md.md5.create(),sha1:r.md.sha1.create()},t&&(o.version=t.version,o.session.sp=t.sp),o.session.sp.client_random=c.createRandom().getBytes(),o.open=!0,c.queue(o,c.createRecord(o,{type:c.ContentType.handshake,data:c.createClientHello(o)})),c.flush(o)}},o.process=function(e){var t=0;return e&&o.input.putBytes(e),o.fail||(null!==o.record&&o.record.ready&&o.record.fragment.isEmpty()&&(o.record=null),null===o.record&&(t=function(e){var t=0,i=e.input,n=i.length();if(n<5)t=5-n;else{e.record={type:i.getByte(),version:{major:i.getByte(),minor:i.getByte()},length:i.getInt16(),fragment:r.util.createBuffer(),ready:!1};var a=e.record.version.major===e.version.major;a&&e.session&&e.session.version&&(a=e.record.version.minor===e.version.minor),a||e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:c.Alert.Level.fatal,description:c.Alert.Description.protocol_version}})}return t}(o)),o.fail||null===o.record||o.record.ready||(t=function(e){var t=0,i=e.input,r=i.length();return r{const i=r(e,null,!0),n=r(t,null,!0),a=i.compare(n);if(0===a)return null;const s=a>0,o=s?i:n,l=s?n:i,c=!!o.prerelease.length;if(l.prerelease.length&&!c){if(!l.patch&&!l.minor)return"major";if(0===l.compareMain(o))return l.minor&&!l.patch?"minor":"patch"}const u=c?"pre":"";return i.major!==n.major?u+"major":i.minor!==n.minor?u+"minor":i.patch!==n.patch?u+"patch":"prerelease"}},3314(e,t,i){e.exports=i(9679),i(4412),i(943),i(7585),i(260)},3315(e,t,i){"use strict";var r=i(6893),n=i(5234);e.exports=r&&n(function(){return 42!==Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype})},3337(e,t,i){"use strict";var r,n,a=i(9117),s=i(2694),o=i(4188),l=i(7065),c=i(1786),u=i(7509),d=i(4282),h=i(1942),p="USE_FUNCTION_CONSTRUCTOR",m=d("asyncIterator"),g=a.AsyncIterator,f=s.AsyncIteratorPrototype;if(f)r=f;else if(o(g))r=g.prototype;else if(s[p]||a[p])try{n=c(c(c(Function("return async function*(){}()")()))),c(n)===Object.prototype&&(r=n)}catch(e){}r?h&&(r=l(r)):r={},o(r[m])||u(r,m,function(){return this}),e.exports=r},3346(e,t,i){"use strict";var r=i(8660),n=i(3468),a=function(e,t,i){for(var r,n=e;null!=(r=n.next);n=r)if(r.key===t)return n.next=r.next,i||(r.next=e.next,e.next=r),r};e.exports=function(){var e,t={assert:function(e){if(!t.has(e))throw new n("Side channel does not contain "+r(e))},delete:function(t){var i=e&&e.next,r=function(e,t){if(e)return a(e,t,!0)}(e,t);return r&&i&&i===r&&(e=void 0),!!r},get:function(t){return function(e,t){if(e){var i=a(e,t);return i&&i.value}}(e,t)},has:function(t){return function(e,t){return!!e&&!!a(e,t)}(e,t)},set:function(t,i){e||(e={next:void 0}),function(e,t,i){var r=a(e,t);r?r.value=i:e.next={key:t,next:e.next,value:i}}(e,t,i)}};return t}},3468(e){"use strict";e.exports=TypeError},3558(e,t,i){"use strict";var r="undefined"!=typeof Symbol&&Symbol,n=i(2908);e.exports=function(){return"function"==typeof r&&"function"==typeof Symbol&&"symbol"==typeof r("foo")&&"symbol"==typeof Symbol("bar")&&n()}},3574(e,t,i){var r=i(4643);i(7835),i(81),i(4467),i(4793),i(4117),i(5417),i(2374),i(943),i(8550),i(846);var n=r.asn1,a=r.pki,s=e.exports=r.pkcs12=r.pkcs12||{},o={name:"ContentInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.contentType",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:n.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"content"}]},l={name:"PFX",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},o,{name:"PFX.macData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,optional:!0,captureAsn1:"mac",value:[{name:"PFX.macData.mac",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"PFX.macData.mac.digestAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"macAlgorithm"},{name:"PFX.macData.mac.digestAlgorithm.parameters",tagClass:n.Class.UNIVERSAL,captureAsn1:"macAlgorithmParameters"}]},{name:"PFX.macData.mac.digest",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"macDigest"}]},{name:"PFX.macData.macSalt",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"macSalt"},{name:"PFX.macData.iterations",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,optional:!0,capture:"macIterations"}]}]},c={name:"SafeBag",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SafeBag.bagId",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"bagId"},{name:"SafeBag.bagValue",tagClass:n.Class.CONTEXT_SPECIFIC,constructed:!0,captureAsn1:"bagValue"},{name:"SafeBag.bagAttributes",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,optional:!0,capture:"bagAttributes"}]},u={name:"Attribute",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"Attribute.attrId",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"oid"},{name:"Attribute.attrValues",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,capture:"values"}]},d={name:"CertBag",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"CertBag.certId",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"certId"},{name:"CertBag.certValue",tagClass:n.Class.CONTEXT_SPECIFIC,constructed:!0,value:[{name:"CertBag.certValue[0]",tagClass:n.Class.UNIVERSAL,type:n.Class.OCTETSTRING,constructed:!1,capture:"cert"}]}]};function h(e,t,i,r){for(var n=[],a=0;a=0&&n.push(o):n.push(o))}return n}function p(e){if(e.composed||e.constructed){for(var t=r.util.createBuffer(),i=0;i2)throw new Error("Invalid PKCS#12. macData field present but MAC was not validated.");return function(e,t,i,r){if((t=n.fromDer(t,i)).tagClass!==n.Class.UNIVERSAL||t.type!==n.Type.SEQUENCE||!0!==t.constructed)throw new Error("PKCS#12 AuthenticatedSafe expected to be a SEQUENCE OF ContentInfo");for(var s=0;s0&&(l=n.create(n.Class.UNIVERSAL,n.Type.SET,!0,d));var h=[],p=[];null!==t&&(p=r.util.isArray(t)?t:[t]);for(var m=[],g=0;g0){var b=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,m),w=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(a.oids.data).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,n.toDer(b).getBytes())])]);h.push(w)}var k=null;if(null!==e){var S=a.wrapRsaPrivateKey(a.privateKeyToAsn1(e));k=null===i?n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(a.oids.keyBag).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[S]),l]):n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(a.oids.pkcs8ShroudedKeyBag).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[a.encryptPrivateKeyInfo(S,i,o)]),l]);var _=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[k]),x=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(a.oids.data).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,n.toDer(_).getBytes())])]);h.push(x)}var C,I=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,h);if(o.useMac){var E=r.md.sha1.create(),z=new r.util.ByteBuffer(r.random.getBytes(o.saltSize)),P=o.count,A=(e=s.generateKey(i,z,3,P,20),r.hmac.create());A.start(E,e),A.update(n.toDer(I).getBytes());var j=A.getMac();C=n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(a.oids.sha1).getBytes()),n.create(n.Class.UNIVERSAL,n.Type.NULL,!1,"")]),n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,j.getBytes())]),n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,z.getBytes()),n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(P).getBytes())])}return n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(3).getBytes()),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(a.oids.data).getBytes()),n.create(n.Class.CONTEXT_SPECIFIC,0,!0,[n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,n.toDer(I).getBytes())])]),C])},s.generateKey=r.pbe.generatePkcs12Key},3628(e,t,i){"use strict";var r=i(9509),n=Object;e.exports=function(e){return n(r(e))}},3739(e,t,i){var r=i(4643);function n(e,t){r.cipher.registerAlgorithm(e,function(){return new r.aes.Algorithm(e,t)})}i(1457),i(597),i(8550),e.exports=r.aes=r.aes||{},r.aes.startEncrypting=function(e,t,i,r){var n=m({key:e,output:i,decrypt:!1,mode:r});return n.start(t),n},r.aes.createEncryptionCipher=function(e,t){return m({key:e,output:null,decrypt:!1,mode:t})},r.aes.startDecrypting=function(e,t,i,r){var n=m({key:e,output:i,decrypt:!0,mode:r});return n.start(t),n},r.aes.createDecryptionCipher=function(e,t){return m({key:e,output:null,decrypt:!0,mode:t})},r.aes.Algorithm=function(e,t){u||d();var i=this;i.name=e,i.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return p(i._w,e,t,!1)},decrypt:function(e,t){return p(i._w,e,t,!0)}}}),i._init=!1},r.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,i=e.key;if("string"!=typeof i||16!==i.length&&24!==i.length&&32!==i.length){if(r.util.isArray(i)&&(16===i.length||24===i.length||32===i.length)){t=i,i=r.util.createBuffer();for(var n=0;n>>=2,n=0;n>8^255&d^99,a[g]=d,s[d]=g,p=(h=e[d])<<24^d<<16^d<<8^d^h,m=((i=e[g])^(r=e[i])^(n=e[r]))<<24^(g^n)<<16^(g^r^n)<<8^g^i^n;for(var y=0;y<4;++y)l[y][g]=p,c[y][d]=m,p=p<<24|p>>>8,m=m<<24|m>>>8;0===g?g=f=1:(g=i^e[e[e[i^n]]],f^=e[e[f]])}}function h(e,t){for(var i,r=e.slice(0),n=1,s=r.length,l=4*(s+6+1),u=s;u>>16&255]<<24^a[i>>>8&255]<<16^a[255&i]<<8^a[i>>>24]^o[n]<<24,n++):s>6&&u%s===4&&(i=a[i>>>24]<<24^a[i>>>16&255]<<16^a[i>>>8&255]<<8^a[255&i]),r[u]=r[u-s]^i;if(t){for(var d,h=c[0],p=c[1],m=c[2],g=c[3],f=r.slice(0),y=(u=0,(l=r.length)-4);u>>24]]^p[a[d>>>16&255]]^m[a[d>>>8&255]]^g[a[255&d]];r=f}return r}function p(e,t,i,r){var n,o,u,d,h,p,m,g,f,y,v,b,w=e.length/4-1;r?(n=c[0],o=c[1],u=c[2],d=c[3],h=s):(n=l[0],o=l[1],u=l[2],d=l[3],h=a),p=t[0]^e[0],m=t[r?3:1]^e[1],g=t[2]^e[2],f=t[r?1:3]^e[3];for(var k=3,S=1;S>>24]^o[m>>>16&255]^u[g>>>8&255]^d[255&f]^e[++k],v=n[m>>>24]^o[g>>>16&255]^u[f>>>8&255]^d[255&p]^e[++k],b=n[g>>>24]^o[f>>>16&255]^u[p>>>8&255]^d[255&m]^e[++k],f=n[f>>>24]^o[p>>>16&255]^u[m>>>8&255]^d[255&g]^e[++k],p=y,m=v,g=b;i[0]=h[p>>>24]<<24^h[m>>>16&255]<<16^h[g>>>8&255]<<8^h[255&f]^e[++k],i[r?3:1]=h[m>>>24]<<24^h[g>>>16&255]<<16^h[f>>>8&255]<<8^h[255&p]^e[++k],i[2]=h[g>>>24]<<24^h[f>>>16&255]<<16^h[p>>>8&255]<<8^h[255&m]^e[++k],i[r?1:3]=h[f>>>24]<<24^h[p>>>16&255]<<16^h[m>>>8&255]<<8^h[255&g]^e[++k]}function m(e){var t,i="AES-"+((e=e||{}).mode||"CBC").toUpperCase(),n=(t=e.decrypt?r.cipher.createDecipher(i,e.key):r.cipher.createCipher(i,e.key)).start;return t.start=function(e,i){var a=null;i instanceof r.util.ByteBuffer&&(a=i,i={}),(i=i||{}).output=a,i.iv=e,n.call(t,i)},t}},3770(e,t,i){"use strict";var r=i(831),n=String,a=TypeError;e.exports=function(e){if(r(e))return e;throw new a(n(e)+" is not an object")}},3806(e){"use strict";const t=/^[0-9]+$/,i=(e,i)=>{if("number"==typeof e&&"number"==typeof i)return e===i?0:ei(t,e)}},3810(e,t,i){"use strict";const r=i(6106);e.exports=(e,t)=>e.sort((e,i)=>r(i,e,t))},3939(e,t,i){var r=i(4643);i(81),i(9679),i(8550);var n,a=r.pkcs5=r.pkcs5||{};r.util.isNodejs&&!r.options.usePureJavaScript&&(n=i(9701)),e.exports=r.pbkdf2=a.pbkdf2=function(e,t,i,a,s,o){if("function"==typeof s&&(o=s,s=null),r.util.isNodejs&&!r.options.usePureJavaScript&&n.pbkdf2&&(null===s||"object"!=typeof s)&&(n.pbkdf2Sync.length>4||!s||"sha1"===s))return"string"!=typeof s&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),o?4===n.pbkdf2Sync.length?n.pbkdf2(e,t,i,a,function(e,t){if(e)return o(e);o(null,t.toString("binary"))}):n.pbkdf2(e,t,i,a,s,function(e,t){if(e)return o(e);o(null,t.toString("binary"))}):4===n.pbkdf2Sync.length?n.pbkdf2Sync(e,t,i,a).toString("binary"):n.pbkdf2Sync(e,t,i,a,s).toString("binary");if(null==s&&(s="sha1"),"string"==typeof s){if(!(s in r.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=r.md[s].create()}var l=s.digestLength;if(a>4294967295*l){var c=new Error("Derived key is too long.");if(o)return o(c);throw c}var u=Math.ceil(a/l),d=a-(u-1)*l,h=r.hmac.create();h.start(s,e);var p,m,g,f="";if(!o){for(var y=1;y<=u;++y){h.start(null,null),h.update(t),h.update(r.util.int32ToBytes(y)),p=g=h.digest().getBytes();for(var v=2;v<=i;++v)h.start(null,null),h.update(g),m=h.digest().getBytes(),p=r.util.xorBytes(p,m,l),g=m;f+=yu)return o(null,f);h.start(null,null),h.update(t),h.update(r.util.int32ToBytes(y)),p=g=h.digest().getBytes(),v=2,w()}function w(){if(v<=i)return h.start(null,null),h.update(g),m=h.digest().getBytes(),p=r.util.xorBytes(p,m,l),g=m,++v,r.util.setImmediate(w);f+=y{if(e instanceof r)return e;try{return new r(e,t)}catch(e){if(!i)return null;throw e}}},3990(e){"use strict";const t=Object.freeze({loose:!0}),i=Object.freeze({});e.exports=e=>e?"object"!=typeof e?t:e:i},4004(e,t,i){"use strict";const r=i(8848),n=i(8220),a=i(9761),s=i(2386),o=i(1262),l=i(9639);e.exports=(e,t,i,c)=>{switch(t){case"===":return"object"==typeof e&&(e=e.version),"object"==typeof i&&(i=i.version),e===i;case"!==":return"object"==typeof e&&(e=e.version),"object"==typeof i&&(i=i.version),e!==i;case"":case"=":case"==":return r(e,i,c);case"!=":return n(e,i,c);case">":return a(e,i,c);case">=":return s(e,i,c);case"<":return o(e,i,c);case"<=":return l(e,i,c);default:throw new TypeError(`Invalid operator: ${t}`)}}},4042(e,t,i){"use strict";const r=i(6106);e.exports=(e,t)=>e.sort((e,i)=>r(e,i,t))},4056(e,t,i){var r=i(4643);i(3739),i(7835),i(2684),i(4467),i(5206),i(4793),i(5417),i(8550),i(846);var n=r.asn1,a=e.exports=r.pkcs7=r.pkcs7||{};function s(e){var t={},i=[];if(!n.validate(e,a.asn1.recipientInfoValidator,t,i)){var s=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw s.errors=i,s}return{version:t.version.charCodeAt(0),issuer:r.pki.RDNAttributesAsArray(t.issuer),serialNumber:r.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:n.derToOid(t.encAlgorithm),parameter:t.encParameter?t.encParameter.value:void 0,content:t.encKey}}}function o(e){return n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,n.integerToDer(e.version).getBytes()),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[r.pki.distinguishedNameToAsn1({attributes:e.issuer}),n.create(n.Class.UNIVERSAL,n.Type.INTEGER,!1,r.util.hexToBytes(e.serialNumber))]),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(e.encryptedContent.algorithm).getBytes()),n.create(n.Class.UNIVERSAL,n.Type.NULL,!1,"")]),n.create(n.Class.UNIVERSAL,n.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function l(e){for(var t=[],i=0;i0){for(var i=n.create(n.Class.CONTEXT_SPECIFIC,1,!0,[]),a=0;a=i&&s0&&s.value[0].value.push(n.create(n.Class.CONTEXT_SPECIFIC,0,!0,t)),a.length>0&&s.value[0].value.push(n.create(n.Class.CONTEXT_SPECIFIC,1,!0,a)),s.value[0].value.push(n.create(n.Class.UNIVERSAL,n.Type.SET,!0,e.signerInfos)),n.create(n.Class.UNIVERSAL,n.Type.SEQUENCE,!0,[n.create(n.Class.UNIVERSAL,n.Type.OID,!1,n.oidToDer(e.type).getBytes()),s])},addSigner:function(t){var i=t.issuer,n=t.serialNumber;if(t.certificate){var a=t.certificate;"string"==typeof a&&(a=r.pki.certificateFromPem(a)),i=a.issuer.attributes,n=a.serialNumber}var s=t.key;if(!s)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof s&&(s=r.pki.privateKeyFromPem(s));var o=t.digestAlgorithm||r.pki.oids.sha1;switch(o){case r.pki.oids.sha1:case r.pki.oids.sha256:case r.pki.oids.sha384:case r.pki.oids.sha512:case r.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+o)}var l=t.authenticatedAttributes||[];if(l.length>0){for(var c=!1,u=!1,d=0;d=0;l--)P>>=8,P+=C.at(l)+z.at(l),z.setAt(l,255&P);E.putBuffer(z)}w=E,d.putBuffer(_)}return d.truncate(d.length()-a),d},s.pbe.getCipher=function(e,t,i){switch(e){case s.oids.pkcs5PBES2:return s.pbe.getCipherForPBES2(e,t,i);case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case s.oids["pbewithSHAAnd40BitRC2-CBC"]:return s.pbe.getCipherForPKCS12PBE(e,t,i);default:var r=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw r.oid=e,r.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],r}},s.pbe.getCipherForPBES2=function(e,t,i){var n,o={},l=[];if(!a.validate(t,c,o,l))throw(n=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=l,n;if((e=a.derToOid(o.kdfOid))!==s.oids.pkcs5PBKDF2)throw(n=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.")).oid=e,n.supportedOids=["pkcs5PBKDF2"],n;if((e=a.derToOid(o.encOid))!==s.oids["aes128-CBC"]&&e!==s.oids["aes192-CBC"]&&e!==s.oids["aes256-CBC"]&&e!==s.oids["des-EDE3-CBC"]&&e!==s.oids.desCBC)throw(n=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.")).oid=e,n.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],n;var u,d,p=o.kdfSalt,m=r.util.createBuffer(o.kdfIterationCount);switch(m=m.getInt(m.length()<<3),s.oids[e]){case"aes128-CBC":u=16,d=r.aes.createDecryptionCipher;break;case"aes192-CBC":u=24,d=r.aes.createDecryptionCipher;break;case"aes256-CBC":u=32,d=r.aes.createDecryptionCipher;break;case"des-EDE3-CBC":u=24,d=r.des.createDecryptionCipher;break;case"desCBC":u=8,d=r.des.createDecryptionCipher}var g=h(o.prfOid),f=r.pkcs5.pbkdf2(i,p,m,u,g),y=o.encIv,v=d(f);return v.start(y),v},s.pbe.getCipherForPKCS12PBE=function(e,t,i){var n={},o=[];if(!a.validate(t,u,n,o))throw(g=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.")).errors=o,g;var l,c,d,p=r.util.createBuffer(n.salt),m=r.util.createBuffer(n.iterations);switch(m=m.getInt(m.length()<<3),e){case s.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:l=24,c=8,d=r.des.startDecrypting;break;case s.oids["pbewithSHAAnd40BitRC2-CBC"]:l=5,c=8,d=function(e,t){var i=r.rc2.createDecryptionCipher(e,40);return i.start(t,null),i};break;default:var g;throw(g=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.")).oid=e,g}var f=h(n.prfOid),y=s.pbe.generatePkcs12Key(i,p,1,m,l,f);return f.start(),d(y,s.pbe.generatePkcs12Key(i,p,2,m,c,f))},s.pbe.opensslDeriveBytes=function(e,t,i,n){if(null==n){if(!("md5"in r.md))throw new Error('"md5" hash algorithm unavailable.');n=r.md.md5.create()}null===t&&(t="");for(var a=[d(n,e+t)],s=16,o=1;s>>0,o>>>0];for(var l=n.fullMessageLength.length-1;l>=0;--l)n.fullMessageLength[l]+=o[1],o[1]=o[0]+(n.fullMessageLength[l]/4294967296>>>0),n.fullMessageLength[l]=n.fullMessageLength[l]>>>0,o[0]=o[1]/4294967296>>>0;return t.putBytes(a),u(e,i,t),(t.read>2048||0===t.length())&&t.compact(),n},n.digest=function(){var s=r.util.createBuffer();s.putBytes(t.bytes());var o=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;s.putBytes(a.substr(0,n.blockLength-o));for(var l,c=0,d=n.fullMessageLength.length-1;d>=0;--d)c=(l=8*n.fullMessageLength[d]+c)/4294967296>>>0,s.putInt32Le(l>>>0);var h={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};u(h,i,s);var p=r.util.createBuffer();return p.putInt32Le(h.h0),p.putInt32Le(h.h1),p.putInt32Le(h.h2),p.putInt32Le(h.h3),p},n};var a=null,s=null,o=null,l=null,c=!1;function u(e,t,i){for(var r,n,a,c,u,d,h,p=i.length();p>=64;){for(n=e.h0,a=e.h1,c=e.h2,u=e.h3,h=0;h<16;++h)t[h]=i.getInt32Le(),r=n+(u^a&(c^u))+l[h]+t[h],n=u,u=c,c=a,a+=r<<(d=o[h])|r>>>32-d;for(;h<32;++h)r=n+(c^u&(a^c))+l[h]+t[s[h]],n=u,u=c,c=a,a+=r<<(d=o[h])|r>>>32-d;for(;h<48;++h)r=n+(a^c^u)+l[h]+t[s[h]],n=u,u=c,c=a,a+=r<<(d=o[h])|r>>>32-d;for(;h<64;++h)r=n+(c^(a|~u))+l[h]+t[s[h]],n=u,u=c,c=a,a+=r<<(d=o[h])|r>>>32-d;e.h0=e.h0+n|0,e.h1=e.h1+a|0,e.h2=e.h2+c|0,e.h3=e.h3+u|0,p-=64}}},4416(e,t){"use strict";var i={}.propertyIsEnumerable,r=Object.getOwnPropertyDescriptor,n=r&&!i.call({1:2},1);t.f=n?function(e){var t=r(this,e);return!!t&&t.enumerable}:i},4418(e,t,i){"use strict";var r=i(6881),n=i(3628),a=r({}.hasOwnProperty);e.exports=Object.hasOwn||function(e,t){return a(n(e),t)}},4466(e,t,i){"use strict";var r=i(6893),n=i(9622),a=i(3315),s=i(3770),o=i(2344),l=TypeError,c=Object.defineProperty,u=Object.getOwnPropertyDescriptor,d="enumerable",h="configurable",p="writable";t.f=r?a?function(e,t,i){if(s(e),t=o(t),s(i),"function"==typeof e&&"prototype"===t&&"value"in i&&p in i&&!i[p]){var r=u(e,t);r&&r[p]&&(e[t]=i.value,i={configurable:h in i?i[h]:r[h],enumerable:d in i?i[d]:r[d],writable:!1})}return c(e,t,i)}:c:function(e,t,i){if(s(e),t=o(t),s(i),n)try{return c(e,t,i)}catch(e){}if("get"in i||"set"in i)throw new l("Accessors not supported");return"value"in i&&(e[t]=i.value),e}},4467(e,t,i){var r=i(4643);r.pki=r.pki||{};var n=e.exports=r.pki.oids=r.oids=r.oids||{};function a(e,t){n[e]=t,n[t]=e}function s(e,t){n[e]=t}a("1.2.840.113549.1.1.1","rsaEncryption"),a("1.2.840.113549.1.1.4","md5WithRSAEncryption"),a("1.2.840.113549.1.1.5","sha1WithRSAEncryption"),a("1.2.840.113549.1.1.7","RSAES-OAEP"),a("1.2.840.113549.1.1.8","mgf1"),a("1.2.840.113549.1.1.9","pSpecified"),a("1.2.840.113549.1.1.10","RSASSA-PSS"),a("1.2.840.113549.1.1.11","sha256WithRSAEncryption"),a("1.2.840.113549.1.1.12","sha384WithRSAEncryption"),a("1.2.840.113549.1.1.13","sha512WithRSAEncryption"),a("1.3.101.112","EdDSA25519"),a("1.2.840.10040.4.3","dsa-with-sha1"),a("1.3.14.3.2.7","desCBC"),a("1.3.14.3.2.26","sha1"),a("1.3.14.3.2.29","sha1WithRSASignature"),a("2.16.840.1.101.3.4.2.1","sha256"),a("2.16.840.1.101.3.4.2.2","sha384"),a("2.16.840.1.101.3.4.2.3","sha512"),a("2.16.840.1.101.3.4.2.4","sha224"),a("2.16.840.1.101.3.4.2.5","sha512-224"),a("2.16.840.1.101.3.4.2.6","sha512-256"),a("1.2.840.113549.2.2","md2"),a("1.2.840.113549.2.5","md5"),a("1.2.840.113549.1.7.1","data"),a("1.2.840.113549.1.7.2","signedData"),a("1.2.840.113549.1.7.3","envelopedData"),a("1.2.840.113549.1.7.4","signedAndEnvelopedData"),a("1.2.840.113549.1.7.5","digestedData"),a("1.2.840.113549.1.7.6","encryptedData"),a("1.2.840.113549.1.9.1","emailAddress"),a("1.2.840.113549.1.9.2","unstructuredName"),a("1.2.840.113549.1.9.3","contentType"),a("1.2.840.113549.1.9.4","messageDigest"),a("1.2.840.113549.1.9.5","signingTime"),a("1.2.840.113549.1.9.6","counterSignature"),a("1.2.840.113549.1.9.7","challengePassword"),a("1.2.840.113549.1.9.8","unstructuredAddress"),a("1.2.840.113549.1.9.14","extensionRequest"),a("1.2.840.113549.1.9.20","friendlyName"),a("1.2.840.113549.1.9.21","localKeyId"),a("1.2.840.113549.1.9.22.1","x509Certificate"),a("1.2.840.113549.1.12.10.1.1","keyBag"),a("1.2.840.113549.1.12.10.1.2","pkcs8ShroudedKeyBag"),a("1.2.840.113549.1.12.10.1.3","certBag"),a("1.2.840.113549.1.12.10.1.4","crlBag"),a("1.2.840.113549.1.12.10.1.5","secretBag"),a("1.2.840.113549.1.12.10.1.6","safeContentsBag"),a("1.2.840.113549.1.5.13","pkcs5PBES2"),a("1.2.840.113549.1.5.12","pkcs5PBKDF2"),a("1.2.840.113549.1.12.1.1","pbeWithSHAAnd128BitRC4"),a("1.2.840.113549.1.12.1.2","pbeWithSHAAnd40BitRC4"),a("1.2.840.113549.1.12.1.3","pbeWithSHAAnd3-KeyTripleDES-CBC"),a("1.2.840.113549.1.12.1.4","pbeWithSHAAnd2-KeyTripleDES-CBC"),a("1.2.840.113549.1.12.1.5","pbeWithSHAAnd128BitRC2-CBC"),a("1.2.840.113549.1.12.1.6","pbewithSHAAnd40BitRC2-CBC"),a("1.2.840.113549.2.7","hmacWithSHA1"),a("1.2.840.113549.2.8","hmacWithSHA224"),a("1.2.840.113549.2.9","hmacWithSHA256"),a("1.2.840.113549.2.10","hmacWithSHA384"),a("1.2.840.113549.2.11","hmacWithSHA512"),a("1.2.840.113549.3.7","des-EDE3-CBC"),a("2.16.840.1.101.3.4.1.2","aes128-CBC"),a("2.16.840.1.101.3.4.1.22","aes192-CBC"),a("2.16.840.1.101.3.4.1.42","aes256-CBC"),a("2.5.4.3","commonName"),a("2.5.4.4","surname"),a("2.5.4.5","serialNumber"),a("2.5.4.6","countryName"),a("2.5.4.7","localityName"),a("2.5.4.8","stateOrProvinceName"),a("2.5.4.9","streetAddress"),a("2.5.4.10","organizationName"),a("2.5.4.11","organizationalUnitName"),a("2.5.4.12","title"),a("2.5.4.13","description"),a("2.5.4.15","businessCategory"),a("2.5.4.17","postalCode"),a("2.5.4.42","givenName"),a("1.3.6.1.4.1.311.60.2.1.2","jurisdictionOfIncorporationStateOrProvinceName"),a("1.3.6.1.4.1.311.60.2.1.3","jurisdictionOfIncorporationCountryName"),a("2.16.840.1.113730.1.1","nsCertType"),a("2.16.840.1.113730.1.13","nsComment"),s("2.5.29.1","authorityKeyIdentifier"),s("2.5.29.2","keyAttributes"),s("2.5.29.3","certificatePolicies"),s("2.5.29.4","keyUsageRestriction"),s("2.5.29.5","policyMapping"),s("2.5.29.6","subtreesConstraint"),s("2.5.29.7","subjectAltName"),s("2.5.29.8","issuerAltName"),s("2.5.29.9","subjectDirectoryAttributes"),s("2.5.29.10","basicConstraints"),s("2.5.29.11","nameConstraints"),s("2.5.29.12","policyConstraints"),s("2.5.29.13","basicConstraints"),a("2.5.29.14","subjectKeyIdentifier"),a("2.5.29.15","keyUsage"),s("2.5.29.16","privateKeyUsagePeriod"),a("2.5.29.17","subjectAltName"),a("2.5.29.18","issuerAltName"),a("2.5.29.19","basicConstraints"),s("2.5.29.20","cRLNumber"),s("2.5.29.21","cRLReason"),s("2.5.29.22","expirationDate"),s("2.5.29.23","instructionCode"),s("2.5.29.24","invalidityDate"),s("2.5.29.25","cRLDistributionPoints"),s("2.5.29.26","issuingDistributionPoint"),s("2.5.29.27","deltaCRLIndicator"),s("2.5.29.28","issuingDistributionPoint"),s("2.5.29.29","certificateIssuer"),s("2.5.29.30","nameConstraints"),a("2.5.29.31","cRLDistributionPoints"),a("2.5.29.32","certificatePolicies"),s("2.5.29.33","policyMappings"),s("2.5.29.34","policyConstraints"),a("2.5.29.35","authorityKeyIdentifier"),s("2.5.29.36","policyConstraints"),a("2.5.29.37","extKeyUsage"),s("2.5.29.46","freshestCRL"),s("2.5.29.54","inhibitAnyPolicy"),a("1.3.6.1.4.1.11129.2.4.2","timestampList"),a("1.3.6.1.5.5.7.1.1","authorityInfoAccess"),a("1.3.6.1.5.5.7.3.1","serverAuth"),a("1.3.6.1.5.5.7.3.2","clientAuth"),a("1.3.6.1.5.5.7.3.3","codeSigning"),a("1.3.6.1.5.5.7.3.4","emailProtection"),a("1.3.6.1.5.5.7.3.8","timeStamping")},4517(e,t,i){"use strict";const r=i(1361),{MAX_LENGTH:n,MAX_SAFE_INTEGER:a}=i(9543),{safeRe:s,t:o}=i(2841),l=i(3990),{compareIdentifiers:c}=i(3806);class u{constructor(e,t){if(t=l(t),e instanceof u){if(e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease)return e;e=e.version}else if("string"!=typeof e)throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>n)throw new TypeError(`version is longer than ${n} characters`);r("SemVer",e,t),this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease;const i=e.trim().match(t.loose?s[o.LOOSE]:s[o.FULL]);if(!i)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+i[1],this.minor=+i[2],this.patch=+i[3],this.major>a||this.major<0)throw new TypeError("Invalid major version");if(this.minor>a||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>a||this.patch<0)throw new TypeError("Invalid patch version");i[4]?this.prerelease=i[4].split(".").map(e=>{if(/^[0-9]+$/.test(e)){const t=+e;if(t>=0&&te.major?1:this.minore.minor?1:this.patche.patch?1:0}comparePre(e){if(e instanceof u||(e=new u(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let t=0;do{const i=this.prerelease[t],n=e.prerelease[t];if(r("prerelease compare",t,i,n),void 0===i&&void 0===n)return 0;if(void 0===n)return 1;if(void 0===i)return-1;if(i!==n)return c(i,n)}while(++t)}compareBuild(e){e instanceof u||(e=new u(e,this.options));let t=0;do{const i=this.build[t],n=e.build[t];if(r("build compare",t,i,n),void 0===i&&void 0===n)return 0;if(void 0===n)return 1;if(void 0===i)return-1;if(i!==n)return c(i,n)}while(++t)}inc(e,t,i){if(e.startsWith("pre")){if(!t&&!1===i)throw new Error("invalid increment argument: identifier is empty");if(t){const e=`-${t}`.match(this.options.loose?s[o.PRERELEASELOOSE]:s[o.PRERELEASE]);if(!e||e[1]!==t)throw new Error(`invalid identifier: ${t}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t,i);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t,i);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t,i),this.inc("pre",t,i);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t,i),this.inc("pre",t,i);break;case"release":if(0===this.prerelease.length)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":{const e=Number(i)?1:0;if(0===this.prerelease.length)this.prerelease=[e];else{let r=this.prerelease.length;for(;--r>=0;)"number"==typeof this.prerelease[r]&&(this.prerelease[r]++,r=-2);if(-1===r){if(t===this.prerelease.join(".")&&!1===i)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(e)}}if(t){let r=[t,e];!1===i&&(r=[t]),0===c(this.prerelease[0],t)?isNaN(this.prerelease[1])&&(this.prerelease=r):this.prerelease=r}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}e.exports=u},4530(e,t,i){"use strict";var r=i(6881),n=i(5234),a=i(4188),s=i(4418),o=i(6893),l=i(2735).CONFIGURABLE,c=i(3029),u=i(3086),d=u.enforce,h=u.get,p=String,m=Object.defineProperty,g=r("".slice),f=r("".replace),y=r([].join),v=o&&!n(function(){return 8!==m(function(){},"length",{value:8}).length}),b=String(String).split("String"),w=e.exports=function(e,t,i){"Symbol("===g(p(t),0,7)&&(t="["+f(p(t),/^Symbol\(([^)]*)\).*$/,"$1")+"]"),i&&i.getter&&(t="get "+t),i&&i.setter&&(t="set "+t),(!s(e,"name")||l&&e.name!==t)&&(o?m(e,"name",{value:t,configurable:!0}):e.name=t),v&&i&&s(i,"arity")&&e.length!==i.arity&&m(e,"length",{value:i.arity});try{i&&s(i,"constructor")&&i.constructor?o&&m(e,"prototype",{writable:!1}):e.prototype&&(e.prototype=void 0)}catch(e){}var r=d(e);return s(r,"source")||(r.source=y(b,"string"==typeof t?t:"")),e};Function.prototype.toString=w(function(){return a(this)&&h(this).source||c(this)},"toString")},4531(e){"use strict";e.exports=Function.prototype.call},4533(e,t,i){"use strict";i(2662),i(8491),i(5750),i(2152),i(7072),i(7511),i(9982)},4578(e,t,i){"use strict";var r=i(6881);e.exports=r({}.isPrototypeOf)},4582(e,t,i){"use strict";var r=i(5234),n=i(9123);e.exports=!r(function(){var e=new Error("a");return!("stack"in e)||(Object.defineProperty(e,"stack",n(1,7)),7!==e.stack)})},4607(e,t,i){"use strict";var r=i(528),n=i(9903),a=n([r("%String.prototype.indexOf%")]);e.exports=function(e,t){var i=r(e,!!t);return"function"==typeof i&&a(e,".prototype.")>-1?n([i]):i}},4643(e){e.exports={options:{usePureJavaScript:!1}}},4726(e,t,i){var r,n;n=i(348),r={default_feedback:{warning:"",suggestions:["Use a few words, avoid common phrases","No need for symbols, digits, or uppercase letters"]},get_feedback:function(e,t){var i,n,a,s,o,l;if(0===t.length)return this.default_feedback;if(e>2)return{warning:"",suggestions:[]};for(s=t[0],n=0,a=(l=t.slice(1)).length;ns.token.length&&(s=o);return i="Add another word or two. Uncommon words are better.",null!=(r=this.get_match_feedback(s,1===t.length))?(r.suggestions.unshift(i),null==r.warning&&(r.warning="")):r={warning:"",suggestions:[i]},r},get_match_feedback:function(e,t){switch(e.pattern){case"dictionary":return this.get_dictionary_match_feedback(e,t);case"spatial":return e.graph.toUpperCase(),{warning:1===e.turns?"Straight rows of keys are easy to guess":"Short keyboard patterns are easy to guess",suggestions:["Use a longer keyboard pattern with more turns"]};case"repeat":return{warning:1===e.base_token.length?'Repeats like "aaa" are easy to guess':'Repeats like "abcabcabc" are only slightly harder to guess than "abc"',suggestions:["Avoid repeated words and characters"]};case"sequence":return{warning:"Sequences like abc or 6543 are easy to guess",suggestions:["Avoid sequences"]};case"regex":if("recent_year"===e.regex_name)return{warning:"Recent years are easy to guess",suggestions:["Avoid recent years","Avoid years that are associated with you"]};break;case"date":return{warning:"Dates are often easy to guess",suggestions:["Avoid dates and years that are associated with you"]}}},get_dictionary_match_feedback:function(e,t){var i,r,a,s;return a="passwords"===e.dictionary_name?!t||e.l33t||e.reversed?e.guesses_log10<=4?"This is similar to a commonly used password":void 0:e.rank<=10?"This is a top-10 common password":e.rank<=100?"This is a top-100 common password":"This is a very common password":"english_wikipedia"===e.dictionary_name?t?"A word by itself is easy to guess":void 0:"surnames"===(i=e.dictionary_name)||"male_names"===i||"female_names"===i?t?"Names and surnames by themselves are easy to guess":"Common names and surnames are easy to guess":"",r=[],(s=e.token).match(n.START_UPPER)?r.push("Capitalization doesn't help very much"):s.match(n.ALL_UPPER)&&s.toLowerCase()!==s&&r.push("All-uppercase is almost as easy to guess as all-lowercase"),e.reversed&&e.token.length>=4&&r.push("Reversed words aren't much harder to guess"),e.l33t&&r.push("Predictable substitutions like '@' instead of 'a' don't help very much"),{warning:a,suggestions:r}}},e.exports=r},4793(e,t,i){var r=i(4643);i(7835),i(8550);var n=r.asn1,a=e.exports=r.pkcs7asn1=r.pkcs7asn1||{};r.pkcs7=r.pkcs7||{},r.pkcs7.asn1=a;var s={name:"ContentInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};a.contentInfoValidator=s;var o={name:"EncryptedContentInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};a.envelopedDataValidator={name:"EnvelopedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(o)},a.encryptedDataValidator={name:"EncryptedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"}].concat(o)};var l={name:"SignerInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:n.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};a.signedDataValidator={name:"SignedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},s,{name:"SignedData.Certificates",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:n.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,capture:"signerInfos",optional:!0,value:[l]}]},a.recipientInfoValidator={name:"RecipientInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter",optional:!0}]},{name:"RecipientInfo.encryptedKey",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},4798(e,t,i){"use strict";var r=i(9117),n=Object.defineProperty;e.exports=function(e,t){try{n(r,e,{value:t,configurable:!0,writable:!0})}catch(i){r[e]=t}return t}},4826(e,t,i){"use strict";i.r(t),i.d(t,{decode:()=>v,default:()=>S,encode:()=>b,toASCII:()=>k,toUnicode:()=>w,ucs2decode:()=>p,ucs2encode:()=>m});const r=2147483647,n=36,a=/^xn--/,s=/[^\0-\x7F]/,o=/[\x2E\u3002\uFF0E\uFF61]/g,l={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},c=Math.floor,u=String.fromCharCode;function d(e){throw new RangeError(l[e])}function h(e,t){const i=e.split("@");let r="";i.length>1&&(r=i[0]+"@",e=i[1]);const n=function(e,t){const i=[];let r=e.length;for(;r--;)i[r]=t(e[r]);return i}((e=e.replace(o,".")).split("."),t).join(".");return r+n}function p(e){const t=[];let i=0;const r=e.length;for(;i=55296&&n<=56319&&iString.fromCodePoint(...e),g=function(e){return e>=48&&e<58?e-48+26:e>=65&&e<91?e-65:e>=97&&e<123?e-97:n},f=function(e,t){return e+22+75*(e<26)-((0!=t)<<5)},y=function(e,t,i){let r=0;for(e=i?c(e/700):e>>1,e+=c(e/t);e>455;r+=n)e=c(e/35);return c(r+36*e/(e+38))},v=function(e){const t=[],i=e.length;let a=0,s=128,o=72,l=e.lastIndexOf("-");l<0&&(l=0);for(let i=0;i=128&&d("not-basic"),t.push(e.charCodeAt(i));for(let u=l>0?l+1:0;u=i&&d("invalid-input");const l=g(e.charCodeAt(u++));l>=n&&d("invalid-input"),l>c((r-a)/t)&&d("overflow"),a+=l*t;const h=s<=o?1:s>=o+26?26:s-o;if(lc(r/p)&&d("overflow"),t*=p}const h=t.length+1;o=y(a-l,h,0==l),c(a/h)>r-s&&d("overflow"),s+=c(a/h),a%=h,t.splice(a++,0,s)}return String.fromCodePoint(...t)},b=function(e){const t=[],i=(e=p(e)).length;let a=128,s=0,o=72;for(const i of e)i<128&&t.push(u(i));const l=t.length;let h=l;for(l&&t.push("-");h=a&&tc((r-s)/p)&&d("overflow"),s+=(i-a)*p,a=i;for(const i of e)if(ir&&d("overflow"),i===a){let e=s;for(let i=n;;i+=n){const r=i<=o?1:i>=o+26?26:i-o;if(ep;r=0<=p?++l:--l)for(n=c=m=r,g=a;m<=g?cg;n=m<=g?++c:--c)u.slice(r,+n+1||9e9)in h&&(d=h[f=u.slice(r,+n+1||9e9)],o.push({pattern:"dictionary",i:r,j:n,token:e.slice(r,+n+1||9e9),matched_word:f,rank:d,dictionary_name:i,reversed:!1,l33t:!1}));return this.sorted(o)},reverse_dictionary_match:function(e,t){var i,r,n,a,o,l;for(null==t&&(t=s),l=e.split("").reverse().join(""),a=0,i=(n=this.dictionary_match(l,t)).length;a0&&(d[n]=l);return d},enumerate_l33t_subs:function(e){var t,i,r,n,a,s,o,l,c,u,d,h,p,m,g;for(a=function(){var t;for(n in t=[],e)t.push(n);return t}(),g=[[]],i=function(e){var t,i,r,a,s,o,l,c;for(i=[],s={},o=0,a=e.length;of;s=0<=f?++p:--p)if(v[s][0]===o){n=s;break}-1===n?(w=v.concat([[o,a]]),u.push(w)):((b=v.slice(0)).splice(n,1),b.push([o,a]),u.push(v),u.push(b))}return g=i(u),r(y)}},r(a),m=[],c=0,o=g.length;c "+w);return e}().join(", "),d.push(c)}return this.sorted(d.filter(function(e){return e.token.length>1}))},spatial_match:function(e,t){var i,r,a;for(r in null==t&&(t=n),a=[],t)i=t[r],this.extend(a,this.spatial_match_helper(e,i,r));return this.sorted(a)},SHIFTED_RX:/[~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?]/,spatial_match_helper:function(e,t,i){var r,n,a,s,o,l,c,u,d,h,p,m,g,f;for(p=[],c=0;c2&&p.push({pattern:"spatial",i:c,j:u-1,token:e.slice(c,u),graph:i,turns:f,shifted_count:g}),c=u;break}u+=1}return p},repeat_match:function(e){var t,i,r,n,a,s,o,l,c,u,d,h,p,g,f;for(g=[],a=/(.+)\1+/g,u=/(.+?)\1+/g,d=/^(.+?)\1+$/,c=0;ch[0].length?(p=s,n=d.exec(p[0])[1]):n=(p=h)[1],o=(f=[p.index,p.index+p[0].length-1])[0],l=f[1],r=(t=m.most_guessable_match_sequence(n,this.omnimatch(n))).sequence,i=t.guesses,g.push({pattern:"repeat",i:o,j:l,token:p[0],base_token:n,base_guesses:i,base_matches:r,repeat_count:p[0].length/n.length}),c=l+1;return g},MAX_DELTA:5,sequence_match:function(e){var t,i,r,n,a,s,o,l,c,u;if(1===e.length)return[];for(u=this,c=function(t,i,r){var n,a,s,o;if((i-t>1||1===Math.abs(r))&&0<(n=Math.abs(r))&&n<=u.MAX_DELTA)return o=e.slice(t,+i+1||9e9),/^[a-z]+$/.test(o)?(a="lower",s=26):/^[A-Z]+$/.test(o)?(a="upper",s=26):/^\d+$/.test(o)?(a="digits",s=10):(a="unicode",s=26),l.push({pattern:"sequence",i:t,j:i,token:e.slice(t,+i+1||9e9),sequence_name:a,sequence_space:s,ascending:r>0})},l=[],i=0,a=null,n=s=1,o=e.length;1<=o?so;n=1<=o?++s:--s)t=e.charCodeAt(n)-e.charCodeAt(n-1),null==a&&(a=t),t!==a&&(c(i,r=n-1,a),i=r,a=t);return c(i,e.length-1,a),l},regex_match:function(e,t){var i,r,n,a;for(p in null==t&&(t=o),i=[],t)for((r=t[p]).lastIndex=0;n=r.exec(e);)a=n[0],i.push({pattern:"regex",token:a,i:n.index,j:n.index+n[0].length-1,regex_name:p,regex_match:n});return this.sorted(i)},date_match:function(e){var t,i,n,a,s,o,l,c,u,d,h,p,g,f,y,v,b,w,k,S,_,x,C,I,E,z,P,A,j,T,D,O,N,R;for(p=[],g=/^\d{4,8}$/,f=/^(\d{1,4})([\s\/\\_.-])(\d{1,2})\2(\d{1,4})$/,o=b=0,_=e.length-4;0<=_?b<=_:b>=_;o=0<=_?++b:--b)for(l=w=x=o+3,C=o+7;(x<=C?w<=C:w>=C)&&!(l>=e.length);l=x<=C?++w:--w)if(R=e.slice(o,+l+1||9e9),g.exec(R)){for(n=[],k=0,d=(I=r[R.length]).length;k0){for(t=n[0],y=function(e){return Math.abs(e.year-m.REFERENCE_YEAR)},v=y(n[0]),S=0,h=(z=n.slice(1)).length;S=A;o=0<=A?++O:--O)for(l=N=j=o+5,T=o+9;(j<=T?N<=T:N>=T)&&!(l>=e.length);l=j<=T?++N:--N)R=e.slice(o,+l+1||9e9),null!=(D=f.exec(R))&&null!=(s=this.map_ints_to_dmy([parseInt(D[1]),parseInt(D[3]),parseInt(D[4])]))&&p.push({pattern:"date",token:R,i:o,j:l,separator:D[2],year:s.year,month:s.month,day:s.day});return this.sorted(p.filter(function(e){var t,i,r,n;for(t=!1,n=0,i=p.length;n=e.j){t=!0;break}return!t}))},map_ints_to_dmy:function(e){var t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,f;if(!(e[1]>31||e[1]<=0)){for(o=0,l=0,g=0,s=0,r=e.length;s2050)return;i>31&&(l+=1),i>12&&(o+=1),i<=0&&(g+=1)}if(!(l>=2||3===o||g>=2)){for(c=0,n=(u=[[e[2],e.slice(0,2)],[e[0],e.slice(1,3)]]).length;c99?e:e>50?e+1900:e+2e3}},e.exports=h},4940(e){"use strict";var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}e.exports=t},4943(e){"use strict";e.exports=ReferenceError},4977(e,t,i){"use strict";var r=i(4188),n=i(3174),a=TypeError;e.exports=function(e){if(r(e))return e;throw new a(n(e)+" is not a function")}},5039(e,t,i){"use strict";const r=i(4517),n=i(7476);e.exports=(e,t,i)=>{let a=null,s=null,o=null;try{o=new n(t,i)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(a&&-1!==s.compare(e)||(a=e,s=new r(a,i)))}),a}},5054(e,t,i){"use strict";var r=i(1025),n=i(831),a=i(9509),s=i(4121);e.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var e,t=!1,i={};try{(e=r(Object.prototype,"__proto__","set"))(i,[]),t=i instanceof Array}catch(e){}return function(i,r){return a(i),s(r),n(i)?(t?e(i,r):i.__proto__=r,i):i}}():void 0)},5114(e,t,i){var r=i(4643);i(5417),i(8550),(e.exports=r.pss=r.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t,i=e.md,n=e.mgf,a=i.digestLength,s=e.salt||null;if("string"==typeof s&&(s=r.util.createBuffer(s)),"saltLength"in e)t=e.saltLength;else{if(null===s)throw new Error("Salt length not specified or specific salt not given.");t=s.length()}if(null!==s&&s.length()!==t)throw new Error("Given salt length does not match length of given salt.");var o=e.prng||r.random;return{encode:function(e,l){var c,u,d=l-1,h=Math.ceil(d/8),p=e.digest().getBytes();if(h>8*h-d&255;return(w=String.fromCharCode(w.charCodeAt(0)&~k)+w.substr(1))+g+String.fromCharCode(188)},verify:function(e,s,o){var l,c=o-1,u=Math.ceil(c/8);if(s=s.substr(-u),u>8*u-c&255;if(0!==(h.charCodeAt(0)&m))throw new Error("Bits beyond keysize not zero as expected.");var g=n.generate(p,d),f="";for(l=0;l65&&-1!==s){var o=t[s];","===o?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+o+t.substr(s+1),a=n-s-1,s=-1,++n}else" "!==t[n]&&"\t"!==t[n]&&","!==t[n]||(s=n);return t}function s(e){return e.replace(/^\s+/,"")}n.encode=function(e,t){t=t||{};var i,n="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(n+=a(i={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]})),e.contentDomain&&(n+=a(i={name:"Content-Domain",values:[e.contentDomain]})),e.dekInfo&&(i={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&i.values.push(e.dekInfo.parameters),n+=a(i)),e.headers)for(var s=0;s{let a=null,s=null,o=null;try{o=new n(t,i)}catch(e){return null}return e.forEach(e=>{o.test(e)&&(a&&1!==s.compare(e)||(a=e,s=new r(a,i)))}),a}},5382(e,t,i){"use strict";var r=i(8088),n=i(7308),a=i(4582),s=Error.captureStackTrace;e.exports=function(e,t,i,o){a&&(s?s(e,t):r(e,"stack",n(i,o)))}},5417(e,t,i){var r=i(4643);i(3739),i(7585),i(7391),i(8550),r.random&&r.random.getBytes?e.exports=r.random:function(t){var i={},n=new Array(4),a=r.util.createBuffer();function s(){var e=r.prng.create(i);return e.getBytes=function(t,i){return e.generate(t,i)},e.getBytesSync=function(t){return e.generate(t)},e}i.formatKey=function(e){var t=r.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),r.aes._expandKey(e,!1)},i.formatSeed=function(e){var t=r.util.createBuffer(e);return(e=new Array(4))[0]=t.getInt32(),e[1]=t.getInt32(),e[2]=t.getInt32(),e[3]=t.getInt32(),e},i.cipher=function(e,t){return r.aes._updateBlock(e,t,n,!1),a.putInt32(n[0]),a.putInt32(n[1]),a.putInt32(n[2]),a.putInt32(n[3]),a.getBytes()},i.increment=function(e){return++e[3],e},i.md=r.md.sha256;var o=s(),l=null,c=r.util.globalScope,u=c.crypto||c.msCrypto;if(u&&u.getRandomValues&&(l=function(e){return u.getRandomValues(e)}),r.options.usePureJavaScript||!r.util.isNodejs&&!l){if("undefined"==typeof window||window.document,o.collectInt(+new Date,32),"undefined"!=typeof navigator){var d="";for(var h in navigator)try{"string"==typeof navigator[h]&&(d+=navigator[h])}catch(e){}o.collect(d),d=null}t&&(t().mousemove(function(e){o.collectInt(e.clientX,16),o.collectInt(e.clientY,16)}),t().keypress(function(e){o.collectInt(e.charCode,8)}))}if(r.random)for(var h in o)r.random[h]=o[h];else r.random=o;r.random.createInstance=s,e.exports=r.random}("undefined"!=typeof jQuery?jQuery:null)},5438(e,t,i){"use strict";var r=i(9345),n=i(4188),a=i(8689),s=i(4282)("toStringTag"),o=Object,l="Arguments"===a(function(){return arguments}());e.exports=r?a:function(e){var t,i,r;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(i=function(e,t){try{return e[t]}catch(e){}}(t=o(e),s))?i:l?a(t):"Object"===(r=a(t))&&n(t.callee)?"Arguments":r}},5442(e,t,i){"use strict";var r=i(4826);function n(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var a=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,o=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,l=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),c=["'"].concat(l),u=["%","/","?",";","#"].concat(c),d=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,p=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},g={javascript:!0,"javascript:":!0},f={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=i(5810);function v(e,t,i){if(e&&"object"==typeof e&&e instanceof n)return e;var r=new n;return r.parse(e,t,i),r}n.prototype.parse=function(e,t,i){if("string"!=typeof e)throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var n=e.indexOf("?"),s=-1!==n&&n127?T+="x":T+=j[D];if(!T.match(h)){var N=P.slice(0,I),R=P.slice(I+1),U=j.match(p);U&&(N.push(U[1]),R.unshift(U[2])),R.length&&(v="/"+R.join(".")+v),this.hostname=N.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),z||(this.hostname=r.toASCII(this.hostname));var F=this.port?":"+this.port:"",q=this.hostname||"";this.host=q+F,this.href+=this.host,z&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==v[0]&&(v="/"+v))}if(!m[k])for(I=0,A=c.length;I0)&&i.host.split("@"))&&(i.auth=z.shift(),i.hostname=z.shift(),i.host=i.hostname)),i.search=e.search,i.query=e.query,null===i.pathname&&null===i.search||(i.path=(i.pathname?i.pathname:"")+(i.search?i.search:"")),i.href=i.format(),i;if(!S.length)return i.pathname=null,i.search?i.path="/"+i.search:i.path=null,i.href=i.format(),i;for(var x=S.slice(-1)[0],C=(i.host||e.host||S.length>1)&&("."===x||".."===x)||""===x,I=0,E=S.length;E>=0;E--)"."===(x=S[E])?S.splice(E,1):".."===x?(S.splice(E,1),I++):I&&(S.splice(E,1),I--);if(!w&&!k)for(;I--;I)S.unshift("..");!w||""===S[0]||S[0]&&"/"===S[0].charAt(0)||S.unshift(""),C&&"/"!==S.join("/").substr(-1)&&S.push("");var z,P=""===S[0]||S[0]&&"/"===S[0].charAt(0);return _&&(i.hostname=P?"":S.length?S.shift():"",i.host=i.hostname,(z=!!(i.host&&i.host.indexOf("@")>0)&&i.host.split("@"))&&(i.auth=z.shift(),i.hostname=z.shift(),i.host=i.hostname)),(w=w||i.host&&S.length)&&!P&&S.unshift(""),S.length>0?i.pathname=S.join("/"):(i.pathname=null,i.path=null),null===i.pathname&&null===i.search||(i.path=(i.pathname?i.pathname:"")+(i.search?i.search:"")),i.auth=e.auth||i.auth,i.slashes=i.slashes||e.slashes,i.href=i.format(),i},n.prototype.parseHost=function(){var e=this.host,t=s.exec(e);t&&(":"!==(t=t[0])&&(this.port=t.substr(1)),e=e.substr(0,e.length-t.length)),e&&(this.hostname=e)},t.parse=v,t.resolve=function(e,t){return v(e,!1,!0).resolve(t)},t.resolveObject=function(e,t){return e?v(e,!1,!0).resolveObject(t):t},t.format=function(e){return"string"==typeof e&&(e=v(e)),e instanceof n?e.format():n.prototype.format.call(e)},t.Url=n},5604(e,t,i){"use strict";var r=i(9117),n=i(4188);e.exports=function(e,t){return arguments.length<2?(i=r[e],n(i)?i:void 0):r[e]&&r[e][t];var i}},5613(e,t,i){"use strict";var r=i(9117),n=i(9304).f,a=i(8088),s=i(7509),o=i(4798),l=i(8657),c=i(8489);e.exports=function(e,t){var i,u,d,h,p,m=e.target,g=e.global,f=e.stat;if(i=g?r:f?r[m]||o(m,{}):r[m]&&r[m].prototype)for(u in t){if(h=t[u],d=e.dontCallGetSet?(p=n(i,u))&&p.value:i[u],!c(g?u:m+(f?".":"#")+u,e.forced)&&void 0!==d){if(typeof h==typeof d)continue;l(h,d)}(e.sham||d&&d.sham)&&a(h,"sham",!0),s(i,u,h,e)}}},5628(e,t,i){var r=i(4643);i(7835);var n=r.asn1;t.privateKeyValidator={name:"PrivateKeyInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},t.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:n.Class.UNIVERSAL,type:n.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}},5629(e,t,i){"use strict";var r=i(1843),n=i(1274).concat("length","prototype");t.f=Object.getOwnPropertyNames||function(e){return r(e,n)}},5691(e,t,i){"use strict";var r=i(8689),n=i(6881);e.exports=function(e){if("Function"===r(e))return n(e)}},5731(e){"use strict";e.exports=SyntaxError},5750(e,t,i){"use strict";i(3133)},5804(e){var t;t={estimate_attack_times:function(e){var t,i,r,n;for(r in t={},i={online_throttling_100_per_hour:e/(100/3600),online_no_throttling_10_per_second:e/10,offline_slow_hashing_1e4_per_second:e/1e4,offline_fast_hashing_1e10_per_second:e/1e10})n=i[r],t[r]=this.display_time(n);return{crack_times_seconds:i,crack_times_display:t,score:this.guesses_to_score(e)}},guesses_to_score:function(e){return e<1005?0:e<1000005?1:e<100000005?2:e<10000000005?3:4},display_time:function(e){var t,i,r,n,a,s,o;return a=31*86400,i=100*(o=32140800),n=(s=e<1?[null,"less than a second"]:e<60?[t=Math.round(e),t+" second"]:e<3600?[t=Math.round(e/60),t+" minute"]:e<86400?[t=Math.round(e/3600),t+" hour"]:enew r(e,t).patch},6095(e){"use strict";e.exports=Function.prototype.apply},6106(e,t,i){"use strict";const r=i(4517);e.exports=(e,t,i)=>{const n=new r(e,i),a=new r(t,i);return n.compare(a)||n.compareBuild(a)}},6193(e,t,i){"use strict";var r=i(1539),n=Object.prototype.hasOwnProperty,a=Array.isArray,s={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:r.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1,throwOnLimitExceeded:!1},o=function(e){return e.replace(/&#(\d+);/g,function(e,t){return String.fromCharCode(parseInt(t,10))})},l=function(e,t,i){if(e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1)return e.split(",");if(t.throwOnLimitExceeded&&i>=t.arrayLimit)throw new RangeError("Array limit exceeded. Only "+t.arrayLimit+" element"+(1===t.arrayLimit?"":"s")+" allowed in an array.");return e},c=function(e,t,i,a){if(e){var s=i.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/g,c=i.depth>0&&/(\[[^[\]]*])/.exec(s),u=c?s.slice(0,c.index):s,d=[];if(u){if(!i.plainObjects&&n.call(Object.prototype,u)&&!i.allowPrototypes)return;d.push(u)}for(var h=0;i.depth>0&&null!==(c=o.exec(s))&&h0&&"[]"===e[e.length-1]){var s=e.slice(0,-1).join("");a=Array.isArray(t)&&t[s]?t[s].length:0}for(var o=n?t:l(t,i,a),c=e.length-1;c>=0;--c){var u,d=e[c];if("[]"===d&&i.parseArrays)u=i.allowEmptyArrays&&(""===o||i.strictNullHandling&&null===o)?[]:r.combine([],o);else{u=i.plainObjects?{__proto__:null}:{};var h="["===d.charAt(0)&&"]"===d.charAt(d.length-1)?d.slice(1,-1):d,p=i.decodeDotInKeys?h.replace(/%2E/g,"."):h,m=parseInt(p,10);i.parseArrays||""!==p?!isNaN(m)&&d!==p&&String(m)===p&&m>=0&&i.parseArrays&&m<=i.arrayLimit?(u=[])[m]=o:"__proto__"!==p&&(u[p]=o):u={0:o}}o=u}return o}(d,t,i,a)}};e.exports=function(e,t){var i=function(e){if(!e)return s;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.decodeDotInKeys&&"boolean"!=typeof e.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(void 0!==e.throwOnLimitExceeded&&"boolean"!=typeof e.throwOnLimitExceeded)throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var t=void 0===e.charset?s.charset:e.charset,i=void 0===e.duplicates?s.duplicates:e.duplicates;if("combine"!==i&&"first"!==i&&"last"!==i)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===e.allowDots?!0===e.decodeDotInKeys||s.allowDots:!!e.allowDots,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:s.allowEmptyArrays,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:s.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:s.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:s.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:s.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:s.comma,decodeDotInKeys:"boolean"==typeof e.decodeDotInKeys?e.decodeDotInKeys:s.decodeDotInKeys,decoder:"function"==typeof e.decoder?e.decoder:s.decoder,delimiter:"string"==typeof e.delimiter||r.isRegExp(e.delimiter)?e.delimiter:s.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:s.depth,duplicates:i,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:s.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:s.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:s.plainObjects,strictDepth:"boolean"==typeof e.strictDepth?!!e.strictDepth:s.strictDepth,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:s.strictNullHandling,throwOnLimitExceeded:"boolean"==typeof e.throwOnLimitExceeded&&e.throwOnLimitExceeded}}(t);if(""===e||null==e)return i.plainObjects?{__proto__:null}:{};for(var u="string"==typeof e?function(e,t){var i={__proto__:null},c=t.ignoreQueryPrefix?e.replace(/^\?/,""):e;c=c.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var u=t.parameterLimit===1/0?void 0:t.parameterLimit,d=c.split(t.delimiter,t.throwOnLimitExceeded?u+1:u);if(t.throwOnLimitExceeded&&d.length>u)throw new RangeError("Parameter limit exceeded. Only "+u+" parameter"+(1===u?"":"s")+" allowed.");var h,p=-1,m=t.charset;if(t.charsetSentinel)for(h=0;h-1&&(f=a(f)?[f]:f);var w=n.call(i,g);w&&"combine"===t.duplicates?i[g]=r.combine(i[g],f):w&&"last"!==t.duplicates||(i[g]=f)}return i}(e,i):e,d=i.plainObjects?{__proto__:null}:{},h=Object.keys(u),p=0;p>16-t},o=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=r.rc2=r.rc2||{},r.rc2.expandKey=function(e,t){"string"==typeof e&&(e=r.util.createBuffer(e)),t=t||128;var i,a=e,s=e.length(),o=t,l=Math.ceil(o/8),c=255>>(7&o);for(i=s;i<128;i++)a.putByte(n[a.at(i-1)+a.at(i-s)&255]);for(a.setAt(128-l,n[a.at(128-l)&c]),i=127-l;i>=0;i--)a.setAt(i,n[a.at(i+1)^a.at(i+l)]);return a};var l=function(e,t,i){var n,l,c,u,d=!1,h=null,p=null,m=null,g=[];for(e=r.rc2.expandKey(e,t),c=0;c<64;c++)g.push(e.getInt16Le());i?(n=function(e){for(c=0;c<4;c++)e[c]+=g[u]+(e[(c+3)%4]&e[(c+2)%4])+(~e[(c+3)%4]&e[(c+1)%4]),e[c]=s(e[c],a[c]),u++},l=function(e){for(c=0;c<4;c++)e[c]+=g[63&e[(c+3)%4]]}):(n=function(e){for(c=3;c>=0;c--)e[c]=o(e[c],a[c]),e[c]-=g[u]+(e[(c+3)%4]&e[(c+2)%4])+(~e[(c+3)%4]&e[(c+1)%4]),u--},l=function(e){for(c=3;c>=0;c--)e[c]-=g[63&e[(c+3)%4]]});var f=function(e){var t=[];for(c=0;c<4;c++){var r=h.getInt16Le();null!==m&&(i?r^=m.getInt16Le():m.putInt16Le(r)),t.push(65535&r)}u=i?0:63;for(var n=0;n=8;)f([[5,n],[1,l],[6,n],[1,l],[5,n]])},finish:function(e){var t=!0;if(i)if(e)t=e(8,h,!i);else{var r=8===h.length()?8:8-h.length();h.fillWithByte(r,r)}if(t&&(d=!0,y.update()),!i&&(t=0===h.length()))if(e)t=e(8,p,!i);else{var n=p.length(),a=p.at(n-1);a>n?t=!1:p.truncate(a)}return t}}};r.rc2.startEncrypting=function(e,t,i){var n=r.rc2.createEncryptionCipher(e,128);return n.start(t,i),n},r.rc2.createEncryptionCipher=function(e,t){return l(e,t,!0)},r.rc2.startDecrypting=function(e,t,i){var n=r.rc2.createDecryptionCipher(e,128);return n.start(t,i),n},r.rc2.createDecryptionCipher=function(e,t){return l(e,t,!1)}},6348(e,t,i){"use strict";var r=i(528),n=i(4607),a=i(8660),s=i(7004),o=i(3468),l=r("%WeakMap%",!0),c=n("WeakMap.prototype.get",!0),u=n("WeakMap.prototype.set",!0),d=n("WeakMap.prototype.has",!0),h=n("WeakMap.prototype.delete",!0);e.exports=l?function(){var e,t,i={assert:function(e){if(!i.has(e))throw new o("Side channel does not contain "+a(e))},delete:function(i){if(l&&i&&("object"==typeof i||"function"==typeof i)){if(e)return h(e,i)}else if(s&&t)return t.delete(i);return!1},get:function(i){return l&&i&&("object"==typeof i||"function"==typeof i)&&e?c(e,i):t&&t.get(i)},has:function(i){return l&&i&&("object"==typeof i||"function"==typeof i)&&e?d(e,i):!!t&&t.has(i)},set:function(i,r){l&&i&&("object"==typeof i||"function"==typeof i)?(e||(e=new l),u(e,i,r)):s&&(t||(t=s()),t.set(i,r))}};return i}:s},6364(e,t,i){"use strict";const r=i(7476);e.exports=(e,t)=>new r(e,t).set.map(e=>e.map(e=>e.value).join(" ").trim().split(" "))},6369(e,t,i){"use strict";var r=i(7859),n=i(7345),a=i(6423);e.exports=r?function(e){return r(e)}:n?function(e){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new TypeError("getProto: not an object");return n(e)}:a?function(e){return a(e)}:null},6381(e,t,i){"use strict";const r=i(4517);e.exports=(e,t)=>new r(e,t).major},6404(e,t,i){var r,n,a,s,o,l;n=i(4842),a=i(348),o=i(5804),r=i(4726),s=function(){return(new Date).getTime()},l=function(e,t){var i,l,c,u,d,h,p,m,g,f,y;for(null==t&&(t=[]),f=s(),g=[],c=0,u=t.length;cOi,$Wc:()=>on,$bb:()=>U,$yx:()=>rt,Aal:()=>Wi,Ajz:()=>si,B$5:()=>vt,BI1:()=>Tt,BJ2:()=>hr,BZb:()=>gn,BiA:()=>Br,BtZ:()=>ki,BwH:()=>xr,C$D:()=>ni,CAO:()=>fr,CDy:()=>Lr,CXO:()=>ge,Cqu:()=>$i,Ctk:()=>Mt,Cyf:()=>lt,Czj:()=>bi,D4i:()=>Ge,DAT:()=>Gt,Deq:()=>Qt,Duf:()=>zr,E9A:()=>Sr,EEW:()=>qr,ESg:()=>Zi,E_p:()=>Ht,Eip:()=>et,FHZ:()=>Ft,FU_:()=>Xr,GPN:()=>Xt,Geh:()=>P,GvV:()=>ft,H4N:()=>ot,HYJ:()=>gi,HpL:()=>ji,HvI:()=>fi,I8U:()=>pi,IEs:()=>Pe,IKh:()=>rn,ILj:()=>pe,ISg:()=>Yr,Ia5:()=>Wt,ItQ:()=>Ri,Iwk:()=>Ki,J5t:()=>Ot,JME:()=>Jr,JeQ:()=>lr,KA1:()=>Qr,KTv:()=>wi,Lpo:()=>ut,Lqc:()=>ct,Lxb:()=>Dr,M4X:()=>_i,MVt:()=>Nr,MXC:()=>dt,Mh2:()=>Ei,MpJ:()=>jt,N$E:()=>Vt,N0M:()=>zi,NJs:()=>pr,NnM:()=>Xi,Nu0:()=>Bi,O0Z:()=>Ai,Oyk:()=>We,P6V:()=>St,PQG:()=>mt,PUO:()=>R,PmN:()=>It,PrK:()=>mi,Q4Q:()=>hn,QGd:()=>_r,RLo:()=>Cr,RS6:()=>er,RV8:()=>Xe,Rg:()=>un,Rhw:()=>Qe,Rto:()=>Ci,RyU:()=>Wr,Ryz:()=>mr,SE3:()=>gt,S_8:()=>Ti,SaD:()=>vr,St$:()=>ti,TIj:()=>ht,Tm2:()=>vi,U1K:()=>Ji,UEo:()=>Yt,UM9:()=>Kt,Ug_:()=>Bt,Uq6:()=>wt,UuR:()=>Ct,V1r:()=>tt,V4B:()=>gr,VB8:()=>Vr,VJm:()=>nr,VO6:()=>it,VUr:()=>or,W53:()=>jr,WYM:()=>Dt,WmO:()=>$r,Wy_:()=>ui,XDS:()=>Ar,YQx:()=>sr,YV2:()=>ai,YVq:()=>yt,YjR:()=>cn,ZI_:()=>nt,ZT8:()=>Nt,Zi3:()=>sn,_5w:()=>cr,_Cx:()=>pt,_RG:()=>Rr,a5H:()=>$t,aKQ:()=>Pt,awy:()=>tr,azX:()=>an,bEY:()=>kt,bRr:()=>oi,bax:()=>di,bcK:()=>kr,bkt:()=>fn,bnN:()=>z,cCJ:()=>dn,cLc:()=>tn,cPU:()=>Ce,cXT:()=>ei,ctP:()=>ii,dC$:()=>li,dEp:()=>ci,eD1:()=>Gr,ekg:()=>Pr,faW:()=>Ui,fgh:()=>Ur,g4C:()=>Mr,gR3:()=>Mi,hEI:()=>Di,hGK:()=>Ye,hkC:()=>qi,iSd:()=>rr,iqP:()=>mn,jQA:()=>Ir,jkw:()=>Hr,k0l:()=>Si,kJV:()=>ir,kie:()=>Ni,kj1:()=>Kr,lIU:()=>n,le5:()=>T,lnM:()=>zt,ltG:()=>Ke,m9z:()=>ri,mcm:()=>dr,n0P:()=>Fr,oKC:()=>st,okU:()=>Zt,okn:()=>at,oul:()=>Er,ozA:()=>Gi,pII:()=>nn,pLY:()=>Qi,pXu:()=>Je,pYi:()=>Zr,pd2:()=>Ze,ps7:()=>$e,px3:()=>Ii,q$k:()=>Or,q83:()=>Et,q8u:()=>He,qO7:()=>Rt,qn8:()=>ar,qqE:()=>yr,qsA:()=>Yi,rqp:()=>Li,sGC:()=>Fi,sPv:()=>yi,sTy:()=>xt,sdu:()=>ln,srv:()=>xi,tff:()=>_t,tys:()=>bt,u4f:()=>At,uVl:()=>Hi,uv3:()=>en,v5M:()=>be,v7k:()=>ur,vh6:()=>wr,wlc:()=>br,x$X:()=>Tr,xFA:()=>hi,xY8:()=>qt,xhx:()=>Ut,xiq:()=>Lt,yM2:()=>Vi,yle:()=>pn,ymW:()=>Pi,zRt:()=>Jt}),e=i.hmd(e);let a=null;function s(){return null!==a&&0!==a.byteLength||(a=new Uint8Array(r.memory.buffer)),a}let o=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0});o.decode();let l=0;function c(e,t){return function(e,t){return l+=t,l>=2146435072&&(o=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),o.decode(),l=t),o.decode(s().subarray(e,e+t))}(e>>>=0,t)}let u=new Array(128).fill(void 0);u.push(void 0,null,!0,!1);let d=u.length;function h(e){d===u.length&&u.push(u.length+1);const t=d;return d=u[t],u[t]=e,t}function p(e){return u[e]}let m=0;const g=new TextEncoder;function f(e,t,i){if(void 0===i){const i=g.encode(e),r=t(i.length,1)>>>0;return s().subarray(r,r+i.length).set(i),m=i.length,r}let r=e.length,n=t(r,1)>>>0;const a=s();let o=0;for(;o127)break;a[n+o]=t}if(o!==r){0!==o&&(e=e.slice(o)),n=i(n,r,r=o+3*e.length,1)>>>0;const t=s().subarray(n+o,n+r);o+=g.encodeInto(e,t).written,n=i(n,r,o,1)>>>0}return m=o,n}"encodeInto"in g||(g.encodeInto=function(e,t){const i=g.encode(e);return t.set(i),{read:e.length,written:i.length}});let y=null;function v(){return(null===y||!0===y.buffer.detached||void 0===y.buffer.detached&&y.buffer!==r.memory.buffer)&&(y=new DataView(r.memory.buffer)),y}function b(e){return null==e}function w(e){const t=typeof e;if("number"==t||"boolean"==t||null==e)return`${e}`;if("string"==t)return`"${e}"`;if("symbol"==t){const t=e.description;return null==t?"Symbol":`Symbol(${t})`}if("function"==t){const t=e.name;return"string"==typeof t&&t.length>0?`Function(${t})`:"Function"}if(Array.isArray(e)){const t=e.length;let i="[";t>0&&(i+=w(e[0]));for(let r=1;r1))return toString.call(e);if(r=i[1],"Object"==r)try{return"Object("+JSON.stringify(e)+")"}catch(e){return"Object"}return e instanceof Error?`${e.name}: ${e.message}\n${e.stack}`:r}function k(e,t){try{return e.apply(this,t)}catch(e){r.__wbindgen_exn_store(h(e))}}function S(e){const t=p(e);return function(e){e<132||(u[e]=d,d=e)}(e),t}function _(e,t){return e>>>=0,s().subarray(e/1,e/1+t)}const x="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>e.dtor(e.a,e.b));function C(e,t,i,r){const n={a:e,b:t,cnt:1,dtor:i},a=(...e)=>{n.cnt++;const t=n.a;n.a=0;try{return r(t,n.b,...e)}finally{n.a=t,a._wbg_cb_unref()}};return a._wbg_cb_unref=()=>{0===--n.cnt&&(n.dtor(n.a,n.b),n.a=0,x.unregister(n))},x.register(a,n,n),a}function I(e,t){e>>>=0;const i=v(),r=[];for(let n=e;n>>0;return s().set(e,i/1),m=e.length,i}function z(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m;var i=b(t)?0:f(t,r.__wbindgen_malloc,r.__wbindgen_realloc),n=m;r.import_ssh_key(o,l,c,i,n);var a=v().getInt32(o+0,!0),s=v().getInt32(o+4,!0);if(v().getInt32(o+8,!0))throw S(s);return S(a)}finally{r.__wbindgen_add_to_stack_pointer(16)}}function P(e){r.init_sdk(b(e)?5:e)}function A(e,t){const i=t(4*e.length,4)>>>0,r=v();for(let t=0;t{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_attachmentsclient_free(e>>>0,1));class V{static __wrap(e){e>>>=0;const t=Object.create(V.prototype);return t.__wbg_ptr=e,M.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,M.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_attachmentsclient_free(e,0)}decrypt_buffer(e,t,i){try{const l=r.__wbindgen_add_to_stack_pointer(-16),c=E(i,r.__wbindgen_malloc),u=m;r.attachmentsclient_decrypt_buffer(l,this.__wbg_ptr,h(e),h(t),c,u);var n=v().getInt32(l+0,!0),a=v().getInt32(l+4,!0),s=v().getInt32(l+8,!0);if(v().getInt32(l+12,!0))throw S(s);var o=_(n,a).slice();return r.__wbindgen_free(n,1*a,1),o}finally{r.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(V.prototype[Symbol.dispose]=V.prototype.free);const $="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_authclient_free(e>>>0,1));class K{static __wrap(e){e>>>=0;const t=Object.create(K.prototype);return t.__wbg_ptr=e,$.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,$.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_authclient_free(e,0)}send_access(){const e=r.authclient_registration(this.__wbg_ptr);return De.__wrap(e)}registration(){const e=r.authclient_registration(this.__wbg_ptr);return je.__wrap(e)}login(e){const t=r.authclient_login(this.__wbg_ptr,h(e));return ke.__wrap(t)}}Symbol.dispose&&(K.prototype[Symbol.dispose]=K.prototype.free);const W="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_cipheradminclient_free(e>>>0,1));class H{static __wrap(e){e>>>=0;const t=Object.create(H.prototype);return t.__wbg_ptr=e,W.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,W.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_cipheradminclient_free(e,0)}list_org_ciphers(e,t){return S(r.cipheradminclient_list_org_ciphers(this.__wbg_ptr,h(e),t))}update_collection(e,t){const i=A(t,r.__wbindgen_malloc),n=m;return S(r.cipheradminclient_update_collection(this.__wbg_ptr,h(e),i,n))}edit(e,t){return S(r.cipheradminclient_edit(this.__wbg_ptr,h(e),h(t)))}create(e){return S(r.cipheradminclient_create(this.__wbg_ptr,h(e)))}delete_many(e,t){const i=A(e,r.__wbindgen_malloc),n=m;return S(r.cipheradminclient_delete_many(this.__wbg_ptr,i,n,h(t)))}soft_delete(e){return S(r.cipheradminclient_soft_delete(this.__wbg_ptr,h(e)))}soft_delete_many(e,t){const i=A(e,r.__wbindgen_malloc),n=m;return S(r.cipheradminclient_soft_delete_many(this.__wbg_ptr,i,n,h(t)))}delete(e){return S(r.cipheradminclient_delete(this.__wbg_ptr,h(e)))}restore_many(e,t){const i=A(e,r.__wbindgen_malloc),n=m;return S(r.cipheradminclient_restore_many(this.__wbg_ptr,i,n,h(t)))}restore(e){return S(r.cipheradminclient_restore(this.__wbg_ptr,h(e)))}}Symbol.dispose&&(H.prototype[Symbol.dispose]=H.prototype.free);const G="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_cipherriskclient_free(e>>>0,1));class Q{static __wrap(e){e>>>=0;const t=Object.create(Q.prototype);return t.__wbg_ptr=e,G.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,G.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_cipherriskclient_free(e,0)}compute_risk(e,t){const i=A(e,r.__wbindgen_malloc),n=m;return S(r.cipherriskclient_compute_risk(this.__wbg_ptr,i,n,h(t)))}password_reuse_map(e){const t=A(e,r.__wbindgen_malloc),i=m;return S(r.cipherriskclient_password_reuse_map(this.__wbg_ptr,t,i))}}Symbol.dispose&&(Q.prototype[Symbol.dispose]=Q.prototype.free);const J="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_ciphersclient_free(e>>>0,1));class Y{static __wrap(e){e>>>=0;const t=Object.create(Y.prototype);return t.__wbg_ptr=e,J.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,J.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_ciphersclient_free(e,0)}share_cipher(e,t,i,n){const a=A(i,r.__wbindgen_malloc),s=m;return S(r.ciphersclient_share_cipher(this.__wbg_ptr,h(e),h(t),a,s,b(n)?0:h(n)))}share_ciphers_bulk(e,t,i){const n=A(e,r.__wbindgen_malloc),a=m,s=A(i,r.__wbindgen_malloc),o=m;return S(r.ciphersclient_share_ciphers_bulk(this.__wbg_ptr,n,a,h(t),s,o))}decrypt_list(e){try{const s=r.__wbindgen_add_to_stack_pointer(-16),o=A(e,r.__wbindgen_malloc),l=m;r.ciphersclient_decrypt_list(s,this.__wbg_ptr,o,l);var t=v().getInt32(s+0,!0),i=v().getInt32(s+4,!0),n=v().getInt32(s+8,!0);if(v().getInt32(s+12,!0))throw S(n);var a=I(t,i).slice();return r.__wbindgen_free(t,4*i,4),a}finally{r.__wbindgen_add_to_stack_pointer(16)}}encrypt_list(e){try{const s=r.__wbindgen_add_to_stack_pointer(-16),o=A(e,r.__wbindgen_malloc),l=m;r.ciphersclient_encrypt_list(s,this.__wbg_ptr,o,l);var t=v().getInt32(s+0,!0),i=v().getInt32(s+4,!0),n=v().getInt32(s+8,!0);if(v().getInt32(s+12,!0))throw S(n);var a=I(t,i).slice();return r.__wbindgen_free(t,4*i,4),a}finally{r.__wbindgen_add_to_stack_pointer(16)}}move_to_organization(e,t){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ciphersclient_move_to_organization(a,this.__wbg_ptr,h(e),h(t));var i=v().getInt32(a+0,!0),n=v().getInt32(a+4,!0);if(v().getInt32(a+8,!0))throw S(n);return S(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}set_fido2_credentials(e,t){try{const a=r.__wbindgen_add_to_stack_pointer(-16),s=A(t,r.__wbindgen_malloc),o=m;r.ciphersclient_set_fido2_credentials(a,this.__wbg_ptr,h(e),s,o);var i=v().getInt32(a+0,!0),n=v().getInt32(a+4,!0);if(v().getInt32(a+8,!0))throw S(n);return S(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}decrypt_fido2_credentials(e){try{const s=r.__wbindgen_add_to_stack_pointer(-16);r.ciphersclient_decrypt_fido2_credentials(s,this.__wbg_ptr,h(e));var t=v().getInt32(s+0,!0),i=v().getInt32(s+4,!0),n=v().getInt32(s+8,!0);if(v().getInt32(s+12,!0))throw S(n);var a=I(t,i).slice();return r.__wbindgen_free(t,4*i,4),a}finally{r.__wbindgen_add_to_stack_pointer(16)}}decrypt_fido2_private_key(e){let t,i;try{const d=r.__wbindgen_add_to_stack_pointer(-16);r.ciphersclient_decrypt_fido2_private_key(d,this.__wbg_ptr,h(e));var n=v().getInt32(d+0,!0),a=v().getInt32(d+4,!0),s=v().getInt32(d+8,!0),o=v().getInt32(d+12,!0),l=n,u=a;if(o)throw l=0,u=0,S(s);return t=l,i=u,c(l,u)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(t,i,1)}}decrypt_list_with_failures(e){const t=A(e,r.__wbindgen_malloc),i=m;return S(r.ciphersclient_decrypt_list_with_failures(this.__wbg_ptr,t,i))}encrypt_cipher_for_rotation(e,t){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.ciphersclient_encrypt_cipher_for_rotation(a,this.__wbg_ptr,h(e),h(t));var i=v().getInt32(a+0,!0),n=v().getInt32(a+4,!0);if(v().getInt32(a+8,!0))throw S(n);return S(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}decrypt_list_full_with_failures(e){const t=A(e,r.__wbindgen_malloc),i=m;return S(r.ciphersclient_decrypt_list_full_with_failures(this.__wbg_ptr,t,i))}admin(){const e=r.ciphersclient_admin(this.__wbg_ptr);return H.__wrap(e)}decrypt(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ciphersclient_decrypt(n,this.__wbg_ptr,h(e));var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}encrypt(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.ciphersclient_encrypt(n,this.__wbg_ptr,h(e));var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}get(e){const t=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;return S(r.ciphersclient_get(this.__wbg_ptr,t,i))}list(){return S(r.ciphersclient_list(this.__wbg_ptr))}update_collection(e,t,i){const n=A(t,r.__wbindgen_malloc),a=m;return S(r.ciphersclient_update_collection(this.__wbg_ptr,h(e),n,a,i))}edit(e){return S(r.ciphersclient_edit(this.__wbg_ptr,h(e)))}create(e){return S(r.ciphersclient_create(this.__wbg_ptr,h(e)))}delete_many(e,t){const i=A(e,r.__wbindgen_malloc),n=m;return S(r.ciphersclient_delete_many(this.__wbg_ptr,i,n,b(t)?0:h(t)))}soft_delete(e){return S(r.ciphersclient_soft_delete(this.__wbg_ptr,h(e)))}soft_delete_many(e,t){const i=A(e,r.__wbindgen_malloc),n=m;return S(r.ciphersclient_soft_delete_many(this.__wbg_ptr,i,n,b(t)?0:h(t)))}delete(e){return S(r.ciphersclient_delete(this.__wbg_ptr,h(e)))}restore_many(e){const t=A(e,r.__wbindgen_malloc),i=m;return S(r.ciphersclient_restore_many(this.__wbg_ptr,t,i))}restore(e){return S(r.ciphersclient_restore(this.__wbg_ptr,h(e)))}}Symbol.dispose&&(Y.prototype[Symbol.dispose]=Y.prototype.free);const X="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_collectionviewnodeitem_free(e>>>0,1));class Z{static __wrap(e){e>>>=0;const t=Object.create(Z.prototype);return t.__wbg_ptr=e,X.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,X.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_collectionviewnodeitem_free(e,0)}get_parent(){return S(r.collectionviewnodeitem_get_parent(this.__wbg_ptr))}get_children(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.collectionviewnodeitem_get_children(n,this.__wbg_ptr);var e=v().getInt32(n+0,!0),t=v().getInt32(n+4,!0),i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),i}finally{r.__wbindgen_add_to_stack_pointer(16)}}get_ancestors(){return S(r.collectionviewnodeitem_get_ancestors(this.__wbg_ptr))}get_item(){return S(r.collectionviewnodeitem_get_item(this.__wbg_ptr))}}Symbol.dispose&&(Z.prototype[Symbol.dispose]=Z.prototype.free);const ee="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_collectionviewtree_free(e>>>0,1));class te{static __wrap(e){e>>>=0;const t=Object.create(te.prototype);return t.__wbg_ptr=e,ee.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ee.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_collectionviewtree_free(e,0)}get_flat_items(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.collectionviewtree_get_flat_items(n,this.__wbg_ptr);var e=v().getInt32(n+0,!0),t=v().getInt32(n+4,!0),i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),i}finally{r.__wbindgen_add_to_stack_pointer(16)}}get_root_items(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.collectionviewtree_get_root_items(n,this.__wbg_ptr);var e=v().getInt32(n+0,!0),t=v().getInt32(n+4,!0),i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),i}finally{r.__wbindgen_add_to_stack_pointer(16)}}get_item_for_view(e){const t=r.collectionviewtree_get_item_for_view(this.__wbg_ptr,h(e));return 0===t?void 0:Z.__wrap(t)}}Symbol.dispose&&(te.prototype[Symbol.dispose]=te.prototype.free);const ie="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_collectionsclient_free(e>>>0,1));class re{static __wrap(e){e>>>=0;const t=Object.create(re.prototype);return t.__wbg_ptr=e,ie.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ie.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_collectionsclient_free(e,0)}decrypt_list(e){try{const s=r.__wbindgen_add_to_stack_pointer(-16),o=A(e,r.__wbindgen_malloc),l=m;r.collectionsclient_decrypt_list(s,this.__wbg_ptr,o,l);var t=v().getInt32(s+0,!0),i=v().getInt32(s+4,!0),n=v().getInt32(s+8,!0);if(v().getInt32(s+12,!0))throw S(n);var a=I(t,i).slice();return r.__wbindgen_free(t,4*i,4),a}finally{r.__wbindgen_add_to_stack_pointer(16)}}get_collection_tree(e){const t=A(e,r.__wbindgen_malloc),i=m,n=r.collectionsclient_get_collection_tree(this.__wbg_ptr,t,i);return te.__wrap(n)}decrypt(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.collectionsclient_decrypt(n,this.__wbg_ptr,h(e));var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(re.prototype[Symbol.dispose]=re.prototype.free);const ne="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_cryptoclient_free(e>>>0,1));class ae{static __wrap(e){e>>>=0;const t=Object.create(ae.prototype);return t.__wbg_ptr=e,ne.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ne.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_cryptoclient_free(e,0)}enroll_pin(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16),a=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),s=m;r.cryptoclient_enroll_pin(n,this.__wbg_ptr,a,s);var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}make_key_pair(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.cryptoclient_make_key_pair(n,this.__wbg_ptr,h(e));var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}make_update_kdf(e,t){try{const a=r.__wbindgen_add_to_stack_pointer(-16),s=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),o=m;r.cryptoclient_make_update_kdf(a,this.__wbg_ptr,s,o,h(t));var i=v().getInt32(a+0,!0),n=v().getInt32(a+4,!0);if(v().getInt32(a+8,!0))throw S(n);return S(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}initialize_org_crypto(e){return S(r.cryptoclient_initialize_org_crypto(this.__wbg_ptr,h(e)))}initialize_user_crypto(e){return S(r.cryptoclient_initialize_user_crypto(this.__wbg_ptr,h(e)))}verify_asymmetric_keys(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.cryptoclient_verify_asymmetric_keys(n,this.__wbg_ptr,h(e));var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}get_v2_rotated_account_keys(){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.cryptoclient_get_v2_rotated_account_keys(i,this.__wbg_ptr);var e=v().getInt32(i+0,!0),t=v().getInt32(i+4,!0);if(v().getInt32(i+8,!0))throw S(t);return S(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}make_keys_for_user_crypto_v2(){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.cryptoclient_make_keys_for_user_crypto_v2(i,this.__wbg_ptr);var e=v().getInt32(i+0,!0),t=v().getInt32(i+4,!0);if(v().getInt32(i+8,!0))throw S(t);return S(e)}finally{r.__wbindgen_add_to_stack_pointer(16)}}enroll_pin_with_encrypted_pin(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16),a=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),s=m;r.cryptoclient_enroll_pin_with_encrypted_pin(n,this.__wbg_ptr,a,s);var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}unseal_password_protected_key_envelope(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=f(t,r.__wbindgen_malloc,r.__wbindgen_realloc),d=m;r.cryptoclient_unseal_password_protected_key_envelope(o,this.__wbg_ptr,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(ae.prototype[Symbol.dispose]=ae.prototype.free);const se="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_exporterclient_free(e>>>0,1));class oe{static __wrap(e){e>>>=0;const t=Object.create(oe.prototype);return t.__wbg_ptr=e,se.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,se.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_exporterclient_free(e,0)}export_cxf(e,t){let i,n;try{const p=r.__wbindgen_add_to_stack_pointer(-16),g=A(t,r.__wbindgen_malloc),f=m;r.exporterclient_export_cxf(p,this.__wbg_ptr,h(e),g,f);var a=v().getInt32(p+0,!0),s=v().getInt32(p+4,!0),o=v().getInt32(p+8,!0),l=v().getInt32(p+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}import_cxf(e){try{const s=r.__wbindgen_add_to_stack_pointer(-16),o=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),l=m;r.exporterclient_import_cxf(s,this.__wbg_ptr,o,l);var t=v().getInt32(s+0,!0),i=v().getInt32(s+4,!0),n=v().getInt32(s+8,!0);if(v().getInt32(s+12,!0))throw S(n);var a=I(t,i).slice();return r.__wbindgen_free(t,4*i,4),a}finally{r.__wbindgen_add_to_stack_pointer(16)}}export_vault(e,t,i){let n,a;try{const g=r.__wbindgen_add_to_stack_pointer(-16),f=A(e,r.__wbindgen_malloc),y=m,b=A(t,r.__wbindgen_malloc),w=m;r.exporterclient_export_vault(g,this.__wbg_ptr,f,y,b,w,h(i));var s=v().getInt32(g+0,!0),o=v().getInt32(g+4,!0),l=v().getInt32(g+8,!0),u=v().getInt32(g+12,!0),d=s,p=o;if(u)throw d=0,p=0,S(l);return n=d,a=p,c(d,p)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(n,a,1)}}export_organization_vault(e,t,i){let n,a;try{const g=r.__wbindgen_add_to_stack_pointer(-16),f=A(e,r.__wbindgen_malloc),y=m,b=A(t,r.__wbindgen_malloc),w=m;r.exporterclient_export_organization_vault(g,this.__wbg_ptr,f,y,b,w,h(i));var s=v().getInt32(g+0,!0),o=v().getInt32(g+4,!0),l=v().getInt32(g+8,!0),u=v().getInt32(g+12,!0),d=s,p=o;if(u)throw d=0,p=0,S(l);return n=d,a=p,c(d,p)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(n,a,1)}}}Symbol.dispose&&(oe.prototype[Symbol.dispose]=oe.prototype.free);const le="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_foldersclient_free(e>>>0,1));class ce{static __wrap(e){e>>>=0;const t=Object.create(ce.prototype);return t.__wbg_ptr=e,le.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,le.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_foldersclient_free(e,0)}decrypt_list(e){try{const s=r.__wbindgen_add_to_stack_pointer(-16),o=A(e,r.__wbindgen_malloc),l=m;r.foldersclient_decrypt_list(s,this.__wbg_ptr,o,l);var t=v().getInt32(s+0,!0),i=v().getInt32(s+4,!0),n=v().getInt32(s+8,!0);if(v().getInt32(s+12,!0))throw S(n);var a=I(t,i).slice();return r.__wbindgen_free(t,4*i,4),a}finally{r.__wbindgen_add_to_stack_pointer(16)}}get(e){return S(r.foldersclient_get(this.__wbg_ptr,h(e)))}edit(e,t){return S(r.foldersclient_edit(this.__wbg_ptr,h(e),h(t)))}list(){return S(r.foldersclient_list(this.__wbg_ptr))}create(e){return S(r.foldersclient_create(this.__wbg_ptr,h(e)))}decrypt(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.foldersclient_decrypt(n,this.__wbg_ptr,h(e));var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}encrypt(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.foldersclient_encrypt(n,this.__wbg_ptr,h(e));var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(ce.prototype[Symbol.dispose]=ce.prototype.free);const ue="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_generatorclient_free(e>>>0,1));class de{static __wrap(e){e>>>=0;const t=Object.create(de.prototype);return t.__wbg_ptr=e,ue.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ue.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_generatorclient_free(e,0)}passphrase(e){let t,i;try{const d=r.__wbindgen_add_to_stack_pointer(-16);r.generatorclient_passphrase(d,this.__wbg_ptr,h(e));var n=v().getInt32(d+0,!0),a=v().getInt32(d+4,!0),s=v().getInt32(d+8,!0),o=v().getInt32(d+12,!0),l=n,u=a;if(o)throw l=0,u=0,S(s);return t=l,i=u,c(l,u)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(t,i,1)}}password(e){let t,i;try{const d=r.__wbindgen_add_to_stack_pointer(-16);r.generatorclient_password(d,this.__wbg_ptr,h(e));var n=v().getInt32(d+0,!0),a=v().getInt32(d+4,!0),s=v().getInt32(d+8,!0),o=v().getInt32(d+12,!0),l=n,u=a;if(o)throw l=0,u=0,S(s);return t=l,i=u,c(l,u)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(t,i,1)}}}Symbol.dispose&&(de.prototype[Symbol.dispose]=de.prototype.free);const he="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_incomingmessage_free(e>>>0,1));class pe{static __wrap(e){e>>>=0;const t=Object.create(pe.prototype);return t.__wbg_ptr=e,he.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,he.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_incomingmessage_free(e,0)}parse_payload_as_json(){return S(r.incomingmessage_parse_payload_as_json(this.__wbg_ptr))}constructor(e,t,i,n){const a=E(e,r.__wbindgen_malloc),s=m;var o=b(n)?0:f(n,r.__wbindgen_malloc,r.__wbindgen_realloc),l=m;const c=r.incomingmessage_new(a,s,h(t),h(i),o,l);return this.__wbg_ptr=c>>>0,he.register(this,this.__wbg_ptr,this),this}get payload(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.__wbg_get_incomingmessage_payload(n,this.__wbg_ptr);var e=v().getInt32(n+0,!0),t=v().getInt32(n+4,!0),i=_(e,t).slice();return r.__wbindgen_free(e,1*t,1),i}finally{r.__wbindgen_add_to_stack_pointer(16)}}set payload(e){const t=E(e,r.__wbindgen_malloc),i=m;r.__wbg_set_incomingmessage_payload(this.__wbg_ptr,t,i)}get destination(){return S(r.__wbg_get_incomingmessage_destination(this.__wbg_ptr))}set destination(e){r.__wbg_set_incomingmessage_destination(this.__wbg_ptr,h(e))}get source(){return S(r.__wbg_get_incomingmessage_source(this.__wbg_ptr))}set source(e){r.__wbg_set_incomingmessage_source(this.__wbg_ptr,h(e))}get topic(){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.__wbg_get_incomingmessage_topic(i,this.__wbg_ptr);var e=v().getInt32(i+0,!0),t=v().getInt32(i+4,!0);let n;return 0!==e&&(n=c(e,t).slice(),r.__wbindgen_free(e,1*t,1)),n}finally{r.__wbindgen_add_to_stack_pointer(16)}}set topic(e){var t=b(e)?0:f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;r.__wbg_set_incomingmessage_topic(this.__wbg_ptr,t,i)}}Symbol.dispose&&(pe.prototype[Symbol.dispose]=pe.prototype.free);const me="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_ipcclient_free(e>>>0,1));class ge{static __wrap(e){e>>>=0;const t=Object.create(ge.prototype);return t.__wbg_ptr=e,me.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,me.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_ipcclient_free(e,0)}isRunning(){return S(r.ipcclient_isRunning(this.__wbg_ptr))}static newWithSdkInMemorySessions(e){j(e,be);const t=r.ipcclient_newWithSdkInMemorySessions(e.__wbg_ptr);return ge.__wrap(t)}static newWithClientManagedSessions(e,t){j(e,be);const i=r.ipcclient_newWithClientManagedSessions(e.__wbg_ptr,h(t));return ge.__wrap(i)}send(e){j(e,_e);var t=e.__destroy_into_raw();return S(r.ipcclient_send(this.__wbg_ptr,t))}start(){return S(r.ipcclient_start(this.__wbg_ptr))}subscribe(){return S(r.ipcclient_subscribe(this.__wbg_ptr))}}Symbol.dispose&&(ge.prototype[Symbol.dispose]=ge.prototype.free);const fe="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_ipcclientsubscription_free(e>>>0,1));class ye{static __wrap(e){e>>>=0;const t=Object.create(ye.prototype);return t.__wbg_ptr=e,fe.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,fe.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_ipcclientsubscription_free(e,0)}receive(e){return S(r.ipcclientsubscription_receive(this.__wbg_ptr,b(e)?0:h(e)))}}Symbol.dispose&&(ye.prototype[Symbol.dispose]=ye.prototype.free);const ve="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_ipccommunicationbackend_free(e>>>0,1));class be{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ve.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_ipccommunicationbackend_free(e,0)}constructor(e){const t=r.ipccommunicationbackend_new(h(e));return this.__wbg_ptr=t>>>0,ve.register(this,this.__wbg_ptr,this),this}receive(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16);j(e,pe);var t=e.__destroy_into_raw();r.ipccommunicationbackend_receive(n,this.__wbg_ptr,t);var i=v().getInt32(n+0,!0);if(v().getInt32(n+4,!0))throw S(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(be.prototype[Symbol.dispose]=be.prototype.free);const we="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_loginclient_free(e>>>0,1));class ke{static __wrap(e){e>>>=0;const t=Object.create(ke.prototype);return t.__wbg_ptr=e,we.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,we.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_loginclient_free(e,0)}get_password_prelogin(e){const t=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;return S(r.loginclient_get_password_prelogin(this.__wbg_ptr,t,i))}login_via_password(e){return S(r.loginclient_login_via_password(this.__wbg_ptr,h(e)))}}Symbol.dispose&&(ke.prototype[Symbol.dispose]=ke.prototype.free);const Se="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_outgoingmessage_free(e>>>0,1));class _e{static __wrap(e){e>>>=0;const t=Object.create(_e.prototype);return t.__wbg_ptr=e,Se.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Se.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_outgoingmessage_free(e,0)}static new_json_payload(e,t,i){try{const l=r.__wbindgen_add_to_stack_pointer(-16);var n=b(i)?0:f(i,r.__wbindgen_malloc,r.__wbindgen_realloc),a=m;r.outgoingmessage_new_json_payload(l,h(e),h(t),n,a);var s=v().getInt32(l+0,!0),o=v().getInt32(l+4,!0);if(v().getInt32(l+8,!0))throw S(o);return _e.__wrap(s)}finally{r.__wbindgen_add_to_stack_pointer(16)}}constructor(e,t,i){const n=E(e,r.__wbindgen_malloc),a=m;var s=b(i)?0:f(i,r.__wbindgen_malloc,r.__wbindgen_realloc),o=m;const l=r.outgoingmessage_new(n,a,h(t),s,o);return this.__wbg_ptr=l>>>0,Se.register(this,this.__wbg_ptr,this),this}get payload(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.__wbg_get_outgoingmessage_payload(n,this.__wbg_ptr);var e=v().getInt32(n+0,!0),t=v().getInt32(n+4,!0),i=_(e,t).slice();return r.__wbindgen_free(e,1*t,1),i}finally{r.__wbindgen_add_to_stack_pointer(16)}}set payload(e){const t=E(e,r.__wbindgen_malloc),i=m;r.__wbg_set_outgoingmessage_payload(this.__wbg_ptr,t,i)}get destination(){return S(r.__wbg_get_incomingmessage_destination(this.__wbg_ptr))}set destination(e){r.__wbg_set_incomingmessage_destination(this.__wbg_ptr,h(e))}get topic(){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.__wbg_get_outgoingmessage_topic(i,this.__wbg_ptr);var e=v().getInt32(i+0,!0),t=v().getInt32(i+4,!0);let n;return 0!==e&&(n=c(e,t).slice(),r.__wbindgen_free(e,1*t,1)),n}finally{r.__wbindgen_add_to_stack_pointer(16)}}set topic(e){var t=b(e)?0:f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;r.__wbg_set_outgoingmessage_topic(this.__wbg_ptr,t,i)}}Symbol.dispose&&(_e.prototype[Symbol.dispose]=_e.prototype.free);const xe="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_passwordmanagerclient_free(e>>>0,1));class Ce{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,xe.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_passwordmanagerclient_free(e,0)}user_crypto_management(){const e=r.passwordmanagerclient_user_crypto_management(this.__wbg_ptr);return Be.__wrap(e)}constructor(e,t){const i=r.passwordmanagerclient_new(h(e),b(t)?0:h(t));return this.__wbg_ptr=i>>>0,xe.register(this,this.__wbg_ptr,this),this}auth(){const e=r.passwordmanagerclient_auth(this.__wbg_ptr);return K.__wrap(e)}echo(e){let t,i;try{const s=r.__wbindgen_add_to_stack_pointer(-16),o=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),l=m;r.passwordmanagerclient_echo(s,this.__wbg_ptr,o,l);var n=v().getInt32(s+0,!0),a=v().getInt32(s+4,!0);return t=n,i=a,c(n,a)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(t,i,1)}}throw(e){try{const i=r.__wbindgen_add_to_stack_pointer(-16),n=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),a=m;r.passwordmanagerclient_throw(i,this.__wbg_ptr,n,a);var t=v().getInt32(i+0,!0);if(v().getInt32(i+4,!0))throw S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}vault(){const e=r.passwordmanagerclient_vault(this.__wbg_ptr);return Ve.__wrap(e)}crypto(){const e=r.passwordmanagerclient_crypto(this.__wbg_ptr);return ae.__wrap(e)}version(){let e,t;try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.passwordmanagerclient_version(a,this.__wbg_ptr);var i=v().getInt32(a+0,!0),n=v().getInt32(a+4,!0);return e=i,t=n,c(i,n)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(e,t,1)}}http_get(e){const t=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;return S(r.passwordmanagerclient_http_get(this.__wbg_ptr,t,i))}platform(){const e=r.passwordmanagerclient_platform(this.__wbg_ptr);return Ee.__wrap(e)}exporters(){const e=r.passwordmanagerclient_exporters(this.__wbg_ptr);return oe.__wrap(e)}generator(){const e=r.passwordmanagerclient_generator(this.__wbg_ptr);return de.__wrap(e)}}Symbol.dispose&&(Ce.prototype[Symbol.dispose]=Ce.prototype.free);const Ie="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_platformclient_free(e>>>0,1));class Ee{static __wrap(e){e>>>=0;const t=Object.create(Ee.prototype);return t.__wbg_ptr=e,Ie.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ie.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_platformclient_free(e,0)}load_flags(e){try{const i=r.__wbindgen_add_to_stack_pointer(-16);r.platformclient_load_flags(i,this.__wbg_ptr,h(e));var t=v().getInt32(i+0,!0);if(v().getInt32(i+4,!0))throw S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}state(){const e=r.passwordmanagerclient_platform(this.__wbg_ptr);return Ue.__wrap(e)}}Symbol.dispose&&(Ee.prototype[Symbol.dispose]=Ee.prototype.free);const ze="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_purecrypto_free(e>>>0,1));class Pe{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,ze.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_purecrypto_free(e,0)}static random_number(e,t){return r.purecrypto_random_number(e,t)>>>0}static rsa_decrypt_data(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=E(e,r.__wbindgen_malloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_rsa_decrypt_data(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static rsa_encrypt_data(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=E(e,r.__wbindgen_malloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_rsa_encrypt_data(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static symmetric_decrypt(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),g=m,y=E(t,r.__wbindgen_malloc),b=m;r.purecrypto_symmetric_decrypt(h,p,g,y,b);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static wrap_symmetric_key(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=E(e,r.__wbindgen_malloc),g=m,f=E(t,r.__wbindgen_malloc),y=m;r.purecrypto_wrap_symmetric_key(h,p,g,f,y);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static derive_kdf_material(e,t,i){try{const l=r.__wbindgen_add_to_stack_pointer(-16),c=E(e,r.__wbindgen_malloc),u=m,d=E(t,r.__wbindgen_malloc),p=m;r.purecrypto_derive_kdf_material(l,c,u,d,p,h(i));var n=v().getInt32(l+0,!0),a=v().getInt32(l+4,!0),s=v().getInt32(l+8,!0);if(v().getInt32(l+12,!0))throw S(s);var o=_(n,a).slice();return r.__wbindgen_free(n,1*a,1),o}finally{r.__wbindgen_add_to_stack_pointer(16)}}static rsa_generate_keypair(){try{const a=r.__wbindgen_add_to_stack_pointer(-16);r.purecrypto_rsa_generate_keypair(a);var e=v().getInt32(a+0,!0),t=v().getInt32(a+4,!0),i=v().getInt32(a+8,!0);if(v().getInt32(a+12,!0))throw S(i);var n=_(e,t).slice();return r.__wbindgen_free(e,1*t,1),n}finally{r.__wbindgen_add_to_stack_pointer(16)}}static unwrap_symmetric_key(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_unwrap_symmetric_key(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static rsa_extract_public_key(e){try{const s=r.__wbindgen_add_to_stack_pointer(-16),o=E(e,r.__wbindgen_malloc),l=m;r.purecrypto_rsa_extract_public_key(s,o,l);var t=v().getInt32(s+0,!0),i=v().getInt32(s+4,!0),n=v().getInt32(s+8,!0);if(v().getInt32(s+12,!0))throw S(n);var a=_(t,i).slice();return r.__wbindgen_free(t,1*i,1),a}finally{r.__wbindgen_add_to_stack_pointer(16)}}static wrap_decapsulation_key(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=E(e,r.__wbindgen_malloc),g=m,f=E(t,r.__wbindgen_malloc),y=m;r.purecrypto_wrap_decapsulation_key(h,p,g,f,y);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static wrap_encapsulation_key(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=E(e,r.__wbindgen_malloc),g=m,f=E(t,r.__wbindgen_malloc),y=m;r.purecrypto_wrap_encapsulation_key(h,p,g,f,y);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static symmetric_decrypt_bytes(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_symmetric_decrypt_bytes(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static symmetric_encrypt_bytes(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=E(e,r.__wbindgen_malloc),g=m,f=E(t,r.__wbindgen_malloc),y=m;r.purecrypto_symmetric_encrypt_bytes(h,p,g,f,y);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static decapsulate_key_unsigned(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_decapsulate_key_unsigned(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static encapsulate_key_unsigned(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=E(e,r.__wbindgen_malloc),g=m,f=E(t,r.__wbindgen_malloc),y=m;r.purecrypto_encapsulate_key_unsigned(h,p,g,f,y);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static symmetric_decrypt_string(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),g=m,y=E(t,r.__wbindgen_malloc),b=m;r.purecrypto_symmetric_decrypt_string(h,p,g,y,b);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static symmetric_encrypt_string(e,t){let i,n;try{const h=r.__wbindgen_add_to_stack_pointer(-16),p=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),g=m,y=E(t,r.__wbindgen_malloc),b=m;r.purecrypto_symmetric_encrypt_string(h,p,g,y,b);var a=v().getInt32(h+0,!0),s=v().getInt32(h+4,!0),o=v().getInt32(h+8,!0),l=v().getInt32(h+12,!0),u=a,d=s;if(l)throw u=0,d=0,S(o);return i=u,n=d,c(u,d)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(i,n,1)}}static unwrap_decapsulation_key(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_unwrap_decapsulation_key(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static unwrap_encapsulation_key(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_unwrap_encapsulation_key(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static symmetric_decrypt_filedata(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=E(e,r.__wbindgen_malloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_symmetric_decrypt_filedata(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static symmetric_encrypt_filedata(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=E(e,r.__wbindgen_malloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_symmetric_encrypt_filedata(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static make_user_key_aes256_cbc_hmac(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.purecrypto_make_user_key_aes256_cbc_hmac(n);var e=v().getInt32(n+0,!0),t=v().getInt32(n+4,!0),i=_(e,t).slice();return r.__wbindgen_free(e,1*t,1),i}finally{r.__wbindgen_add_to_stack_pointer(16)}}static verifying_key_for_signing_key(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_verifying_key_for_signing_key(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static symmetric_decrypt_array_buffer(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=E(e,r.__wbindgen_malloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_symmetric_decrypt_array_buffer(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static key_algorithm_for_verifying_key(e){try{const n=r.__wbindgen_add_to_stack_pointer(-16),a=E(e,r.__wbindgen_malloc),s=m;r.purecrypto_key_algorithm_for_verifying_key(n,a,s);var t=v().getInt32(n+0,!0),i=v().getInt32(n+4,!0);if(v().getInt32(n+8,!0))throw S(i);return S(t)}finally{r.__wbindgen_add_to_stack_pointer(16)}}static decrypt_user_key_with_master_key(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_decrypt_user_key_with_master_key(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static make_user_key_xchacha20_poly1305(){try{const n=r.__wbindgen_add_to_stack_pointer(-16);r.purecrypto_make_user_key_xchacha20_poly1305(n);var e=v().getInt32(n+0,!0),t=v().getInt32(n+4,!0),i=_(e,t).slice();return r.__wbindgen_free(e,1*t,1),i}finally{r.__wbindgen_add_to_stack_pointer(16)}}static verify_and_unwrap_signed_public_key(e,t){try{const o=r.__wbindgen_add_to_stack_pointer(-16),l=E(e,r.__wbindgen_malloc),c=m,u=E(t,r.__wbindgen_malloc),d=m;r.purecrypto_verify_and_unwrap_signed_public_key(o,l,c,u,d);var i=v().getInt32(o+0,!0),n=v().getInt32(o+4,!0),a=v().getInt32(o+8,!0);if(v().getInt32(o+12,!0))throw S(a);var s=_(i,n).slice();return r.__wbindgen_free(i,1*n,1),s}finally{r.__wbindgen_add_to_stack_pointer(16)}}static decrypt_user_key_with_master_password(e,t,i,n){try{const c=r.__wbindgen_add_to_stack_pointer(-16),u=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),d=m,p=f(t,r.__wbindgen_malloc,r.__wbindgen_realloc),g=m,y=f(i,r.__wbindgen_malloc,r.__wbindgen_realloc),b=m;r.purecrypto_decrypt_user_key_with_master_password(c,u,d,p,g,y,b,h(n));var a=v().getInt32(c+0,!0),s=v().getInt32(c+4,!0),o=v().getInt32(c+8,!0);if(v().getInt32(c+12,!0))throw S(o);var l=_(a,s).slice();return r.__wbindgen_free(a,1*s,1),l}finally{r.__wbindgen_add_to_stack_pointer(16)}}static encrypt_user_key_with_master_password(e,t,i,n){let a,s;try{const y=r.__wbindgen_add_to_stack_pointer(-16),b=E(e,r.__wbindgen_malloc),w=m,k=f(t,r.__wbindgen_malloc,r.__wbindgen_realloc),_=m,x=f(i,r.__wbindgen_malloc,r.__wbindgen_realloc),C=m;r.purecrypto_encrypt_user_key_with_master_password(y,b,w,k,_,x,C,h(n));var o=v().getInt32(y+0,!0),l=v().getInt32(y+4,!0),u=v().getInt32(y+8,!0),d=v().getInt32(y+12,!0),p=o,g=l;if(d)throw p=0,g=0,S(u);return a=p,s=g,c(p,g)}finally{r.__wbindgen_add_to_stack_pointer(16),r.__wbindgen_free(a,s,1)}}}Symbol.dispose&&(Pe.prototype[Symbol.dispose]=Pe.prototype.free);const Ae="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_registrationclient_free(e>>>0,1));class je{static __wrap(e){e>>>=0;const t=Object.create(je.prototype);return t.__wbg_ptr=e,Ae.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Ae.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_registrationclient_free(e,0)}post_keys_for_tde_registration(e){return S(r.registrationclient_post_keys_for_tde_registration(this.__wbg_ptr,h(e)))}post_keys_for_jit_password_registration(e){return S(r.registrationclient_post_keys_for_jit_password_registration(this.__wbg_ptr,h(e)))}post_keys_for_key_connector_registration(e,t,i){const n=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),a=m,s=f(t,r.__wbindgen_malloc,r.__wbindgen_realloc),o=m;return S(r.registrationclient_post_keys_for_key_connector_registration(this.__wbg_ptr,n,a,s,o,h(i)))}}Symbol.dispose&&(je.prototype[Symbol.dispose]=je.prototype.free);const Te="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_sendaccessclient_free(e>>>0,1));class De{static __wrap(e){e>>>=0;const t=Object.create(De.prototype);return t.__wbg_ptr=e,Te.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Te.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_sendaccessclient_free(e,0)}request_send_access_token(e){return S(r.sendaccessclient_request_send_access_token(this.__wbg_ptr,h(e)))}}Symbol.dispose&&(De.prototype[Symbol.dispose]=De.prototype.free);const Oe="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_servercommunicationconfigclient_free(e>>>0,1));class Ne{__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Oe.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_servercommunicationconfigclient_free(e,0)}getConfig(e){const t=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;return S(r.servercommunicationconfigclient_getConfig(this.__wbg_ptr,t,i))}acquireCookie(e){const t=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;return S(r.servercommunicationconfigclient_acquireCookie(this.__wbg_ptr,t,i))}needsBootstrap(e){const t=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;return S(r.servercommunicationconfigclient_needsBootstrap(this.__wbg_ptr,t,i))}setCommunicationType(e,t){const i=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),n=m;return S(r.servercommunicationconfigclient_setCommunicationType(this.__wbg_ptr,i,n,h(t)))}constructor(e,t){const i=r.servercommunicationconfigclient_new(h(e),h(t));return this.__wbg_ptr=i>>>0,Oe.register(this,this.__wbg_ptr,this),this}cookies(e){const t=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),i=m;return S(r.servercommunicationconfigclient_cookies(this.__wbg_ptr,t,i))}}Symbol.dispose&&(Ne.prototype[Symbol.dispose]=Ne.prototype.free);const Re="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_stateclient_free(e>>>0,1));class Ue{static __wrap(e){e>>>=0;const t=Object.create(Ue.prototype);return t.__wbg_ptr=e,Re.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Re.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_stateclient_free(e,0)}initialize_state(e){return S(r.stateclient_initialize_state(this.__wbg_ptr,h(e)))}register_cipher_repository(e){r.stateclient_register_cipher_repository(this.__wbg_ptr,h(e))}register_folder_repository(e){r.stateclient_register_folder_repository(this.__wbg_ptr,h(e))}register_client_managed_repositories(e){r.stateclient_register_client_managed_repositories(this.__wbg_ptr,h(e))}}Symbol.dispose&&(Ue.prototype[Symbol.dispose]=Ue.prototype.free);const Fe="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_totpclient_free(e>>>0,1));class qe{static __wrap(e){e>>>=0;const t=Object.create(qe.prototype);return t.__wbg_ptr=e,Fe.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Fe.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_totpclient_free(e,0)}generate_totp(e,t){try{const a=r.__wbindgen_add_to_stack_pointer(-16),s=f(e,r.__wbindgen_malloc,r.__wbindgen_realloc),o=m;r.totpclient_generate_totp(a,this.__wbg_ptr,s,o,!b(t),b(t)?0:t);var i=v().getInt32(a+0,!0),n=v().getInt32(a+4,!0);if(v().getInt32(a+8,!0))throw S(n);return S(i)}finally{r.__wbindgen_add_to_stack_pointer(16)}}}Symbol.dispose&&(qe.prototype[Symbol.dispose]=qe.prototype.free);const Le="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_usercryptomanagementclient_free(e>>>0,1));class Be{static __wrap(e){e>>>=0;const t=Object.create(Be.prototype);return t.__wbg_ptr=e,Le.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Le.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_usercryptomanagementclient_free(e,0)}rotate_user_keys(e){return S(r.usercryptomanagementclient_rotate_user_keys(this.__wbg_ptr,h(e)))}get_untrusted_organization_public_keys(){return S(r.usercryptomanagementclient_get_untrusted_organization_public_keys(this.__wbg_ptr))}get_untrusted_emergency_access_public_keys(){return S(r.usercryptomanagementclient_get_untrusted_emergency_access_public_keys(this.__wbg_ptr))}}Symbol.dispose&&(Be.prototype[Symbol.dispose]=Be.prototype.free);const Me="undefined"==typeof FinalizationRegistry?{register:()=>{},unregister:()=>{}}:new FinalizationRegistry(e=>r.__wbg_vaultclient_free(e>>>0,1));class Ve{static __wrap(e){e>>>=0;const t=Object.create(Ve.prototype);return t.__wbg_ptr=e,Me.register(t,t.__wbg_ptr,t),t}__destroy_into_raw(){const e=this.__wbg_ptr;return this.__wbg_ptr=0,Me.unregister(this),e}free(){const e=this.__destroy_into_raw();r.__wbg_vaultclient_free(e,0)}attachments(){const e=r.ciphersclient_admin(this.__wbg_ptr);return V.__wrap(e)}cipher_risk(){const e=r.ciphersclient_admin(this.__wbg_ptr);return Q.__wrap(e)}collections(){const e=r.ciphersclient_admin(this.__wbg_ptr);return re.__wrap(e)}totp(){const e=r.ciphersclient_admin(this.__wbg_ptr);return qe.__wrap(e)}ciphers(){const e=r.ciphersclient_admin(this.__wbg_ptr);return Y.__wrap(e)}folders(){const e=r.ciphersclient_admin(this.__wbg_ptr);return ce.__wrap(e)}}function $e(e,t){return h(Error(c(e,t)))}function Ke(e){return Number(p(e))}function We(e,t){const i=f(String(p(t)),r.__wbindgen_malloc,r.__wbindgen_realloc),n=m;v().setInt32(e+4,n,!0),v().setInt32(e+0,i,!0)}function He(e,t){const i=p(t),r="bigint"==typeof i?i:void 0;v().setBigInt64(e+8,b(r)?BigInt(0):r,!0),v().setInt32(e+0,!b(r),!0)}function Ge(e){const t=p(e),i="boolean"==typeof t?t:void 0;return b(i)?16777215:i?1:0}function Qe(e,t){const i=f(w(p(t)),r.__wbindgen_malloc,r.__wbindgen_realloc),n=m;v().setInt32(e+4,n,!0),v().setInt32(e+0,i,!0)}function Je(e,t){return p(e)in p(t)}function Ye(e){return"bigint"==typeof p(e)}function Xe(e){return"function"==typeof p(e)}function Ze(e){return null===p(e)}function et(e){const t=p(e);return"object"==typeof t&&null!==t}function tt(e){return"string"==typeof p(e)}function it(e){return void 0===p(e)}function rt(e,t){return p(e)===p(t)}function nt(e,t){return p(e)==p(t)}function at(e,t){const i=p(t),r="number"==typeof i?i:void 0;v().setFloat64(e+8,b(r)?0:r,!0),v().setInt32(e+0,!b(r),!0)}function st(e,t){const i=p(t),n="string"==typeof i?i:void 0;var a=b(n)?0:f(n,r.__wbindgen_malloc,r.__wbindgen_realloc),s=m;v().setInt32(e+4,s,!0),v().setInt32(e+0,a,!0)}function ot(e,t){throw new Error(c(e,t))}function lt(e){p(e)._wbg_cb_unref()}function ct(e,t){p(e).abort(p(t))}function ut(){return k(function(e){p(e).abort()},arguments)}function dt(e){p(e).abort()}function ht(){return k(function(e,t,i){let n,a;try{return n=t,a=i,h(p(e).acquireCookies(c(t,i)))}finally{r.__wbindgen_free(n,a,1)}},arguments)}function pt(e,t,i,r){p(e).addEventListener(c(t,i),p(r))}function mt(){return k(function(e,t,i,r,n){p(e).append(c(t,i),c(r,n))},arguments)}function gt(){return k(function(e,t,i,r,n,a){p(e).append(c(t,i),p(r),c(n,a))},arguments)}function ft(){return k(function(e,t,i,r,n){p(e).append(c(t,i),c(r,n))},arguments)}function yt(){return k(function(e,t,i,r){p(e).append(c(t,i),p(r))},arguments)}function vt(){return k(function(e){return h(p(e).arrayBuffer())},arguments)}function bt(){return k(function(e,t,i){return h(p(e).call(p(t),p(i)))},arguments)}function wt(){return k(function(e,t){return h(p(e).call(p(t)))},arguments)}function kt(e){const t=p(e).cipher;return b(t)?0:h(t)}function St(e){return h(clearTimeout(S(e)))}function _t(e){return h(Z.__wrap(e))}function xt(){return k(function(e,t,i,r){return h(p(e).createObjectStore(c(t,i),p(r)))},arguments)}function Ct(e){return h(p(e).crypto)}function It(e,t,i,r){console.debug(p(e),p(t),p(i),p(r))}function Et(e){console.debug(p(e))}function zt(){return k(function(e,t,i){p(e).deleteObjectStore(c(t,i))},arguments)}function Pt(){return k(function(e,t){return h(p(e).delete(p(t)))},arguments)}function At(e){return p(e).done}function jt(e){return h(Object.entries(p(e)))}function Tt(){return k(function(e){const t=p(e).error;return b(t)?0:h(t)},arguments)}function Dt(e,t){let i,n;try{i=e,n=t,console.error(c(e,t))}finally{r.__wbindgen_free(i,n,1)}}function Ot(e){console.error(p(e))}function Nt(e,t,i,r){console.error(p(e),p(t),p(i),p(r))}function Rt(e){return h(fetch(p(e)))}function Ut(e,t){return h(p(e).fetch(p(t)))}function Ft(e){const t=p(e).folder;return b(t)?0:h(t)}function qt(){return k(function(e){return h(p(e).getAll())},arguments)}function Lt(e){return p(e).getFullYear()}function Bt(){return k(function(e,t){globalThis.crypto.getRandomValues(_(e,t))},arguments)}function Mt(){return k(function(e,t){globalThis.crypto.getRandomValues(_(e,t))},arguments)}function Vt(){return k(function(e,t){p(e).getRandomValues(p(t))},arguments)}function $t(e){return p(e).getTime()}function Kt(){return k(function(e,t,i){let n,a;try{return n=t,a=i,h(p(e).get(c(t,i)))}finally{r.__wbindgen_free(n,a,1)}},arguments)}function Wt(e,t){return h(p(e)[t>>>0])}function Ht(e){return h(p(e).get_access_token())}function Gt(){return k(function(e,t,i){let n,a;try{return n=t,a=i,h(p(e).get(c(t,i)))}finally{r.__wbindgen_free(n,a,1)}},arguments)}function Qt(){return k(function(e,t){return h(Reflect.get(p(e),p(t)))},arguments)}function Jt(){return k(function(e,t,i){let n,a;try{return n=t,a=i,h(p(e).get(c(t,i)))}finally{r.__wbindgen_free(n,a,1)}},arguments)}function Yt(){return k(function(e,t){return h(p(e).get(p(t)))},arguments)}function Xt(e,t){return h(p(e)[p(t)])}function Zt(){return k(function(e,t){return Reflect.has(p(e),p(t))},arguments)}function ei(e){return h(p(e).headers)}function ti(e){return h(pe.__wrap(e))}function ii(){return k(function(e){const t=p(e).indexedDB;return b(t)?0:h(t)},arguments)}function ri(){return k(function(e){const t=p(e).indexedDB;return b(t)?0:h(t)},arguments)}function ni(e,t,i,r){console.info(p(e),p(t),p(i),p(r))}function ai(e){console.info(p(e))}function si(e){let t;try{t=p(e)instanceof ArrayBuffer}catch(e){t=!1}return t}function oi(e){let t;try{t=p(e)instanceof DOMException}catch(e){t=!1}return t}function li(e){let t;try{t=p(e)instanceof IDBDatabase}catch(e){t=!1}return t}function ci(e){let t;try{t=p(e)instanceof IDBOpenDBRequest}catch(e){t=!1}return t}function ui(e){let t;try{t=p(e)instanceof IDBRequest}catch(e){t=!1}return t}function di(e){let t;try{t=p(e)instanceof Map}catch(e){t=!1}return t}function hi(e){let t;try{t=p(e)instanceof Response}catch(e){t=!1}return t}function pi(e){let t;try{t=p(e)instanceof Uint8Array}catch(e){t=!1}return t}function mi(e){let t;try{t=p(e)instanceof Window}catch(e){t=!1}return t}function gi(e){let t;try{t=p(e)instanceof WorkerGlobalScope}catch(e){t=!1}return t}function fi(e){return h(ye.__wrap(e))}function yi(e){return Array.isArray(p(e))}function vi(e){return Number.isSafeInteger(p(e))}function bi(){return h(Symbol.iterator)}function wi(e){return p(e).length}function ki(e){return p(e).length}function Si(){return k(function(e){return h(p(e).list())},arguments)}function _i(){return k(function(e){return h(p(e).list())},arguments)}function xi(e){return h(p(e).msCrypto)}function Ci(e,t){const i=f(p(t).name,r.__wbindgen_malloc,r.__wbindgen_realloc),n=m;v().setInt32(e+4,n,!0),v().setInt32(e+0,i,!0)}function Ii(){return h(new Date)}function Ei(e,t){let i,n;try{return i=e,n=t,h(new Error(c(e,t)))}finally{r.__wbindgen_free(i,n,1)}}function zi(){return h(new Object)}function Pi(){return k(function(){return h(new AbortController)},arguments)}function Ai(e,t){try{var i={a:e,b:t};const n=new Promise((e,t)=>{const n=i.a;i.a=0;try{return function(e,t,i,n){r.wasm_bindgen__convert__closures_____invoke__hc4d57ad329cc6f58(e,t,h(i),h(n))}(n,i.b,e,t)}finally{i.a=n}});return h(n)}finally{i.a=i.b=0}}function ji(e){return h(new Uint8Array(p(e)))}function Ti(){return h(new Map)}function Di(){return k(function(){return h(new FormData)},arguments)}function Oi(){return h(new Error)}function Ni(){return k(function(){return h(new Headers)},arguments)}function Ri(e,t){return h(new Error(c(e,t)))}function Ui(){return h(new Array)}function Fi(e,t){return h(new Uint8Array(_(e,t)))}function qi(e,t){return h(new Function(c(e,t)))}function Li(e){return h(new Uint8Array(e>>>0))}function Bi(e){return h(new Array(e>>>0))}function Mi(){return k(function(e,t,i){return h(new Request(c(e,t),p(i)))},arguments)}function Vi(){return k(function(e,t){return h(new Blob(p(e),p(t)))},arguments)}function $i(){return k(function(e){return h(p(e).next())},arguments)}function Ki(e){return h(p(e).next)}function Wi(e){return h(p(e).node)}function Hi(e){return p(e).now()}function Gi(){return k(function(e,t,i){return h(p(e).objectStore(c(t,i)))},arguments)}function Qi(){return k(function(e,t,i,r){return h(p(e).open(c(t,i),r>>>0))},arguments)}function Ji(){return k(function(e,t){return h(JSON.parse(c(e,t)))},arguments)}function Yi(e){p(e).preventDefault()}function Xi(e){return h(p(e).process)}function Zi(e,t,i){Uint8Array.prototype.set.call(_(e,t),p(i))}function er(e,t){return p(e).push(p(t))}function tr(){return k(function(e,t,i){return h(p(e).put(p(t),p(i)))},arguments)}function ir(e){return h(p(e).queueMicrotask)}function rr(e){queueMicrotask(p(e))}function nr(){return k(function(e,t){p(e).randomFillSync(S(t))},arguments)}function ar(){return k(function(e,t,i){let n,a;try{return n=t,a=i,h(p(e).remove(c(t,i)))}finally{r.__wbindgen_free(n,a,1)}},arguments)}function sr(){return k(function(e,t,i){let n,a;try{return n=t,a=i,h(p(e).remove(c(t,i)))}finally{r.__wbindgen_free(n,a,1)}},arguments)}function or(){return k(function(){return h(e.require)},arguments)}function lr(e){return h(Promise.resolve(p(e)))}function cr(){return k(function(e){return h(p(e).result)},arguments)}function ur(){return k(function(e,t,i,n){let a,s;try{return a=t,s=i,h(p(e).save(c(t,i),S(n)))}finally{r.__wbindgen_free(a,s,1)}},arguments)}function dr(){return k(function(e,t){return h(p(e).send(_e.__wrap(t)))},arguments)}function hr(e,t){return h(setTimeout(p(e),t))}function pr(e,t,i){p(e)[S(t)]=S(i)}function mr(){return k(function(e,t,i,n){let a,s;try{return a=t,s=i,h(p(e).set(c(t,i),S(n)))}finally{r.__wbindgen_free(a,s,1)}},arguments)}function gr(){return k(function(e,t,i,n){let a,s;try{return a=t,s=i,h(p(e).set(c(t,i),S(n)))}finally{r.__wbindgen_free(a,s,1)}},arguments)}function fr(e,t,i){return h(p(e).set(p(t),p(i)))}function yr(e,t){p(e).body=p(t)}function vr(e,t,i){p(e)[t>>>0]=S(i)}function br(e,t){p(e).cache=q[t]}function wr(e,t){p(e).credentials=L[t]}function kr(e,t){p(e).headers=p(t)}function Sr(e,t,i){p(e).method=c(t,i)}function _r(e,t){p(e).mode=B[t]}function xr(e,t,i){let n,a;try{n=t,a=i,p(e).name=c(t,i)}finally{r.__wbindgen_free(n,a,1)}}function Cr(e,t){p(e).onerror=p(t)}function Ir(e,t){p(e).onsuccess=p(t)}function Er(e,t){p(e).onupgradeneeded=p(t)}function zr(e,t){p(e).signal=p(t)}function Pr(e,t,i){p(e).type=c(t,i)}function Ar(e,t,i){let n,a;try{n=t,a=i,p(e).variant=c(t,i)}finally{r.__wbindgen_free(n,a,1)}}function jr(e){return h(p(e).signal)}function Tr(e,t){const i=f(p(t).stack,r.__wbindgen_malloc,r.__wbindgen_realloc),n=m;v().setInt32(e+4,n,!0),v().setInt32(e+0,i,!0)}function Dr(){const e=void 0===i.g?null:i.g;return b(e)?0:h(e)}function Or(){const e="undefined"==typeof globalThis?null:globalThis;return b(e)?0:h(e)}function Nr(){const e="undefined"==typeof self?null:self;return b(e)?0:h(e)}function Rr(){const e="undefined"==typeof window?null:window;return b(e)?0:h(e)}function Ur(){return h(performance)}function Fr(e){return p(e).status}function qr(){return k(function(e){return h(JSON.stringify(p(e)))},arguments)}function Lr(e,t,i){return h(p(e).subarray(t>>>0,i>>>0))}function Br(e){const t=p(e).target;return b(t)?0:h(t)}function Mr(){return k(function(e){return h(p(e).text())},arguments)}function Vr(e,t){return h(p(e).then(p(t)))}function $r(e,t,i){return h(p(e).then(p(t),p(i)))}function Kr(e){const t=p(e).transaction;return b(t)?0:h(t)}function Wr(){return k(function(e,t,i){return h(p(e).transaction(p(t),F[i]))},arguments)}function Hr(e,t){const i=f(p(t).url,r.__wbindgen_malloc,r.__wbindgen_realloc),n=m;v().setInt32(e+4,n,!0),v().setInt32(e+0,i,!0)}function Gr(e){return h(p(e).value)}function Qr(e){return h(p(e).versions)}function Jr(e){console.warn(p(e))}function Yr(e,t,i,r){console.warn(p(e),p(t),p(i),p(r))}function Xr(e,t){return h(C(e,t,r.wasm_bindgen__closure__destroy__ha6acfc0fc44e75c9,D))}function Zr(e,t){return h(c(e,t))}function en(e,t){return h(C(e,t,r.wasm_bindgen__closure__destroy__h14b8abadf056d28e,O))}function tn(e,t){return h(C(e,t,r.wasm_bindgen__closure__destroy__hb3274d877c18ac57,D))}function rn(e,t){return h(C(e,t,r.wasm_bindgen__closure__destroy__hb3274d877c18ac57,N))}function nn(e){return h(BigInt.asUintN(64,e))}function an(e,t){var i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),h(i)}function sn(e,t){return h(C(e,t,r.wasm_bindgen__closure__destroy__h2b9785764fab287c,O))}function on(e,t){var i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),h(i)}function ln(e,t){var i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),h(i)}function cn(e,t){return h(C(e,t,r.wasm_bindgen__closure__destroy__h14b8abadf056d28e,D))}function un(e){return h(e)}function dn(e,t){var i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),h(i)}function hn(e,t){return h(_(e,t))}function pn(e){return h(e)}function mn(e,t){var i=I(e,t).slice();return r.__wbindgen_free(e,4*t,4),h(i)}function gn(e){return h(p(e))}function fn(e){S(e)}Symbol.dispose&&(Ve.prototype[Symbol.dispose]=Ve.prototype.free)},6423(e,t,i){"use strict";var r,n=i(9903),a=i(9336);try{r=[].__proto__===Array.prototype}catch(e){if(!e||"object"!=typeof e||!("code"in e)||"ERR_PROTO_ACCESS"!==e.code)throw e}var s=!!r&&a&&a(Object.prototype,"__proto__"),o=Object,l=o.getPrototypeOf;e.exports=s&&"function"==typeof s.get?n([s.get]):"function"==typeof l&&function(e){return l(null==e?e:o(e))}},6486(e,t,i){"use strict";const r=i(7229),n=i(7851);e.exports=(e,t,i)=>{const a=[];let s=null,o=null;const l=e.sort((e,t)=>n(e,t,i));for(const e of l)r(e,t,i)?(o=e,s||(s=e)):(o&&a.push([s,o]),o=null,s=null);s&&a.push([s,null]);const c=[];for(const[e,t]of a)e===t?c.push(e):t||e!==l[0]?t?e===l[0]?c.push(`<=${t}`):c.push(`${e} - ${t}`):c.push(`>=${e}`):c.push("*");const u=c.join(" || "),d="string"==typeof t.raw?t.raw:String(t);return u.length0?Math.floor(e):Math.ceil(e)}function y(e,i){var r,n,a=e.length,s=i.length,o=new Array(a),l=0,c=t;for(n=0;n=c?1:0,o[n]=r-l*c;for(;n0&&o.push(l),o}function v(e,t){return e.length>=t.length?y(e,t):y(t,e)}function b(e,i){var r,n,a=e.length,s=new Array(a),o=t;for(n=0;n0;)s[n++]=i%o,i=Math.floor(i/o);return s}function w(e,i){var r,n,a=e.length,s=i.length,o=new Array(a),l=0,c=t;for(r=0;r0;)s[n++]=l%o,l=Math.floor(l/o);return s}function x(e,t){for(var i=[];t-- >0;)i.push(0);return i.concat(e)}function C(e,t){var i=Math.max(e.length,t.length);if(i<=30)return S(e,t);i=Math.ceil(i/2);var r=e.slice(i),n=e.slice(0,i),a=t.slice(i),s=t.slice(0,i),o=C(n,s),l=C(r,a),c=C(v(n,r),v(s,a)),u=v(v(o,x(w(w(c,o),l),i)),x(l,2*i));return m(u),u}function I(e,i,r){return new l(e=0;--r)a=(s=a*c+e[r])-(n=f(s/i))*i,l[r]=0|n;return[l,0|a]}function P(e,i){var r,n=Q(i);if(s)return[new u(e.value/n.value),new u(e.value%n.value)];var a,d=e.value,y=n.value;if(0===y)throw new Error("Cannot divide by zero");if(e.isSmall)return n.isSmall?[new c(f(d/y)),new c(d%y)]:[o[0],e];if(n.isSmall){if(1===y)return[e,o[0]];if(-1==y)return[e.negate(),o[0]];var v=Math.abs(y);if(v=0;n--){for(r=h-1,v[n+d]!==f&&(r=Math.floor((v[n+d]*h+v[n+d-1])/f)),a=0,s=0,l=b.length,o=0;oc&&(a=(a+1)*h),r=Math.ceil(a/s);do{if(A(o=_(i,r),d)<=0)break;r--}while(r);u.push(r),d=w(d,o)}return u.reverse(),[p(u),p(d)]}(d,y),a=r[0];var S=e.sign!==n.sign,x=r[1],C=e.sign;return"number"==typeof a?(S&&(a=-a),a=new c(a)):a=new l(a,S),"number"==typeof x?(C&&(x=-x),x=new c(x)):x=new l(x,C),[a,x]}function A(e,t){if(e.length!==t.length)return e.length>t.length?1:-1;for(var i=e.length-1;i>=0;i--)if(e[i]!==t[i])return e[i]>t[i]?1:-1;return 0}function j(e){var t=e.abs();return!t.isUnit()&&(!!(t.equals(2)||t.equals(3)||t.equals(5))||!(t.isEven()||t.isDivisibleBy(3)||t.isDivisibleBy(5))&&(!!t.lesser(49)||void 0))}function T(e,t){for(var i,r,a,s=e.prev(),o=s,l=0;o.isEven();)o=o.divide(2),l++;e:for(r=0;r=0?r=w(e,t):(r=w(t,e),i=!i),"number"==typeof(r=p(r))?(i&&(r=-r),new c(r)):new l(r,i)}(i,r,this.sign)},l.prototype.minus=l.prototype.subtract,c.prototype.subtract=function(e){var t=Q(e),i=this.value;if(i<0!==t.sign)return this.add(t.negate());var r=t.value;return t.isSmall?new c(i-r):k(r,Math.abs(i),i>=0)},c.prototype.minus=c.prototype.subtract,u.prototype.subtract=function(e){return new u(this.value-Q(e).value)},u.prototype.minus=u.prototype.subtract,l.prototype.negate=function(){return new l(this.value,!this.sign)},c.prototype.negate=function(){var e=this.sign,t=new c(-this.value);return t.sign=!e,t},u.prototype.negate=function(){return new u(-this.value)},l.prototype.abs=function(){return new l(this.value,!1)},c.prototype.abs=function(){return new c(Math.abs(this.value))},u.prototype.abs=function(){return new u(this.value>=0?this.value:-this.value)},l.prototype.multiply=function(e){var i,r,n,a=Q(e),s=this.value,c=a.value,u=this.sign!==a.sign;if(a.isSmall){if(0===c)return o[0];if(1===c)return this;if(-1===c)return this.negate();if((i=Math.abs(c))0?C(s,c):S(s,c),u)},l.prototype.times=l.prototype.multiply,c.prototype._multiplyBySmall=function(e){return d(e.value*this.value)?new c(e.value*this.value):I(Math.abs(e.value),h(Math.abs(this.value)),this.sign!==e.sign)},l.prototype._multiplyBySmall=function(e){return 0===e.value?o[0]:1===e.value?this:-1===e.value?this.negate():I(Math.abs(e.value),this.value,this.sign!==e.sign)},c.prototype.multiply=function(e){return Q(e)._multiplyBySmall(this)},c.prototype.times=c.prototype.multiply,u.prototype.multiply=function(e){return new u(this.value*Q(e).value)},u.prototype.times=u.prototype.multiply,l.prototype.square=function(){return new l(E(this.value),!1)},c.prototype.square=function(){var e=this.value*this.value;return d(e)?new c(e):new l(E(h(Math.abs(this.value))),!1)},u.prototype.square=function(e){return new u(this.value*this.value)},l.prototype.divmod=function(e){var t=P(this,e);return{quotient:t[0],remainder:t[1]}},u.prototype.divmod=c.prototype.divmod=l.prototype.divmod,l.prototype.divide=function(e){return P(this,e)[0]},u.prototype.over=u.prototype.divide=function(e){return new u(this.value/Q(e).value)},c.prototype.over=c.prototype.divide=l.prototype.over=l.prototype.divide,l.prototype.mod=function(e){return P(this,e)[1]},u.prototype.mod=u.prototype.remainder=function(e){return new u(this.value%Q(e).value)},c.prototype.remainder=c.prototype.mod=l.prototype.remainder=l.prototype.mod,l.prototype.pow=function(e){var t,i,r,n=Q(e),a=this.value,s=n.value;if(0===s)return o[1];if(0===a)return o[0];if(1===a)return o[1];if(-1===a)return n.isEven()?o[1]:o[-1];if(n.sign)return o[0];if(!n.isSmall)throw new Error("The exponent "+n.toString()+" is too large.");if(this.isSmall&&d(t=Math.pow(a,s)))return new c(f(t));for(i=this,r=o[1];!0&s&&(r=r.times(i),--s),0!==s;)s/=2,i=i.square();return r},c.prototype.pow=l.prototype.pow,u.prototype.pow=function(e){var t=Q(e),i=this.value,r=t.value,n=BigInt(0),a=BigInt(1),s=BigInt(2);if(r===n)return o[1];if(i===n)return o[0];if(i===a)return o[1];if(i===BigInt(-1))return t.isEven()?o[1]:o[-1];if(t.isNegative())return new u(n);for(var l=this,c=o[1];(r&a)===a&&(c=c.times(l),--r),r!==n;)r/=s,l=l.square();return c},l.prototype.modPow=function(e,t){if(e=Q(e),(t=Q(t)).isZero())throw new Error("Cannot take modPow with modulus 0");var i=o[1],r=this.mod(t);for(e.isNegative()&&(e=e.multiply(o[-1]),r=r.modInv(t));e.isPositive();){if(r.isZero())return o[0];e.isOdd()&&(i=i.multiply(r).mod(t)),e=e.divide(2),r=r.square().mod(t)}return i},u.prototype.modPow=c.prototype.modPow=l.prototype.modPow,l.prototype.compareAbs=function(e){var t=Q(e),i=this.value,r=t.value;return t.isSmall?1:A(i,r)},c.prototype.compareAbs=function(e){var t=Q(e),i=Math.abs(this.value),r=t.value;return t.isSmall?i===(r=Math.abs(r))?0:i>r?1:-1:-1},u.prototype.compareAbs=function(e){var t=this.value,i=Q(e).value;return(t=t>=0?t:-t)===(i=i>=0?i:-i)?0:t>i?1:-1},l.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=Q(e),i=this.value,r=t.value;return this.sign!==t.sign?t.sign?1:-1:t.isSmall?this.sign?-1:1:A(i,r)*(this.sign?-1:1)},l.prototype.compareTo=l.prototype.compare,c.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=Q(e),i=this.value,r=t.value;return t.isSmall?i==r?0:i>r?1:-1:i<0!==t.sign?i<0?-1:1:i<0?1:-1},c.prototype.compareTo=c.prototype.compare,u.prototype.compare=function(e){if(e===1/0)return-1;if(e===-1/0)return 1;var t=this.value,i=Q(e).value;return t===i?0:t>i?1:-1},u.prototype.compareTo=u.prototype.compare,l.prototype.equals=function(e){return 0===this.compare(e)},u.prototype.eq=u.prototype.equals=c.prototype.eq=c.prototype.equals=l.prototype.eq=l.prototype.equals,l.prototype.notEquals=function(e){return 0!==this.compare(e)},u.prototype.neq=u.prototype.notEquals=c.prototype.neq=c.prototype.notEquals=l.prototype.neq=l.prototype.notEquals,l.prototype.greater=function(e){return this.compare(e)>0},u.prototype.gt=u.prototype.greater=c.prototype.gt=c.prototype.greater=l.prototype.gt=l.prototype.greater,l.prototype.lesser=function(e){return this.compare(e)<0},u.prototype.lt=u.prototype.lesser=c.prototype.lt=c.prototype.lesser=l.prototype.lt=l.prototype.lesser,l.prototype.greaterOrEquals=function(e){return this.compare(e)>=0},u.prototype.geq=u.prototype.greaterOrEquals=c.prototype.geq=c.prototype.greaterOrEquals=l.prototype.geq=l.prototype.greaterOrEquals,l.prototype.lesserOrEquals=function(e){return this.compare(e)<=0},u.prototype.leq=u.prototype.lesserOrEquals=c.prototype.leq=c.prototype.lesserOrEquals=l.prototype.leq=l.prototype.lesserOrEquals,l.prototype.isEven=function(){return!(1&this.value[0])},c.prototype.isEven=function(){return!(1&this.value)},u.prototype.isEven=function(){return(this.value&BigInt(1))===BigInt(0)},l.prototype.isOdd=function(){return!(1&~this.value[0])},c.prototype.isOdd=function(){return!(1&~this.value)},u.prototype.isOdd=function(){return(this.value&BigInt(1))===BigInt(1)},l.prototype.isPositive=function(){return!this.sign},c.prototype.isPositive=function(){return this.value>0},u.prototype.isPositive=c.prototype.isPositive,l.prototype.isNegative=function(){return this.sign},c.prototype.isNegative=function(){return this.value<0},u.prototype.isNegative=c.prototype.isNegative,l.prototype.isUnit=function(){return!1},c.prototype.isUnit=function(){return 1===Math.abs(this.value)},u.prototype.isUnit=function(){return this.abs().value===BigInt(1)},l.prototype.isZero=function(){return!1},c.prototype.isZero=function(){return 0===this.value},u.prototype.isZero=function(){return this.value===BigInt(0)},l.prototype.isDivisibleBy=function(e){var t=Q(e);return!t.isZero()&&(!!t.isUnit()||(0===t.compareAbs(2)?this.isEven():this.mod(t).isZero()))},u.prototype.isDivisibleBy=c.prototype.isDivisibleBy=l.prototype.isDivisibleBy,l.prototype.isPrime=function(t){var i=j(this);if(i!==e)return i;var r=this.abs(),a=r.bitLength();if(a<=64)return T(r,[2,3,5,7,11,13,17,19,23,29,31,37]);for(var s=Math.log(2)*a.toJSNumber(),o=Math.ceil(!0===t?2*Math.pow(s,2):s),l=[],c=0;c-i?new c(e-1):new l(r,!0)},u.prototype.prev=function(){return new u(this.value-BigInt(1))};for(var D=[1];2*D[D.length-1]<=t;)D.push(2*D[D.length-1]);var O=D.length,N=D[O-1];function R(e){return Math.abs(e)<=t}function U(e,t,i){t=Q(t);for(var r=e.isNegative(),a=t.isNegative(),s=r?e.not():e,o=a?t.not():t,l=0,c=0,u=null,d=null,h=[];!s.isZero()||!o.isZero();)l=(u=P(s,N))[1].toJSNumber(),r&&(l=N-1-l),c=(d=P(o,N))[1].toJSNumber(),a&&(c=N-1-c),s=u[0],o=d[0],h.push(i(l,c));for(var p=0!==i(r?1:0,a?1:0)?n(-1):n(0),m=h.length-1;m>=0;m-=1)p=p.multiply(N).add(n(h[m]));return p}l.prototype.shiftLeft=function(e){var t=Q(e).toJSNumber();if(!R(t))throw new Error(String(t)+" is too large for shifting.");if(t<0)return this.shiftRight(-t);var i=this;if(i.isZero())return i;for(;t>=O;)i=i.multiply(N),t-=O-1;return i.multiply(D[t])},u.prototype.shiftLeft=c.prototype.shiftLeft=l.prototype.shiftLeft,l.prototype.shiftRight=function(e){var t,i=Q(e).toJSNumber();if(!R(i))throw new Error(String(i)+" is too large for shifting.");if(i<0)return this.shiftLeft(-i);for(var r=this;i>=O;){if(r.isZero()||r.isNegative()&&r.isUnit())return r;r=(t=P(r,N))[1].isNegative()?t[0].prev():t[0],i-=O-1}return(t=P(r,D[i]))[1].isNegative()?t[0].prev():t[0]},u.prototype.shiftRight=c.prototype.shiftRight=l.prototype.shiftRight,l.prototype.not=function(){return this.negate().prev()},u.prototype.not=c.prototype.not=l.prototype.not,l.prototype.and=function(e){return U(this,e,function(e,t){return e&t})},u.prototype.and=c.prototype.and=l.prototype.and,l.prototype.or=function(e){return U(this,e,function(e,t){return e|t})},u.prototype.or=c.prototype.or=l.prototype.or,l.prototype.xor=function(e){return U(this,e,function(e,t){return e^t})},u.prototype.xor=c.prototype.xor=l.prototype.xor;var F=1<<30;function q(e){var i=e.value,r="number"==typeof i?i|F:"bigint"==typeof i?i|BigInt(F):i[0]+i[1]*t|1073758208;return r&-r}function L(e,t){if(t.compareTo(e)<=0){var i=L(e,t.square(t)),r=i.p,a=i.e,s=r.multiply(t);return s.compareTo(e)<=0?{p:s,e:2*a+1}:{p:r,e:2*a}}return{p:n(1),e:0}}function B(e,t){return e=Q(e),t=Q(t),e.greater(t)?e:t}function M(e,t){return e=Q(e),t=Q(t),e.lesser(t)?e:t}function V(e,t){if(e=Q(e).abs(),t=Q(t).abs(),e.equals(t))return e;if(e.isZero())return t;if(t.isZero())return e;for(var i,r,n=o[1];e.isEven()&&t.isEven();)i=M(q(e),q(t)),e=e.divide(i),t=t.divide(i),n=n.multiply(i);for(;e.isEven();)e=e.divide(q(e));do{for(;t.isEven();)t=t.divide(q(t));e.greater(t)&&(r=t,t=e,e=r),t=t.subtract(e)}while(!t.isZero());return n.isUnit()?e:e.multiply(n)}l.prototype.bitLength=function(){var e=this;return e.compareTo(n(0))<0&&(e=e.negate().subtract(n(1))),0===e.compareTo(n(0))?n(0):n(L(e,n(2)).e).add(n(1))},u.prototype.bitLength=c.prototype.bitLength=l.prototype.bitLength;var $=function(e,t,i,r){i=i||a,e=String(e),r||(e=e.toLowerCase(),i=i.toLowerCase());var n,s=e.length,o=Math.abs(t),l={};for(n=0;n=o){if("1"===d&&1===o)continue;throw new Error(d+" is not a valid digit in base "+t+".")}t=Q(t);var c=[],u="-"===e[0];for(n=u?1:0;n"!==e[n]&&n=0;r--)n=n.add(e[r].times(a)),a=a.times(t);return i?n.negate():n}function W(e,t){if((t=n(t)).isZero()){if(e.isZero())return{value:[0],isNegative:!1};throw new Error("Cannot convert nonzero numbers to base 0.")}if(t.equals(-1)){if(e.isZero())return{value:[0],isNegative:!1};if(e.isNegative())return{value:[].concat.apply([],Array.apply(null,Array(-e.toJSNumber())).map(Array.prototype.valueOf,[1,0])),isNegative:!1};var i=Array.apply(null,Array(e.toJSNumber()-1)).map(Array.prototype.valueOf,[0,1]);return i.unshift([1]),{value:[].concat.apply([],i),isNegative:!1}}var r=!1;if(e.isNegative()&&t.isPositive()&&(r=!0,e=e.abs()),t.isUnit())return e.isZero()?{value:[0],isNegative:!1}:{value:Array.apply(null,Array(e.toJSNumber())).map(Number.prototype.valueOf,1),isNegative:r};for(var a,s=[],o=e;o.isNegative()||o.compareAbs(t)>=0;){a=o.divmod(t),o=a.quotient;var l=a.remainder;l.isNegative()&&(l=t.minus(l).abs(),o=o.next()),s.push(l.toJSNumber())}return s.push(o.toJSNumber()),{value:s.reverse(),isNegative:r}}function H(e,t,i){var r=W(e,t);return(r.isNegative?"-":"")+r.value.map(function(e){return function(e,t){return e<(t=t||a).length?t[e]:"<"+e+">"}(e,i)}).join("")}function G(e){if(d(+e)){var t=+e;if(t===f(t))return s?new u(BigInt(t)):new c(t);throw new Error("Invalid integer: "+e)}var i="-"===e[0];i&&(e=e.slice(1));var r=e.split(/e/i);if(r.length>2)throw new Error("Invalid integer: "+r.join("e"));if(2===r.length){var n=r[1];if("+"===n[0]&&(n=n.slice(1)),(n=+n)!==f(n)||!d(n))throw new Error("Invalid integer: "+n+" is not a valid exponent.");var a=r[0],o=a.indexOf(".");if(o>=0&&(n-=a.length-o-1,a=a.slice(0,o)+a.slice(o+1)),n<0)throw new Error("Cannot include negative exponent part for integers");e=a+=new Array(n+1).join("0")}if(!/^([0-9][0-9]*)$/.test(e))throw new Error("Invalid integer: "+e);if(s)return new u(BigInt(i?"-"+e:e));for(var h=[],p=e.length,g=p-7;p>0;)h.push(+e.slice(g,p)),(g-=7)<0&&(g=0),p-=7;return m(h),new l(h,i)}function Q(e){return"number"==typeof e?function(e){if(s)return new u(BigInt(e));if(d(e)){if(e!==f(e))throw new Error(e+" is not an integer.");return new c(e)}return G(e.toString())}(e):"string"==typeof e?G(e):"bigint"==typeof e?new u(e):e}l.prototype.toArray=function(e){return W(this,e)},c.prototype.toArray=function(e){return W(this,e)},u.prototype.toArray=function(e){return W(this,e)},l.prototype.toString=function(t,i){if(t===e&&(t=10),10!==t||i)return H(this,t,i);for(var r,n=this.value,a=n.length,s=String(n[--a]);--a>=0;)r=String(n[a]),s+="0000000".slice(r.length)+r;return(this.sign?"-":"")+s},c.prototype.toString=function(t,i){return t===e&&(t=10),10!=t||i?H(this,t,i):String(this.value)},u.prototype.toString=c.prototype.toString,u.prototype.toJSON=l.prototype.toJSON=c.prototype.toJSON=function(){return this.toString()},l.prototype.valueOf=function(){return parseInt(this.toString(),10)},l.prototype.toJSNumber=l.prototype.valueOf,c.prototype.valueOf=function(){return this.value},c.prototype.toJSNumber=c.prototype.valueOf,u.prototype.valueOf=u.prototype.toJSNumber=function(){return parseInt(this.toString(),10)};for(var J=0;J<1e3;J++)o[J]=Q(J),J>0&&(o[-J]=Q(-J));return o.one=o[1],o.zero=o[0],o.minusOne=o[-1],o.max=B,o.min=M,o.gcd=V,o.lcm=function(e,t){return e=Q(e).abs(),t=Q(t).abs(),e.divide(V(e,t)).multiply(t)},o.isInstance=function(e){return e instanceof l||e instanceof c||e instanceof u},o.randBetween=function(e,i,r){e=Q(e),i=Q(i);var n=r||Math.random,a=M(e,i),s=B(e,i).subtract(a).add(1);if(s.isSmall)return a.add(Math.floor(n()*s));for(var l=W(s,t).value,c=[],u=!0,d=0;d0?I.join(",")||null:void 0}];else if(l(f))j=f;else{var D=Object.keys(I);j=y?D.sort(y):D}var O=h?String(i).replace(/\./g,"%2E"):String(i),N=s&&l(I)&&1===I.length?O+"[]":O;if(o&&l(I)&&0===I.length)return N+"[]";for(var R=0;R0?k+w:""}},6712(e,t,i){"use strict";var r=i(831);e.exports=function(e){return r(e)||null===e}},6744(e,t,i){"use strict";var r=i(142);e.exports=function(e){var t=+e;return t!=t||0===t?0:r(t)}},6759(e,t,i){"use strict";var r=i(9389);e.exports=function(e,t,i){for(var n=0,a=arguments.length>2?i:r(t),s=new e(a);a>n;)s[n]=t[n++];return s}},6783(e,t,i){"use strict";const r=i(4517),n=i(3955),{safeRe:a,t:s}=i(2841);e.exports=(e,t)=>{if(e instanceof r)return e;if("number"==typeof e&&(e=String(e)),"string"!=typeof e)return null;let i=null;if((t=t||{}).rtl){const r=t.includePrerelease?a[s.COERCERTLFULL]:a[s.COERCERTL];let n;for(;(n=r.exec(e))&&(!i||i.index+i[0].length!==e.length);)i&&n.index+n[0].length===i.index+i[0].length||(i=n),r.lastIndex=n.index+n[1].length+n[2].length;r.lastIndex=-1}else i=e.match(t.includePrerelease?a[s.COERCEFULL]:a[s.COERCE]);if(null===i)return null;const o=i[2],l=i[3]||"0",c=i[4]||"0",u=t.includePrerelease&&i[5]?`-${i[5]}`:"",d=t.includePrerelease&&i[6]?`+${i[6]}`:"";return n(`${o}.${l}.${c}${u}${d}`,t)}},6821(e,t,i){"use strict";var r=i(9117),n=i(8732),a=i(1617),s=r.DataView;e.exports=function(e){if(!n||0!==a(e))return!1;try{return new s(e),!1}catch(e){return!0}}},6881(e,t,i){"use strict";var r=i(9055),n=Function.prototype,a=n.call,s=r&&n.bind.bind(a,a);e.exports=r?s:function(e){return function(){return a.apply(e,arguments)}}},6882(e,t,i){"use strict";var r=i(2422);e.exports=function(e){return r(e)||0===e?e:e<0?-1:1}},6893(e,t,i){"use strict";var r=i(5234);e.exports=!r(function(){return 7!==Object.defineProperty({},1,{get:function(){return 7}})[1]})},6973(){},7004(e,t,i){"use strict";var r=i(528),n=i(4607),a=i(8660),s=i(3468),o=r("%Map%",!0),l=n("Map.prototype.get",!0),c=n("Map.prototype.set",!0),u=n("Map.prototype.has",!0),d=n("Map.prototype.delete",!0),h=n("Map.prototype.size",!0);e.exports=!!o&&function(){var e,t={assert:function(e){if(!t.has(e))throw new s("Side channel does not contain "+a(e))},delete:function(t){if(e){var i=d(e,t);return 0===h(e)&&(e=void 0),i}return!1},get:function(t){if(e)return l(e,t)},has:function(t){return!!e&&u(e,t)},set:function(t,i){e||(e=new o),c(e,t,i)}};return t}},7015(e,t,i){"use strict";i(1242)},7028(e){"use strict";var t=TypeError;e.exports=function(e){if("string"==typeof e)return e;throw new t("Argument is not a string")}},7060(e,t,i){"use strict";var r=i(9117),n=i(6881),a=r.Uint8Array,s=r.SyntaxError,o=r.parseInt,l=Math.min,c=/[^\da-f]/i,u=n(c.exec),d=n("".slice);e.exports=function(e,t){var i=e.length;if(i%2!=0)throw new s("String should be an even number of characters");for(var r=t?l(t.length,i/2):i/2,n=t||new a(r),h=0,p=0;p"+e+""},f=function(e){e.write(g("")),e.close();var t=e.parentWindow.Object;return e=null,t},y=function(){try{r=new ActiveXObject("htmlfile")}catch(e){}var e,t,i;y="undefined"!=typeof document?document.domain&&r?f(r):(t=c("iframe"),i="java"+h+":",t.style.display="none",l.appendChild(t),t.src=String(i),(e=t.contentWindow.document).open(),e.write(g("document.F=Object")),e.close(),e.F):f(r);for(var n=s.length;n--;)delete y[d][s[n]];return y()};o[p]=!0,e.exports=Object.create||function(e,t){var i;return null!==e?(m[d]=n(e),i=new m,m[d]=null,i[p]=e):i=y(),void 0===t?i:a.f(i,t)}},7072(e,t,i){"use strict";i(6295)},7137(e,t,i){"use strict";var r=i(1843),n=i(1274);e.exports=Object.keys||function(e){return r(e,n)}},7183(e,t,i){"use strict";const r=i(8854);e.exports=(e,t,i)=>r(e,t,"<",i)},7196(e){"use strict";e.exports="undefined"!=typeof Reflect&&Reflect&&Reflect.apply},7226(e,t,i){"use strict";const r=i(8854);e.exports=(e,t,i)=>r(e,t,">",i)},7229(e,t,i){"use strict";const r=i(7476);e.exports=(e,t,i)=>{try{t=new r(t,i)}catch(e){return!1}return t.test(e)}},7308(e,t,i){"use strict";var r=i(6881),n=Error,a=r("".replace),s=String(new n("zxcasd").stack),o=/\n\s*at [^:]*:[^\n]*/,l=o.test(s);e.exports=function(e,t){if(l&&"string"==typeof e&&!n.prepareStackTrace)for(;t--;)e=a(e,o,"");return e}},7345(e,t,i){"use strict";var r=i(9629);e.exports=r.getPrototypeOf||null},7390(e,t,i){var r=i(4643);i(8550),e.exports=r.log=r.log||{},r.log.levels=["none","error","warning","info","debug","verbose","max"];var n={},a=[],s=null;r.log.LEVEL_LOCKED=2,r.log.NO_LEVEL_CHECK=4,r.log.INTERPOLATE=8;for(var o=0;o=32)return l();var e=32-t.pools[0].messageLength<<5;t.collect(t.seedFileSync(e)),l()}function l(){t.reseeds=4294967295===t.reseeds?0:t.reseeds+1;var e=t.plugin.md.create();e.update(t.keyBytes);for(var i=1,r=0;r<32;++r)t.reseeds%i===0&&(e.update(t.pools[r].digest().getBytes()),t.pools[r].start()),i<<=1;t.keyBytes=e.digest().getBytes(),e.start(),e.update(t.keyBytes);var n=e.digest().getBytes();t.key=t.plugin.formatKey(t.keyBytes),t.seed=t.plugin.formatSeed(n),t.generated=0}function c(e){var t=null,i=r.util.globalScope,n=i.crypto||i.msCrypto;n&&n.getRandomValues&&(t=function(e){return n.getRandomValues(e)});var a=r.util.createBuffer();if(t)for(;a.length()>16)))<<16,h=4294967295&(u=(2147483647&(u+=c>>15))+(u>>31)),l=0;l<3;++l)d=h>>>(l<<3),d^=Math.floor(256*Math.random()),a.putByte(255&d);return a.getBytes(e)}return t.pools=a,t.pool=0,t.generate=function(e,i){if(!i)return t.generateSync(e);var n=t.plugin.cipher,a=t.plugin.increment,s=t.plugin.formatKey,o=t.plugin.formatSeed,c=r.util.createBuffer();t.key=null,function u(d){if(d)return i(d);if(c.length()>=e)return i(null,c.getBytes(e));if(t.generated>1048575&&(t.key=null),null===t.key)return r.util.nextTick(function(){!function(e){if(t.pools[0].messageLength>=32)return l(),e();var i=32-t.pools[0].messageLength<<5;t.seedFile(i,function(i,r){if(i)return e(i);t.collect(r),l(),e()})}(u)});var h=n(t.key,t.seed);t.generated+=h.length,c.putBytes(h),t.key=s(n(t.key,a(t.seed))),t.seed=o(n(t.key,t.seed)),r.util.setImmediate(u)}()},t.generateSync=function(e){var i=t.plugin.cipher,n=t.plugin.increment,a=t.plugin.formatKey,s=t.plugin.formatSeed;t.key=null;for(var l=r.util.createBuffer();l.length()1048575&&(t.key=null),null===t.key&&o();var c=i(t.key,t.seed);t.generated+=c.length,l.putBytes(c),t.key=a(i(t.key,n(t.seed))),t.seed=s(i(t.key,t.seed))}return l.getBytes(e)},n?(t.seedFile=function(e,t){n.randomBytes(e,function(e,i){if(e)return t(e);t(null,i.toString())})},t.seedFileSync=function(e){return n.randomBytes(e).toString()}):(t.seedFile=function(e,t){try{t(null,c(e))}catch(e){t(e)}},t.seedFileSync=c),t.collect=function(e){for(var i=e.length,r=0;r>n&255);t.collect(r)},t.registerWorker=function(e){e===self?t.seedFile=function(e,t){self.addEventListener("message",function e(i){var r=i.data;r.forge&&r.forge.prng&&(self.removeEventListener("message",e),t(r.forge.prng.err,r.forge.prng.bytes))}),self.postMessage({forge:{prng:{needed:e}}})}:e.addEventListener("message",function(i){var r=i.data;r.forge&&r.forge.prng&&t.seedFile(r.forge.prng.needed,function(t,i){e.postMessage({forge:{prng:{err:t,bytes:i}}})})})},t}},7403(e,t,i){"use strict";const r=i(7476);e.exports=(e,t)=>{try{return new r(e,t).range||"*"}catch(e){return null}}},7458(e,t,i){"use strict";var r=i(5604);e.exports=r("document","documentElement")},7476(e,t,i){"use strict";const r=/\s+/g;class n{constructor(e,t){if(t=s(t),e instanceof n)return e.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:new n(e.raw,t);if(e instanceof o)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e.trim().replace(r," "),this.set=this.raw.split("||").map(e=>this.parseRange(e.trim())).filter(e=>e.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const e=this.set[0];if(this.set=this.set.filter(e=>!y(e[0])),0===this.set.length)this.set=[e];else if(this.set.length>1)for(const e of this.set)if(1===e.length&&v(e[0])){this.set=[e];break}}this.formatted=void 0}get range(){if(void 0===this.formatted){this.formatted="";for(let e=0;e0&&(this.formatted+="||");const t=this.set[e];for(let e=0;e0&&(this.formatted+=" "),this.formatted+=t[e].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){const t=((this.options.includePrerelease&&g)|(this.options.loose&&f))+":"+e,i=a.get(t);if(i)return i;const r=this.options.loose,n=r?u[d.HYPHENRANGELOOSE]:u[d.HYPHENRANGE];e=e.replace(n,A(this.options.includePrerelease)),l("hyphen replace",e),e=e.replace(u[d.COMPARATORTRIM],h),l("comparator trim",e),e=e.replace(u[d.TILDETRIM],p),l("tilde trim",e),e=e.replace(u[d.CARETTRIM],m),l("caret trim",e);let s=e.split(" ").map(e=>w(e,this.options)).join(" ").split(/\s+/).map(e=>P(e,this.options));r&&(s=s.filter(e=>(l("loose invalid filter",e,this.options),!!e.match(u[d.COMPARATORLOOSE])))),l("range list",s);const c=new Map,v=s.map(e=>new o(e,this.options));for(const e of v){if(y(e))return[e];c.set(e.value,e)}c.size>1&&c.has("")&&c.delete("");const b=[...c.values()];return a.set(t,b),b}intersects(e,t){if(!(e instanceof n))throw new TypeError("a Range is required");return this.set.some(i=>b(i,t)&&e.set.some(e=>b(e,t)&&i.every(i=>e.every(e=>i.intersects(e,t)))))}test(e){if(!e)return!1;if("string"==typeof e)try{e=new c(e,this.options)}catch(e){return!1}for(let t=0;t"<0.0.0-0"===e.value,v=e=>""===e.value,b=(e,t)=>{let i=!0;const r=e.slice();let n=r.pop();for(;i&&r.length;)i=r.every(e=>n.intersects(e,t)),n=r.pop();return i},w=(e,t)=>(e=e.replace(u[d.BUILD],""),l("comp",e,t),e=x(e,t),l("caret",e),e=S(e,t),l("tildes",e),e=I(e,t),l("xrange",e),e=z(e,t),l("stars",e),e),k=e=>!e||"x"===e.toLowerCase()||"*"===e,S=(e,t)=>e.trim().split(/\s+/).map(e=>_(e,t)).join(" "),_=(e,t)=>{const i=t.loose?u[d.TILDELOOSE]:u[d.TILDE];return e.replace(i,(t,i,r,n,a)=>{let s;return l("tilde",e,t,i,r,n,a),k(i)?s="":k(r)?s=`>=${i}.0.0 <${+i+1}.0.0-0`:k(n)?s=`>=${i}.${r}.0 <${i}.${+r+1}.0-0`:a?(l("replaceTilde pr",a),s=`>=${i}.${r}.${n}-${a} <${i}.${+r+1}.0-0`):s=`>=${i}.${r}.${n} <${i}.${+r+1}.0-0`,l("tilde return",s),s})},x=(e,t)=>e.trim().split(/\s+/).map(e=>C(e,t)).join(" "),C=(e,t)=>{l("caret",e,t);const i=t.loose?u[d.CARETLOOSE]:u[d.CARET],r=t.includePrerelease?"-0":"";return e.replace(i,(t,i,n,a,s)=>{let o;return l("caret",e,t,i,n,a,s),k(i)?o="":k(n)?o=`>=${i}.0.0${r} <${+i+1}.0.0-0`:k(a)?o="0"===i?`>=${i}.${n}.0${r} <${i}.${+n+1}.0-0`:`>=${i}.${n}.0${r} <${+i+1}.0.0-0`:s?(l("replaceCaret pr",s),o="0"===i?"0"===n?`>=${i}.${n}.${a}-${s} <${i}.${n}.${+a+1}-0`:`>=${i}.${n}.${a}-${s} <${i}.${+n+1}.0-0`:`>=${i}.${n}.${a}-${s} <${+i+1}.0.0-0`):(l("no pr"),o="0"===i?"0"===n?`>=${i}.${n}.${a}${r} <${i}.${n}.${+a+1}-0`:`>=${i}.${n}.${a}${r} <${i}.${+n+1}.0-0`:`>=${i}.${n}.${a} <${+i+1}.0.0-0`),l("caret return",o),o})},I=(e,t)=>(l("replaceXRanges",e,t),e.split(/\s+/).map(e=>E(e,t)).join(" ")),E=(e,t)=>{e=e.trim();const i=t.loose?u[d.XRANGELOOSE]:u[d.XRANGE];return e.replace(i,(i,r,n,a,s,o)=>{l("xRange",e,i,r,n,a,s,o);const c=k(n),u=c||k(a),d=u||k(s),h=d;return"="===r&&h&&(r=""),o=t.includePrerelease?"-0":"",c?i=">"===r||"<"===r?"<0.0.0-0":"*":r&&h?(u&&(a=0),s=0,">"===r?(r=">=",u?(n=+n+1,a=0,s=0):(a=+a+1,s=0)):"<="===r&&(r="<",u?n=+n+1:a=+a+1),"<"===r&&(o="-0"),i=`${r+n}.${a}.${s}${o}`):u?i=`>=${n}.0.0${o} <${+n+1}.0.0-0`:d&&(i=`>=${n}.${a}.0${o} <${n}.${+a+1}.0-0`),l("xRange return",i),i})},z=(e,t)=>(l("replaceStars",e,t),e.trim().replace(u[d.STAR],"")),P=(e,t)=>(l("replaceGTE0",e,t),e.trim().replace(u[t.includePrerelease?d.GTE0PRE:d.GTE0],"")),A=e=>(t,i,r,n,a,s,o,l,c,u,d,h)=>`${i=k(r)?"":k(n)?`>=${r}.0.0${e?"-0":""}`:k(a)?`>=${r}.${n}.0${e?"-0":""}`:s?`>=${i}`:`>=${i}${e?"-0":""}`} ${l=k(c)?"":k(u)?`<${+c+1}.0.0-0`:k(d)?`<${c}.${+u+1}.0-0`:h?`<=${c}.${u}.${d}-${h}`:e?`<${c}.${u}.${+d+1}-0`:`<=${l}`}`.trim(),j=(e,t,i)=>{for(let i=0;i0){const r=e[i].semver;if(r.major===t.major&&r.minor===t.minor&&r.patch===t.patch)return!0}return!1}return!0}},7509(e,t,i){"use strict";var r=i(4188),n=i(4466),a=i(4530),s=i(4798);e.exports=function(e,t,i,o){o||(o={});var l=o.enumerable,c=void 0!==o.name?o.name:t;if(r(i)&&a(i,c,o),o.global)l?e[t]=i:s(t,i);else{try{o.unsafe?e[t]&&(l=!0):delete e[t]}catch(e){}l?e[t]=i:n.f(e,t,{value:i,enumerable:!1,configurable:!o.nonConfigurable,writable:!o.nonWritable})}return e}},7511(e,t,i){"use strict";i(5200)},7555(e,t,i){"use strict";const r=i(7851);e.exports=(e,t,i)=>r(t,e,i)},7568(e,t,i){"use strict";var r=i(6881),n=i(5234),a=i(8689),s=Object,o=r("".split);e.exports=n(function(){return!s("z").propertyIsEnumerable(0)})?function(e){return"String"===a(e)?o(e,""):s(e)}:s},7575(e,t,i){"use strict";var r=i(3468),n=i(8660),a=i(3346),s=i(7004),o=i(6348)||s||a;e.exports=function(){var e,t={assert:function(e){if(!t.has(e))throw new r("Side channel does not contain "+n(e))},delete:function(t){return!!e&&e.delete(t)},get:function(t){return e&&e.get(t)},has:function(t){return!!e&&e.has(t)},set:function(t,i){e||(e=o()),e.set(t,i)}};return t}},7585(e,t,i){var r=i(4643);i(9679),i(8550);var n=e.exports=r.sha256=r.sha256||{};r.md.sha256=r.md.algorithms.sha256=n,n.create=function(){s||(a=String.fromCharCode(128),a+=r.util.fillString(String.fromCharCode(0),64),o=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],s=!0);var e=null,t=r.util.createBuffer(),i=new Array(64),n={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8,start:function(){n.messageLength=0,n.fullMessageLength=n.messageLength64=[];for(var i=n.messageLengthSize/4,a=0;a>>0,o>>>0];for(var c=n.fullMessageLength.length-1;c>=0;--c)n.fullMessageLength[c]+=o[1],o[1]=o[0]+(n.fullMessageLength[c]/4294967296>>>0),n.fullMessageLength[c]=n.fullMessageLength[c]>>>0,o[0]=o[1]/4294967296>>>0;return t.putBytes(a),l(e,i,t),(t.read>2048||0===t.length())&&t.compact(),n},n.digest=function(){var s=r.util.createBuffer();s.putBytes(t.bytes());var o,c=n.fullMessageLength[n.fullMessageLength.length-1]+n.messageLengthSize&n.blockLength-1;s.putBytes(a.substr(0,n.blockLength-c));for(var u=8*n.fullMessageLength[0],d=0;d>>0,s.putInt32(u>>>0),u=o>>>0;s.putInt32(u);var h={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};l(h,i,s);var p=r.util.createBuffer();return p.putInt32(h.h0),p.putInt32(h.h1),p.putInt32(h.h2),p.putInt32(h.h3),p.putInt32(h.h4),p.putInt32(h.h5),p.putInt32(h.h6),p.putInt32(h.h7),p},n};var a=null,s=!1,o=null;function l(e,t,i){for(var r,n,a,s,l,c,u,d,h,p,m,g,f,y=i.length();y>=64;){for(l=0;l<16;++l)t[l]=i.getInt32();for(;l<64;++l)r=((r=t[l-2])>>>17|r<<15)^(r>>>19|r<<13)^r>>>10,n=((n=t[l-15])>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,t[l]=r+t[l-7]+n+t[l-16]|0;for(c=e.h0,u=e.h1,d=e.h2,h=e.h3,p=e.h4,m=e.h5,g=e.h6,f=e.h7,l=0;l<64;++l)a=(c>>>2|c<<30)^(c>>>13|c<<19)^(c>>>22|c<<10),s=c&u|d&(c^u),r=f+((p>>>6|p<<26)^(p>>>11|p<<21)^(p>>>25|p<<7))+(g^p&(m^g))+o[l]+t[l],f=g,g=m,m=p,p=h+r>>>0,h=d,d=u,u=c,c=r+(n=a+s)>>>0;e.h0=e.h0+c|0,e.h1=e.h1+u|0,e.h2=e.h2+d|0,e.h3=e.h3+h|0,e.h4=e.h4+p|0,e.h5=e.h5+m|0,e.h6=e.h6+g|0,e.h7=e.h7+f|0,y-=64}}},7588(e){"use strict";e.exports={}},7611(e,t,i){"use strict";var r=i(6744),n=Math.min;e.exports=function(e){var t=r(e);return t>0?n(t,9007199254740991):0}},7612(e,t,i){"use strict";var r=i(5613),n=i(9117),a=i(7028),s=i(7060);n.Uint8Array&&r({target:"Uint8Array",stat:!0},{fromHex:function(e){return s(a(e)).bytes}})},7827(e){var t;t={qwerty:{"!":["`~",null,null,"2@","qQ",null],'"':[";:","[{","]}",null,null,"/?"],"#":["2@",null,null,"4$","eE","wW"],$:["3#",null,null,"5%","rR","eE"],"%":["4$",null,null,"6^","tT","rR"],"&":["6^",null,null,"8*","uU","yY"],"'":[";:","[{","]}",null,null,"/?"],"(":["8*",null,null,"0)","oO","iI"],")":["9(",null,null,"-_","pP","oO"],"*":["7&",null,null,"9(","iI","uU"],"+":["-_",null,null,null,"]}","[{"],",":["mM","kK","lL",".>",null,null],"-":["0)",null,null,"=+","[{","pP"],".":[",<","lL",";:","/?",null,null],"/":[".>",";:","'\"",null,null,null],0:["9(",null,null,"-_","pP","oO"],1:["`~",null,null,"2@","qQ",null],2:["1!",null,null,"3#","wW","qQ"],3:["2@",null,null,"4$","eE","wW"],4:["3#",null,null,"5%","rR","eE"],5:["4$",null,null,"6^","tT","rR"],6:["5%",null,null,"7&","yY","tT"],7:["6^",null,null,"8*","uU","yY"],8:["7&",null,null,"9(","iI","uU"],9:["8*",null,null,"0)","oO","iI"],":":["lL","pP","[{","'\"","/?",".>"],";":["lL","pP","[{","'\"","/?",".>"],"<":["mM","kK","lL",".>",null,null],"=":["-_",null,null,null,"]}","[{"],">":[",<","lL",";:","/?",null,null],"?":[".>",";:","'\"",null,null,null],"@":["1!",null,null,"3#","wW","qQ"],A:[null,"qQ","wW","sS","zZ",null],B:["vV","gG","hH","nN",null,null],C:["xX","dD","fF","vV",null,null],D:["sS","eE","rR","fF","cC","xX"],E:["wW","3#","4$","rR","dD","sS"],F:["dD","rR","tT","gG","vV","cC"],G:["fF","tT","yY","hH","bB","vV"],H:["gG","yY","uU","jJ","nN","bB"],I:["uU","8*","9(","oO","kK","jJ"],J:["hH","uU","iI","kK","mM","nN"],K:["jJ","iI","oO","lL",",<","mM"],L:["kK","oO","pP",";:",".>",",<"],M:["nN","jJ","kK",",<",null,null],N:["bB","hH","jJ","mM",null,null],O:["iI","9(","0)","pP","lL","kK"],P:["oO","0)","-_","[{",";:","lL"],Q:[null,"1!","2@","wW","aA",null],R:["eE","4$","5%","tT","fF","dD"],S:["aA","wW","eE","dD","xX","zZ"],T:["rR","5%","6^","yY","gG","fF"],U:["yY","7&","8*","iI","jJ","hH"],V:["cC","fF","gG","bB",null,null],W:["qQ","2@","3#","eE","sS","aA"],X:["zZ","sS","dD","cC",null,null],Y:["tT","6^","7&","uU","hH","gG"],Z:[null,"aA","sS","xX",null,null],"[":["pP","-_","=+","]}","'\"",";:"],"\\":["]}",null,null,null,null,null],"]":["[{","=+",null,"\\|",null,"'\""],"^":["5%",null,null,"7&","yY","tT"],_:["0)",null,null,"=+","[{","pP"],"`":[null,null,null,"1!",null,null],a:[null,"qQ","wW","sS","zZ",null],b:["vV","gG","hH","nN",null,null],c:["xX","dD","fF","vV",null,null],d:["sS","eE","rR","fF","cC","xX"],e:["wW","3#","4$","rR","dD","sS"],f:["dD","rR","tT","gG","vV","cC"],g:["fF","tT","yY","hH","bB","vV"],h:["gG","yY","uU","jJ","nN","bB"],i:["uU","8*","9(","oO","kK","jJ"],j:["hH","uU","iI","kK","mM","nN"],k:["jJ","iI","oO","lL",",<","mM"],l:["kK","oO","pP",";:",".>",",<"],m:["nN","jJ","kK",",<",null,null],n:["bB","hH","jJ","mM",null,null],o:["iI","9(","0)","pP","lL","kK"],p:["oO","0)","-_","[{",";:","lL"],q:[null,"1!","2@","wW","aA",null],r:["eE","4$","5%","tT","fF","dD"],s:["aA","wW","eE","dD","xX","zZ"],t:["rR","5%","6^","yY","gG","fF"],u:["yY","7&","8*","iI","jJ","hH"],v:["cC","fF","gG","bB",null,null],w:["qQ","2@","3#","eE","sS","aA"],x:["zZ","sS","dD","cC",null,null],y:["tT","6^","7&","uU","hH","gG"],z:[null,"aA","sS","xX",null,null],"{":["pP","-_","=+","]}","'\"",";:"],"|":["]}",null,null,null,null,null],"}":["[{","=+",null,"\\|",null,"'\""],"~":[null,null,null,"1!",null,null]},dvorak:{"!":["`~",null,null,"2@","'\"",null],'"':[null,"1!","2@",",<","aA",null],"#":["2@",null,null,"4$",".>",",<"],$:["3#",null,null,"5%","pP",".>"],"%":["4$",null,null,"6^","yY","pP"],"&":["6^",null,null,"8*","gG","fF"],"'":[null,"1!","2@",",<","aA",null],"(":["8*",null,null,"0)","rR","cC"],")":["9(",null,null,"[{","lL","rR"],"*":["7&",null,null,"9(","cC","gG"],"+":["/?","]}",null,"\\|",null,"-_"],",":["'\"","2@","3#",".>","oO","aA"],"-":["sS","/?","=+",null,null,"zZ"],".":[",<","3#","4$","pP","eE","oO"],"/":["lL","[{","]}","=+","-_","sS"],0:["9(",null,null,"[{","lL","rR"],1:["`~",null,null,"2@","'\"",null],2:["1!",null,null,"3#",",<","'\""],3:["2@",null,null,"4$",".>",",<"],4:["3#",null,null,"5%","pP",".>"],5:["4$",null,null,"6^","yY","pP"],6:["5%",null,null,"7&","fF","yY"],7:["6^",null,null,"8*","gG","fF"],8:["7&",null,null,"9(","cC","gG"],9:["8*",null,null,"0)","rR","cC"],":":[null,"aA","oO","qQ",null,null],";":[null,"aA","oO","qQ",null,null],"<":["'\"","2@","3#",".>","oO","aA"],"=":["/?","]}",null,"\\|",null,"-_"],">":[",<","3#","4$","pP","eE","oO"],"?":["lL","[{","]}","=+","-_","sS"],"@":["1!",null,null,"3#",",<","'\""],A:[null,"'\"",",<","oO",";:",null],B:["xX","dD","hH","mM",null,null],C:["gG","8*","9(","rR","tT","hH"],D:["iI","fF","gG","hH","bB","xX"],E:["oO",".>","pP","uU","jJ","qQ"],F:["yY","6^","7&","gG","dD","iI"],G:["fF","7&","8*","cC","hH","dD"],H:["dD","gG","cC","tT","mM","bB"],I:["uU","yY","fF","dD","xX","kK"],J:["qQ","eE","uU","kK",null,null],K:["jJ","uU","iI","xX",null,null],L:["rR","0)","[{","/?","sS","nN"],M:["bB","hH","tT","wW",null,null],N:["tT","rR","lL","sS","vV","wW"],O:["aA",",<",".>","eE","qQ",";:"],P:[".>","4$","5%","yY","uU","eE"],Q:[";:","oO","eE","jJ",null,null],R:["cC","9(","0)","lL","nN","tT"],S:["nN","lL","/?","-_","zZ","vV"],T:["hH","cC","rR","nN","wW","mM"],U:["eE","pP","yY","iI","kK","jJ"],V:["wW","nN","sS","zZ",null,null],W:["mM","tT","nN","vV",null,null],X:["kK","iI","dD","bB",null,null],Y:["pP","5%","6^","fF","iI","uU"],Z:["vV","sS","-_",null,null,null],"[":["0)",null,null,"]}","/?","lL"],"\\":["=+",null,null,null,null,null],"]":["[{",null,null,null,"=+","/?"],"^":["5%",null,null,"7&","fF","yY"],_:["sS","/?","=+",null,null,"zZ"],"`":[null,null,null,"1!",null,null],a:[null,"'\"",",<","oO",";:",null],b:["xX","dD","hH","mM",null,null],c:["gG","8*","9(","rR","tT","hH"],d:["iI","fF","gG","hH","bB","xX"],e:["oO",".>","pP","uU","jJ","qQ"],f:["yY","6^","7&","gG","dD","iI"],g:["fF","7&","8*","cC","hH","dD"],h:["dD","gG","cC","tT","mM","bB"],i:["uU","yY","fF","dD","xX","kK"],j:["qQ","eE","uU","kK",null,null],k:["jJ","uU","iI","xX",null,null],l:["rR","0)","[{","/?","sS","nN"],m:["bB","hH","tT","wW",null,null],n:["tT","rR","lL","sS","vV","wW"],o:["aA",",<",".>","eE","qQ",";:"],p:[".>","4$","5%","yY","uU","eE"],q:[";:","oO","eE","jJ",null,null],r:["cC","9(","0)","lL","nN","tT"],s:["nN","lL","/?","-_","zZ","vV"],t:["hH","cC","rR","nN","wW","mM"],u:["eE","pP","yY","iI","kK","jJ"],v:["wW","nN","sS","zZ",null,null],w:["mM","tT","nN","vV",null,null],x:["kK","iI","dD","bB",null,null],y:["pP","5%","6^","fF","iI","uU"],z:["vV","sS","-_",null,null,null],"{":["0)",null,null,"]}","/?","lL"],"|":["=+",null,null,null,null,null],"}":["[{",null,null,null,"=+","/?"],"~":[null,null,null,"1!",null,null]},keypad:{"*":["/",null,null,null,"-","+","9","8"],"+":["9","*","-",null,null,null,null,"6"],"-":["*",null,null,null,null,null,"+","9"],".":["0","2","3",null,null,null,null,null],"/":[null,null,null,null,"*","9","8","7"],0:[null,"1","2","3",".",null,null,null],1:[null,null,"4","5","2","0",null,null],2:["1","4","5","6","3",".","0",null],3:["2","5","6",null,null,null,".","0"],4:[null,null,"7","8","5","2","1",null],5:["4","7","8","9","6","3","2","1"],6:["5","8","9","+",null,null,"3","2"],7:[null,null,null,"/","8","5","4",null],8:["7",null,"/","*","9","6","5","4"],9:["8","/","*","-","+",null,"6","5"]},mac_keypad:{"*":["/",null,null,null,null,null,"-","9"],"+":["6","9","-",null,null,null,null,"3"],"-":["9","/","*",null,null,null,"+","6"],".":["0","2","3",null,null,null,null,null],"/":["=",null,null,null,"*","-","9","8"],0:[null,"1","2","3",".",null,null,null],1:[null,null,"4","5","2","0",null,null],2:["1","4","5","6","3",".","0",null],3:["2","5","6","+",null,null,".","0"],4:[null,null,"7","8","5","2","1",null],5:["4","7","8","9","6","3","2","1"],6:["5","8","9","-","+",null,"3","2"],7:[null,null,null,"=","8","5","4",null],8:["7",null,"=","/","9","6","5","4"],9:["8","=","/","*","-","+","6","5"],"=":[null,null,null,null,"/","9","8","7"]}},e.exports=t},7835(e,t,i){var r=i(4643);i(8550),i(4467);var n=e.exports=r.asn1=r.asn1||{};function a(e,t,i){if(i>t){var r=new Error("Too few bytes to parse DER.");throw r.available=e.length(),r.remaining=t,r.requested=i,r}}function s(e,t,i,r){if(i>=r.maxDepth)throw new Error("ASN.1 parsing error: Max depth exceeded.");var o;a(e,t,2);var l=e.getByte();t--;var c=192&l,u=31&l;o=e.length();var d,h,p=function(e,t){var i=e.getByte();if(t--,128!==i){var r;if(128&i){var n=127&i;a(e,t,n),r=e.getInt(n<<3)}else r=i;if(r<0)throw new Error("Negative length: "+r);return r}}(e,t);if(t-=o-e.length(),void 0!==p&&p>t){if(r.strict){var m=new Error("Too few bytes to read ASN.1 value.");throw m.available=e.length(),m.remaining=t,m.requested=p,m}p=t}var g=!(32&~l);if(g)if(d=[],void 0===p)for(;;){if(a(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}o=e.length(),d.push(s(e,t,i+1,r)),t-=o-e.length()}else for(;p>0;)o=e.length(),d.push(s(e,p,i+1,r)),t-=o-e.length(),p-=o-e.length();if(void 0===d&&c===n.Class.UNIVERSAL&&u===n.Type.BITSTRING&&(h=e.bytes(p)),void 0===d&&r.decodeBitStrings&&c===n.Class.UNIVERSAL&&u===n.Type.BITSTRING&&p>1){var f=e.read,y=t,v=0;if(u===n.Type.BITSTRING&&(a(e,t,1),v=e.getByte(),t--),0===v)try{o=e.length();var b=s(e,t,i+1,{strict:!0,decodeBitStrings:!0}),w=o-e.length();t-=w,u==n.Type.BITSTRING&&w++;var k=b.tagClass;w!==p||k!==n.Class.UNIVERSAL&&k!==n.Class.CONTEXT_SPECIFIC||(d=[b])}catch(e){}void 0===d&&(e.read=f,t=y)}if(void 0===d){if(void 0===p){if(r.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");p=t}if(u===n.Type.BMPSTRING)for(d="";p>0;p-=2)a(e,t,2),d+=String.fromCharCode(e.getInt16()),t-=2;else d=e.getBytes(p),t-=p}var S=void 0===h?null:{bitStringContents:h};return n.create(c,u,g,d,S)}n.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},n.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},n.maxDepth=256,n.create=function(e,t,i,a,s){if(r.util.isArray(a)){for(var o=[],l=0;l1)||(0!==e.value.charCodeAt(0)||128&e.value.charCodeAt(1))&&(255!==e.value.charCodeAt(0)||128&~e.value.charCodeAt(1))?a.putBytes(e.value):a.putBytes(e.value.substr(1));if(t.putByte(i),a.length()<=127)t.putByte(127&a.length());else{var l=a.length(),c="";do{c+=String.fromCharCode(255&l),l>>>=8}while(l>0);for(t.putByte(128|c.length),o=c.length-1;o>=0;--o)t.putByte(c.charCodeAt(o))}return t.putBuffer(a),t},n.oidToDer=function(e){var t,i,n,a,s=e.split("."),o=r.util.createBuffer();o.putByte(40*parseInt(s[0],10)+parseInt(s[1],10));for(var l=2;l4294967295)throw new Error("OID value too large; max is 32-bits.");do{a=127&n,n>>>=7,t||(a|=128),i.push(a),t=!1}while(n>0);for(var c=i.length-1;c>=0;--c)o.putByte(i[c])}return o},n.derToOid=function(e){var t;"string"==typeof e&&(e=r.util.createBuffer(e));var i=e.getByte();t=Math.floor(i/40)+"."+i%40;for(var n=0;e.length()>0;){if(n>70368744177663)throw new Error("OID value too large; max is 53-bits.");n*=128,128&(i=e.getByte())?n+=127&i:(t+="."+(n+i),n=0)}return t},n.utcTimeToDate=function(e){var t=new Date,i=parseInt(e.substr(0,2),10);i=i>=50?1900+i:2e3+i;var r=parseInt(e.substr(2,2),10)-1,n=parseInt(e.substr(4,2),10),a=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var l=e.charAt(10),c=10;"+"!==l&&"-"!==l&&(o=parseInt(e.substr(10,2),10),c+=2)}if(t.setUTCFullYear(i,r,n),t.setUTCHours(a,s,o,0),c&&("+"===(l=e.charAt(c))||"-"===l)){var u=60*parseInt(e.substr(c+1,2),10)+parseInt(e.substr(c+4,2),10);u*=6e4,"+"===l?t.setTime(+t-u):t.setTime(+t+u)}return t},n.generalizedTimeToDate=function(e){var t=new Date,i=parseInt(e.substr(0,4),10),r=parseInt(e.substr(4,2),10)-1,n=parseInt(e.substr(6,2),10),a=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),l=0,c=0,u=!1;"Z"===e.charAt(e.length-1)&&(u=!0);var d=e.length-5,h=e.charAt(d);return"+"!==h&&"-"!==h||(c=60*parseInt(e.substr(d+1,2),10)+parseInt(e.substr(d+4,2),10),c*=6e4,"+"===h&&(c*=-1),u=!0),"."===e.charAt(14)&&(l=1e3*parseFloat(e.substr(14),10)),u?(t.setUTCFullYear(i,r,n),t.setUTCHours(a,s,o,l),t.setTime(+t+c)):(t.setFullYear(i,r,n),t.setHours(a,s,o,l)),t},n.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",i=[];i.push((""+e.getUTCFullYear()).substr(2)),i.push(""+(e.getUTCMonth()+1)),i.push(""+e.getUTCDate()),i.push(""+e.getUTCHours()),i.push(""+e.getUTCMinutes()),i.push(""+e.getUTCSeconds());for(var r=0;r=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var i=new Error("Integer too large; max is 32-bits.");throw i.integer=e,i},n.derToInteger=function(e){"string"==typeof e&&(e=r.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},n.validate=function(e,t,i,a){var s=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)a&&(e.tagClass!==t.tagClass&&a.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&a.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(s=!0,t.value&&r.util.isArray(t.value))for(var o=0,l=0;s&&l0&&(a+="\n");for(var s="",l=0;l1?a+="0x"+r.util.bytesToHex(e.value.slice(1)):a+="(none)",e.value.length>0){var h=e.value.charCodeAt(0);1==h?a+=" (1 unused bit shown)":h>1&&(a+=" ("+h+" unused bits shown)")}}else if(e.type===n.Type.OCTETSTRING)o.test(e.value)||(a+="("+e.value+") "),a+="0x"+r.util.bytesToHex(e.value);else if(e.type===n.Type.UTF8)try{a+=r.util.decodeUtf8(e.value)}catch(t){if("URI malformed"!==t.message)throw t;a+="0x"+r.util.bytesToHex(e.value)+" (malformed UTF8)"}else e.type===n.Type.PRINTABLESTRING||e.type===n.Type.IA5String?a+=e.value:o.test(e.value)?a+="0x"+r.util.bytesToHex(e.value):0===e.value.length?a+="[null]":a+=e.value}return a}},7851(e,t,i){"use strict";const r=i(4517);e.exports=(e,t,i)=>new r(e,i).compare(new r(t,i))},7859(e){"use strict";e.exports="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null},7885(e,t,i){var r=i(4643);i(3739),i(3105);var n=e.exports=r.tls;function a(e,t,i){var a=t.entity===r.tls.ConnectionEnd.client;e.read.cipherState={init:!1,cipher:r.cipher.createDecipher("AES-CBC",a?i.keys.server_write_key:i.keys.client_write_key),iv:a?i.keys.server_write_IV:i.keys.client_write_IV},e.write.cipherState={init:!1,cipher:r.cipher.createCipher("AES-CBC",a?i.keys.client_write_key:i.keys.server_write_key),iv:a?i.keys.client_write_IV:i.keys.server_write_IV},e.read.cipherFunction=c,e.write.cipherFunction=s,e.read.macLength=e.write.macLength=i.mac_length,e.read.macFunction=e.write.macFunction=n.hmac_sha1}function s(e,t){var i,a=!1,s=t.macFunction(t.macKey,t.sequenceNumber,e);e.fragment.putBytes(s),t.updateSequenceNumber(),i=e.version.minor===n.Versions.TLS_1_0.minor?t.cipherState.init?null:t.cipherState.iv:r.random.getBytesSync(16),t.cipherState.init=!0;var l=t.cipherState.cipher;return l.start({iv:i}),e.version.minor>=n.Versions.TLS_1_1.minor&&l.output.putBytes(i),l.update(e.fragment),l.finish(o)&&(e.fragment=l.output,e.length=e.fragment.length(),a=!0),a}function o(e,t,i){if(!i){var r=e-t.length()%e;t.fillWithByte(r-1,r)}return!0}function l(e,t,i){var r=!0;if(i){for(var n=t.length(),a=t.last(),s=n-1-a;s=o?(e.fragment=s.output.getBytes(u-o),c=s.output.getBytes(o)):e.fragment=s.output.getBytes(),e.fragment=r.util.createBuffer(e.fragment),e.length=e.fragment.length();var d=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),a=function(e,t,i){var n=r.hmac.create();return n.start("SHA1",e),n.update(t),t=n.digest().getBytes(),n.start(null,null),n.update(i),t===(i=n.digest().getBytes())}(t.macKey,c,d)&&a,a}n.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=n.BulkCipherAlgorithm.aes,e.cipher_type=n.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=n.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:a},n.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=n.BulkCipherAlgorithm.aes,e.cipher_type=n.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=n.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:a}},7991(e,t){"use strict";t.byteLength=function(e){var t=o(e),i=t[0],r=t[1];return 3*(i+r)/4-r},t.toByteArray=function(e){var t,i,a=o(e),s=a[0],l=a[1],c=new n(function(e,t,i){return 3*(t+i)/4-i}(0,s,l)),u=0,d=l>0?s-4:s;for(i=0;i>16&255,c[u++]=t>>8&255,c[u++]=255&t;return 2===l&&(t=r[e.charCodeAt(i)]<<2|r[e.charCodeAt(i+1)]>>4,c[u++]=255&t),1===l&&(t=r[e.charCodeAt(i)]<<10|r[e.charCodeAt(i+1)]<<4|r[e.charCodeAt(i+2)]>>2,c[u++]=t>>8&255,c[u++]=255&t),c},t.fromByteArray=function(e){for(var t,r=e.length,n=r%3,a=[],s=16383,o=0,l=r-n;ol?l:o+s));return 1===n?(t=e[r-1],a.push(i[t>>2]+i[t<<4&63]+"==")):2===n&&(t=(e[r-2]<<8)+e[r-1],a.push(i[t>>10]+i[t>>4&63]+i[t<<2&63]+"=")),a.join("")};for(var i=[],r=[],n="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)i[s]=a[s],r[a.charCodeAt(s)]=s;function o(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function l(e){return i[e>>18&63]+i[e>>12&63]+i[e>>6&63]+i[63&e]}function c(e,t,i){for(var r,n=[],a=t;a0!==r(e,t,i)},8323(e,t,i){var r=i(4643);i(8550),i(5417),i(121),e.exports=r.kem=r.kem||{};var n=r.jsbn.BigInteger;function a(e,t,i,n){e.generate=function(e,a){for(var s=new r.util.ByteBuffer,o=Math.ceil(a/n)+i,l=new r.util.ByteBuffer,c=i;c0&&(s=r.util.fillString(String.fromCharCode(0),l)+s),{encapsulation:t.encrypt(s,"NONE"),key:e.generate(s,a)}},decrypt:function(t,i,r){var n=t.decrypt(i,"NONE");return e.generate(n,r)}}},r.kem.kdf1=function(e,t){a(this,e,0,t||e.digestLength)},r.kem.kdf2=function(e,t){a(this,e,1,t||e.digestLength)}},8449(e){"use strict";e.exports=Math.floor},8474(e,t,i){"use strict";const r=i(3955);e.exports=(e,t)=>{const i=r(e,t);return i?i.version:null}},8479(e){"use strict";e.exports=Math.abs},8489(e,t,i){"use strict";var r=i(5234),n=i(4188),a=/#|\.prototype\./,s=function(e,t){var i=l[o(e)];return i===u||i!==c&&(n(t)?r(t):!!t)},o=s.normalize=function(e){return String(e).replace(a,".").toLowerCase()},l=s.data={},c=s.NATIVE="N",u=s.POLYFILL="P";e.exports=s},8491(e,t,i){"use strict";i(2352)},8529(e,t,i){"use strict";var r=i(5438),n=TypeError;e.exports=function(e){if("Uint8Array"===r(e))return e;throw new n("Argument is not an Uint8Array")}},8550(e,t,i){var r=i(4643),n=i(2089),a=e.exports=r.util=r.util||{};function s(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function o(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(a.isArrayBuffer(e)||a.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var i=0;i15?(i=Date.now(),s(e)):(t.push(e),1===t.length&&n.setAttribute("a",r=!r))}}a.nextTick=a.setImmediate}(),a.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,a.globalScope=a.isNodejs?i.g:"undefined"==typeof self?window:self,a.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},a.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},a.isArrayBufferView=function(e){return e&&a.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},a.ByteBuffer=o,a.ByteStringBuffer=o,a.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},a.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},a.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},a.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},a.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var i=this.data;t>0;)1&t&&(i+=e),(t>>>=1)>0&&(e+=e);return this.data=i,this._optimizeConstructedString(t),this},a.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},a.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(a.encodeUtf8(e))},a.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},a.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},a.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},a.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},a.ByteStringBuffer.prototype.putInt=function(e,t){s(t);var i="";do{t-=8,i+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(i)},a.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},a.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),i=2<=i&&(t-=i<<1),t},a.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},a.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},a.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},a.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},a.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},a.ByteStringBuffer.prototype.copy=function(){var e=a.createBuffer(this.data);return e.read=this.read,e},a.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},a.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},a.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},a.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var i=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),r=new Uint8Array(this.length()+t);return r.set(i),this.data=new DataView(r.buffer),this},a.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},a.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var i=0;i>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},a.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},a.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},a.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},a.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},a.DataBuffer.prototype.putInt=function(e,t){s(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},a.DataBuffer.prototype.putSignedInt=function(e,t){return s(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},a.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),i=2<=i&&(t-=i<<1),t},a.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},a.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},a.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},a.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},a.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},a.DataBuffer.prototype.copy=function(){return new a.DataBuffer(this)},a.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},a.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},a.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},a.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(i+=e),(t>>>=1)>0&&(e+=e);return i},a.xorBytes=function(e,t,i){for(var r="",n="",a="",s=0,o=0;i>0;--i,++s)n=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(r+=a,a="",o=0),a+=String.fromCharCode(n),++o;return r+a},a.hexToBytes=function(e){var t="",i=0;for(!0&e.length&&(i=1,t+=String.fromCharCode(parseInt(e[0],16)));i>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",c=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],u="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";a.encode64=function(e,t){for(var i,r,n,a="",s="",o=0;o>2),a+=l.charAt((3&i)<<4|r>>4),isNaN(r)?a+="==":(a+=l.charAt((15&r)<<2|n>>6),a+=isNaN(n)?"=":l.charAt(63&n)),t&&a.length>t&&(s+=a.substr(0,t)+"\r\n",a=a.substr(t));return s+a},a.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,i,r,n,a="",s=0;s>4),64!==r&&(a+=String.fromCharCode((15&i)<<4|r>>2),64!==n&&(a+=String.fromCharCode((3&r)<<6|n)));return a},a.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},a.decodeUtf8=function(e){return decodeURIComponent(escape(e))},a.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:n.encode,decode:n.decode}},a.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},a.binary.raw.decode=function(e,t,i){var r=t;r||(r=new Uint8Array(e.length));for(var n=i=i||0,a=0;a>2),a+=l.charAt((3&i)<<4|r>>4),isNaN(r)?a+="==":(a+=l.charAt((15&r)<<2|n>>6),a+=isNaN(n)?"=":l.charAt(63&n)),t&&a.length>t&&(s+=a.substr(0,t)+"\r\n",a=a.substr(t));return s+a},a.binary.base64.decode=function(e,t,i){var r,n,a,s,o=t;o||(o=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var l=0,u=i=i||0;l>4,64!==a&&(o[u++]=(15&n)<<4|a>>2,64!==s&&(o[u++]=(3&a)<<6|s));return t?u-i:o.subarray(0,u)},a.binary.base58.encode=function(e,t){return a.binary.baseN.encode(e,u,t)},a.binary.base58.decode=function(e,t){return a.binary.baseN.decode(e,u,t)},a.text={utf8:{},utf16:{}},a.text.utf8.encode=function(e,t,i){e=a.encodeUtf8(e);var r=t;r||(r=new Uint8Array(e.length));for(var n=i=i||0,s=0;s0&&a.push(i),s=r.lastIndex;var o=t[0][1];switch(o){case"s":case"o":n");break;case"%":a.push("%");break;default:a.push("<%"+o+"?>")}}return a.push(e.substring(s)),a.join("")},a.formatNumber=function(e,t,i,r){var n=e,a=isNaN(t=Math.abs(t))?2:t,s=void 0===i?",":i,o=void 0===r?".":r,l=n<0?"-":"",c=parseInt(n=Math.abs(+n||0).toFixed(a),10)+"",u=c.length>3?c.length%3:0;return l+(u?c.substr(0,u)+o:"")+c.substr(u).replace(/(\d{3})(?=\d)/g,"$1"+o)+(a?s+Math.abs(n-c).toFixed(a).slice(2):"")},a.formatSize=function(e){return e>=1073741824?a.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?a.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?a.formatNumber(e/1024,0)+" KiB":a.formatNumber(e,0)+" bytes"},a.bytesFromIP=function(e){return-1!==e.indexOf(".")?a.bytesFromIPv4(e):-1!==e.indexOf(":")?a.bytesFromIPv6(e):null},a.bytesFromIPv4=function(e){if(4!==(e=e.split(".")).length)return null;for(var t=a.createBuffer(),i=0;ii[r].end-i[r].start&&(r=i.length-1)):i.push({start:l,end:l})}t.push(s)}if(i.length>0){var c=i[r];c.end-c.start>0&&(t.splice(c.start,c.end-c.start+1,""),0===c.start&&t.unshift(""),7===c.end&&t.push(""))}return t.join(":")},a.estimateCores=function(e,t){if("function"==typeof e&&(t=e,e={}),e=e||{},"cores"in a&&!e.update)return t(null,a.cores);if("undefined"!=typeof navigator&&"hardwareConcurrency"in navigator&&navigator.hardwareConcurrency>0)return a.cores=navigator.hardwareConcurrency,t(null,a.cores);if("undefined"==typeof Worker)return a.cores=1,t(null,a.cores);if("undefined"==typeof Blob)return a.cores=2,t(null,a.cores);var i=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){for(var t=Date.now(),i=t+4;Date.now()o.st&&n.stn.st&&o.st="8"&&(i="00"+i);var n=r.util.hexToBytes(i);e.putInt32(n.length),e.putBytes(n)}function s(e,t){e.putInt32(t.length),e.putString(t)}function o(){for(var e=r.md.sha1.create(),t=arguments.length,i=0;i(e=new r(e,i),t=new r(t,i),e.intersects(t,i))},8657(e,t,i){"use strict";var r=i(4418),n=i(3168),a=i(9304),s=i(4466);e.exports=function(e,t,i){for(var o=n(t),l=s.f,c=a.f,u=0;u-1e3&&e<1e3||S.call(/e/,t))return t;var i=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-I(-e):I(e);if(r!==e){var n=String(r),a=v.call(t,n.length+1);return b.call(n,i,"$&_")+"."+b.call(b.call(a,/([0-9]{3})/g,"$&_"),/_$/,"")}}return b.call(t,i,"$&_")}var N=i(6973),R=N.custom,U=K(R)?R:null,F={__proto__:null,double:'"',single:"'"},q={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function L(e,t,i){var r=i.quoteStyle||t,n=F[r];return n+e+n}function B(e){return b.call(String(e),/"/g,""")}function M(e){return!j||!("object"==typeof e&&(j in e||void 0!==e[j]))}function V(e){return"[object Array]"===G(e)&&M(e)}function $(e){return"[object RegExp]"===G(e)&&M(e)}function K(e){if(A)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!P)return!1;try{return P.call(e),!0}catch(e){}return!1}e.exports=function e(t,r,n,o){var l=r||{};if(H(l,"quoteStyle")&&!H(F,l.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(H(l,"maxStringLength")&&("number"==typeof l.maxStringLength?l.maxStringLength<0&&l.maxStringLength!==1/0:null!==l.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var g=!H(l,"customInspect")||l.customInspect;if("boolean"!=typeof g&&"symbol"!==g)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(H(l,"indent")&&null!==l.indent&&"\t"!==l.indent&&!(parseInt(l.indent,10)===l.indent&&l.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(H(l,"numericSeparator")&&"boolean"!=typeof l.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var w=l.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return J(t,l);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var S=String(t);return w?O(t,S):S}if("bigint"==typeof t){var I=String(t)+"n";return w?O(t,I):I}var z=void 0===l.depth?5:l.depth;if(void 0===n&&(n=0),n>=z&&z>0&&"object"==typeof t)return V(t)?"[Array]":"[Object]";var R,q=function(e,t){var i;if("\t"===e.indent)i="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;i=x.call(Array(e.indent+1)," ")}return{base:i,prev:x.call(Array(t+1),i)}}(l,n);if(void 0===o)o=[];else if(Q(o,t)>=0)return"[Circular]";function W(t,i,r){if(i&&(o=C.call(o)).push(i),r){var a={depth:l.depth};return H(l,"quoteStyle")&&(a.quoteStyle=l.quoteStyle),e(t,a,n+1,o)}return e(t,l,n+1,o)}if("function"==typeof t&&!$(t)){var Y=function(e){if(e.name)return e.name;var t=y.call(f.call(e),/^function\s*([\w$]+)/);return t?t[1]:null}(t),re=ie(t,W);return"[Function"+(Y?": "+Y:" (anonymous)")+"]"+(re.length>0?" { "+x.call(re,", ")+" }":"")}if(K(t)){var ne=A?b.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):P.call(t);return"object"!=typeof t||A?ne:X(ne)}if((R=t)&&"object"==typeof R&&("undefined"!=typeof HTMLElement&&R instanceof HTMLElement||"string"==typeof R.nodeName&&"function"==typeof R.getAttribute)){for(var ae="<"+k.call(String(t.nodeName)),se=t.attributes||[],oe=0;oe"}if(V(t)){if(0===t.length)return"[]";var le=ie(t,W);return q&&!function(e){for(var t=0;t=0)return!1;return!0}(le)?"["+te(le,q)+"]":"[ "+x.call(le,", ")+" ]"}if(function(e){return"[object Error]"===G(e)&&M(e)}(t)){var ce=ie(t,W);return"cause"in Error.prototype||!("cause"in t)||T.call(t,"cause")?0===ce.length?"["+String(t)+"]":"{ ["+String(t)+"] "+x.call(ce,", ")+" }":"{ ["+String(t)+"] "+x.call(_.call("[cause]: "+W(t.cause),ce),", ")+" }"}if("object"==typeof t&&g){if(U&&"function"==typeof t[U]&&N)return N(t,{depth:z-n});if("symbol"!==g&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!a||!e||"object"!=typeof e)return!1;try{a.call(e);try{c.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var ue=[];return s&&s.call(t,function(e,i){ue.push(W(i,t,!0)+" => "+W(e,t))}),ee("Map",a.call(t),ue,q)}if(function(e){if(!c||!e||"object"!=typeof e)return!1;try{c.call(e);try{a.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var de=[];return u&&u.call(t,function(e){de.push(W(e,t))}),ee("Set",c.call(t),de,q)}if(function(e){if(!d||!e||"object"!=typeof e)return!1;try{d.call(e,d);try{h.call(e,h)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return Z("WeakMap");if(function(e){if(!h||!e||"object"!=typeof e)return!1;try{h.call(e,h);try{d.call(e,d)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return Z("WeakSet");if(function(e){if(!p||!e||"object"!=typeof e)return!1;try{return p.call(e),!0}catch(e){}return!1}(t))return Z("WeakRef");if(function(e){return"[object Number]"===G(e)&&M(e)}(t))return X(W(Number(t)));if(function(e){if(!e||"object"!=typeof e||!E)return!1;try{return E.call(e),!0}catch(e){}return!1}(t))return X(W(E.call(t)));if(function(e){return"[object Boolean]"===G(e)&&M(e)}(t))return X(m.call(t));if(function(e){return"[object String]"===G(e)&&M(e)}(t))return X(W(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&t===globalThis||void 0!==i.g&&t===i.g)return"{ [object globalThis] }";if(!function(e){return"[object Date]"===G(e)&&M(e)}(t)&&!$(t)){var he=ie(t,W),pe=D?D(t)===Object.prototype:t instanceof Object||t.constructor===Object,me=t instanceof Object?"":"null prototype",ge=!pe&&j&&Object(t)===t&&j in t?v.call(G(t),8,-1):me?"Object":"",fe=(pe||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(ge||me?"["+x.call(_.call([],ge||[],me||[]),": ")+"] ":"");return 0===he.length?fe+"{}":q?fe+"{"+te(he,q)+"}":fe+"{ "+x.call(he,", ")+" }"}return String(t)};var W=Object.prototype.hasOwnProperty||function(e){return e in this};function H(e,t){return W.call(e,t)}function G(e){return g.call(e)}function Q(e,t){if(e.indexOf)return e.indexOf(t);for(var i=0,r=e.length;it.maxStringLength){var i=e.length-t.maxStringLength,r="... "+i+" more character"+(i>1?"s":"");return J(v.call(e,0,t.maxStringLength),t)+r}var n=q[t.quoteStyle||"single"];return n.lastIndex=0,L(b.call(b.call(e,n,"\\$1"),/[\x00-\x1f]/g,Y),"single",t)}function Y(e){var t=e.charCodeAt(0),i={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return i?"\\"+i:"\\x"+(t<16?"0":"")+w.call(t.toString(16))}function X(e){return"Object("+e+")"}function Z(e){return e+" { ? }"}function ee(e,t,i,r){return e+" ("+t+") {"+(r?te(i,r):x.call(i,", "))+"}"}function te(e,t){if(0===e.length)return"";var i="\n"+t.prev+t.base;return i+x.call(e,","+i)+"\n"+t.prev}function ie(e,t){var i=V(e),r=[];if(i){r.length=e.length;for(var n=0;n0===r(e,t,i)},8854(e,t,i){"use strict";const r=i(4517),n=i(1565),{ANY:a}=n,s=i(7476),o=i(7229),l=i(9761),c=i(1262),u=i(9639),d=i(2386);e.exports=(e,t,i,h)=>{let p,m,g,f,y;switch(e=new r(e,h),t=new s(t,h),i){case">":p=l,m=u,g=c,f=">",y=">=";break;case"<":p=c,m=d,g=l,f="<",y="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(o(e,t,h))return!1;for(let i=0;i{e.semver===a&&(e=new n(">=0.0.0")),s=s||e,o=o||e,p(e.semver,s.semver,h)?s=e:g(e.semver,o.semver,h)&&(o=e)}),s.operator===f||s.operator===y)return!1;if((!o.operator||o.operator===f)&&m(e,o.semver))return!1;if(o.operator===y&&g(e,o.semver))return!1}return!0}},8868(e,t,i){"use strict";const r=i(4517);e.exports=(e,t,i,n,a)=>{"string"==typeof i&&(a=n,n=i,i=void 0);try{return new r(e instanceof r?e.version:e,i).inc(t,n,a).version}catch(e){return null}}},8944(e,t,i){"use strict";var r=i(3008),n=i(5234),a=i(9117).String;e.exports=!!Object.getOwnPropertySymbols&&!n(function(){var e=Symbol("symbol detection");return!a(e)||!(Object(e)instanceof Symbol)||!Symbol.sham&&r&&r<41})},8953(e){"use strict";e.exports=class{constructor(){this.max=1e3,this.map=new Map}get(e){const t=this.map.get(e);return void 0===t?void 0:(this.map.delete(e),this.map.set(e,t),t)}delete(e){return this.map.delete(e)}set(e,t){if(!this.delete(e)&&void 0!==t){if(this.map.size>=this.max){const e=this.map.keys().next().value;this.delete(e)}this.map.set(e,t)}return this}}},9055(e,t,i){"use strict";var r=i(5234);e.exports=!r(function(){var e=function(){}.bind();return"function"!=typeof e||e.hasOwnProperty("prototype")})},9110(e){"use strict";e.exports=EvalError},9117(e,t,i){"use strict";var r=function(e){return e&&e.Math===Math&&e};e.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof i.g&&i.g)||r("object"==typeof this&&this)||function(){return this}()||Function("return this")()},9120(e,t,i){"use strict";var r=i(9117);e.exports=r},9123(e){"use strict";e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},9138(e,t,i){"use strict";var r=i(8794);e.exports=Function.prototype.bind||r},9304(e,t,i){"use strict";var r=i(6893),n=i(9944),a=i(4416),s=i(9123),o=i(380),l=i(2344),c=i(4418),u=i(9622),d=Object.getOwnPropertyDescriptor;t.f=r?d:function(e,t){if(e=o(e),t=l(t),u)try{return d(e,t)}catch(e){}if(c(e,t))return s(!n(a.f,e,t),e[t])}},9318(e,t){t.read=function(e,t,i,r,n){var a,s,o=8*n-r-1,l=(1<>1,u=-7,d=i?n-1:0,h=i?-1:1,p=e[t+d];for(d+=h,a=p&(1<<-u)-1,p>>=-u,u+=o;u>0;a=256*a+e[t+d],d+=h,u-=8);for(s=a&(1<<-u)-1,a>>=-u,u+=r;u>0;s=256*s+e[t+d],d+=h,u-=8);if(0===a)a=1-c;else{if(a===l)return s?NaN:1/0*(p?-1:1);s+=Math.pow(2,r),a-=c}return(p?-1:1)*s*Math.pow(2,a-r)},t.write=function(e,t,i,r,n,a){var s,o,l,c=8*a-n-1,u=(1<>1,h=23===n?Math.pow(2,-24)-Math.pow(2,-77):0,p=r?0:a-1,m=r?1:-1,g=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(o=isNaN(t)?1:0,s=u):(s=Math.floor(Math.log(t)/Math.LN2),t*(l=Math.pow(2,-s))<1&&(s--,l*=2),(t+=s+d>=1?h/l:h*Math.pow(2,1-d))*l>=2&&(s++,l/=2),s+d>=u?(o=0,s=u):s+d>=1?(o=(t*l-1)*Math.pow(2,n),s+=d):(o=t*Math.pow(2,d-1)*Math.pow(2,n),s=0));n>=8;e[i+p]=255&o,p+=m,o/=256,n-=8);for(s=s<0;e[i+p]=255&s,p+=m,s/=256,c-=8);e[i+p-m]|=128*g}},9336(e,t,i){"use strict";var r=i(1292);if(r)try{r([],"length")}catch(e){r=null}e.exports=r},9345(e,t,i){"use strict";var r={};r[i(4282)("toStringTag")]="z",e.exports="[object z]"===String(r)},9389(e,t,i){"use strict";var r=i(7611);e.exports=function(e){return r(e.length)}},9428(e,t,i){"use strict";const r=i(3955);e.exports=(e,t)=>{const i=r(e,t);return i&&i.prerelease.length?i.prerelease:null}},9435(e,t,i){"use strict";var r=i(5613),n=i(9117),a=i(7028),s=i(8529),o=i(2676),l=i(7060);n.Uint8Array&&r({target:"Uint8Array",proto:!0,forced:function(){try{var e=new ArrayBuffer(16,{maxByteLength:1024});new Uint8Array(e).setFromHex("cafed00d")}catch(e){return!0}}()},{setFromHex:function(e){s(this),a(e),o(this.buffer);var t=l(e,this).read;return{read:t,written:t/2}}})},9509(e,t,i){"use strict";var r=i(4318),n=TypeError;e.exports=function(e){if(r(e))throw new n("Can't call method on "+e);return e}},9543(e){"use strict";const t=Number.MAX_SAFE_INTEGER||9007199254740991;e.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:16,MAX_SAFE_BUILD_LENGTH:250,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:"2.0.0",FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}},9622(e,t,i){"use strict";var r=i(6893),n=i(5234),a=i(5926);e.exports=!r&&!n(function(){return 7!==Object.defineProperty(a("div"),"a",{get:function(){return 7}}).a})},9629(e){"use strict";e.exports=Object},9639(e,t,i){"use strict";const r=i(7851);e.exports=(e,t,i)=>r(e,t,i)<=0},9679(e,t,i){var r=i(4643);e.exports=r.md=r.md||{},r.md.algorithms=r.md.algorithms||{}},9701(){},9761(e,t,i){"use strict";const r=i(7851);e.exports=(e,t,i)=>r(e,t,i)>0},9809(e,t,i){"use strict";var r=i(8944);e.exports=r&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},9838(e){"use strict";e.exports=Error},9866(e,t,i){"use strict";var r=i(2618);e.exports=function(e,t){return void 0===e?arguments.length<2?"":t:r(e)}},9903(e,t,i){"use strict";var r=i(9138),n=i(3468),a=i(4531),s=i(8165);e.exports=function(e){if(e.length<1||"function"!=typeof e[0])throw new n("a function is required");return s(r,a,e)}},9942(e){"use strict";function t(e){if("string"!=typeof e)throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}function i(e,t){for(var i,r="",n=0,a=-1,s=0,o=0;o<=e.length;++o){if(o2){var l=r.lastIndexOf("/");if(l!==r.length-1){-1===l?(r="",n=0):n=(r=r.slice(0,l)).length-1-r.lastIndexOf("/"),a=o,s=0;continue}}else if(2===r.length||1===r.length){r="",n=0,a=o,s=0;continue}t&&(r.length>0?r+="/..":r="..",n=2)}else r.length>0?r+="/"+e.slice(a+1,o):r=e.slice(a+1,o),n=o-a-1;a=o,s=0}else 46===i&&-1!==s?++s:s=-1}return r}var r={resolve:function(){for(var e,r="",n=!1,a=arguments.length-1;a>=-1&&!n;a--){var s;a>=0?s=arguments[a]:(void 0===e&&(e=process.cwd()),s=e),t(s),0!==s.length&&(r=s+"/"+r,n=47===s.charCodeAt(0))}return r=i(r,!n),n?r.length>0?"/"+r:"/":r.length>0?r:"."},normalize:function(e){if(t(e),0===e.length)return".";var r=47===e.charCodeAt(0),n=47===e.charCodeAt(e.length-1);return 0!==(e=i(e,!r)).length||r||(e="."),e.length>0&&n&&(e+="/"),r?"/"+e:e},isAbsolute:function(e){return t(e),e.length>0&&47===e.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var e,i=0;i0&&(void 0===e?e=n:e+="/"+n)}return void 0===e?".":r.normalize(e)},relative:function(e,i){if(t(e),t(i),e===i)return"";if((e=r.resolve(e))===(i=r.resolve(i)))return"";for(var n=1;nc){if(47===i.charCodeAt(o+d))return i.slice(o+d+1);if(0===d)return i.slice(o+d)}else s>c&&(47===e.charCodeAt(n+d)?u=d:0===d&&(u=0));break}var h=e.charCodeAt(n+d);if(h!==i.charCodeAt(o+d))break;47===h&&(u=d)}var p="";for(d=n+u+1;d<=a;++d)d!==a&&47!==e.charCodeAt(d)||(0===p.length?p+="..":p+="/..");return p.length>0?p+i.slice(o+u):(o+=u,47===i.charCodeAt(o)&&++o,i.slice(o))},_makeLong:function(e){return e},dirname:function(e){if(t(e),0===e.length)return".";for(var i=e.charCodeAt(0),r=47===i,n=-1,a=!0,s=e.length-1;s>=1;--s)if(47===(i=e.charCodeAt(s))){if(!a){n=s;break}}else a=!1;return-1===n?r?"/":".":r&&1===n?"//":e.slice(0,n)},basename:function(e,i){if(void 0!==i&&"string"!=typeof i)throw new TypeError('"ext" argument must be a string');t(e);var r,n=0,a=-1,s=!0;if(void 0!==i&&i.length>0&&i.length<=e.length){if(i.length===e.length&&i===e)return"";var o=i.length-1,l=-1;for(r=e.length-1;r>=0;--r){var c=e.charCodeAt(r);if(47===c){if(!s){n=r+1;break}}else-1===l&&(s=!1,l=r+1),o>=0&&(c===i.charCodeAt(o)?-1===--o&&(a=r):(o=-1,a=l))}return n===a?a=l:-1===a&&(a=e.length),e.slice(n,a)}for(r=e.length-1;r>=0;--r)if(47===e.charCodeAt(r)){if(!s){n=r+1;break}}else-1===a&&(s=!1,a=r+1);return-1===a?"":e.slice(n,a)},extname:function(e){t(e);for(var i=-1,r=0,n=-1,a=!0,s=0,o=e.length-1;o>=0;--o){var l=e.charCodeAt(o);if(47!==l)-1===n&&(a=!1,n=o+1),46===l?-1===i?i=o:1!==s&&(s=1):-1!==i&&(s=-1);else if(!a){r=o+1;break}}return-1===i||-1===n||0===s||1===s&&i===n-1&&i===r+1?"":e.slice(i,n)},format:function(e){if(null===e||"object"!=typeof e)throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return function(e,t){var i=t.dir||t.root,r=t.base||(t.name||"")+(t.ext||"");return i?i===t.root?i+r:i+"/"+r:r}(0,e)},parse:function(e){t(e);var i={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return i;var r,n=e.charCodeAt(0),a=47===n;a?(i.root="/",r=1):r=0;for(var s=-1,o=0,l=-1,c=!0,u=e.length-1,d=0;u>=r;--u)if(47!==(n=e.charCodeAt(u)))-1===l&&(c=!1,l=u+1),46===n?-1===s?s=u:1!==d&&(d=1):-1!==s&&(d=-1);else if(!c){o=u+1;break}return-1===s||-1===l||0===d||1===d&&s===l-1&&s===o+1?-1!==l&&(i.base=i.name=0===o&&a?e.slice(1,l):e.slice(o,l)):(0===o&&a?(i.name=e.slice(1,s),i.base=e.slice(1,l)):(i.name=e.slice(o,s),i.base=e.slice(o,l)),i.ext=e.slice(s,l)),o>0?i.dir=e.slice(0,o-1):a&&(i.dir="/"),i},sep:"/",delimiter:":",win32:null,posix:null};r.posix=r,e.exports=r},9944(e,t,i){"use strict";var r=i(9055),n=Function.prototype.call;e.exports=r?n.bind(n):function(){return n.apply(n,arguments)}},9982(e,t,i){"use strict";i(1685)}},s={};function o(e){var t=s[e];if(void 0!==t)return t.exports;var i=s[e]={id:e,loaded:!1,exports:{}};return a[e].call(i.exports,i,i.exports,o),i.loaded=!0,i.exports}o.m=a,e="function"==typeof Symbol,t=e?Symbol("webpack queues"):"__webpack_queues__",i=e?Symbol("webpack exports"):"__webpack_exports__",r=e?Symbol("webpack error"):"__webpack_error__",n=e=>{e&&e.d<1&&(e.d=1,e.forEach(e=>e.r--),e.forEach(e=>e.r--?e.r++:e()))},o.a=(e,a,s)=>{var o;s&&((o=[]).d=-1);var l,c,u,d=new Set,h=e.exports,p=new Promise((e,t)=>{u=t,c=e});p[i]=h,p[t]=e=>(o&&e(o),d.forEach(e),p.catch(e=>{})),e.exports=p,a(e=>{var a;l=(e=>e.map(e=>{if(null!==e&&"object"==typeof e){if(e[t])return e;if(e.then){var a=[];a.d=0,e.then(e=>{s[i]=e,n(a)},e=>{s[r]=e,n(a)});var s={};return s[t]=e=>e(a),s}}var o={};return o[t]=e=>{},o[i]=e,o}))(e);var s=()=>l.map(e=>{if(e[r])throw e[r];return e[i]}),c=new Promise(e=>{(a=()=>e(s)).r=0;var i=e=>e!==o&&!d.has(e)&&(d.add(e),e&&!e.d&&(a.r++,e.push(a)));l.map(e=>e[t](i))});return a.r?c:s()},e=>(e?u(p[r]=e):c(h),n(o))),o&&o.d<0&&(o.d=0)},o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var i in t)o.o(t,i)&&!o.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},o.f={},o.e=e=>Promise.all(Object.keys(o.f).reduce((t,i)=>(o.f[i](e,t),t),[])),o.u=e=>e+".background.js",o.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),o.hmd=e=>((e=Object.create(e)).children||(e.children=[]),Object.defineProperty(e,"exports",{enumerable:!0,set:()=>{throw new Error("ES Modules may not assign module.exports or exports.*, Use ESM export syntax, instead: "+e.id)}}),e),o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.nmd=e=>(e.paths=[],e.children||(e.children=[]),e),o.v=(e,t,i,r)=>{var n=fetch(o.p+""+i+".module.wasm"),a=()=>n.then(e=>e.arrayBuffer()).then(e=>WebAssembly.instantiate(e,r)).then(t=>Object.assign(e,t.instance.exports));return n.then(t=>"function"==typeof WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(t,r).then(t=>Object.assign(e,t.instance.exports),e=>{if("application/wasm"!==t.headers.get("Content-Type"))return console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",e),a();throw e}):a())},(()=>{var e;o.g.importScripts&&(e=o.g.location+"");var t=o.g.document;if(!e&&t&&(t.currentScript&&"SCRIPT"===t.currentScript.tagName.toUpperCase()&&(e=t.currentScript.src),!e)){var i=t.getElementsByTagName("script");if(i.length)for(var r=i.length-1;r>-1&&(!e||!/^http(s?):/.test(e));)e=i[r--].src}if(!e)throw new Error("Automatic publicPath is not supported in this browser");e=e.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),o.p=e})(),(()=>{var e={792:1};o.f.i=(t,i)=>{e[t]||importScripts(o.p+o.u(t))};var t=self.webpackChunk_bitwarden_browser=self.webpackChunk_bitwarden_browser||[],i=t.push.bind(t);t.push=t=>{var[r,n,a]=t;for(var s in n)o.o(n,s)&&(o.m[s]=n[s]);for(a&&a(o);r.length;)e[r.pop()]=1;i(t)}})(),(()=>{"use strict";var e={};o.r(e),o.d(e,{Lq:()=>aE,Mt:()=>nE,sF:()=>YI,Zx:()=>hE,f3:()=>VI,zT:()=>pE,QS:()=>gE});var t,i={};o.r(i),o.d(i,{B:()=>mz,KQ:()=>yz,ji:()=>sz,jK:()=>hz,gb:()=>pz,Vm:()=>gz}),function(e){e[e.Debug=0]="Debug",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(t||(t={}));class r{constructor(e,t=null){this.isDev=e,this.filter=t,this.timersMap=new Map}debug(e,...i){this.isDev&&this.write(t.Debug,e,...i)}info(e,...i){this.write(t.Info,e,...i)}warning(e,...i){this.write(t.Warning,e,...i)}error(e,...i){this.write(t.Error,e,...i)}write(e,i,...r){if(null==this.filter||!this.filter(e))switch(e){case t.Debug:case t.Info:console.log(i,...r);break;case t.Warning:console.warn(i,...r);break;case t.Error:console.error(i,...r)}}measure(e,t,i,r,n){const a=`[${i}]: ${r}`,s=performance.measure(a,{start:e,detail:{devtools:{dataType:"track-entry",track:i,trackGroup:t,properties:n}}});return this.info(`${a} took ${s.duration}`,n),s}mark(e){const t=performance.mark(e,{detail:{devtools:{dataType:"marker"}}});return this.info(t.name,(new Date).toISOString()),t}}o(4533);var n=function(e,t){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},n(e,t)};function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}function s(e,t){var i,r,n,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},s=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return s.next=o(0),s.throw=o(1),s.return=o(2),"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(o){return function(l){return function(o){if(i)throw new TypeError("Generator is already executing.");for(;s&&(s=0,o[0]&&(a=0)),a;)try{if(i=1,r&&(n=2&o[0]?r.return:o[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,o[1])).done)return n;switch(r=0,n&&(o=[2&o[0],n.value]),o[0]){case 0:case 1:n=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(!((n=(n=a.trys).length>0&&n[n.length-1])||6!==o[0]&&2!==o[0])){a=0;continue}if(3===o[0]&&(!n||o[1]>n[0]&&o[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function c(e,t){var i="function"==typeof Symbol&&e[Symbol.iterator];if(!i)return e;var r,n,a=i.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=a.next()).done;)s.push(r.value)}catch(e){n={error:e}}finally{try{r&&!r.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}return s}function u(e,t,i){if(i||2===arguments.length)for(var r,n=0,a=t.length;n0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,i=this,r=i.hasError,n=i.isStopped,a=i.observers;return r||n?y:(this.currentObservers=null,a.push(e),new f(function(){t.currentObservers=null,g(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,i=t.hasError,r=t.thrownError,n=t.isStopped;i?e.error(r):n&&e.complete()},t.prototype.asObservable=function(){var e=new $;return e.source=this,e},t.create=function(e,t){return new G(e,t)},t}($),G=function(e){function t(t,i){var r=e.call(this)||this;return r.destination=t,r.source=i,r}return a(t,e),t.prototype.next=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.next)||void 0===i||i.call(t,e)},t.prototype.error=function(e){var t,i;null===(i=null===(t=this.destination)||void 0===t?void 0:t.error)||void 0===i||i.call(t,e)},t.prototype.complete=function(){var e,t;null===(t=null===(e=this.destination)||void 0===e?void 0:e.complete)||void 0===t||t.call(e)},t.prototype._subscribe=function(e){var t,i;return null!==(i=null===(t=this.source)||void 0===t?void 0:t.subscribe(e))&&void 0!==i?i:y},t}(H);function Q(e){return function(t){if(function(e){return h(null==e?void 0:e.lift)}(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw new TypeError("Unable to lift unknown Observable type")}}function J(e,t,i,r,n){return new Y(e,t,i,r,n)}var Y=function(e){function t(t,i,r,n,a,s){var o=e.call(this,t)||this;return o.onFinalize=a,o.shouldUnsubscribe=s,o._next=i?function(e){try{i(e)}catch(e){t.error(e)}}:e.prototype._next,o._error=n?function(e){try{n(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,o._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,o}return a(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var i=this.closed;e.prototype.unsubscribe.call(this),!i&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(T);function X(e,t){return Q(function(i,r){var n=0;i.subscribe(J(r,function(i){r.next(e.call(t,i,n++))}))})}var Z=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function ee(e){return h(null==e?void 0:e.then)}function te(e){return h(e[L])}function ie(e){return Symbol.asyncIterator&&h(null==e?void 0:e[Symbol.asyncIterator])}function re(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var ne="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ae(e){return h(null==e?void 0:e[ne])}function se(e){return function(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,n=i.apply(e,t||[]),a=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),s("next"),s("throw"),s("return",function(e){return function(t){return Promise.resolve(t).then(e,c)}}),r[Symbol.asyncIterator]=function(){return this},r;function s(e,t){n[e]&&(r[e]=function(t){return new Promise(function(i,r){a.push([e,t,i,r])>1||o(e,t)})},t&&(r[e]=t(r[e])))}function o(e,t){try{(i=n[e](t)).value instanceof d?Promise.resolve(i.value.v).then(l,c):u(a[0][2],i)}catch(e){u(a[0][3],e)}var i}function l(e){o("next",e)}function c(e){o("throw",e)}function u(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}(this,arguments,function(){var t,i,r;return s(this,function(n){switch(n.label){case 0:t=e.getReader(),n.label=1;case 1:n.trys.push([1,,9,10]),n.label=2;case 2:return[4,d(t.read())];case 3:return i=n.sent(),r=i.value,i.done?[4,d(void 0)]:[3,5];case 4:return[2,n.sent()];case 5:return[4,d(r)];case 6:return[4,n.sent()];case 7:return n.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function oe(e){return h(null==e?void 0:e.getReader)}function le(e){if(e instanceof $)return e;if(null!=e){if(te(e))return r=e,new $(function(e){var t=r[L]();if(h(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")});if(Z(e))return function(e){return new $(function(t){for(var i=0;i0&&d(n)},void 0,void 0,function(){(null==a?void 0:a.closed)||null==a||a.unsubscribe(),o=null})),!c&&d(null!=r?"number"==typeof r?r:+r-l.now():n)})}function qe(e){throw new Ue(e)}function Le(e,t){return Q(function(i,r){var n=null,a=0,s=!1,o=function(){return s&&!n&&r.complete()};i.subscribe(J(r,function(i){null==n||n.unsubscribe();var s=0,l=a++;le(e(i,l)).subscribe(n=J(r,function(e){return r.next(t?t(i,e,l,s++):e)},function(){n=null,o()}))},function(){s=!0,o()}))})}class Be{constructor(e){this.groups=[],this.users=[],this.externalId=e.externalId,e.groups&&(this.groups=e.groups),e.users&&(this.users=e.users)}}Be.isUpdate=e=>e instanceof Me;class Me extends Be{constructor(e){var t,i;super(e),this.name=null!==(i=null===(t=e.name)||void 0===t?void 0:t.encryptedString)&&void 0!==i?i:null}}class Ve extends Be{constructor(e){if(null==e||null==e.name||null==e.name.encryptedString)throw new Error("CollectionWithIdRequest must contain name.");super({externalId:e.externalId}),this.name=e.name.encryptedString,this.id=e.id}}(Re=Ne||(Ne={})).AutoConfirm="pm-19934-auto-confirm-organization-users",Re.DefaultUserCollectionRestore="pm-30883-my-items-restored-users",Re.BulkReinviteUI="pm-28416-bulk-reinvite-ux-improvements",Re.PM23801_PrefetchPasswordPrelogin="pm-23801-prefetch-password-prelogin",Re.PM27086_UpdateAuthenticationApisForInputPassword="pm-27086-update-authentication-apis-for-input-password",Re.SafariAccountSwitching="pm-5594-safari-account-switching",Re.PM31088_MasterPasswordServiceEmitSalt="pm-31088-master-password-service-emit-salt",Re.UseUndeterminedCipherScenarioTriggeringLogic="undetermined-cipher-scenario-logic",Re.MacOsNativeCredentialSync="macos-native-credential-sync",Re.WindowsDesktopAutotype="windows-desktop-autotype",Re.WindowsDesktopAutotypeGA="windows-desktop-autotype-ga",Re.SSHAgentV2="ssh-agent-v2",Re.TrialPaymentOptional="PM-8163-trial-payment",Re.PM24032_NewNavigationPremiumUpgradeButton="pm-24032-new-navigation-premium-upgrade-button",Re.PM23713_PremiumBadgeOpensNewPremiumUpgradeDialog="pm-23713-premium-badge-opens-new-premium-upgrade-dialog",Re.PM26462_Milestone_3="pm-26462-milestone-3",Re.PM23341_Milestone_2="pm-23341-milestone-2",Re.PM29594_UpdateIndividualSubscriptionPage="pm-29594-update-individual-subscription-page",Re.PM29593_PremiumToOrganizationUpgrade="pm-29593-premium-to-organization-upgrade",Re.PrivateKeyRegeneration="pm-12241-private-key-regeneration",Re.EnrollAeadOnKeyRotation="enroll-aead-on-key-rotation",Re.ForceUpdateKDFSettings="pm-18021-force-update-kdf-settings",Re.SdkKeyRotation="pm-30144-sdk-key-rotation",Re.LinuxBiometricsV2="pm-26340-linux-biometrics-v2",Re.NoLogoutOnKdfChange="pm-23995-no-logout-on-kdf-change",Re.PasskeyUnlock="pm-2035-passkey-unlock",Re.DataRecoveryTool="pm-28813-data-recovery-tool",Re.ConsolidatedSessionTimeoutComponent="pm-26056-consolidated-session-timeout-component",Re.PM27279_V2RegistrationTdeJit="pm-27279-v2-registration-tde-jit",Re.EnableAccountEncryptionV2KeyConnectorRegistration="enable-account-encryption-v2-key-connector-registration",Re.EnableAccountEncryptionV2JitPasswordRegistration="enable-account-encryption-v2-jit-password-registration",Re.UseSdkPasswordGenerators="pm-19976-use-sdk-password-generators",Re.SendUIRefresh="pm-28175-send-ui-refresh",Re.SendEmailOTP="pm-19051-send-email-verification",Re.EventManagementForDataDogAndCrowdStrike="event-management-for-datadog-and-crowdstrike",Re.EventManagementForHuntress="event-management-for-huntress",Re.PhishingDetection="phishing-detection",Re.Milestone11AppPageImprovements="pm-30538-dirt-milestone-11-app-page-improvements",Re.PM19941MigrateCipherDomainToSdk="pm-19941-migrate-cipher-domain-to-sdk",Re.PM22134SdkCipherListView="pm-22134-sdk-cipher-list-view",Re.PM22136_SdkCipherEncryption="pm-22136-sdk-cipher-encryption",Re.CipherKeyEncryption="cipher-key-encryption",Re.BrowserPremiumSpotlight="pm-23384-browser-premium-spotlight",Re.MigrateMyVaultToMyItems="pm-20558-migrate-myvault-to-myitems",Re.PM27632_SdkCipherCrudOperations="pm-27632-cipher-crud-operations-to-sdk",Re.PM30521_AutofillButtonViewLoginScreen="pm-30521-autofill-button-view-login-screen",Re.PM29438_WelcomeDialogWithExtensionPrompt="pm-29438-welcome-dialog-with-extension-prompt",Re.PM29438_DialogWithExtensionPromptAccountAge="pm-29438-dialog-with-extension-prompt-account-age",Re.PM29437_WelcomeDialog="pm-29437-welcome-dialog-no-ext-prompt",Re.PM31039ItemActionInExtension="pm-31039-item-action-in-extension",Re.ContentScriptIpcChannelFramework="content-script-ipc-channel-framework",Re.WebAuthnRelatedOrigins="pm-30529-webauthn-related-origins",Re.PM19148_InnovationArchive="pm-19148-innovation-archive",Re.DesktopUiMigrationMilestone1="desktop-ui-migration-milestone-1",Re.DesktopUiMigrationMilestone2="desktop-ui-migration-milestone-2",Re.RouterFocusManagement="router-focus-management";const $e=!1,Ke={[Ne.AutoConfirm]:$e,[Ne.DefaultUserCollectionRestore]:$e,[Ne.BulkReinviteUI]:$e,[Ne.UseUndeterminedCipherScenarioTriggeringLogic]:$e,[Ne.MacOsNativeCredentialSync]:$e,[Ne.WindowsDesktopAutotype]:$e,[Ne.WindowsDesktopAutotypeGA]:$e,[Ne.SSHAgentV2]:$e,[Ne.PM31039ItemActionInExtension]:$e,[Ne.UseSdkPasswordGenerators]:$e,[Ne.SendUIRefresh]:$e,[Ne.SendEmailOTP]:$e,[Ne.EventManagementForDataDogAndCrowdStrike]:$e,[Ne.EventManagementForHuntress]:$e,[Ne.PhishingDetection]:$e,[Ne.Milestone11AppPageImprovements]:$e,[Ne.CipherKeyEncryption]:$e,[Ne.PM19941MigrateCipherDomainToSdk]:$e,[Ne.PM22134SdkCipherListView]:$e,[Ne.PM22136_SdkCipherEncryption]:$e,[Ne.BrowserPremiumSpotlight]:$e,[Ne.PM27632_SdkCipherCrudOperations]:$e,[Ne.MigrateMyVaultToMyItems]:$e,[Ne.PM30521_AutofillButtonViewLoginScreen]:$e,[Ne.PM29438_WelcomeDialogWithExtensionPrompt]:$e,[Ne.PM29438_DialogWithExtensionPromptAccountAge]:5,[Ne.PM29437_WelcomeDialog]:$e,[Ne.PM23801_PrefetchPasswordPrelogin]:$e,[Ne.PM27086_UpdateAuthenticationApisForInputPassword]:$e,[Ne.SafariAccountSwitching]:$e,[Ne.PM31088_MasterPasswordServiceEmitSalt]:$e,[Ne.TrialPaymentOptional]:$e,[Ne.PM24032_NewNavigationPremiumUpgradeButton]:$e,[Ne.PM23713_PremiumBadgeOpensNewPremiumUpgradeDialog]:$e,[Ne.PM26462_Milestone_3]:$e,[Ne.PM23341_Milestone_2]:$e,[Ne.PM29594_UpdateIndividualSubscriptionPage]:$e,[Ne.PM29593_PremiumToOrganizationUpgrade]:$e,[Ne.PrivateKeyRegeneration]:$e,[Ne.EnrollAeadOnKeyRotation]:$e,[Ne.ForceUpdateKDFSettings]:$e,[Ne.SdkKeyRotation]:$e,[Ne.LinuxBiometricsV2]:$e,[Ne.NoLogoutOnKdfChange]:$e,[Ne.PasskeyUnlock]:$e,[Ne.DataRecoveryTool]:$e,[Ne.ConsolidatedSessionTimeoutComponent]:$e,[Ne.PM27279_V2RegistrationTdeJit]:$e,[Ne.EnableAccountEncryptionV2KeyConnectorRegistration]:$e,[Ne.EnableAccountEncryptionV2JitPasswordRegistration]:$e,[Ne.ContentScriptIpcChannelFramework]:$e,[Ne.WebAuthnRelatedOrigins]:$e,[Ne.PM19148_InnovationArchive]:$e,[Ne.DesktopUiMigrationMilestone1]:$e,[Ne.DesktopUiMigrationMilestone2]:$e,[Ne.RouterFocusManagement]:$e};function We(e,t){return null==(null==e?void 0:e.featureStates)||null==e.featureStates[t]?Ke[t]:e.featureStates[t]}var He,Ge,Qe,Je,Ye,Xe,Ze,et,tt,it,rt,nt,at;!function(e){e[e.Default=0]="Default",e[e.BillingSync=1]="BillingSync",e[e.Scim=2]="Scim"}(He||(He={})),function(e){e[e.CloudBillingSync=1]="CloudBillingSync",e[e.Scim=2]="Scim"}(Ge||(Ge={})),function(e){e[e.Invited=0]="Invited",e[e.Accepted=1]="Accepted",e[e.Confirmed=2]="Confirmed",e[e.Revoked=-1]="Revoked"}(Qe||(Qe={})),function(e){e[e.Owner=0]="Owner",e[e.Admin=1]="Admin",e[e.User=2]="User",e[e.Custom=4]="Custom"}(Je||(Je={})),(nt=Ye||(Ye={}))[nt.TwoFactorAuthentication=0]="TwoFactorAuthentication",nt[nt.MasterPassword=1]="MasterPassword",nt[nt.PasswordGenerator=2]="PasswordGenerator",nt[nt.SingleOrg=3]="SingleOrg",nt[nt.RequireSso=4]="RequireSso",nt[nt.OrganizationDataOwnership=5]="OrganizationDataOwnership",nt[nt.DisableSend=6]="DisableSend",nt[nt.SendOptions=7]="SendOptions",nt[nt.ResetPassword=8]="ResetPassword",nt[nt.MaximumVaultTimeout=9]="MaximumVaultTimeout",nt[nt.DisablePersonalVaultExport=10]="DisablePersonalVaultExport",nt[nt.ActivateAutofill=11]="ActivateAutofill",nt[nt.AutomaticAppLogIn=12]="AutomaticAppLogIn",nt[nt.FreeFamiliesSponsorshipPolicy=13]="FreeFamiliesSponsorshipPolicy",nt[nt.RemoveUnlockWithPin=14]="RemoveUnlockWithPin",nt[nt.RestrictedItemTypes=15]="RestrictedItemTypes",nt[nt.UriMatchDefaults=16]="UriMatchDefaults",nt[nt.AutotypeDefaultSetting=17]="AutotypeDefaultSetting",nt[nt.AutoConfirm=18]="AutoConfirm",nt[nt.BlockClaimedDomainAccountCreation=19]="BlockClaimedDomainAccountCreation",function(e){e[e.Msp=0]="Msp",e[e.Reseller=1]="Reseller",e[e.BusinessUnit=2]="BusinessUnit"}(Xe||(Xe={})),function(e){e[e.Invited=0]="Invited",e[e.Accepted=1]="Accepted",e[e.Confirmed=2]="Confirmed",e[e.Revoked=-1]="Revoked"}(Ze||(Ze={})),function(e){e[e.ProviderAdmin=0]="ProviderAdmin",e[e.ServiceUser=1]="ServiceUser"}(et||(et={})),function(e){e[e.Default=0]="Default",e[e.AzureAd=1]="AzureAd",e[e.Okta=2]="Okta",e[e.OneLogin=3]="OneLogin",e[e.JumpCloud=4]="JumpCloud",e[e.GoogleWorkspace=5]="GoogleWorkspace",e[e.Rippling=6]="Rippling"}(tt||(tt={})),function(e){e[e.Pending=0]="Pending",e[e.Created=1]="Created",e[e.Billable=2]="Billable"}(it||(it={})),(at=rt||(rt={}))[at.AesCbc256_B64=0]="AesCbc256_B64",at[at.AesCbc256_HmacSha256_B64=2]="AesCbc256_HmacSha256_B64",at[at.CoseEncrypt0=7]="CoseEncrypt0",at[at.Rsa2048_OaepSha256_B64=3]="Rsa2048_OaepSha256_B64",at[at.Rsa2048_OaepSha1_B64=4]="Rsa2048_OaepSha1_B64",at[at.Rsa2048_OaepSha256_HmacSha256_B64=5]="Rsa2048_OaepSha256_HmacSha256_B64",at[at.Rsa2048_OaepSha1_HmacSha256_B64=6]="Rsa2048_OaepSha1_HmacSha256_B64";const st={[rt.AesCbc256_B64]:2,[rt.AesCbc256_HmacSha256_B64]:3,[rt.Rsa2048_OaepSha256_B64]:1,[rt.Rsa2048_OaepSha1_B64]:1,[rt.Rsa2048_OaepSha256_HmacSha256_B64]:2,[rt.Rsa2048_OaepSha1_HmacSha256_B64]:2,[rt.CoseEncrypt0]:1};var ot,lt,ct;!function(e){e[e.Direct=0]="Direct",e[e.Azure=1]="Azure"}(ot||(ot={})),function(e){e[e.ServerAuthorization=1]="ServerAuthorization",e[e.LocalAuthorization=2]="LocalAuthorization"}(lt||(lt={})),function(e){e.Local="local",e.Memory="memory",e.Session="session"}(ct||(ct={}));class ut{}var dt,ht,pt;class mt extends ut{constructor(){super(...arguments),this.store={},this.updatesSubject=new H}get valuesRequireDeserialization(){return!0}get updates$(){return this.updatesSubject.asObservable()}get(e){const t=this.store[e];if(t){const e=JSON.parse(t);return Promise.resolve(e)}return Promise.resolve(null)}has(e){return t=this,i=void 0,n=function*(){return null!=(yield this.get(e))},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}save(e,t){return null==t?this.remove(e):(this.store[e]=JSON.stringify(t),this.updatesSubject.next({key:e,updateType:"save"}),Promise.resolve())}remove(e){return delete this.store[e],this.updatesSubject.next({key:e,updateType:"remove"}),Promise.resolve()}}!function(e){e.Both="both",e.Disk="disk",e.Memory="memory"}(dt||(dt={}));class gt{constructor(e,t){this.diskStorageService=e,this.memoryStorageService=t}get(e,t){switch(e){case"disk":return[e,this.diskStorageService];case"memory":return[e,this.memoryStorageService];default:throw new Error(`Unexpected location: ${e}`)}}}!function(e){e.Auto="auto",e.Pin="pin"}(ht||(ht={})),function(e){e.System="system",e.Light="light",e.Dark="dark"}(pt||(pt={}));const ft={System:"system",Light:"light",Dark:"dark"};var yt=o(9942),vt=o(1048);function bt(){for(var e=[],t=0;ti+1&&e.charCodeAt(r-1)<=32;)r-=1;if(47===e.charCodeAt(i)&&47===e.charCodeAt(i+1))i+=2;else{const t=e.indexOf(":/",i);if(-1!==t){const r=t-i,n=e.charCodeAt(i),a=e.charCodeAt(i+1),s=e.charCodeAt(i+2),o=e.charCodeAt(i+3),l=e.charCodeAt(i+4);if(5===r&&104===n&&116===a&&116===s&&112===o&&115===l);else if(4===r&&104===n&&116===a&&116===s&&112===o);else if(3===r&&119===n&&115===a&&115===s);else if(2===r&&119===n&&115===a);else for(let r=i;r=97&&t<=122||t>=48&&t<=57||46===t||45===t||43===t))return null}for(i=t+2;47===e.charCodeAt(i);)i+=1}}let t=-1,a=-1,s=-1;for(let o=i;o=65&&i<=90&&(n=!0)}if(-1!==t&&t>i&&ti&&si+1&&46===e.charCodeAt(r-1);)r-=1;const a=0!==i||r!==e.length?e.slice(i,r):e;return n?a.toLowerCase():a}function kt(e){return e>=97&&e<=122||e>=48&&e<=57||e>127}function St(e){if(e.length>255)return!1;if(0===e.length)return!1;if(!kt(e.charCodeAt(0))&&46!==e.charCodeAt(0)&&95!==e.charCodeAt(0))return!1;let t=-1,i=-1;const r=e.length;for(let n=0;n64||46===i||45===i||95===i)return!1;t=n}else if(!kt(r)&&45!==r&&95!==r)return!1;i=r}return r-t-1<=63&&45!==i}const _t=function({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:i=!0,extractHostname:r=!0,mixedInputs:n=!0,validHosts:a=null,validateHostname:s=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:i,extractHostname:r,mixedInputs:n,validHosts:a,validateHostname:s}}({});function xt(e,t,i,r,n){const a=function(e){return void 0===e?_t:function({allowIcannDomains:e=!0,allowPrivateDomains:t=!1,detectIp:i=!0,extractHostname:r=!0,mixedInputs:n=!0,validHosts:a=null,validateHostname:s=!0}){return{allowIcannDomains:e,allowPrivateDomains:t,detectIp:i,extractHostname:r,mixedInputs:n,validHosts:a,validateHostname:s}}(e)}(r);return"string"!=typeof e?n:(a.extractHostname?a.mixedInputs?n.hostname=wt(e,St(e)):n.hostname=wt(e,!1):n.hostname=e,a.detectIp&&null!==n.hostname&&(n.isIp=function(e){if(e.length<3)return!1;let t=e.startsWith("[")?1:0,i=e.length;if("]"===e[i-1]&&(i-=1),i-t>39)return!1;let r=!1;for(;t=48&&i<=57||i>=97&&i<=102||i>=65&&i<=90))return!1}return r}(s=n.hostname)||function(e){if(e.length<7)return!1;if(e.length>15)return!1;let t=0;for(let i=0;i57)return!1}return 3===t&&46!==e.charCodeAt(0)&&46!==e.charCodeAt(e.length-1)}(s),n.isIp)?n:a.validateHostname&&a.extractHostname&&null!==n.hostname&&!St(n.hostname)?(n.hostname=null,n):(0===t||null===n.hostname||(i(n.hostname,a,n),2===t||null===n.publicSuffix||(n.domain=function(e,t,i){if(null!==i.validHosts){const e=i.validHosts;for(const i of e)if(function(e,t){return!!e.endsWith(t)&&(e.length===t.length||"."===e[e.length-t.length-1])}(t,i))return i}let r=0;if(t.startsWith("."))for(;r3){const t=e.length-1,r=e.charCodeAt(t),n=e.charCodeAt(t-1),a=e.charCodeAt(t-2),s=e.charCodeAt(t-3);if(109===r&&111===n&&99===a&&46===s)return i.isIcann=!0,i.isPrivate=!1,i.publicSuffix="com",!0;if(103===r&&114===n&&111===a&&46===s)return i.isIcann=!0,i.isPrivate=!1,i.publicSuffix="org",!0;if(117===r&&100===n&&101===a&&46===s)return i.isIcann=!0,i.isPrivate=!1,i.publicSuffix="edu",!0;if(118===r&&111===n&&103===a&&46===s)return i.isIcann=!0,i.isPrivate=!1,i.publicSuffix="gov",!0;if(116===r&&101===n&&110===a&&46===s)return i.isIcann=!0,i.isPrivate=!1,i.publicSuffix="net",!0;if(101===r&&100===n&&46===a)return i.isIcann=!0,i.isPrivate=!1,i.publicSuffix="de",!0}return!1}(e,t,i))return;const n=e.split("."),a=(t.allowPrivateDomains?2:0)|(t.allowIcannDomains?1:0),s=Et(n,Ct,n.length-1,a);if(null!==s)return i.isIcann=s.isIcann,i.isPrivate=s.isPrivate,void(i.publicSuffix=n.slice(s.index+1).join("."));const o=Et(n,It,n.length-1,a);if(null!==o)return i.isIcann=o.isIcann,i.isPrivate=o.isPrivate,void(i.publicSuffix=n.slice(o.index).join("."));i.isIcann=!1,i.isPrivate=!1,i.publicSuffix=null!==(r=n[n.length-1])&&void 0!==r?r:null}const Pt={domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,publicSuffix:null,subdomain:null};function At(e,t={}){return xt(e,5,zt,t,{domain:null,domainWithoutSuffix:null,hostname:null,isIcann:null,isIp:null,isPrivate:null,publicSuffix:null,subdomain:null})}o(5984);const jt="undefined"==typeof self?o(5442):null;class Tt{static init(){Tt.inited||(Tt.inited=!0,Tt.isNode="undefined"!=typeof process&&null!=process.release&&"node"===process.release.name,Tt.isBrowser="undefined"!=typeof window,Tt.isMobileBrowser=Tt.isBrowser&&this.isMobile(window),Tt.isAppleMobileBrowser=Tt.isBrowser&&this.isAppleMobile(window),Tt.isNode?Tt.global=o.g:Tt.isBrowser?Tt.global=window:Tt.global=self)}static fromB64ToArray(e){if(null==e)return null;if(Tt.isNode)return new Uint8Array(Buffer.from(e,"base64"));{const t=Tt.global.atob(e),i=new Uint8Array(t.length);for(let e=0;e("00"+e.toString(16)).slice(-2)).join("")}}static hexStringToArrayBuffer(e){if(e.length%2!=0)throw"HexString has to be an even length";const t=new ArrayBuffer(e.length/2),i=new Uint8Array(t);for(let t=0;t{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}static isGuid(e){return RegExp(Tt.guidRegex,"i").test(e)}static getHostname(e){if(Tt.isNullOrWhitespace(e))return null;if((e=e.trim()).startsWith("data:"))return null;if(e.startsWith("about:"))return null;if(e.startsWith("file:"))return null;if(e.indexOf("!")>0)return null;try{const t=function(e,t={}){var i;return(i=Pt).domain=null,i.domainWithoutSuffix=null,i.hostname=null,i.isIcann=null,i.isIp=null,i.isPrivate=null,i.publicSuffix=null,i.subdomain=null,xt(e,0,zt,t,Pt).hostname}(e,{validHosts:this.validHosts});if(null!=t)return t}catch(e){return null}return null}static getHost(e){const t=Tt.getUrl(e);try{return null!=t&&""!==t.host?t.host:null}catch(e){return null}}static getDomain(e){if(Tt.isNullOrWhitespace(e))return null;if((e=e.trim()).startsWith("data:"))return null;if(e.startsWith("about:"))return null;try{const t=At(e,{validHosts:this.validHosts,allowPrivateDomains:!0});if(null!=t&&null!=t.hostname)return"localhost"===t.hostname||t.isIp?t.hostname:null!=t.domain?t.domain:null}catch(e){return null}return null}static getQueryParams(e){const t=Tt.getUrl(e);if(null==t||null==t.search||""===t.search)return null;const i=new Map;return("?"===t.search[0]?t.search.substr(1):t.search).split("&").forEach(e=>{const t=e.split("=");t.length<1||i.set(decodeURIComponent(t[0]).toLowerCase(),null==t[1]?"":decodeURIComponent(t[1]))}),i}static getSortFunction(e,t){return(i,r)=>null==i[t]&&null!=r[t]?-1:null!=i[t]&&null==r[t]?1:null==i[t]&&null==r[t]?0:e.collator?e.collator.compare(i[t],r[t]):i[t].localeCompare(r[t])}static isNullOrWhitespace(e){return null==e||"string"!=typeof e||""===e.trim()}static isNullOrEmpty(e){return null==e||"string"!=typeof e||""==e}static isPromise(e){return null!=e&&"function"==typeof e.then&&"function"==typeof e.catch}static nameOf(e){return e}static assign(e,t){return Object.assign(e,t)}static iterateEnum(e){return Object.keys(e).filter(e=>Number.isNaN(+e)).map(t=>e[t])}static getUrl(e){return this.isNullOrWhitespace(e)?null:(e=e.trim(),Tt.getUrlObject(e))}static camelToPascalCase(e){return e.charAt(0).toUpperCase()+e.slice(1)}static pickTextColorBasedOnBgColor(e,t=186,i=!1){const r="#"===e.charAt(0)?e.substring(1,7):e;return.299*parseInt(r.substring(0,2),16)+.587*parseInt(r.substring(2,4),16)+.114*parseInt(r.substring(4,6),16)>t?i?"black":"black !important":i?"white":"white !important"}static stringToColor(e){let t=0;for(let i=0;i>8*e&255).toString(16)).substr(-2);return i}static getContainerService(){if(null==this.global.bitwardenContainerService)throw new Error("global bitwardenContainerService not initialized.");return this.global.bitwardenContainerService}static validateHexColor(e){return/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/.test(e)}static mapToRecord(e){return null==e?null:e instanceof Map?Object.fromEntries(e):e}static recordToMap(e){if(null==e)return null;if(e instanceof Map)return e;const t=Object.entries(e);return 0===t.length?new Map:isNaN(Number(t[0][0]))?new Map(t):new Map(t.map(e=>[Number(e[0]),e[1]]))}static merge(e,t){return Object.assign(e,t)}static encodeRFC3986URIComponent(e){return encodeURIComponent(e).replace(/[!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}static normalizePath(e){return yt.normalize(decodeURIComponent(e)).replace(/^(\.\.(\/|\\|$))+/,"")}static invalidUrlPatterns(e){const t=decodeURIComponent(e.toLocaleLowerCase());return!!["..","%2e","\\","%5c"].some(e=>t.includes(e))||!(!t.includes("?")||!this.validateQueryParameters(t))}static validateQueryParameters(e){try{let t;return!!e.includes("?")&&(t=e.split("?")[1],["/","%2f","#","%23"].some(e=>t.includes(e)))}catch(e){throw new Error(`Error validating query parameters: ${e}`)}}static isMobile(e){let t=!1;var i;return i=e.navigator.userAgent||e.navigator.vendor||e.opera,(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(i)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(i.substr(0,4)))&&(t=!0),t||null!=e.navigator.userAgent.match(/iPad/i)}static delay(e){return new Promise(t=>setTimeout(t,e))}static asyncToObservable(e){return bt(void 0).pipe(Le(()=>e()))}static daysRemaining(e){const t=e.getTime()-Date.now();return Math.max(0,Math.floor(t/864e5))}static isAppleMobile(e){return null!=e.navigator.userAgent.match(/iPhone/i)||null!=e.navigator.userAgent.match(/iPad/i)}static getUrlObject(e){const t=e.indexOf("://")>-1;if(!t&&e.indexOf(".")>-1)e="http://"+e;else if(!t)return null;try{return null!=jt?new jt.URL(e):new URL(e)}catch(e){}return null}}Tt.inited=!1,Tt.isNode=!1,Tt.isBrowser=!0,Tt.isMobileBrowser=!1,Tt.isAppleMobileBrowser=!1,Tt.global=null,Tt.regexpEmojiPresentation=/(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5-\uDED7\uDEEB\uDEEC\uDEF4-\uDEFC\uDFE0-\uDFEB]|\uD83E[\uDD0C-\uDD3A\uDD3C-\uDD45\uDD47-\uDD78\uDD7A-\uDDCB\uDDCD-\uDDFF\uDE70-\uDE74\uDE78-\uDE7A\uDE80-\uDE86\uDE90-\uDEA8\uDEB0-\uDEB6\uDEC0-\uDEC2\uDED0-\uDED6])/g,Tt.validHosts=["localhost"],Tt.originalMinimumPasswordLength=8,Tt.minimumPasswordLength=12,Tt.maximumPasswordLength=128,Tt.DomainMatchBlacklist=new Map([["google.com",new Set(["script.google.com"])]]),Tt.guidRegex=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/,Tt.init();var Dt=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ot="[error: cannot decrypt]";class Nt{constructor(e,t,i,r){null!=t?this.initFromData(e,t,i,r):this.initFromEncryptedString(e)}get ivBytes(){return null==this.iv?null:Tt.fromB64ToArray(this.iv)}get macBytes(){return null==this.mac?null:Tt.fromB64ToArray(this.mac)}get dataBytes(){return null==this.data?null:Tt.fromB64ToArray(this.data)}toSdk(){return this.encryptedString}toJSON(){return this.encryptedString}static fromJSON(e){return null==e?null:new Nt(e)}initFromData(e,t,i,r){this.encryptedString=null!=i?e+"."+i+"|"+t:e+"."+t,null!=r&&(this.encryptedString=this.encryptedString+"|"+r),this.encryptionType=e,this.data=t,this.iv=i,this.mac=r}initFromEncryptedString(e){if(this.encryptedString=e,!this.encryptedString)return;const{encType:t,encPieces:i}=Nt.parseEncryptedString(this.encryptedString);if(this.encryptionType=t,i.length===st[t])switch(t){case rt.AesCbc256_HmacSha256_B64:this.iv=i[0],this.data=i[1],this.mac=i[2];break;case rt.AesCbc256_B64:this.iv=i[0],this.data=i[1];break;case rt.Rsa2048_OaepSha256_B64:case rt.Rsa2048_OaepSha1_B64:this.data=i[0];break;case rt.Rsa2048_OaepSha256_HmacSha256_B64:case rt.Rsa2048_OaepSha1_HmacSha256_B64:this.data=i[0],this.mac=i[1];break;default:return}}static parseEncryptedString(e){const t=e.split(".");let i,r=null;if(2===t.length)try{i=parseInt(t[0],null),r=t[1].split("|")}catch(e){return{encType:NaN,encPieces:[]}}else r=e.split("|"),i=rt.AesCbc256_B64;return{encType:i,encPieces:r}}static isSerializedEncString(e){if(null==e)return!1;const{encType:t,encPieces:i}=this.parseEncryptedString(e);return!isNaN(t)&&0!==i.length&&st[t]===i.length}decrypt(e){return Dt(this,arguments,void 0,function*(e,t=null,i){if(null!=this.decryptedValue)return this.decryptedValue;try{if(null==t&&(t=yield this.getKeyForDecryption(e)),null==t)throw new Error("No key to decrypt EncString with orgId "+e);const i=Tt.getContainerService().getEncryptService();this.decryptedValue=yield i.decryptString(this,t)}catch(e){console.error("[EncString Generic Decrypt] failed to decrypt encstring. Context: "+(null!=i?i:"No context"),e),this.decryptedValue=Ot}return this.decryptedValue})}getKeyForDecryption(e){return Dt(this,void 0,void 0,function*(){const t=Tt.getContainerService().getKeyService();return null!=e?yield t.getOrgKey(e):yield t.getUserKey()})}}class Rt{buildDomainModel(e,t,i,r=[]){for(const n in i){if(!i.hasOwnProperty(n))continue;const a=t[i[n]||n];r.indexOf(n)>-1?e[n]=a||null:e[n]=a?new Nt(a):null}}buildDataModel(e,t,i,r=[]){for(const n in i){if(!i.hasOwnProperty(n))continue;const a=e[i[n]||n];r.indexOf(n)>-1?t[n]=null!=a?a:null:t[n]=null!=a?a.encryptedString:null}}decryptObj(e,t,i){return r=this,n=arguments,s=function*(e,t,i,r=null,n="No Domain Context"){var a,s;for(const o of i)t[o]=null!==(s=yield null===(a=e[o])||void 0===a?void 0:a.decrypt(null,r,`Property: ${o}; ObjectContext: ${n}`))&&void 0!==s?s:null;return t},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}}class Ut extends Rt{constructor(e){super(),this.readOnly=!1,this.hidePasswords=!1,this.manage=!1,this.type=0,this.id=e.id,this.name=e.name,this.organizationId=e.organizationId}static fromCollectionData(e){if(null==e||null==e.name||null==e.organizationId)throw new Error("CollectionData must contain name and organizationId.");const t=new Ut(Object.assign(Object.assign({},e),{name:new Nt(e.name)}));return t.externalId=e.externalId,t.readOnly=e.readOnly,t.hidePasswords=e.hidePasswords,t.manage=e.manage,t.type=e.type,t.defaultUserCollectionEmail=e.defaultUserCollectionEmail,t}static fromCollectionView(e,t,i){return r=this,n=void 0,s=function*(){const r=new Ut({name:yield t.encryptString(e.name,i),id:e.id,organizationId:e.organizationId});return r.externalId=e.externalId,r.readOnly=e.readOnly,r.hidePasswords=e.hidePasswords,r.manage=e.manage,r.type=e.type,r},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}decrypt(e,t){return qt.fromCollection(this,t,e)}static isCollectionId(e){return"string"==typeof e&&null!=e}}var Ft=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class qt{constructor(e){this.readOnly=!1,this.hidePasswords=!1,this.manage=!1,this.assigned=!1,this.type=0,this.id=e.id,this.organizationId=e.organizationId,this._name=e.name}set name(e){this._name=e}get name(){var e;return null!==(e=this.defaultUserCollectionEmail)&&void 0!==e?e:this._name}canEditItems(e){if(null!=e&&e.id!==this.organizationId)throw new Error("Id of the organization provided does not match the org id of the collection.");return(null==e?void 0:e.canEditAllCiphers)||this.manage||this.assigned&&!this.readOnly}canEdit(e){if(this.isDefaultCollection)return!1;if(null!=e&&e.id!==this.organizationId)throw new Error("Id of the organization provided does not match the org id of the collection.");return this.manage}canDelete(e){if(null!=e&&e.id!==this.organizationId)throw new Error("Id of the organization provided does not match the org id of the collection.");return(!(null==e?void 0:e.limitCollectionDeletion)||e.isAdmin)&&this.manage&&!this.isDefaultCollection}canViewCollectionInfo(e){return!1}canEditName(e){return this.canEdit(e)&&!this.defaultUserCollectionEmail}get isDefaultCollection(){return 1==this.type}static vaultFilterHead(){return new qt({id:"",organizationId:"",name:""})}static fromCollection(e,t,i){return Ft(this,void 0,void 0,function*(){const r=new qt(Object.assign(Object.assign({},e),{name:""}));try{r.name=yield t.decryptString(e.name,i)}catch(e){r.name="[error: cannot decrypt]",console.error("[CollectionView] Error decrypting collection name",e)}return r.assigned=!0,r.externalId=e.externalId,r.readOnly=e.readOnly,r.hidePasswords=e.hidePasswords,r.manage=e.manage,r.type=e.type,r.defaultUserCollectionEmail=e.defaultUserCollectionEmail,r})}static fromCollectionAccessDetails(e,t,i){return Ft(this,void 0,void 0,function*(){const r=new qt(Object.assign({},e));try{r.name=yield t.decryptString(new Nt(e.name),i)}catch(e){throw console.error("[CollectionView] Error decrypting collection name",e),e}return r.externalId=e.externalId,r.type=e.type,r.assigned=e.assigned,r.defaultUserCollectionEmail=e.defaultUserCollectionEmail,r})}static fromJSON(e){return Object.assign(new qt(Object.assign({},e)),e)}encrypt(e,t){return Ut.fromCollectionView(this,t,e)}}class Lt{constructor(e){this.response=e}getResponseProperty(e,t=null,i=!1){if(null==e||""===e)throw new Error("propertyName must not be null/empty.");if(null==t&&null!=this.response&&(t=this.response),null==t)return null;if(!i&&void 0===t[e]){let i=null;i=e.charAt(0)===e.charAt(0).toUpperCase()?e.charAt(0).toLowerCase():e.charAt(0).toUpperCase(),e.length>1&&(i+=e.slice(1)),void 0===t[e=i]&&(e=e.toLowerCase()),void 0===t[e]&&(e=e.toUpperCase())}return t[e]}}class Bt extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.readOnly=this.getResponseProperty("ReadOnly"),this.hidePasswords=this.getResponseProperty("HidePasswords"),this.manage=this.getResponseProperty("Manage")}}class Mt extends Lt{constructor(e){var t;super(e),this.type=0,this.id=this.getResponseProperty("Id"),this.organizationId=this.getResponseProperty("OrganizationId"),this.name=this.getResponseProperty("Name"),this.externalId=this.getResponseProperty("ExternalId"),this.defaultUserCollectionEmail=this.getResponseProperty("DefaultUserCollectionEmail"),this.type=null!==(t=this.getResponseProperty("Type"))&&void 0!==t?t:0}}class Vt extends Mt{constructor(e){super(e),this.readOnly=this.getResponseProperty("ReadOnly")||!1,this.manage=this.getResponseProperty("Manage")||!1,this.hidePasswords=this.getResponseProperty("HidePasswords")||!1,this.assigned="collectionDetails"==this.getResponseProperty("object")}}class $t extends Vt{constructor(e){super(e),this.groups=[],this.users=[],this.assigned=this.getResponseProperty("Assigned")||!1,this.unmanaged=this.getResponseProperty("Unmanaged")||!1;const t=this.getResponseProperty("Groups");null!=t&&(this.groups=t.map(e=>new Bt(e)));const i=this.getResponseProperty("Users");null!=i&&(this.users=i.map(e=>new Bt(e)))}}class Kt{constructor(e){this.readOnly=!1,this.manage=!1,this.hidePasswords=!1,this.type=0,this.id=e.id,this.organizationId=e.organizationId,this.name=e.name,this.externalId=e.externalId,this.readOnly=e.readOnly,this.manage=e.manage,this.hidePasswords=e.hidePasswords,this.type=e.type,this.defaultUserCollectionEmail=e.defaultUserCollectionEmail}static fromJSON(e){return null==e?null:Object.assign(new Kt(new Vt({})),e)}}var Wt=new $(E),Ht=function(e){function t(t,i,r){void 0===t&&(t=1/0),void 0===i&&(i=1/0),void 0===r&&(r=Ae);var n=e.call(this)||this;return n._bufferSize=t,n._windowTime=i,n._timestampProvider=r,n._buffer=[],n._infiniteTimeWindow=!0,n._infiniteTimeWindow=i===1/0,n._bufferSize=Math.max(1,t),n._windowTime=Math.max(1,i),n}return a(t,e),t.prototype.next=function(t){var i=this,r=i.isStopped,n=i._buffer,a=i._infiniteTimeWindow,s=i._timestampProvider,o=i._windowTime;r||(n.push(t),!a&&n.push(s.now()+o)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),i=this._infiniteTimeWindow,r=this._buffer.slice(),n=0;n0&&(t=new R({next:function(e){return g.next(e)},error:function(e){u=!0,d(),r=Qt(h,n,e),g.error(e)},complete:function(){c=!0,d(),r=Qt(h,s),g.complete()}}),le(e).subscribe(t))})(e)}}function Qt(e,t){for(var i=[],r=2;re.node.name===o);if(0===l.length){const s=o+a+i[t+1];pi.nestedTraverse(e,0,[s,...i.slice(t+2)],r,n,a)}else pi.nestedTraverse(l[0].children,t+1,i,r,l[0],a)}static getTreeNodeObject(e,t){if(e.node.id===t)return e;for(let i=0;inull==t?null:t.map(t=>e(t))}function gi(e){return t=>{if(null==t)return null;const i={};return Object.entries(t).forEach(([t,r])=>{i[t]=e(r)}),i}}class fi{constructor(e,t,i){var r;if(this.stateDefinition=e,this.key=t,this.options=i,null==i.deserializer)throw new Error(`'deserializer' is a required property on key ${this.errorKeyName}`);if(i.cleanupDelayMs<0)throw new Error(`'cleanupDelayMs' must be greater than or equal to 0. Value of ${i.cleanupDelayMs} passed to key ${this.errorKeyName} `);const{enableUpdateLogging:n=!1,enableRetrievalLogging:a=!1}=null!==(r=i.debug)&&void 0!==r?r:{};this.debug={enableUpdateLogging:n,enableRetrievalLogging:a}}get deserializer(){return this.options.deserializer}get cleanupDelayMs(){var e;return this.options.cleanupDelayMs<0?0:null!==(e=this.options.cleanupDelayMs)&&void 0!==e?e:1e3}static array(e,t,i){return new fi(e,t,Object.assign(Object.assign({},i),{deserializer:mi(e=>i.deserializer(e))}))}static record(e,t,i){return new fi(e,t,Object.assign(Object.assign({},i),{deserializer:gi(e=>i.deserializer(e))}))}get fullName(){return`${this.stateDefinition.name}_${this.key}`}get errorKeyName(){return`${this.stateDefinition.name} > ${this.key}`}}const yi=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;var vi;const bi=Symbol("UserKeyDefinition");class wi{constructor(e,t,i){var r;if(this.stateDefinition=e,this.key=t,this.options=i,this[vi]=!0,null==i.deserializer)throw new Error(`'deserializer' is a required property on key ${this.errorKeyName}`);if(i.cleanupDelayMs<0)throw new Error(`'cleanupDelayMs' must be greater than or equal to 0. Value of ${i.cleanupDelayMs} passed to key ${this.errorKeyName} `);this.clearOn=Array.from(new Set(i.clearOn));const{enableUpdateLogging:n=!1,enableRetrievalLogging:a=!1}=null!==(r=i.debug)&&void 0!==r?r:{};this.debug={enableUpdateLogging:n,enableRetrievalLogging:a}}get deserializer(){return this.options.deserializer}get cleanupDelayMs(){var e;return this.options.cleanupDelayMs<0?0:null!==(e=this.options.cleanupDelayMs)&&void 0!==e?e:1e3}static array(e,t,i){return new wi(e,t,Object.assign(Object.assign({},i),{deserializer:mi(e=>i.deserializer(e))}))}static record(e,t,i){return new wi(e,t,Object.assign(Object.assign({},i),{deserializer:gi(e=>i.deserializer(e))}))}get fullName(){return`${this.stateDefinition.name}_${this.key}`}buildKey(e){if(t=e,!yi.test(t))throw new Error(`You cannot build a user key without a valid UserId, building for key ${this.fullName}`);var t;return`user_${e}_${this.stateDefinition.name}_${this.key}`}get errorKeyName(){return`${this.stateDefinition.name} > ${this.key}`}}vi=bi,Symbol("active");class ki{constructor(e,t,i){this.name=e,this.defaultStorageLocation=t,this.storageLocationOverrides=null!=i?i:{}}}const Si=new ki("organizations","disk"),_i=new ki("policies","disk"),xi=new ki("providers","disk"),Ci=(new ki("organizationManagementPreferences","disk",{web:"disk-local"}),new ki("showDeleteManagedUserWarning","disk",{web:"disk-local"}),new ki("autoConfirm","disk",{web:"disk-local"})),Ii=new ki("billing","disk"),Ei=(new ki("billing","memory"),new ki("account","disk")),zi=(new ki("account","memory"),new ki("authRequestLocal","disk",{web:"disk-local"})),Pi=new ki("avatar","disk",{web:"disk-local"}),Ai=new ki("deviceTrust","disk",{web:"disk-local",browser:"disk-backup-local-storage"}),ji=new ki("loginEmail","disk",{web:"disk-local"}),Ti=new ki("loginEmail","memory"),Di=new ki("loginStrategy","memory"),Oi=new ki("masterPassword","disk"),Ni=new ki("masterPassword","memory"),Ri=new ki("masterPasswordUnlock","disk"),Ui=(new ki("router","disk"),new ki("ssoLogin","disk")),Fi=new ki("ssoLoginLocal","disk",{web:"disk-local"}),qi=new ki("token","disk"),Li=new ki("tokenDiskLocal","disk",{web:"disk-local"}),Bi=new ki("token","memory"),Mi=(new ki("sendAccess","disk"),new ki("twoFactor","memory"),new ki("userDecryptionOptions","disk")),Vi=(new ki("organizationInvite","disk"),new ki("vaultTimeoutSettings","disk",{web:"disk-local"})),$i=new ki("badgeSettings","disk"),Ki=new ki("userNotificationSettings","disk"),Wi=new ki("domainSettings","disk"),Hi=new ki("autofillSettings","disk"),Gi=new ki("autofillSettingsLocal","disk",{web:"disk-local"}),Qi=(new ki("autotypeSettings","disk"),new ki("newWebLayoutBanner","disk",{web:"disk-local"}),new ki("bitSideNav","disk"),new ki("phishingDetection","disk")),Ji=(new ki("applicationId","disk",{web:"disk-local"}),new ki("clearEvent","disk")),Yi=new ki("config","disk",{web:"disk-local"}),Xi=(new ki("desktopSettings","disk"),new ki("environment","disk")),Zi=new ki("environment","memory"),er=new ki("interProcessCommunication","memory"),tr=new ki("popupView","memory",{browser:"memory-large-object"}),ir=new ki("sync","disk",{web:"memory"}),rr=new ki("theming","disk",{web:"disk-local"}),nr=new ki("translation","disk",{web:"disk-local"}),ar=(new ki("animation","disk"),new ki("taskScheduler","disk")),sr=new ki("extensionInitialInstall","disk"),or=new ki("webPushSubscription","disk",{web:"disk-local"}),lr=(new ki("popupStyle","disk"),new ki("smOnboarding","disk",{web:"disk-local"}),new ki("extension","disk")),cr=new ki("generator","disk"),ur=new ki("generator","memory"),dr=(new ki("sendBrowser","memory"),new ki("eventCollection","disk")),hr=new ki("encryptedSend","disk",{web:"memory"}),pr=new ki("decryptedSend","memory",{browser:"memory-large-object"}),mr=(new ki("sendAccessAuth","memory"),new ki("collection","disk",{web:"memory"})),gr=new ki("decryptedCollections","memory",{browser:"memory-large-object"}),fr=new ki("folder","disk",{web:"memory"}),yr=new ki("decryptedFolders","memory",{browser:"memory-large-object"}),vr=(new ki("vaultFilter","disk",{web:"disk-local"}),new ki("vaultOnboarding","disk",{web:"disk-local"}),new ki("vaultSettings","disk",{web:"disk-local"})),br=(new ki("vaultBrowser","memory",{browser:"memory-large-object"}),new ki("vaultSearch","memory",{browser:"memory-large-object"})),wr=new ki("ciphers","disk",{web:"memory"}),kr=new ki("ciphersLocal","disk",{web:"disk-local"}),Sr=new ki("ciphersMemory","memory",{browser:"memory-large-object"}),_r=(new ki("bannersDismissed","disk"),new ki("vaultAppearance","disk"),new ki("securityTasks","disk")),xr=(new ki("atRiskPasswordsPage","disk"),new ki("notifications","disk")),Cr=(new ki("nudges","disk",{web:"disk-local"}),new ki("setupExtensionDismissed","disk",{web:"disk-local"}),new ki("vaultWelcomeDialog","disk",{web:"disk-local"}),new ki("vaultBrowserIntroCarousel","disk"),new ki("vaultAtRiskPasswords","memory"),new ki("vaultWelcomeExtensionDialogDismissed","disk",{web:"disk-local"}),new ki("biometricSettings","disk")),Ir=(new ki("encryptedMigration","disk"),new ki("pinUnlock","disk")),Er=new ki("pinUnlock","memory"),zr=new ki("crypto","disk"),Pr=new ki("crypto","memory"),Ar=new ki("kdfConfig","disk"),jr=new ki("keyConnector","disk");var Tr=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Dr{static create(){return new Dr([])}constructor(e){this.migrations=e}with(...e){return this.addMigrator(e,"up")}rollback(...e){return 3===e.length&&(e=[e[0],e[2],e[1]]),this.addMigrator(e,"down")}migrate(e){return this.migrations.reduce((t,i)=>t.then(()=>Tr(this,void 0,void 0,function*(){yield this.runMigrator(i.migrator,e,i.direction)})),Promise.resolve())}addMigrator(e,t="up"){const i=1===e.length?{migrator:new e[0],direction:t}:{migrator:new e[0](e[1],e[2]),direction:t};return new Dr([...this.migrations,i])}runMigrator(e,t,i){return Tr(this,void 0,void 0,function*(){const r=yield e.shouldMigrate(t,i);if(t.info(`Migrator ${e.constructor.name} (to version ${e.toVersion}) should migrate: ${r} - ${i}`),r){const r="up"===i?e.migrate:e.rollback;yield r.bind(e)(t),t.info(`Migrator ${e.constructor.name} (to version ${e.toVersion}) migrated - ${i}`),yield e.updateVersion(t,i),t.info(`Migrator ${e.constructor.name} (to version ${e.toVersion}) updated version - ${i}`)}})}}const Or=new Error("Irreversible migration");class Nr{constructor(e,t){if(this.fromVersion=e,this.toVersion=t,null==e||null==t)throw new Error("Invalid migration");if(e>t)throw new Error("Invalid migration")}shouldMigrate(e,t){const i="up"===t?this.fromVersion:this.toVersion;return Promise.resolve(e.currentVersion===i)}updateVersion(e,t){return i=this,r=void 0,a=function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i,yield e.set("stateVersion",i)},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}}var Rr=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ur={key:"everHadUserKey",stateDefinition:{name:"crypto"}};class Fr extends Nr{migrate(e){return Rr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Rr(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.everHadUserKey;yield e.setToUser(t,Ur,null!=n&&n),null!=n&&delete i.profile.everHadUserKey,yield e.set(t,i)})}(t,i))])})}rollback(e){return Rr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Rr(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Ur);i&&(i.profile=Object.assign(null!==(r=i.profile)&&void 0!==r?r:{},{everHadUserKey:n}),yield e.set(t,i)),yield e.setToUser(t,Ur,null)})}(t,i))])})}}var qr=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Lr={key:"organizationKeys",stateDefinition:{name:"crypto"}};class Br extends Nr{migrate(e){return qr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return qr(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.organizationKeys)||void 0===n?void 0:n.encrypted;null!=a&&(yield e.setToUser(t,Lr,a),delete i.keys.organizationKeys,yield e.set(t,i))})}(t,i))])})}rollback(e){return qr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return qr(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Lr);i&&n&&(i.keys=Object.assign(null!==(r=i.keys)&&void 0!==r?r:{},{organizationKeys:{encrypted:n}}),yield e.set(t,i)),yield e.setToUser(t,Lr,null)})}(t,i))])})}}var Mr=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Vr={name:"environment"},$r={key:"region",stateDefinition:Vr},Kr={key:"urls",stateDefinition:Vr};class Wr extends Nr{migrate(e){return Mr(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.region)&&(yield e.setToGlobal($r,t.region)),null!=(null==t?void 0:t.environmentUrls)&&(yield e.setToGlobal(Kr,t.environmentUrls));const i=yield e.getAccounts();yield Promise.all(i.map(t=>Mr(this,[t],void 0,function*({userId:t,account:i}){var r,n,a,s;null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.region)&&(yield e.setToUser(t,$r,i.settings.region)),null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.environmentUrls)&&(yield e.setToUser(t,Kr,i.settings.environmentUrls)),null===(a=null==i?void 0:i.settings)||void 0===a||delete a.region,null===(s=null==i?void 0:i.settings)||void 0===s||delete s.environmentUrls,yield e.set(t,i)}))),null==t||delete t.region,null==t||delete t.environmentUrls,yield e.set("global",t)})}rollback(e){return Mr(this,void 0,void 0,function*(){let t=yield e.get("global"),i=!1;const r=yield e.getFromGlobal($r);r&&(t||(t={}),i=!0,t.region=r,yield e.setToGlobal($r,null));const n=yield e.getFromGlobal(Kr);n&&(t||(t={}),i=!0,t.environmentUrls=n,yield e.setToGlobal(Kr,null)),i&&(yield e.set("global",t));const a=yield e.getAccounts();yield Promise.all(a.map(({userId:t,account:i})=>function(t,i){return Mr(this,void 0,void 0,function*(){let r=!1;const n=yield e.getFromUser(t,$r);n&&(i||(i={}),i.settings||(i.settings={}),r=!0,i.settings.region=n,yield e.setToUser(t,$r,null));const a=yield e.getFromUser(t,Kr);a&&(i||(i={}),i.settings||(i.settings={}),r=!0,i.settings.environmentUrls=a,yield e.setToUser(t,Kr,null)),r&&(yield e.set(t,i))})}(t,i)))})}}var Hr=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Gr={key:"providerKeys",stateDefinition:{name:"crypto"}};class Qr extends Nr{migrate(e){return Hr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Hr(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.providerKeys)||void 0===n?void 0:n.encrypted;null!=a&&(yield e.setToUser(t,Gr,a),delete i.keys.providerKeys,yield e.set(t,i))})}(t,i))])})}rollback(e){return Hr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Hr(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Gr);i&&n&&(i.keys=Object.assign(null!==(r=i.keys)&&void 0!==r?r:{},{providerKeys:{encrypted:n}}),yield e.set(t,i)),yield e.setToUser(t,Gr,null)})}(t,i))])})}}var Jr=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Yr={key:"clientKeyHalf",stateDefinition:{name:"biometricSettings"}};class Xr extends Nr{migrate(e){return Jr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(t=>Jr(this,[t],void 0,function*({userId:t,account:i}){var r,n;null!=(null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.biometricEncryptionClientKeyHalf)&&(yield e.setToUser(t,Yr,i.keys.biometricEncryptionClientKeyHalf),null===(n=null==i?void 0:i.keys)||void 0===n||delete n.biometricEncryptionClientKeyHalf,yield e.set(t,i))})))})}rollback(e){return Jr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Jr(this,void 0,void 0,function*(){var r;let n=!1;const a=yield e.getFromUser(t,Yr);a&&(null!=i||(i={}),null!==(r=i.keys)&&void 0!==r||(i.keys={}),n=!0,i.keys.biometricEncryptionClientKeyHalf=a,yield e.setToUser(t,Yr,null)),n&&(yield e.set(t,i))})}(t,i)))})}}var Zr=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const en={key:"folders",stateDefinition:{name:"folder"}};class tn extends Nr{migrate(e){return Zr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Zr(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.folders)||void 0===n?void 0:n.encrypted;null!=a&&(yield e.setToUser(t,en,a),delete i.data.folders,yield e.set(t,i))})}(t,i))])})}rollback(e){return Zr(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Zr(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,en);i&&(i.data=Object.assign(null!==(r=i.data)&&void 0!==r?r:{},{folders:{encrypted:n}}),yield e.set(t,i)),yield e.setToUser(t,en,null)})}(t,i))])})}}var rn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const nn={key:"lastSync",stateDefinition:{name:"sync"}};class an extends Nr{migrate(e){return rn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return rn(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.lastSync;yield e.setToUser(t,nn,null!=n?n:null),null!=n&&(delete i.profile.lastSync,yield e.set(t,i))})}(t,i))])})}rollback(e){return rn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return rn(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,nn);i&&(i.profile=Object.assign(null!==(r=i.profile)&&void 0!==r?r:{},{lastSync:n}),yield e.set(t,i)),yield e.setToUser(t,nn,null)})}(t,i))])})}}var sn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const on={key:"enablePasskeys",stateDefinition:{name:"vaultSettings"}};class ln extends Nr{migrate(e){return sn(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.enablePasskeys)&&(yield e.setToGlobal(on,t.enablePasskeys),null==t||delete t.enablePasskeys,yield e.set("global",t))})}rollback(e){return sn(this,void 0,void 0,function*(){let t=yield e.get("global");const i=yield e.getFromGlobal(on);null!=i&&(t=Object.assign(null!=t?t:{},{enablePasskeys:i}),yield e.set("global",t),yield e.setToGlobal(on,void 0))})}}var cn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const un={stateDefinition:{name:"autofillSettings"}};class dn extends Nr{migrate(e){return cn(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.autoFillOverlayVisibility)&&(yield e.setToGlobal({stateDefinition:{name:"autofillSettingsLocal"},key:"inlineMenuVisibility"},t.autoFillOverlayVisibility),delete t.autoFillOverlayVisibility,yield e.set("global",t));const i=yield e.getAccounts();yield Promise.all([...i.map(({userId:t,account:i})=>function(t,i){return cn(this,void 0,void 0,function*(){let r=!1;const n=null==i?void 0:i.settings;null!=(null==n?void 0:n.autoFillOnPageLoadDefault)&&(yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoadDefault"}),n.autoFillOnPageLoadDefault),delete i.settings.autoFillOnPageLoadDefault,r=!0),null!=(null==n?void 0:n.enableAutoFillOnPageLoad)&&(yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoad"}),null==n?void 0:n.enableAutoFillOnPageLoad),delete i.settings.enableAutoFillOnPageLoad,r=!0),null!=(null==n?void 0:n.dismissedAutoFillOnPageLoadCallout)&&(yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoadCalloutIsDismissed"}),null==n?void 0:n.dismissedAutoFillOnPageLoadCallout),delete i.settings.dismissedAutoFillOnPageLoadCallout,r=!0),null!=(null==n?void 0:n.disableAutoTotpCopy)&&(yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autoCopyTotp"}),!(null==n?void 0:n.disableAutoTotpCopy)),delete i.settings.disableAutoTotpCopy,r=!0),null!=(null==n?void 0:n.activateAutoFillOnPageLoadFromPolicy)&&(yield e.setToUser(t,{stateDefinition:{name:"autofillSettingsLocal"},key:"activateAutofillOnPageLoadFromPolicy"},null==n?void 0:n.activateAutoFillOnPageLoadFromPolicy),delete i.settings.activateAutoFillOnPageLoadFromPolicy,r=!0),r&&(yield e.set(t,i))})}(t,i))])})}rollback(e){return cn(this,void 0,void 0,function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal({stateDefinition:{name:"autofillSettingsLocal"},key:"inlineMenuVisibility"});i&&(yield e.set("global",Object.assign(Object.assign({},t),{autoFillOverlayVisibility:i})),yield e.setToGlobal({stateDefinition:{name:"autofillSettingsLocal"},key:"inlineMenuVisibility"},null));const r=yield e.getAccounts();yield Promise.all([...r.map(({userId:t,account:i})=>function(t,i){return cn(this,void 0,void 0,function*(){let r=!1,n=(null==i?void 0:i.settings)||{};const a=yield e.getFromUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoadDefault"})),s=yield e.getFromUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoad"})),o=yield e.getFromUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoadCalloutIsDismissed"})),l=yield e.getFromUser(t,Object.assign(Object.assign({},un),{key:"autoCopyTotp"})),c=yield e.getFromUser(t,{stateDefinition:{name:"autofillSettingsLocal"},key:"activateAutofillOnPageLoadFromPolicy"});null!=a&&(n=Object.assign(Object.assign({},n),{autoFillOnPageLoadDefault:a}),yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoadDefault"}),null),r=!0),null!=s&&(n=Object.assign(Object.assign({},n),{enableAutoFillOnPageLoad:s}),yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoad"}),null),r=!0),null!=o&&(n=Object.assign(Object.assign({},n),{dismissedAutoFillOnPageLoadCallout:o}),yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autofillOnPageLoadCalloutIsDismissed"}),null),r=!0),null!=l&&(n=Object.assign(Object.assign({},n),{disableAutoTotpCopy:!l}),yield e.setToUser(t,Object.assign(Object.assign({},un),{key:"autoCopyTotp"}),null),r=!0),null!=c&&(n=Object.assign(Object.assign({},n),{activateAutoFillOnPageLoadFromPolicy:c}),yield e.setToUser(t,{stateDefinition:{name:"autofillSettingsLocal"},key:"activateAutofillOnPageLoadFromPolicy"},null),r=!0),r&&(yield e.set(t,Object.assign(Object.assign({},i),{settings:n})))})}(t,i))])})}}var hn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const pn={key:"requirePasswordOnStart",stateDefinition:{name:"biometricSettings"}};class mn extends Nr{migrate(e){return hn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(t=>hn(this,[t],void 0,function*({userId:t,account:i}){var r;null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.requirePasswordOnStart)&&(yield e.setToUser(t,pn,i.settings.requirePasswordOnStart),delete i.settings.requirePasswordOnStart,yield e.set(t,i))})))})}rollback(e){return hn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return hn(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,pn);n&&(null!=i||(i={}),null!==(r=i.settings)&&void 0!==r||(i.settings={}),i.settings.requirePasswordOnStart=n,yield e.setToUser(t,pn,null),yield e.set(t,i))})}(t,i)))})}}var gn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const fn={key:"privateKey",stateDefinition:{name:"crypto"}};class yn extends Nr{migrate(e){return gn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return gn(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.privateKey)||void 0===n?void 0:n.encrypted;null!=a&&(yield e.setToUser(t,fn,a),delete i.keys.privateKey,yield e.set(t,i))})}(t,i))])})}rollback(e){return gn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return gn(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,fn);i&&n&&(i.keys=Object.assign(null!==(r=i.keys)&&void 0!==r?r:{},{privateKey:{encrypted:n}}),yield e.set(t,i)),yield e.setToUser(t,fn,null)})}(t,i))])})}}var vn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const bn={key:"collections",stateDefinition:{name:"collection"}};class wn extends Nr{migrate(e){return vn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return vn(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.collections)||void 0===n?void 0:n.encrypted;null!=a&&(yield e.setToUser(t,bn,a),delete i.data.collections,yield e.set(t,i))})}(t,i))])})}rollback(e){return vn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return vn(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,bn);i&&(i.data=Object.assign(null!==(r=i.data)&&void 0!==r?r:{},{collections:{encrypted:n}}),yield e.set(t,i)),yield e.setToUser(t,bn,null)})}(t,i))])})}}var kn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Sn={key:"collapsedGroupings",stateDefinition:{name:"vaultFilter"}};class _n extends Nr{migrate(e){return kn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return kn(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.collapsedGroupings;null!=n&&(yield e.setToUser(t,Sn,n),delete i.settings.collapsedGroupings,yield e.set(t,i))})}(t,i))])})}rollback(e){return kn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return kn(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Sn);i&&(i.settings=Object.assign(null!==(r=i.settings)&&void 0!==r?r:{},{collapsedGroupings:n}),yield e.set(t,i)),yield e.setToUser(t,Sn,null)})}(t,i))])})}}var xn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Cn={key:"dismissedBiometricRequirePasswordOnStartCallout",stateDefinition:{name:"biometricSettings"}},In={key:"promptAutomatically",stateDefinition:{name:"biometricSettings"}};class En extends Nr{migrate(e){return xn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(t=>xn(this,[t],void 0,function*({userId:t,account:i}){var r,n,a,s;null!=i&&(null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.dismissedBiometricRequirePasswordOnStartCallout)&&(yield e.setToUser(t,Cn,i.settings.dismissedBiometricRequirePasswordOnStartCallout)),null!=(null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.disableAutoBiometricsPrompt)&&(yield e.setToUser(t,In,!i.settings.disableAutoBiometricsPrompt)),null===(a=null==i?void 0:i.settings)||void 0===a||delete a.dismissedBiometricRequirePasswordOnStartCallout,null===(s=null==i?void 0:i.settings)||void 0===s||delete s.disableAutoBiometricsPrompt,yield e.set(t,i))})))})}rollback(e){return xn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return xn(this,void 0,void 0,function*(){var r,n;let a=!1;const s=yield e.getFromUser(t,Cn);s&&(null!=i||(i={}),null!==(r=i.settings)&&void 0!==r||(i.settings={}),a=!0,i.settings.dismissedBiometricRequirePasswordOnStartCallout=s,yield e.setToUser(t,Cn,null));const o=yield e.getFromUser(t,In);null!=o&&(null!=i||(i={}),null!==(n=i.settings)&&void 0!==n||(i.settings={}),a=!0,i.settings.disableAutoBiometricsPrompt=!o,yield e.setToUser(t,In,null)),a&&(yield e.set(t,i))})}(t,i)))})}}var zn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Pn={key:"tasks",stateDefinition:{name:"smOnboarding"}};class An extends Nr{migrate(e){return zn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(t=>zn(this,[t],void 0,function*({userId:t,account:i}){var r;null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.smOnboardingTasks)&&(yield e.setToUser(t,Pn,i.settings.smOnboardingTasks),delete i.settings.smOnboardingTasks,yield e.set(t,i))})))})}rollback(e){return zn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return zn(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Pn);n&&(null!=i||(i={}),null!==(r=i.settings)&&void 0!==r||(i.settings={}),i.settings.smOnboardingTasks=n,yield e.setToUser(t,Pn,null),yield e.set(t,i))})}(t,i)))})}}var jn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Tn={stateDefinition:{name:"autofillSettingsLocal"}};class Dn extends Nr{migrate(e){return jn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return jn(this,void 0,void 0,function*(){const r=null==i?void 0:i.settings;void 0!==(null==r?void 0:r.clearClipboard)&&(yield e.setToUser(t,Object.assign(Object.assign({},Tn),{key:"clearClipboardDelay"}),r.clearClipboard),delete i.settings.clearClipboard,yield e.set(t,i))})}(t,i))])})}rollback(e){return jn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return jn(this,void 0,void 0,function*(){let r=(null==i?void 0:i.settings)||{};const n=yield e.getFromUser(t,Object.assign(Object.assign({},Tn),{key:"clearClipboardDelay"}));void 0!==n&&(r=Object.assign(Object.assign({},r),{clearClipboard:n}),yield e.setToUser(t,Object.assign(Object.assign({},Tn),{key:"clearClipboardDelay"}),null),yield e.set(t,Object.assign(Object.assign({},i),{settings:r})))})}(t,i))])})}}var On=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Nn={key:"lastSync",stateDefinition:{name:"sync"}};class Rn extends Nr{rollback(e){return On(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return On(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.lastSync;yield e.setToUser(t,Nn,null!=n?n:null),null!=n&&(delete i.profile.lastSync,yield e.set(t,i))})}(t,i))])})}migrate(e){return On(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return On(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Nn);i&&(i.profile=Object.assign(null!==(r=i.profile)&&void 0!==r?r:{},{lastSync:n}),yield e.set(t,i)),yield e.setToUser(t,Nn,null)})}(t,i))])})}}var Un=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Fn={stateDefinition:{name:"badgeSettings"},key:"enableBadgeCounter"};class qn extends Nr{migrate(e){return Un(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Un(this,void 0,void 0,function*(){const r=null==i?void 0:i.settings;null!=(null==r?void 0:r.disableBadgeCounter)&&(yield e.setToUser(t,Fn,!r.disableBadgeCounter),delete i.settings.disableBadgeCounter,yield e.set(t,i))})}(t,i))])})}rollback(e){return Un(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Un(this,void 0,void 0,function*(){let r=(null==i?void 0:i.settings)||{};const n=yield e.getFromUser(t,Fn);null!=n&&(r=Object.assign(Object.assign({},r),{disableBadgeCounter:!n}),yield e.setToUser(t,Fn,null),yield e.set(t,Object.assign(Object.assign({},i),{settings:r})))})}(t,i))])})}}var Ln=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Bn={key:"biometricUnlockEnabled",stateDefinition:{name:"biometricSettings"}};class Mn extends Nr{migrate(e){return Ln(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(t=>Ln(this,[t],void 0,function*({userId:t,account:i}){var r,n;null!=i&&(null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.biometricUnlock)&&(yield e.setToUser(t,Bn,i.settings.biometricUnlock)),null===(n=null==i?void 0:i.settings)||void 0===n||delete n.biometricUnlock,yield e.set(t,i))})))})}rollback(e){return Ln(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Ln(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Bn);null!=n&&(null!=i||(i={}),null!==(r=i.settings)&&void 0!==r||(i.settings={}),i.settings.biometricUnlock=n,yield e.setToUser(t,Bn,null),yield e.set(t,i))})}(t,i)))})}}var Vn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class $n extends Nr{migrate(e){return Vn(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.disableAddLoginNotification)&&(yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableAddedLoginPrompt"},!t.disableAddLoginNotification),delete t.disableAddLoginNotification,yield e.set("global",t)),null!=(null==t?void 0:t.disableChangedPasswordNotification)&&(yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableChangedPasswordPrompt"},!t.disableChangedPasswordNotification),delete t.disableChangedPasswordNotification,yield e.set("global",t))})}rollback(e){return Vn(this,void 0,void 0,function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableAddedLoginPrompt"}),r=yield e.getFromGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableChangedPasswordPrompt"});i&&(yield e.set("global",Object.assign(Object.assign({},t),{disableAddLoginNotification:!i})),yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableAddedLoginPrompt"},null)),r&&(yield e.set("global",Object.assign(Object.assign({},t),{disableChangedPasswordNotification:!r})),yield e.setToGlobal({stateDefinition:{name:"userNotificationSettings"},key:"enableChangedPasswordPrompt"},null))})}}var Kn,Wn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};!function(e){e[e.TwoFactorAuthentication=0]="TwoFactorAuthentication",e[e.MasterPassword=1]="MasterPassword",e[e.PasswordGenerator=2]="PasswordGenerator",e[e.SingleOrg=3]="SingleOrg",e[e.RequireSso=4]="RequireSso",e[e.PersonalOwnership=5]="PersonalOwnership",e[e.DisableSend=6]="DisableSend",e[e.SendOptions=7]="SendOptions",e[e.ResetPassword=8]="ResetPassword",e[e.MaximumVaultTimeout=9]="MaximumVaultTimeout",e[e.DisablePersonalVaultExport=10]="DisablePersonalVaultExport",e[e.ActivateAutofill=11]="ActivateAutofill"}(Kn||(Kn={}));const Hn={key:"policies",stateDefinition:{name:"policies"}};class Gn extends Nr{migrate(e){return Wn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Wn(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.policies)||void 0===n?void 0:n.encrypted;null!=a&&(yield e.setToUser(t,Hn,a),delete i.data.policies,yield e.set(t,i))})}(t,i)))})}rollback(e){return Wn(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Wn(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Hn);i&&(i.data=Object.assign(null!==(r=i.data)&&void 0!==r?r:{},{policies:{encrypted:n}}),yield e.set(t,i)),yield e.setToUser(t,Hn,null)})}(t,i)))})}}var Qn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Jn={stateDefinition:{name:"autofillSettings"},key:"enableContextMenu"};class Yn extends Nr{migrate(e){return Qn(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.disableContextMenuItem)&&(yield e.setToGlobal(Jn,!t.disableContextMenuItem),delete t.disableContextMenuItem,yield e.set("global",t))})}rollback(e){return Qn(this,void 0,void 0,function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal(Jn);null!=i&&(yield e.set("global",Object.assign(Object.assign({},t),{disableContextMenuItem:!i})),yield e.setToGlobal(Jn,null))})}}var Xn=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Zn={key:"locale",stateDefinition:{name:"translation"}};class ea extends Nr{migrate(e){return Xn(this,void 0,void 0,function*(){const t=yield e.get("global");(null==t?void 0:t.locale)&&(yield e.setToGlobal(Zn,t.locale),delete t.locale,yield e.set("global",t))})}rollback(e){return Xn(this,void 0,void 0,function*(){var t;const i=yield e.getFromGlobal(Zn);if(!i)return;const r=null!==(t=yield e.get("global"))&&void 0!==t?t:{};r.locale=i,yield e.set("global",r),yield e.setToGlobal(Zn,null)})}}var ta=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ia="appId",ra="anonymousAppId",na={key:ia,stateDefinition:{name:"applicationId"}},aa={key:ra,stateDefinition:{name:"applicationId"}};class sa extends Nr{migrate(e){return ta(this,void 0,void 0,function*(){const t=yield e.get(ia),i=yield e.get(ra);null!=t&&(yield e.setToGlobal(na,t),yield e.set(ia,null)),null!=i&&(yield e.setToGlobal(aa,i),yield e.set(ra,null))})}rollback(e){return ta(this,void 0,void 0,function*(){const t=yield e.getFromGlobal(na),i=yield e.getFromGlobal(aa);null!=t&&(yield e.set(ia,t),yield e.setToGlobal(na,null)),null!=i&&(yield e.set(ra,i),yield e.setToGlobal(aa,null))})}}var oa=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const la={stateDefinition:{name:"domainSettings"},key:"defaultUriMatchStrategy"},ca={stateDefinition:{name:"domainSettings"},key:"equivalentDomains"},ua={stateDefinition:{name:"domainSettings"},key:"neverDomains"};class da extends Nr{migrate(e){return oa(this,void 0,void 0,function*(){let t=!1;const i=yield e.get("global");null!=(null==i?void 0:i.neverDomains)&&(yield e.setToGlobal(ua,i.neverDomains),delete i.neverDomains,yield e.set("global",i));const r=yield e.getAccounts();yield Promise.all([...r.map(({userId:i,account:r})=>function(i,r){return oa(this,void 0,void 0,function*(){var n;const a=null==r?void 0:r.settings;null!=(null==a?void 0:a.defaultUriMatch)&&(yield e.setToUser(i,la,a.defaultUriMatch),delete r.settings.defaultUriMatch,t=!0),null!=(null===(n=null==a?void 0:a.settings)||void 0===n?void 0:n.equivalentDomains)&&(yield e.setToUser(i,ca,a.settings.equivalentDomains),delete r.settings.settings.equivalentDomains,delete r.settings.settings,t=!0),t&&(yield e.set(i,r))})}(i,r))])})}rollback(e){return oa(this,void 0,void 0,function*(){let t=!1;const i=(yield e.get("global"))||{},r=yield e.getFromGlobal(ua);null!=r&&(yield e.set("global",Object.assign(Object.assign({},i),{neverDomains:r})),yield e.setToGlobal(ua,null));const n=yield e.getAccounts();yield Promise.all([...n.map(({userId:i,account:r})=>function(i,r){return oa(this,void 0,void 0,function*(){let n=(null==r?void 0:r.settings)||{};const a=yield e.getFromUser(i,la),s=yield e.getFromUser(i,ca);null!=a&&(n=Object.assign(Object.assign({},n),{defaultUriMatch:a}),yield e.setToUser(i,la,null),t=!0),null!=s&&(n=Object.assign(Object.assign({},n),{settings:{equivalentDomains:s}}),yield e.setToUser(i,ca,null),t=!0),t&&(yield e.set(i,Object.assign(Object.assign({},r),{settings:n})))})}(i,r))])})}}var ha=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const pa={key:"selection",stateDefinition:{name:"theming"}};class ma extends Nr{migrate(e){return ha(this,void 0,void 0,function*(){const t=yield e.get("global"),i=null==t?void 0:t.theme;null!=i&&(yield e.setToGlobal(pa,i),delete t.theme,yield e.set("global",t))})}rollback(e){return ha(this,void 0,void 0,function*(){var t;const i=yield e.getFromGlobal(pa);if(null!=i){const r=null!==(t=yield e.get("global"))&&void 0!==t?t:{};r.theme=i,yield e.set("global",r),yield e.removeFromGlobal(pa)}})}}var ga=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const fa={stateDefinition:{name:"vaultSettings"}};class ya extends Nr{migrate(e){return ga(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return ga(this,void 0,void 0,function*(){let r=!1;const n=null==i?void 0:i.settings;null!=(null==n?void 0:n.dontShowCardsCurrentTab)&&(yield e.setToUser(t,Object.assign(Object.assign({},fa),{key:"showCardsCurrentTab"}),!n.dontShowCardsCurrentTab),delete i.settings.dontShowCardsCurrentTab,r=!0),null!=(null==n?void 0:n.dontShowIdentitiesCurrentTab)&&(yield e.setToUser(t,Object.assign(Object.assign({},fa),{key:"showIdentitiesCurrentTab"}),!n.dontShowIdentitiesCurrentTab),delete i.settings.dontShowIdentitiesCurrentTab,r=!0),r&&(yield e.set(t,i))})}(t,i))])})}rollback(e){return ga(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return ga(this,void 0,void 0,function*(){var r;let n=!1,a=null!==(r=null==i?void 0:i.settings)&&void 0!==r?r:{};const s=yield e.getFromUser(t,Object.assign(Object.assign({},fa),{key:"showCardsCurrentTab"})),o=yield e.getFromUser(t,Object.assign(Object.assign({},fa),{key:"showIdentitiesCurrentTab"}));null!=s&&(a=Object.assign(Object.assign({},a),{dontShowCardsCurrentTab:!s}),yield e.setToUser(t,Object.assign(Object.assign({},fa),{key:"showCardsCurrentTab"}),null),n=!0),null!=o&&(a=Object.assign(Object.assign({},a),{dontShowIdentitiesCurrentTab:!o}),yield e.setToUser(t,Object.assign(Object.assign({},fa),{key:"showIdentitiesCurrentTab"}),null),n=!0),n&&(yield e.set(t,Object.assign(Object.assign({},i),{settings:a})))})}(t,i))])})}}var va=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ba={key:"avatarColor",stateDefinition:{name:"avatar"}};class wa extends Nr{migrate(e){return va(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(t=>va(this,[t],void 0,function*({userId:t,account:i}){var r,n;null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.avatarColor)&&(yield e.setToUser(t,ba,i.settings.avatarColor),null===(n=null==i?void 0:i.settings)||void 0===n||delete n.avatarColor,yield e.set(t,i))})))})}rollback(e){return va(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return va(this,void 0,void 0,function*(){let r=!1;const n=yield e.getFromUser(t,ba);n&&(i||(i={}),r=!0,i.settings.avatarColor=n,yield e.setToUser(t,ba,null)),r&&(yield e.set(t,i))})}(t,i)))})}}var ka=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Sa={key:"emailTwoFactorTokenRecord",stateDefinition:{name:"tokenDiskLocal"}},_a={name:"token"},xa={key:"accessToken",stateDefinition:_a},Ca={key:"refreshToken",stateDefinition:_a},Ia={key:"apiKeyClientId",stateDefinition:_a},Ea={key:"apiKeyClientSecret",stateDefinition:_a};class za extends Nr{migrate(e){return ka(this,void 0,void 0,function*(){const t=yield e.get("global"),i={},r=yield e.getAccounts();yield Promise.all([...r.map(({userId:r,account:n})=>function(t,i,r,n){return ka(this,void 0,void 0,function*(){var a,s,o,l,c;let u=!1;const d=null===(a=null==i?void 0:i.profile)||void 0===a?void 0:a.email;null!=r&&null!=i&&null!=d&&(n[d]=r);const h=null===(s=null==i?void 0:i.tokens)||void 0===s?void 0:s.accessToken;null!=h&&("web-disk-local"!==e.type&&(yield e.setToUser(t,xa,h)),delete i.tokens.accessToken,u=!0);const p=null===(o=null==i?void 0:i.tokens)||void 0===o?void 0:o.refreshToken;null!=p&&("web-disk-local"!==e.type&&(yield e.setToUser(t,Ca,p)),delete i.tokens.refreshToken,u=!0);const m=null===(l=null==i?void 0:i.profile)||void 0===l?void 0:l.apiKeyClientId;null!=m&&("web-disk-local"!==e.type&&(yield e.setToUser(t,Ia,m)),delete i.profile.apiKeyClientId,u=!0);const g=null===(c=null==i?void 0:i.keys)||void 0===c?void 0:c.apiKeyClientSecret;null!=g&&("web-disk-local"!==e.type&&(yield e.setToUser(t,Ea,g)),delete i.keys.apiKeyClientSecret,u=!0),u&&(yield e.set(t,i))})}(r,n,null==t?void 0:t.twoFactorToken,i))]),yield e.setToGlobal(Sa,i),null==t||delete t.twoFactorToken,yield e.set("global",t)})}rollback(e){return ka(this,void 0,void 0,function*(){var t;const i=yield e.getAccounts();let r=null;for(const{account:n}of i){const i=null===(t=null==n?void 0:n.profile)||void 0===t?void 0:t.email;if(null!=i&&(r=(yield e.getFromGlobal(Sa))[i],null!=r))break}if(null!=r){let t=yield e.get("global");t||(t={}),t.twoFactorToken=r,yield e.set("global",t)}yield e.setToGlobal(Sa,null),yield Promise.all([...i.map(({userId:t,account:i})=>function(t,i){return ka(this,void 0,void 0,function*(){let r=!1;const n=yield e.getFromUser(t,xa);(null==i?void 0:i.tokens)&&null!=n&&(i.tokens.accessToken=n,r=!0),yield e.setToUser(t,xa,null);const a=yield e.getFromUser(t,Ca);(null==i?void 0:i.tokens)&&null!=a&&(i.tokens.refreshToken=a,r=!0),yield e.setToUser(t,Ca,null);const s=yield e.getFromUser(t,Ia);(null==i?void 0:i.profile)&&null!=s&&(i.profile.apiKeyClientId=s,r=!0),yield e.setToUser(t,Ia,null);const o=yield e.getFromUser(t,Ea);(null==i?void 0:i.keys)&&null!=o&&(i.keys.apiKeyClientSecret=o,r=!0),yield e.setToUser(t,Ea,null),r&&(yield e.set(t,i))})}(t,i))])})}}var Pa=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Aa={key:"accountProfile",stateDefinition:{name:"billing"}};class ja extends Nr{migrate(e){return Pa(this,void 0,void 0,function*(){const t=yield e.getAccounts(),i=(t,i)=>Pa(this,void 0,void 0,function*(){var r,n,a,s;const o=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.hasPremiumPersonally,l=null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.hasPremiumFromOrganization;null==o&&null==l||(yield e.setToUser(t,Aa,{hasPremiumPersonally:o,hasPremiumFromOrganization:l}),null===(a=null==i?void 0:i.profile)||void 0===a||delete a.hasPremiumPersonally,null===(s=null==i?void 0:i.profile)||void 0===s||delete s.hasPremiumFromOrganization,yield e.set(t,i))});yield Promise.all([...t.map(({userId:e,account:t})=>i(e,t))])})}rollback(e){return Pa(this,void 0,void 0,function*(){const t=yield e.getAccounts(),i=(t,i)=>Pa(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Aa);i&&n&&(i.profile=Object.assign(null!==(r=i.profile)&&void 0!==r?r:{},{hasPremiumPersonally:null==n?void 0:n.hasPremiumPersonally,hasPremiumFromOrganization:null==n?void 0:n.hasPremiumFromOrganization}),yield e.set(t,i)),yield e.setToUser(t,Aa,null)});yield Promise.all([...t.map(({userId:e,account:t})=>i(e,t))])})}}var Ta=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Da extends Nr{migrate(e){return Ta(this,void 0,void 0,function*(){const t=yield e.getAccounts();Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Ta(this,void 0,void 0,function*(){var r;if(null!=(null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.everBeenUnlocked))return delete i.profile.everBeenUnlocked,e.set(t,i)})}(t,i)))})}rollback(e){throw Or}updateVersion(e,t){return Ta(this,void 0,void 0,function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const r=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},r),{stateVersion:i}))})}}var Oa,Na,Ra,Ua,Fa=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};!function(e){e[e.Invited=0]="Invited",e[e.Accepted=1]="Accepted",e[e.Confirmed=2]="Confirmed",e[e.Revoked=-1]="Revoked"}(Oa||(Oa={})),function(e){e[e.Owner=0]="Owner",e[e.Admin=1]="Admin",e[e.User=2]="User",e[e.Manager=3]="Manager",e[e.Custom=4]="Custom"}(Na||(Na={})),function(e){e[e.Msp=0]="Msp",e[e.Reseller=1]="Reseller"}(Ra||(Ra={})),function(e){e[e.Free=0]="Free",e[e.Families=1]="Families",e[e.Teams=2]="Teams",e[e.Enterprise=3]="Enterprise",e[e.TeamsStarter=4]="TeamsStarter"}(Ua||(Ua={}));const qa={key:"organizations",stateDefinition:{name:"organizations"}};class La extends Nr{migrate(e){return Fa(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Fa(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.organizations;null!=n&&(yield e.setToUser(t,qa,n),delete i.data.organizations,yield e.set(t,i))})}(t,i)))})}rollback(e){return Fa(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Fa(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,qa);i&&(i.data=Object.assign(null!==(r=i.data)&&void 0!==r?r:{},{organizations:n}),yield e.set(t,i)),yield e.setToUser(t,qa,null)})}(t,i)))})}}var Ba=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ma={stateDefinition:{name:"eventCollection"},key:"eventCollection"};class Va extends Nr{migrate(e){return Ba(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ba(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.eventCollection;null!=n&&(yield e.setToUser(t,Ma,n),delete i.data.eventCollection,yield e.set(t,i))})}(t,i))])})}rollback(e){return Ba(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ba(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Ma);i&&(i.data=Object.assign(null!==(r=i.data)&&void 0!==r?r:{},{eventCollection:n}),yield e.set(t,i)),yield e.setToUser(t,Ma,null)})}(t,i))])})}}var $a=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ka={stateDefinition:{name:"domainSettings"},key:"showFavicons"};class Wa extends Nr{migrate(e){return $a(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.disableFavicon)&&(yield e.setToGlobal(Ka,!t.disableFavicon),delete t.disableFavicon,yield e.set("global",t))})}rollback(e){return $a(this,void 0,void 0,function*(){const t=(yield e.get("global"))||{},i=yield e.getFromGlobal(Ka);null!=i&&(yield e.set("global",Object.assign(Object.assign({},t),{disableFavicon:!i})),yield e.setToGlobal(Ka,null))})}}var Ha=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ga={key:"autoConfirmFingerPrints",stateDefinition:{name:"organizationManagementPreferences"}};class Qa extends Nr{migrate(e){return Ha(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(t=>Ha(this,[t],void 0,function*({userId:t,account:i}){var r,n;null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.autoConfirmFingerPrints)&&(yield e.setToUser(t,Ga,i.settings.autoConfirmFingerPrints),null===(n=null==i?void 0:i.settings)||void 0===n||delete n.autoConfirmFingerPrints,yield e.set(t,i))})))})}rollback(e){return Ha(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Ha(this,void 0,void 0,function*(){let r=!1;const n=yield e.getFromUser(t,Ga);n&&(i||(i={}),r=!0,i.settings.autoConfirmFingerPrints=n,yield e.setToUser(t,Ga,null)),r&&(yield e.set(t,i))})}(t,i)))})}}var Ja=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ya={key:"decryptionOptions",stateDefinition:{name:"userDecryptionOptions"}};class Xa extends Nr{migrate(e){return Ja(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ja(this,void 0,void 0,function*(){const r=null==i?void 0:i.decryptionOptions;null!=r&&(yield e.setToUser(t,Ya,r),delete i.decryptionOptions,yield e.set(t,i))})}(t,i))])})}rollback(e){return Ja(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ja(this,void 0,void 0,function*(){const r=yield e.getFromUser(t,Ya);i&&(i.decryptionOptions=Object.assign(i.decryptionOptions,r),yield e.set(t,i)),yield e.setToUser(t,Ya,null)})}(t,i))])})}}var Za=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const es={name:"environment"},ts={key:"region",stateDefinition:es},is={key:"urls",stateDefinition:es},rs={key:"environment",stateDefinition:es};class ns extends Nr{migrate(e){return Za(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t){return Za(this,void 0,void 0,function*(){const i=yield e.getFromUser(t,ts),r=yield e.getFromUser(t,is);null==i&&null==r||(yield e.setToUser(t,rs,{region:i,urls:r}),yield e.removeFromUser(t,ts),yield e.removeFromUser(t,is))})}(t))]);const i=yield e.getFromGlobal(ts),r=yield e.getFromGlobal(is);null==i&&null==r||(yield e.setToGlobal(rs,{region:i,urls:r}),yield e.removeFromGlobal(ts),yield e.removeFromGlobal(is))})}rollback(e){return Za(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t){return Za(this,void 0,void 0,function*(){const i=yield e.getFromUser(t,rs);yield e.setToUser(t,ts,null==i?void 0:i.region),yield e.setToUser(t,is,null==i?void 0:i.urls),yield e.removeFromUser(t,rs)})}(t))]);const i=yield e.getFromGlobal(rs);yield e.setToGlobal(ts,null==i?void 0:i.region),yield e.setToGlobal(is,null==i?void 0:i.urls),yield e.removeFromGlobal(rs)})}}var as=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ss={key:"promptCancelled",stateDefinition:{name:"biometricSettings"}};class os extends Nr{migrate(e){return as(this,void 0,void 0,function*(){yield Promise.all((yield e.getAccounts()).map(t=>as(this,[t],void 0,function*({userId:t}){null!=e.getFromUser(t,ss)&&(yield e.removeFromUser(t,ss))})))})}rollback(e){return as(this,void 0,void 0,function*(){throw Or})}}var ls=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const cs={name:"desktopSettings"},us={key:"window",stateDefinition:cs},ds={key:"closeToTray",stateDefinition:cs},hs={key:"minimizeToTray",stateDefinition:cs},ps={key:"startToTray",stateDefinition:cs},ms={key:"trayEnabled",stateDefinition:cs},gs={key:"openAtLogin",stateDefinition:cs},fs={key:"alwaysShowDock",stateDefinition:cs},ys={key:"alwaysOnTop",stateDefinition:cs};class vs extends Nr{migrate(e){return ls(this,void 0,void 0,function*(){const t=yield e.get("global");let i=!1;void 0!==(null==t?void 0:t.window)&&(yield e.setToGlobal(us,t.window),i=!0,delete t.window),null!=(null==t?void 0:t.enableCloseToTray)&&(yield e.setToGlobal(ds,t.enableCloseToTray),i=!0,delete t.enableCloseToTray),null!=(null==t?void 0:t.enableMinimizeToTray)&&(yield e.setToGlobal(hs,t.enableMinimizeToTray),i=!0,delete t.enableMinimizeToTray),null!=(null==t?void 0:t.enableStartToTray)&&(yield e.setToGlobal(ps,t.enableStartToTray),i=!0,delete t.enableStartToTray),null!=(null==t?void 0:t.enableTray)&&(yield e.setToGlobal(ms,t.enableTray),i=!0,delete t.enableTray),null!=(null==t?void 0:t.openAtLogin)&&(yield e.setToGlobal(gs,t.openAtLogin),i=!0,delete t.openAtLogin),null!=(null==t?void 0:t.alwaysShowDock)&&(yield e.setToGlobal(fs,t.alwaysShowDock),i=!0,delete t.alwaysShowDock),null!=(null==t?void 0:t.enableAlwaysOnTop)&&(yield e.setToGlobal(ys,t.enableAlwaysOnTop),i=!0,delete t.enableAlwaysOnTop),i&&(yield e.set("global",t));const r=yield e.getAccounts();yield Promise.all(r.map(({userId:t,account:i})=>function(t,i){return ls(this,void 0,void 0,function*(){var r;null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.enableAlwaysOnTop)&&(delete i.settings.enableAlwaysOnTop,yield e.set(t,i))})}(t,i)))})}rollback(e){throw Or}}var bs=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ws={key:"enableDuckDuckGoBrowserIntegration",stateDefinition:{name:"autofillSettings"}};class ks extends Nr{migrate(e){return bs(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.enableDuckDuckGoBrowserIntegration)&&(yield e.setToGlobal(ws,t.enableDuckDuckGoBrowserIntegration),delete t.enableDuckDuckGoBrowserIntegration,yield e.set("global",t))})}rollback(e){return bs(this,void 0,void 0,function*(){var t;const i=yield e.getFromGlobal(ws);if(!i)return;const r=null!==(t=yield e.get("global"))&&void 0!==t?t:{};r.enableDuckDuckGoBrowserIntegration=i,yield e.set("global",r),yield e.removeFromGlobal(ws)})}}var Ss=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const _s={stateDefinition:{name:"config"},key:"serverConfig"};class xs extends Nr{migrate(e){return Ss(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ss(this,void 0,void 0,function*(){var r;null!=(null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.serverConfig)&&(yield e.setToUser(t,_s,i.settings.serverConfig),delete i.settings.serverConfig,yield e.set(t,i))})}(t,i))])})}rollback(e){return Ss(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ss(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,_s);n&&(null!=i||(i={}),null!==(r=i.settings)&&void 0!==r||(i.settings={}),i.settings.serverConfig=n,yield e.setToUser(t,_s,null),yield e.set(t,i))})}(t,i))])})}}var Cs=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Is extends Nr{migrate(e){return Cs(this,void 0,void 0,function*(){const t=yield e.getAccounts();Promise.all(t.map(({userId:t,account:i})=>function(t,i){return Cs(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.organizationKeys)||void 0===n?void 0:n.encrypted;if(null==a)return;const s={};Object.entries(a).forEach(([e,t])=>{s[e]={type:"organization",key:t}}),i.keys.organizationKeys.encrypted=s,yield e.set(t,i)})}(t,i)))})}rollback(e){return Cs(this,void 0,void 0,function*(){const t=yield e.getAccounts();Promise.all(t.map(t=>Cs(this,[t],void 0,function*({userId:t,account:i}){return function(t,i){return Cs(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.organizationKeys)||void 0===n?void 0:n.encrypted;if(null==a)return;const s={};Object.entries(a).forEach(([e,t])=>{s[e]=t.key}),i.keys.organizationKeys.encrypted=s,yield e.set(t,i)})}(t,i)})))})}updateVersion(e,t){return Cs(this,void 0,void 0,function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const r=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},r),{stateVersion:i}))})}}var Es=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const zs={key:"usesKeyConnector",stateDefinition:{name:"keyConnector"}},Ps={key:"convertAccountToKeyConnector",stateDefinition:{name:"keyConnector"}};class As extends Nr{migrate(e){return Es(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Es(this,void 0,void 0,function*(){var r,n;const a=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.usesKeyConnector,s=null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.convertAccountToKeyConnector;null==a&&null==s||(null!=a&&(yield e.setToUser(t,zs,a),delete i.profile.usesKeyConnector),null!=s&&(yield e.setToUser(t,Ps,s),delete i.profile.convertAccountToKeyConnector),yield e.set(t,i))})}(t,i))])})}rollback(e){return Es(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Es(this,void 0,void 0,function*(){const r=yield e.getFromUser(t,zs),n=yield e.getFromUser(t,Ps);null==r&&null==n||(null!=r&&(i.profile.usesKeyConnector=r,yield e.setToUser(t,zs,null)),null!=n&&(i.profile.convertAccountToKeyConnector=n,yield e.setToUser(t,Ps,null)),yield e.set(t,i))})}(t,i))])})}}var js=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ts={key:"storedEmail",stateDefinition:{name:"loginEmail"}};class Ds extends Nr{migrate(e){return js(this,void 0,void 0,function*(){const t=yield e.get("global");null!=(null==t?void 0:t.rememberedEmail)&&(yield e.setToGlobal(Ts,t.rememberedEmail)),null==t||delete t.rememberedEmail,yield e.set("global",t)})}rollback(e){return js(this,void 0,void 0,function*(){let t=yield e.get("global"),i=!1;const r=yield e.getFromGlobal(Ts);r&&(t||(t={}),i=!0,t.rememberedEmail=r,yield e.setToGlobal(Ts,null)),i&&(yield e.set("global",t))})}}class Os extends Nr{migrate(e){return t=this,i=void 0,n=function*(){const t=yield e.get("global");null!=(null==t?void 0:t.installedVersion)&&(delete t.installedVersion,yield e.set("global",t))},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}rollback(e){throw Or}}var Ns=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Rs={key:"deviceKey",stateDefinition:{name:"deviceTrust"}},Us={key:"shouldTrustDevice",stateDefinition:{name:"deviceTrust"}};class Fs extends Nr{migrate(e){return Ns(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ns(this,void 0,void 0,function*(){var r,n;let a=!1;const s=null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.deviceKey;null!=s&&(yield e.setToUser(t,Rs,s),delete i.keys.deviceKey,a=!0);const o=null===(n=null==i?void 0:i.settings)||void 0===n?void 0:n.trustDeviceChoiceForDecryption;null!=o&&(yield e.setToUser(t,Us,o),delete i.settings.trustDeviceChoiceForDecryption,a=!0),a&&(yield e.set(t,i))})}(t,i))])})}rollback(e){return Ns(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ns(this,void 0,void 0,function*(){const r=yield e.getFromUser(t,Rs);(null==i?void 0:i.keys)&&null!=r&&(i.keys.deviceKey=r,yield e.set(t,i)),yield e.setToUser(t,Rs,null);const n=yield e.getFromUser(t,Us);(null==i?void 0:i.settings)&&null!=n&&(i.settings.trustDeviceChoiceForDecryption=n,yield e.set(t,i)),yield e.setToUser(t,Us,null)})}(t,i))])})}}var qs,Ls=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};!function(e){e[e.Text=0]="Text",e[e.File=1]="File"}(qs||(qs={}));const Bs={stateDefinition:{name:"send"},key:"sends"};class Ms extends Nr{migrate(e){return Ls(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ls(this,void 0,void 0,function*(){var r,n;const a=null===(n=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.sends)||void 0===n?void 0:n.encrypted;null!=a&&(yield e.setToUser(t,Bs,a),delete i.data.sends,yield e.set(t,i))})}(t,i))])})}rollback(e){return Ls(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Ls(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Bs);i&&(i.data=Object.assign(null!==(r=i.data)&&void 0!==r?r:{},{sends:{encrypted:n}}),yield e.set(t,i)),yield e.setToUser(t,Bs,null)})}(t,i))])})}}var Vs=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const $s={key:"forceSetPasswordReason",stateDefinition:{name:"masterPassword"}},Ks={key:"masterKeyHash",stateDefinition:{name:"masterPassword"}},Ws={key:"masterKeyEncryptedUserKey",stateDefinition:{name:"masterPassword"}};class Hs extends Nr{migrate(e){return Vs(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Vs(this,void 0,void 0,function*(){var r,n,a;const s=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.forceSetPasswordReason;null!=s&&(yield e.setToUser(t,$s,s),delete i.profile.forceSetPasswordReason,yield e.set(t,i));const o=null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.keyHash;null!=o&&(yield e.setToUser(t,Ks,o),delete i.profile.keyHash,yield e.set(t,i));const l=null===(a=null==i?void 0:i.keys)||void 0===a?void 0:a.masterKeyEncryptedUserKey;null!=l&&(yield e.setToUser(t,Ws,l),delete i.keys.masterKeyEncryptedUserKey,yield e.set(t,i))})}(t,i))])})}rollback(e){return Vs(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Vs(this,void 0,void 0,function*(){var r,n,a;const s=yield e.getFromUser(t,$s),o=yield e.getFromUser(t,Ks),l=yield e.getFromUser(t,Ws);null!=i&&(null!=s&&(i.profile=Object.assign(null!==(r=i.profile)&&void 0!==r?r:{},{forceSetPasswordReason:s})),null!=o&&(i.profile=Object.assign(null!==(n=i.profile)&&void 0!==n?n:{},{keyHash:o})),null!=l&&(i.keys=Object.assign(null!==(a=i.keys)&&void 0!==a?a:{},{masterKeyEncryptedUserKey:l})),yield e.set(t,i)),yield e.setToUser(t,$s,null),yield e.setToUser(t,Ks,null)})}(t,i))])})}}var Gs=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Qs={stateDefinition:{name:"authRequestLocal"},key:"adminAuthRequest"},Js={stateDefinition:{name:"authRequestLocal"},key:"acceptAuthRequests"};class Ys extends Nr{migrate(e){return Gs(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Gs(this,void 0,void 0,function*(){var r;let n=!1;const a=null==i?void 0:i.adminAuthRequest;null!=a&&(yield e.setToUser(t,Qs,a),delete i.adminAuthRequest,n=!0);const s=null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.approveLoginRequests;null!=s&&(yield e.setToUser(t,Js,s),delete i.settings.approveLoginRequests,n=!0),n&&(yield e.set(t,i))})}(t,i))])})}rollback(e){return Gs(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Gs(this,void 0,void 0,function*(){var r;let n=!1;const a=yield e.getFromUser(t,Qs);null!=a&&(i.adminAuthRequest=a,n=!0),yield e.setToUser(t,Qs,null);const s=yield e.getFromUser(t,Js);null!=s&&(i.settings=Object.assign(null!==(r=i.settings)&&void 0!==r?r:{},{approveLoginRequests:s}),n=!0),yield e.setToUser(t,Js,null),n&&(yield e.set(t,i))})}(t,i))])})}}var Xs=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Zs={key:"localData",stateDefinition:{name:"ciphersLocal"}},eo={key:"ciphers",stateDefinition:{name:"ciphers"}};class to extends Nr{migrate(e){return Xs(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Xs(this,void 0,void 0,function*(){var r,n,a;let s=!1;const o=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.localData;null!=o&&(yield e.setToUser(t,Zs,o),delete i.data.localData,s=!0);const l=null===(a=null===(n=null==i?void 0:i.data)||void 0===n?void 0:n.ciphers)||void 0===a?void 0:a.encrypted;null!=l&&(yield e.setToUser(t,eo,l),delete i.data.ciphers,s=!0),s&&(yield e.set(t,i))})}(t,i))])})}rollback(e){return Xs(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Xs(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,Zs);i.data&&null!=n&&(i.data.localData=n,yield e.set(t,i)),yield e.setToUser(t,Zs,null);const a=yield e.getFromUser(t,eo);i.data&&null!=a&&((r=i.data).ciphers||(r.ciphers={encrypted:null}),i.data.ciphers.encrypted=a,yield e.set(t,i)),yield e.setToUser(t,eo,null)})}(t,i))])})}}var io=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ro={key:"refreshTokenMigratedToSecureStorage",stateDefinition:{name:"token"}};class no extends Nr{migrate(e){return io(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t){return io(this,void 0,void 0,function*(){null!=(yield e.getFromUser(t,ro))&&(yield e.removeFromUser(t,ro))})}(t))])})}rollback(e){return io(this,void 0,void 0,function*(){throw Or})}}var ao,so,oo=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};(so=ao||(ao={}))[so.PBKDF2_SHA256=0]="PBKDF2_SHA256",so[so.Argon2id=1]="Argon2id";const lo={key:"kdfConfig",stateDefinition:{name:"kdfConfig"}};class co extends Nr{migrate(e){return oo(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return oo(this,void 0,void 0,function*(){var r,n,a,s,o,l,c,u;const d={iterations:null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.kdfIterations,kdfType:null===(n=null==i?void 0:i.profile)||void 0===n?void 0:n.kdfType,memory:null===(a=null==i?void 0:i.profile)||void 0===a?void 0:a.kdfMemory,parallelism:null===(s=null==i?void 0:i.profile)||void 0===s?void 0:s.kdfParallelism};null!=d&&(yield e.setToUser(t,lo,d),null===(o=null==i?void 0:i.profile)||void 0===o||delete o.kdfIterations,null===(l=null==i?void 0:i.profile)||void 0===l||delete l.kdfType,null===(c=null==i?void 0:i.profile)||void 0===c||delete c.kdfMemory,null===(u=null==i?void 0:i.profile)||void 0===u||delete u.kdfParallelism),yield e.set(t,i)})}(t,i))])})}rollback(e){return oo(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return oo(this,void 0,void 0,function*(){const r=yield e.getFromUser(t,lo);null!=r&&(i.profile.kdfIterations=r.iterations,i.profile.kdfType=r.kdfType,i.profile.kdfMemory=r.memory,i.profile.kdfParallelism=r.parallelism,yield e.setToUser(t,lo,null)),yield e.set(t,i)})}(t,i))])})}}var uo=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class ho extends Nr{migrate(e){return uo(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return uo(this,void 0,void 0,function*(){var r;(null===(r=null==i?void 0:i.keys)||void 0===r?void 0:r.legacyEtmKey)&&(delete i.keys.legacyEtmKey,yield e.set(t,i))})}(t,i)))})}rollback(e){return uo(this,void 0,void 0,function*(){throw Or})}updateVersion(e,t){return uo(this,void 0,void 0,function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const r=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},r),{stateVersion:i}))})}}var po=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const mo={stateDefinition:{name:"account"},key:"accounts"},go={stateDefinition:{name:"account"},key:"activeAccountId"},fo={stateDefinition:{name:"account"},key:"activity"};class yo extends Nr{migrate(e){return po(this,void 0,void 0,function*(){yield this.migrateAuthenticatedAccounts(e),yield this.migrateActiveAccountId(e),yield this.migrateAccountActivity(e)})}rollback(e){return po(this,void 0,void 0,function*(){var t;const i=null!==(t=yield e.getKnownUserIds())&&void 0!==t?t:[];yield e.set("authenticatedAccounts",i),yield e.removeFromGlobal(mo);const r=yield e.getFromGlobal(go);r&&(yield e.set("activeUserId",r)),yield e.removeFromGlobal(go);const n=yield e.getFromGlobal(fo);if(n){const t=Object.entries(n).reduce((e,[t,i])=>(e[t]=new Date(i).getTime(),e),{});yield e.set("accountActivity",t)}yield e.removeFromGlobal(fo)})}migrateAuthenticatedAccounts(e){return po(this,void 0,void 0,function*(){var t;const i=null!==(t=yield e.get("authenticatedAccounts"))&&void 0!==t?t:[],r=(yield Promise.all(i.map(t=>po(this,void 0,void 0,function*(){const i=yield e.get(t);return{userId:t,account:i}})))).reduce((e,{userId:t,account:i})=>{var r,n;return(null==i?void 0:i.profile)&&(e[t]={email:null!==(r=i.profile.email)&&void 0!==r?r:"",emailVerified:null!==(n=i.profile.emailVerified)&&void 0!==n&&n,name:i.profile.name}),e},{});yield e.setToGlobal(mo,r),yield e.remove("authenticatedAccounts")})}migrateAccountActivity(e){return po(this,void 0,void 0,function*(){const t=yield e.get("accountActivity"),i=Object.entries(null!=t?t:{}).reduce((e,[t,i])=>(e[t]=JSON.stringify(new Date(i)),e),{});yield e.setToGlobal(fo,i),yield e.remove("accountActivity")})}migrateActiveAccountId(e){return po(this,void 0,void 0,function*(){const t=yield e.get("activeUserId");yield e.setToGlobal(go,t),yield e.remove("activeUserId")})}}var vo=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const bo={name:"pinUnlock"},wo={stateDefinition:bo,key:"pinKeyEncryptedUserKeyPersistent"},ko={stateDefinition:bo,key:"userKeyEncryptedPin"},So={stateDefinition:bo,key:"oldPinKeyEncryptedMasterKey"};class _o extends Nr{migrate(e){return vo(this,void 0,void 0,function*(){const t=yield e.getAccounts();let i=!1;yield Promise.all([...t.map(({userId:t,account:r})=>function(t,r){return vo(this,void 0,void 0,function*(){var n,a,s,o;null!=(null===(n=null==r?void 0:r.settings)||void 0===n?void 0:n.pinKeyEncryptedUserKey)&&(yield e.setToUser(t,wo,r.settings.pinKeyEncryptedUserKey),delete r.settings.pinKeyEncryptedUserKey,i=!0),null!=(null===(a=null==r?void 0:r.settings)||void 0===a?void 0:a.protectedPin)&&(yield e.setToUser(t,ko,r.settings.protectedPin),delete r.settings.protectedPin,i=!0),null!=(null===(o=null===(s=null==r?void 0:r.settings)||void 0===s?void 0:s.pinProtected)||void 0===o?void 0:o.encrypted)&&(yield e.setToUser(t,So,r.settings.pinProtected.encrypted),delete r.settings.pinProtected,i=!0),i&&(yield e.set(t,r))})}(t,r))])})}rollback(e){return vo(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return vo(this,void 0,void 0,function*(){var r;let n=!1;const a=yield e.getFromUser(t,wo),s=yield e.getFromUser(t,ko),o=yield e.getFromUser(t,So);i||(i={}),null!=a&&(i.settings.pinKeyEncryptedUserKey=a,yield e.setToUser(t,wo,null),n=!0),null!=s&&(i.settings.protectedPin=s,yield e.setToUser(t,ko,null),n=!0),null!=o&&(i.settings=Object.assign(null!==(r=i.settings)&&void 0!==r?r:{},{pinProtected:{encrypted:o}}),yield e.setToUser(t,So,null),n=!0),n&&(yield e.set(t,i))})}(t,i)))})}}var xo=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Co={name:"vaultTimeoutSettings"},Io={key:"vaultTimeout",stateDefinition:Co},Eo={key:"vaultTimeoutAction",stateDefinition:Co},zo={null:"never","-1":"onRestart","-2":"onLocked","-3":"onSleep","-4":"onIdle"},Po={never:null,onRestart:-1,onLocked:-2,onSleep:-3,onIdle:-4};var Ao;!function(e){e.Web="web",e.Browser="browser",e.Desktop="desktop",e.Cli="cli"}(Ao||(Ao={}));class jo extends Nr{migrate(e){return xo(this,void 0,void 0,function*(){const t=yield e.get("global"),i=yield e.getAccounts();yield Promise.all([...i.map(({userId:t,account:i})=>function(t,i){return xo(this,void 0,void 0,function*(){var r,n,a,s;let o=!1,l=null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.vaultTimeout;if(e.clientType===Ao.Cli&&void 0===l&&(l=null),void 0!==l){if(null===l||l<0){const i=zo[l];yield e.setToUser(t,Io,i)}else yield e.setToUser(t,Io,l);null===(n=null==i?void 0:i.settings)||void 0===n||delete n.vaultTimeout,o=!0}const c=null===(a=null==i?void 0:i.settings)||void 0===a?void 0:a.vaultTimeoutAction;null!=c&&(yield e.setToUser(t,Eo,c),null===(s=null==i?void 0:i.settings)||void 0===s||delete s.vaultTimeoutAction,o=!0),o&&(yield e.set(t,i))})}(t,i))]),null==t||delete t.vaultTimeout,null==t||delete t.vaultTimeoutAction,yield e.set("global",t),yield e.remove("global\\.vaultTimeout"),yield e.remove("global\\.vaultTimeoutAction")})}rollback(e){return xo(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return xo(this,void 0,void 0,function*(){let r=!1;const n=yield e.getFromUser(t,Io);(null==i?void 0:i.settings)&&null!=n&&(i.settings.vaultTimeout="string"==typeof n?Po[n]:n,r=!0),yield e.setToUser(t,Io,null);const a=yield e.getFromUser(t,Eo);(null==i?void 0:i.settings)&&null!=a&&(i.settings.vaultTimeoutAction=a,r=!0),yield e.setToUser(t,Eo,null),r&&(yield e.set(t,i))})}(t,i))])})}}var To=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Do={stateDefinition:{name:"generator"},key:"generatorSettings"},Oo={stateDefinition:{name:"generator"},key:"passwordGeneratorSettings"},No={stateDefinition:{name:"generator"},key:"passphraseGeneratorSettings"};class Ro extends Nr{migrate(e){return To(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return To(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.passwordGenerationOptions;if(n){const r=function(e){const t={length:e.length,ambiguous:e.ambiguous,uppercase:e.uppercase,minUppercase:e.minUppercase,lowercase:e.lowercase,minLowercase:e.minLowercase,number:e.number,minNumber:e.minNumber,special:e.special,minSpecial:e.minSpecial};return{generator:{type:e.type},password:t,passphrase:{numWords:e.numWords,wordSeparator:e.wordSeparator,capitalize:e.capitalize,includeNumber:e.includeNumber}}}(n);yield function(e,t,i){return To(this,void 0,void 0,function*(){var r;const n=null!==(r=yield e.getFromUser(t,Do))&&void 0!==r?r:{},a=Object.assign(n,i.generator);yield Promise.all([e.setToUser(t,Do,a),e.setToUser(t,No,i.passphrase),e.setToUser(t,Oo,i.password)])})}(e,t,r),yield function(e,t,i){return To(this,void 0,void 0,function*(){var r;null===(r=null==i?void 0:i.settings)||void 0===r||delete r.passwordGenerationOptions,yield e.set(t,i)})}(e,t,i)}})}(t,i))])})}rollback(e){return To(this,void 0,void 0,function*(){})}}var Uo=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Fo={stateDefinition:{name:"generator"},key:"localGeneratorHistoryBuffer"};class qo extends Nr{migrate(e){return Uo(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Uo(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.data)||void 0===r?void 0:r.passwordGenerationHistory;n&&n.encrypted&&(yield e.setToUser(t,Fo,n.encrypted),delete i.data.passwordGenerationHistory,yield e.set(t,i))})}(t,i))])})}rollback(e){return Uo(this,void 0,void 0,function*(){})}}var Lo=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Bo={stateDefinition:{name:"generator"},key:"generatorSettings"},Mo={stateDefinition:{name:"generator"},key:"catchallGeneratorSettings"},Vo={stateDefinition:{name:"generator"},key:"effUsernameGeneratorSettings"},$o={stateDefinition:{name:"generator"},key:"subaddressGeneratorSettings"},Ko={stateDefinition:{name:"generator"},key:"addyIoBuffer"},Wo={stateDefinition:{name:"generator"},key:"duckDuckGoBuffer"},Ho={stateDefinition:{name:"generator"},key:"fastmailBuffer"},Go={stateDefinition:{name:"generator"},key:"firefoxRelayBuffer"},Qo={stateDefinition:{name:"generator"},key:"forwardEmailBuffer"},Jo={stateDefinition:{name:"generator"},key:"simpleLoginBuffer"};class Yo extends Nr{migrate(e){return Lo(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t,i){return Lo(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.usernameGenerationOptions;if(n){const r=function(e){const t={addyIo:{baseUrl:e.forwardedAnonAddyBaseUrl,token:e.forwardedAnonAddyApiToken,domain:e.forwardedAnonAddyDomain},duckDuckGo:{token:e.forwardedDuckDuckGoToken},fastmail:{token:e.forwardedFastmailApiToken},firefoxRelay:{token:e.forwardedFirefoxApiToken},forwardEmail:{token:e.forwardedForwardEmailApiToken,domain:e.forwardedForwardEmailDomain},simpleLogin:{token:e.forwardedSimpleLoginApiKey,baseUrl:e.forwardedSimpleLoginBaseUrl}};return{generator:{username:e.type,forwarder:e.forwardedService},algorithms:{effUsername:{wordCapitalize:e.wordCapitalize,wordIncludeNumber:e.wordIncludeNumber},subaddress:{subaddressType:e.subaddressType,subaddressEmail:e.subaddressEmail},catchall:{catchallType:e.catchallType,catchallDomain:e.catchallDomain}},forwarders:t}}(n);yield function(e,t,i){return Lo(this,void 0,void 0,function*(){yield Promise.all([e.setToUser(t,Bo,i.generator),e.setToUser(t,Mo,i.algorithms.catchall),e.setToUser(t,Vo,i.algorithms.effUsername),e.setToUser(t,$o,i.algorithms.subaddress),e.setToUser(t,Ko,i.forwarders.addyIo),e.setToUser(t,Wo,i.forwarders.duckDuckGo),e.setToUser(t,Ho,i.forwarders.fastmail),e.setToUser(t,Go,i.forwarders.firefoxRelay),e.setToUser(t,Qo,i.forwarders.forwardEmail),e.setToUser(t,Jo,i.forwarders.simpleLogin)])})}(e,t,r),yield function(e,t,i){return Lo(this,void 0,void 0,function*(){var r;null===(r=null==i?void 0:i.settings)||void 0===r||delete r.usernameGenerationOptions,yield e.set(t,i)})}(e,t,i)}})}(t,i))])})}rollback(e){return Lo(this,void 0,void 0,function*(){})}}var Xo=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Zo={name:"desktopSettings"},el={key:"browserIntegrationEnabled",stateDefinition:Zo},tl={key:"browserIntegrationFingerprintEnabled",stateDefinition:Zo},il={key:"minimizeOnCopy",stateDefinition:Zo};class rl extends Nr{migrate(e){return Xo(this,void 0,void 0,function*(){const t=yield e.get("global"),i=null==t?void 0:t.enableBrowserIntegration,r=null==t?void 0:t.enableBrowserIntegrationFingerprint;let n=!1;null!=i&&(yield e.setToGlobal(el,i),delete t.enableBrowserIntegration,n=!0),null!=r&&(yield e.setToGlobal(tl,r),delete t.enableBrowserIntegrationFingerprint,n=!0),n&&(yield e.set("global",t));const a=yield e.getAccounts();yield Promise.all(a.map(({userId:t,account:i})=>function(t,i){return Xo(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.settings)||void 0===r?void 0:r.minimizeOnCopyToClipboard;null!=n&&(yield e.setToUser(t,il,n),delete i.settings.minimizeOnCopyToClipboard,yield e.set(t,i))})}(t,i)))})}rollback(e){return Xo(this,void 0,void 0,function*(){const t=yield e.getFromGlobal(el),i=yield e.getFromGlobal(tl);if(null!=t){let i=yield e.get("global");null!=i||(i={}),i.enableBrowserIntegration=t,yield e.set("global",i),yield e.removeFromGlobal(el)}if(null!=i){let t=yield e.get("global");null!=t||(t={}),t.enableBrowserIntegrationFingerprint=i,yield e.set("global",t),yield e.removeFromGlobal(tl)}const r=yield e.getAccounts();yield Promise.all(r.map(({userId:t,account:i})=>function(t,i){return Xo(this,void 0,void 0,function*(){const r=yield e.getFromUser(t,il);null!=r&&(null!=i||(i={settings:{}}),i.settings.minimizeOnCopyToClipboard=r,yield e.set(t,i),yield e.removeFromUser(t,il))})}(t,i)))})}}var nl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const al={key:"showBanner",stateDefinition:{name:"unassignedItemsBanner"}};class sl extends Nr{migrate(e){return nl(this,void 0,void 0,function*(){yield Promise.all((yield e.getAccounts()).map(t=>nl(this,[t],void 0,function*({userId:t}){null!=e.getFromUser(t,al)&&(yield e.removeFromUser(t,al))})))})}rollback(e){return nl(this,void 0,void 0,function*(){throw Or})}}var ol=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ll={key:"lastSync",stateDefinition:{name:"sync"}};class cl extends Nr{migrate(e){return ol(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return ol(this,void 0,void 0,function*(){var r;const n=null===(r=null==i?void 0:i.profile)||void 0===r?void 0:r.lastSync;null!=n&&(yield e.setToUser(t,ll,n),delete i.profile.lastSync,yield e.set(t,i))})}(t,i)))})}rollback(e){return ol(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t,account:i})=>function(t,i){return ol(this,void 0,void 0,function*(){var r;const n=yield e.getFromUser(t,ll);null!=n&&(null!=i||(i={}),null!==(r=i.profile)&&void 0!==r||(i.profile={}),i.profile.lastSync=n,yield e.set(t,i),yield e.removeFromUser(t,ll))})}(t,i)))})}}var ul=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const dl={key:"folder",stateDefinition:{name:"folder"}},hl={key:"folders",stateDefinition:{name:"folder"}};class pl extends Nr{migrate(e){return ul(this,void 0,void 0,function*(){const t=yield e.getKnownUserIds();yield Promise.all(t.map(t=>function(t){return ul(this,void 0,void 0,function*(){const i=yield e.getFromUser(t,dl);null!=i&&(yield e.setToUser(t,hl,i)),yield e.removeFromUser(t,dl)})}(t)))})}rollback(e){return ul(this,void 0,void 0,function*(){const t=yield e.getKnownUserIds();yield Promise.all(t.map(t=>function(t){return ul(this,void 0,void 0,function*(){const i=yield e.getFromUser(t,hl);null!=i&&(yield e.setToUser(t,dl,i)),yield e.removeFromUser(t,hl)})}(t)))})}}var ml=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class gl extends Nr{migrate(e){return ml(this,void 0,void 0,function*(){var t;const i=yield e.get("global"),r=null!==(t=null==i?void 0:i.noAutoPromptBiometrics)&&void 0!==t&&t,n=yield e.getAccounts();delete i.noAutoPromptBiometrics,yield Promise.all([...n.map(({userId:t,account:i})=>function(t,i){return ml(this,void 0,void 0,function*(){var n;null!=i&&r&&(i.settings=Object.assign(null!==(n=null==i?void 0:i.settings)&&void 0!==n?n:{},{disableAutoBiometricsPrompt:!0}),yield e.set(t,i))})}(t,i)),e.set("global",i)])})}rollback(e){return ml(this,void 0,void 0,function*(){throw Or})}updateVersion(e,t){return ml(this,void 0,void 0,function*(){const i="up"===t?this.toVersion:this.fromVersion;e.currentVersion=i;const r=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},r),{stateVersion:i}))})}}var fl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const yl={key:"acBannersDismissed",stateDefinition:{name:"showProviderClientVaultPrivacyBanner"}};class vl extends Nr{migrate(e){return fl(this,void 0,void 0,function*(){yield Promise.all((yield e.getAccounts()).map(t=>fl(this,[t],void 0,function*({userId:t}){null!=e.getFromUser(t,yl)&&(yield e.removeFromUser(t,yl))})))})}rollback(e){return fl(this,void 0,void 0,function*(){throw Or})}}var bl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const wl={key:"newCustomizationOptionsCalloutDismissed",stateDefinition:{name:"bannersDismissed"}};class kl extends Nr{migrate(e){return bl(this,void 0,void 0,function*(){yield Promise.all((yield e.getAccounts()).map(t=>bl(this,[t],void 0,function*({userId:t}){null!=e.getFromUser(t,wl)&&(yield e.removeFromUser(t,wl))})))})}rollback(e){return bl(this,void 0,void 0,function*(){throw Or})}}var Sl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const _l={key:"showAccountDeprovisioningBanner",stateDefinition:{name:"accountDeprovisioningBanner"}};class xl extends Nr{migrate(e){return Sl(this,void 0,void 0,function*(){yield Promise.all((yield e.getAccounts()).map(t=>Sl(this,[t],void 0,function*({userId:t}){null!=e.getFromUser(t,_l)&&(yield e.removeFromUser(t,_l))})))})}rollback(e){return Sl(this,void 0,void 0,function*(){throw Or})}}var Cl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Il={stateDefinition:{name:"account"},key:"accounts"},El={key:"masterPasswordUnlockKey",stateDefinition:{name:"masterPasswordUnlock"}},zl={key:"masterKeyEncryptedUserKey",stateDefinition:{name:"masterPassword"}},Pl={key:"kdfConfig",stateDefinition:{name:"kdfConfig"}};class Al extends Nr{migrate(e){return Cl(this,void 0,void 0,function*(){const t=yield e.getFromGlobal(Il),i=yield e.getAccounts();yield Promise.all(i.map(({userId:i})=>function(t,i){return Cl(this,void 0,void 0,function*(){const r=null==i?void 0:i.email,n=yield e.getFromUser(t,Pl),a=yield e.getFromUser(t,zl);null==(yield e.getFromUser(t,El))&&null!=r&&null!=n&&null!=a&&(yield e.setToUser(t,El,{salt:r.trim().toLowerCase(),kdf:n,masterKeyWrappedUserKey:a}))})}(i,t[i])))})}rollback(e){return Cl(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all(t.map(({userId:t})=>function(t){return Cl(this,void 0,void 0,function*(){null!=(yield e.getFromUser(t,El))&&(yield e.removeFromUser(t,El))})}(t)))})}}var jl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Tl={key:"pinKeyEncryptedUserKeyPersistent",stateDefinition:{name:"pinUnlock"}};class Dl extends Nr{migrate(e){return jl(this,void 0,void 0,function*(){const t=yield e.getAccounts();yield Promise.all([...t.map(({userId:t,account:i})=>function(t){return jl(this,void 0,void 0,function*(){null!=(yield e.getFromUser(t,Tl))&&(yield e.removeFromUser(t,Tl))})}(t))])})}rollback(e){return jl(this,void 0,void 0,function*(){throw Or})}}var Ol=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Nl={key:"privateKey",stateDefinition:{name:"crypto"}},Rl={key:"userSigningKey",stateDefinition:{name:"crypto"}},Ul={key:"userSignedPublicKey",stateDefinition:{name:"crypto"}},Fl={key:"accountSecurityState",stateDefinition:{name:"crypto"}},ql={key:"accountCryptographicState",stateDefinition:{name:"crypto"}};class Ll extends Nr{migrate(e){return Ol(this,void 0,void 0,function*(){const t=yield e.getAccounts();for(const{userId:i}of t){const t=yield e.getFromUser(i,ql),r=yield e.getFromUser(i,Nl),n=yield e.getFromUser(i,Rl),a=yield e.getFromUser(i,Ul),s=yield e.getFromUser(i,Fl);if(!t){let t;null!=r&&null==n&&null==a&&null==s?(t={V1:{private_key:r}},yield e.setToUser(i,ql,t)):null!=r&&null!=n&&null!=a&&null!=s?(t={V2:{private_key:r,signing_key:n,signed_public_key:a,security_state:s}},yield e.setToUser(i,ql,t)):e.logService.warning(`Incomplete cryptographic state for user ${i}, skipping migration of account cryptographic state.`)}null!=r&&(yield e.removeFromUser(i,Nl)),null!=n&&(yield e.removeFromUser(i,Rl)),null!=a&&(yield e.removeFromUser(i,Ul)),null!=s&&(yield e.removeFromUser(i,Fl))}})}rollback(e){return Ol(this,void 0,void 0,function*(){throw Or})}}var Bl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Ml extends Nr{migrate(e){return Bl(this,void 0,void 0,function*(){const t=yield e.get("global");if(!t.stateVersion)throw new Error("Migration failed, state version not found");yield e.set("stateVersion",t.stateVersion),delete t.stateVersion,yield e.set("global",t)})}rollback(e){return Bl(this,void 0,void 0,function*(){const t=yield e.get("stateVersion"),i=yield e.get("global");yield e.set("global",Object.assign(Object.assign({},i),{stateVersion:t})),yield e.set("stateVersion",void 0)})}updateVersion(e,t){return Bl(this,void 0,void 0,function*(){const i="up"===t?this.toVersion:this.fromVersion;if(e.currentVersion=i,"up"===t)yield e.set("stateVersion",i);else{const t=(yield e.get("global"))||{};yield e.set("global",Object.assign(Object.assign({},t),{stateVersion:i}))}})}}var Vl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class $l extends Nr{tryAddSetting(e,t,i){if(e.some(({account:e})=>void 0!==t(e))){const r=!e.some(({account:e})=>{var i;return!1===(null!==(i=t(e))&&void 0!==i&&i)});i(r)}}migrate(e){return Vl(this,void 0,void 0,function*(){const t=yield e.get("global"),i=yield e.getAccounts(),r=i.reduce((e,{account:t})=>{var i,r;const n=null!==(r=null===(i=t.settings)||void 0===i?void 0:i.neverDomains)&&void 0!==r?r:{};for(const[t,i]of Object.entries(n))null!=e||(e={}),e[t]=i;return e},void 0),n={};null!=r&&(n.neverDomains=r),this.tryAddSetting(i,e=>{var t;return null===(t=e.settings)||void 0===t?void 0:t.disableAddLoginNotification},e=>n.disableAddLoginNotification=e),this.tryAddSetting(i,e=>{var t;return null===(t=e.settings)||void 0===t?void 0:t.disableChangedPasswordNotification},e=>n.disableChangedPasswordNotification=e),this.tryAddSetting(i,e=>{var t;return null===(t=e.settings)||void 0===t?void 0:t.disableContextMenuItem},e=>n.disableContextMenuItem=e),yield e.set("global",Object.assign(Object.assign({},t),n)),yield Promise.all(i.map(t=>Vl(this,[t],void 0,function*({userId:t,account:i}){var r,n,a,s;null===(r=i.settings)||void 0===r||delete r.disableAddLoginNotification,null===(n=i.settings)||void 0===n||delete n.disableChangedPasswordNotification,null===(a=i.settings)||void 0===a||delete a.disableContextMenuItem,null===(s=i.settings)||void 0===s||delete s.neverDomains,yield e.set(t,i)})))})}rollback(e){throw new Error("Method not implemented.")}}var Kl=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Wl extends Nr{constructor(){super(0,Gl)}shouldMigrate(e){return Promise.resolve(e.currentVersionJl(this,void 0,void 0,function*(){return{userId:e,account:yield this.get(e)}})))})}getKnownUserIds(){return Jl(this,void 0,void 0,function*(){return this.currentVersion<60?function(e){return Jl(this,void 0,void 0,function*(){var t;return null!==(t=yield e.get("authenticatedAccounts"))&&void 0!==t?t:[]})}(this.storageService):function(e){return Jl(this,void 0,void 0,function*(){const t=yield e.get(Xl({stateDefinition:{name:"account"},key:"accounts"}));return Object.keys(null!=t?t:{})})}(this.storageService)})}getUserKey(e,t){return this.currentVersion<9?function(){throw Error("No key builder should be used for versions prior to 9.")}():function(e,t){return`user_${e}_${t.stateDefinition.name}_${t.key}`}(e,t)}getGlobalKey(e){return this.currentVersion<9?function(){throw Error("No key builder should be used for versions prior to 9.")}():Xl(e)}}function Xl(e){return`global_${e.stateDefinition.name}_${e.key}`}function Zl(e,t){return void 0===t&&(t=B),e=null!=e?e:ec,Q(function(i,r){var n,a=!0;i.subscribe(J(r,function(i){var s=t(i);!a&&e(n,s)||(a=!1,n=s,r.next(i))}))})}function ec(e,t){return e===t}function tc(e,t){var i=h(e)?e:function(){return e},r=function(e){return e.error(i())};return new $(t?function(e){return t.schedule(r,0,e)}:r)}class ic{constructor(e,t,i){this.keyDefinition=e,this.activeUserId$=t,this.singleUserStateProvider=i,this.combinedState$=this.activeUserId$.pipe(Le(e=>null!=e?this.singleUserStateProvider.get(e,this.keyDefinition).combinedState$:Wt)),this.state$=this.combinedState$.pipe(X(([e,t])=>t))}update(e){return t=this,i=arguments,n=function*(e,t={}){const i=yield Ce(this.activeUserId$.pipe(Fe({first:1e3,with:()=>tc(()=>new Error(`Timeout while retrieving active user for key ${this.keyDefinition.fullName}.`))})));if(null==i)throw new Error(`Error storing ${this.keyDefinition.fullName} for the active user: No active user at this time.`);return[i,yield this.singleUserStateProvider.get(i,this.keyDefinition).update(e,t)]},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class rc{constructor(e,t){this.activeAccountAccessor=e,this.singleUserStateProvider=t,this.activeUserId$=this.activeAccountAccessor.activeUserId$.pipe(Zl((e,t)=>null==e||null==t?e==t:e===t))}get(e){return new ic(e,this.activeUserId$,this.singleUserStateProvider)}}function nc(e){return new $(function(t){le(e()).subscribe(t)})}function ac(e,t,i){var r=h(e)||t||i?{next:e,error:t,complete:i}:e;return r?Q(function(e,t){var i;null===(i=r.subscribe)||void 0===i||i.call(r);var n=!0;e.subscribe(J(t,function(e){var i;null===(i=r.next)||void 0===i||i.call(r,e),t.next(e)},function(){var e;n=!1,null===(e=r.complete)||void 0===e||e.call(r),t.complete()},function(e){var i;n=!1,null===(i=r.error)||void 0===i||i.call(r,e),t.error(e)},function(){var e,t;n&&(null===(e=r.unsubscribe)||void 0===e||e.call(r)),null===(t=r.finalize)||void 0===t||t.call(r)}))}):B}function sc(e,t,i){void 0===e&&(e=0),void 0===i&&(i=De);var r=-1;return null!=t&&(me(t)?i=t:r=t),new $(function(t){var n=Oe(e)?+e-i.now():e;n<0&&(n=0);var a=0;return i.schedule(function(){t.closed||(t.next(a++),0<=r?this.schedule(void 0,r):t.complete())},n)})}function oc(e,t,i){return r=this,n=void 0,s=function*(){if(t.valuesRequireDeserialization){const r=yield t.get(e);return i(r)}{const i=yield t.get(e);return null!=i?i:null}},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}var lc=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class cc{constructor(e,t,i,r){this.key=e,this.storageService=t,this.keyDefinition=i,this.logService=r;const n=t.updates$.pipe(Ie(t=>t.key===e),Le(r=>lc(this,void 0,void 0,function*(){return"remove"===r.updateType?null:yield oc(e,t,i.deserializer)})));let a=_e(nc(()=>oc(e,t,i.deserializer)),n);i.debug.enableRetrievalLogging&&(a=a.pipe(ac({next:t=>{this.logService.info(`Retrieving '${e}' from storage, value is ${null==t?"null":"non-null"}`)}}))),0!==i.cleanupDelayMs&&(a=a.pipe(Gt({connector:()=>new Ht(1),resetOnRefCountZero:()=>sc(i.cleanupDelayMs)}))),this.state$=a}update(e){return lc(this,arguments,void 0,function*(e,t={}){const i=function(e){const{combineLatestWith:t=null,shouldUpdate:i=()=>!0,msTimeout:r=1e3}=e;return{combineLatestWith:t,shouldUpdate:i,msTimeout:r}}(t);null!=this.updatePromise&&(yield this.updatePromise);try{return this.updatePromise=this.internalUpdate(e,i),yield this.updatePromise}finally{this.updatePromise=null}})}internalUpdate(e,t){return lc(this,void 0,void 0,function*(){const i=yield this.getStateForUpdate(),r=null!=t.combineLatestWith?yield Ce(t.combineLatestWith.pipe(Fe(t.msTimeout))):null;if(!t.shouldUpdate(i,r))return i;const n=e(i,r);return yield this.doStorageSave(n,i),n})}doStorageSave(e,t){return lc(this,void 0,void 0,function*(){this.keyDefinition.debug.enableUpdateLogging&&this.logService.info(`Updating '${this.key}' from ${null==t?"null":"non-null"} to ${null==e?"null":"non-null"}`),yield this.storageService.save(this.key,e)})}getStateForUpdate(){return lc(this,void 0,void 0,function*(){return yield oc(this.key,this.storageService,this.keyDefinition.deserializer)})}}class uc extends cc{constructor(e,t,i){super(function(e){return`global_${e.stateDefinition.name}_${e.key}`}(e),t,e,i)}}class dc{constructor(e,t){this.storageServiceProvider=e,this.logService=t,this.globalStateCache={}}get(e){const[t,i]=this.storageServiceProvider.get(e.stateDefinition.defaultStorageLocation,e.stateDefinition.storageLocationOverrides),r=this.buildCacheKey(t,e),n=this.globalStateCache[r];if(null!=n)return n;const a=new uc(e,i,this.logService);return this.globalStateCache[r]=a,a}buildCacheKey(e,t){return`${e}_${t.fullName}`}}class hc extends cc{constructor(e,t,i,r,n){super(t.buildKey(e),i,t,n),this.userId=e,this.stateEventRegistrarService=r,this.combinedState$=ai([bt(e),this.state$])}doStorageSave(e,t){const i=Object.create(null,{doStorageSave:{get:()=>super.doStorageSave}});return r=this,n=void 0,s=function*(){yield i.doStorageSave.call(this,e,t),yield this.stateEventRegistrarService.registerEvents(this.keyDefinition)},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}}class pc{constructor(e,t,i){this.storageServiceProvider=e,this.stateEventRegistrarService=t,this.logService=i,this.cache={}}get(e,t){const[i,r]=this.storageServiceProvider.get(t.stateDefinition.defaultStorageLocation,t.stateDefinition.storageLocationOverrides),n=this.buildCacheKey(i,e,t),a=this.cache[n];if(null!=a)return a;const s=new hc(e,t,r,this.stateEventRegistrarService,this.logService);return this.cache[n]=s,s}buildCacheKey(e,t,i){return`${e}_${i.fullName}_${t}`}}class mc{constructor(e,t,i,r){this.activeUserStateProvider=e,this.singleUserStateProvider=t,this.globalStateProvider=i,this.derivedStateProvider=r,this.getActive=this.activeUserStateProvider.get.bind(this.activeUserStateProvider),this.getUser=this.singleUserStateProvider.get.bind(this.singleUserStateProvider),this.getGlobal=this.globalStateProvider.get.bind(this.globalStateProvider),this.getDerived=this.derivedStateProvider.get.bind(this.derivedStateProvider),this.activeUserId$=this.activeUserStateProvider.activeUserId$}getUserState$(e,t){return t?this.getUser(t,e).state$:this.activeUserId$.pipe(Ie(e=>null!=e),ci(1),Le(t=>this.getUser(t,e).state$))}getUserStateOrDefault$(e,t){const{userId:i,defaultValue:r=null}=t;return i?this.getUser(i,e).state$:this.activeUserId$.pipe(ci(1),Le(t=>null!=t?this.getUser(t,e).state$:bt(r)))}setUserState(e,t,i){return r=this,n=void 0,s=function*(){return i?[i,yield this.getUser(i,e).update(()=>t)]:yield this.getActive(e).update(()=>t)},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}}function gc(e,t){return h(t)?de(e,t,1):de(e,1)}class fc{get(e,t,i){return new yc(e,t,i)}}class yc{constructor(e,t,i){this.state$=e.pipe(gc(e=>{return r=this,n=void 0,s=function*(){return yield t.derive(e,i)},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}))}forceValue(e){return Promise.resolve(e)}}class vc{}var bc=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const wc="global",kc="_user_auto",Sc="DuckDuckGoSharedKey";class _c{constructor(e,t,i){this.storageService=e,this.secureStorageService=t,this.activeUserAccessor=i}clean(e){return bc(this,void 0,void 0,function*(){yield this.setUserKeyAutoUnlock(null,e),yield this.clearUserKeyBiometric(e.userId)})}getUserKeyAutoUnlock(e){return bc(this,void 0,void 0,function*(){return null==e.userId?null:yield this.secureStorageService.get(`${e.userId}${kc}`,{userId:e.userId,keySuffix:"auto"})})}setUserKeyAutoUnlock(e,t){return bc(this,void 0,void 0,function*(){null!=t.userId&&(yield this.saveSecureStorageKey(kc,e,t.userId,"auto"))})}clearUserKeyBiometric(e){return bc(this,void 0,void 0,function*(){null!=e&&(yield this.saveSecureStorageKey("_user_biometric",null,e,"biometric"))})}getDuckDuckGoSharedKey(){return bc(this,void 0,void 0,function*(){return null==(yield this.getActiveUserIdFromStorage())?null:yield this.secureStorageService.get(Sc)})}setDuckDuckGoSharedKey(e){return bc(this,void 0,void 0,function*(){null!=(yield this.getActiveUserIdFromStorage())&&(null==e?yield this.secureStorageService.remove(Sc):yield this.secureStorageService.save(Sc,e))})}setEnableDuckDuckGoBrowserIntegration(e){return bc(this,void 0,void 0,function*(){var t;const i=null!==(t=yield this.storageService.get(wc))&&void 0!==t?t:new vc;i.enableDuckDuckGoBrowserIntegration=e,yield this.storageService.save(wc,i)})}getActiveUserIdFromStorage(){return bc(this,void 0,void 0,function*(){return yield Ce(this.activeUserAccessor.activeUserId$)})}saveSecureStorageKey(e,t,i,r){return bc(this,void 0,void 0,function*(){return null==t?yield this.secureStorageService.remove(`${i}${e}`,{keySuffix:r}):yield this.secureStorageService.save(`${i}${e}`,t,{keySuffix:r})})}}const xc=fi.array(Ji,"lock",{deserializer:e=>e}),Cc=fi.array(Ji,"logout",{deserializer:e=>e});class Ic{constructor(e,t){this.storageServiceProvider=t,this.stateEventStateMap={lock:e.get(xc),logout:e.get(Cc)}}registerEvents(e){return t=this,i=void 0,n=function*(){for(const t of e.clearOn){const i=this.stateEventStateMap[t],[r]=this.storageServiceProvider.get(e.stateDefinition.defaultStorageLocation,e.stateDefinition.storageLocationOverrides),n={state:e.stateDefinition.name,key:e.key,location:r};yield i.update(e=>(null!=e||(e=[]),e.push(n),e),{shouldUpdate:e=>null==e||-1===e.findIndex(e=>e.state===n.state&&e.key===n.key&&e.location===n.location)})}},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class Ec{constructor(e,t){this.storageServiceProvider=t,this.stateEventMap={lock:e.get(xc),logout:e.get(Cc)}}handleEvent(e,t){return i=this,r=void 0,a=function*(){let i=yield Ce(this.stateEventMap[e].state$);null!=i||(i=[]);const r=[];for(const e of i)try{const[,i]=this.storageServiceProvider.get(e.location,{}),r=this.storageKeyFor(t,e);null!=(yield i.get(r))&&(yield i.remove(r))}catch(t){let i="Unknown Error";null!=t&&"object"==typeof t&&"message"in t&&"string"==typeof t.message&&(i=t.message),r.push(`${i} in ${e.state} > ${e.key} located ${e.location}`)}if(r.length>0)throw new Error(`One or more errors occurred while handling event '${e}' for user ${t}.\n${r.join("\n")}`)},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}storageKeyFor(e,t){return new wi(new ki(t.state,t.location),t.key,{deserializer:e=>e,clearOn:[]}).buildKey(e)}}const zc=wi.record(mr,"collections",{deserializer:e=>Kt.fromJSON(e),clearOn:["logout"]}),Pc=new wi(gr,"decryptedCollections",{deserializer:e=>{var t;return null!==(t=null==e?void 0:e.map(e=>qt.fromJSON(e)))&&void 0!==t?t:null},clearOn:["logout","lock"]});var Ac=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class jc{constructor(e,t,i,r){this.keyService=e,this.encryptService=t,this.i18nService=i,this.stateProvider=r,this.collectionViewCache=new Map}encryptedState(e){return this.stateProvider.getUser(e,zc)}decryptedState(e){return this.stateProvider.getUser(e,Pc)}encryptedCollections$(e){return this.encryptedState(e).state$.pipe(X(e=>null==e?null:Object.values(e).map(e=>Ut.fromCollectionData(e))))}decryptedCollections$(e){const t=this.collectionViewCache.get(e);if(t)return t;const i=this.decryptedState(e).state$.pipe(Le(t=>null!==t?bt(null!=t?t:[]):this.initializeDecryptedState(e).pipe(Le(()=>Wt))),Jt({bufferSize:1,refCount:!0}));return this.collectionViewCache.set(e,i),i}defaultUserCollection$(e,t){return this.decryptedCollections$(e).pipe(X(e=>e.find(e=>e.isDefaultCollection&&e.organizationId===t)))}initializeDecryptedState(e){return ai([this.encryptedCollections$(e),this.keyService.orgKeys$(e).pipe(Ie(e=>!!e))]).pipe(Le(([t,i])=>this.decryptMany$(t,i).pipe(di(t=>this.setDecryptedCollections(t,e)))))}upsert(e,t){return Ac(this,void 0,void 0,function*(){if(null==e)return;yield this.encryptedState(t).update(t=>(null==t&&(t={}),t[e.id]=e,t));const i=yield Ce(this.keyService.orgKeys$(t).pipe(Le(t=>{if(!t)throw new Error("No key for this collection's organization.");return this.decryptMany$([Ut.fromCollectionData(e)],t)})));yield this.decryptedState(t).update(t=>{if(null==t&&(t=[]),!(null==i?void 0:i.length))return t;const r=i[0],n=t.findIndex(t=>t.id==e.id);return n>=0?t[n]=r:t.push(r),t})})}replace(e,t){return Ac(this,void 0,void 0,function*(){yield this.encryptedState(t).update(()=>e),yield this.decryptedState(t).update(()=>null)})}delete(e,t){return Ac(this,void 0,void 0,function*(){yield this.encryptedState(t).update(t=>(null==t&&(t={}),e.forEach(e=>{delete t[e]}),t)),yield this.decryptedState(t).update(t=>(null==t&&(t=[]),e.forEach(e=>{var i;(null==t?void 0:t.length)&&(t=null!==(i=t.filter(t=>t.id!=e))&&void 0!==i?i:[])}),t))})}encrypt(e,t){return Ac(this,void 0,void 0,function*(){const i=yield Ce(this.keyService.orgKeys$(t).pipe(Ie(e=>!!e),X(t=>t[e.organizationId])));return yield e.encrypt(i,this.encryptService)})}decryptMany$(e,t){if(null===e||0==e.length||null===t)return bt([]);const i=[];return e.forEach(e=>{i.push(Se(e.decrypt(t[e.organizationId],this.encryptService)))}),ai(i).pipe(X(e=>e.sort(Tt.getSortFunction(this.i18nService,"name"))))}getAllNested(e){const t=this.groupByOrganization(e),i=[];for(const e of t.values()){const t=[];for(const i of e){const e=Object.assign(new qt(Object.assign(Object.assign({},i),{name:i.name})),i),r=i.name?i.name.replace(/^\/+|\/+$/g,"").split("/"):[];pi.nestedTraverse(t,0,r,e,void 0,"/")}i.push(...t)}return i}groupByOrganization(e){const t=new Map;return e.map(e=>{var i;const r=e.organizationId;(null!==(i=t.get(r))&&void 0!==i?i:t.set(r,[]).get(r)).push(e)}),t}getNested(e,t){const i=this.getAllNested(e);return pi.getTreeNodeObjectFromList(i,t)}setDecryptedCollections(e,t){return Ac(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(Pc,e,t)})}}class Tc extends Lt{constructor(e,t){super(e);const i=this.getResponseProperty("Data");this.data=null==i?[]:i.map(e=>new t(e)),this.continuationToken=this.getResponseProperty("ContinuationToken")}}class Dc{constructor(e){this.ids=null==e?[]:e}}class Oc extends Lt{constructor(e=null){if(super(e),null==e)return this;this.accessEventLogs=this.getResponseProperty("AccessEventLogs"),this.accessImportExport=this.getResponseProperty("AccessImportExport"),this.accessReports=this.getResponseProperty("AccessReports"),this.createNewCollections=this.getResponseProperty("CreateNewCollections"),this.editAnyCollection=this.getResponseProperty("EditAnyCollection"),this.deleteAnyCollection=this.getResponseProperty("DeleteAnyCollection"),this.manageCiphers=this.getResponseProperty("ManageCiphers"),this.manageGroups=this.getResponseProperty("ManageGroups"),this.manageSso=this.getResponseProperty("ManageSso"),this.managePolicies=this.getResponseProperty("ManagePolicies"),this.manageUsers=this.getResponseProperty("ManageUsers"),this.manageResetPassword=this.getResponseProperty("ManageResetPassword"),this.manageScim=this.getResponseProperty("ManageScim")}}class Nc extends Lt{constructor(e){super(e),this.collections=[],this.groups=[],this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.type=this.getResponseProperty("Type"),this.status=this.getResponseProperty("Status"),this.permissions=new Oc(this.getResponseProperty("Permissions")),this.externalId=this.getResponseProperty("ExternalId"),this.accessSecretsManager=this.getResponseProperty("AccessSecretsManager"),this.resetPasswordEnrolled=this.getResponseProperty("ResetPasswordEnrolled"),this.hasMasterPassword=this.getResponseProperty("HasMasterPassword");const t=this.getResponseProperty("Collections");null!=t&&(this.collections=t.map(e=>new Bt(e)));const i=this.getResponseProperty("Groups");null!=i&&(this.groups=i)}}class Rc extends Nc{constructor(e){var t,i;super(e),this.name=this.getResponseProperty("Name"),this.email=this.getResponseProperty("Email"),this.avatarColor=this.getResponseProperty("AvatarColor"),this.twoFactorEnabled=this.getResponseProperty("TwoFactorEnabled"),this.usesKeyConnector=null!==(t=this.getResponseProperty("UsesKeyConnector"))&&void 0!==t&&t,this.managedByOrganization=null!==(i=this.getResponseProperty("ManagedByOrganization"))&&void 0!==i&&i}}class Uc extends Nc{constructor(e){var t;super(e),this.managedByOrganization=null!==(t=this.getResponseProperty("ManagedByOrganization"))&&void 0!==t&&t,this.ssoExternalId=this.getResponseProperty("SsoExternalId")}}class Fc extends Lt{constructor(e){super(e),this.organizationUserId=this.getResponseProperty("OrganizationUserId"),this.kdf=this.getResponseProperty("Kdf"),this.kdfIterations=this.getResponseProperty("KdfIterations"),this.kdfMemory=this.getResponseProperty("KdfMemory"),this.kdfParallelism=this.getResponseProperty("KdfParallelism"),this.resetPasswordKey=this.getResponseProperty("ResetPasswordKey"),this.encryptedPrivateKey=this.getResponseProperty("EncryptedPrivateKey")}}class qc extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.error=this.getResponseProperty("Error")}}class Lc extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.key=this.getResponseProperty("Key")}}class Bc extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.email=this.getResponseProperty("Email"),this.name=this.getResponseProperty("Name"),this.type=this.getResponseProperty("Type"),this.status=this.getResponseProperty("Status")}}var Mc=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Vc{constructor(e){this.apiService=e}getOrganizationUser(e,t,i){return Mc(this,void 0,void 0,function*(){const r=new URLSearchParams;(null==i?void 0:i.includeGroups)&&r.set("includeGroups","true");const n=yield this.apiService.send("GET",`/organizations/${e}/users/${t}?${r.toString()}`,null,!0,!0);return new Uc(n)})}getAllUsers(e,t){return Mc(this,void 0,void 0,function*(){const i=new URLSearchParams;(null==t?void 0:t.includeCollections)&&i.set("includeCollections","true"),(null==t?void 0:t.includeGroups)&&i.set("includeGroups","true");const r=yield this.apiService.send("GET",`/organizations/${e}/users?${i.toString()}`,null,!0,!0);return new Tc(r,Rc)})}getAllMiniUserDetails(e){return Mc(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET",`/organizations/${e}/users/mini-details`,null,!0,!0);return new Tc(t,Bc)})}getOrganizationUserResetPasswordDetails(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("GET","/organizations/"+e+"/users/"+t+"/reset-password-details",null,!0,!0);return new Fc(i)})}getManyOrganizationUserAccountRecoveryDetails(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("POST","/organizations/"+e+"/users/account-recovery-details",new Dc(t),!0,!0);return new Tc(i,Fc)})}postOrganizationUserInvite(e,t){return this.apiService.send("POST","/organizations/"+e+"/users/invite",t,!0,!1)}postOrganizationUserReinvite(e,t){return this.apiService.send("POST","/organizations/"+e+"/users/"+t+"/reinvite",null,!0,!1)}postManyOrganizationUserReinvite(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("POST","/organizations/"+e+"/users/reinvite",new Dc(t),!0,!0);return new Tc(i,qc)})}postOrganizationUserAcceptInit(e,t,i){return this.apiService.send("POST","/organizations/"+e+"/users/"+t+"/accept-init",i,!0,!1)}postOrganizationUserAccept(e,t,i){return this.apiService.send("POST","/organizations/"+e+"/users/"+t+"/accept",i,!0,!1)}postOrganizationUserConfirm(e,t,i){return this.apiService.send("POST","/organizations/"+e+"/users/"+t+"/confirm",i,!0,!1)}postOrganizationUserAutoConfirm(e,t,i){return this.apiService.send("POST","/organizations/"+e+"/users/"+t+"/auto-confirm",i,!0,!1)}postOrganizationUsersPublicKey(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("POST","/organizations/"+e+"/users/public-keys",new Dc(t),!0,!0);return new Tc(i,Lc)})}postOrganizationUserBulkConfirm(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("POST","/organizations/"+e+"/users/confirm",t,!0,!0);return new Tc(i,qc)})}putOrganizationUserBulkEnableSecretsManager(e,t){return Mc(this,void 0,void 0,function*(){yield this.apiService.send("PUT","/organizations/"+e+"/users/enable-secrets-manager",new Dc(t),!0,!1)})}putOrganizationUser(e,t,i){return this.apiService.send("PUT","/organizations/"+e+"/users/"+t,i,!0,!1)}putOrganizationUserResetPasswordEnrollment(e,t,i){return this.apiService.send("PUT","/organizations/"+e+"/users/"+t+"/reset-password-enrollment",i,!0,!1)}putOrganizationUserResetPassword(e,t,i){return this.apiService.send("PUT","/organizations/"+e+"/users/"+t+"/reset-password",i,!0,!1)}removeOrganizationUser(e,t){return this.apiService.send("DELETE","/organizations/"+e+"/users/"+t,null,!0,!1)}removeManyOrganizationUsers(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("DELETE","/organizations/"+e+"/users",new Dc(t),!0,!0);return new Tc(i,qc)})}revokeOrganizationUser(e,t){return this.apiService.send("PUT","/organizations/"+e+"/users/"+t+"/revoke",null,!0,!1)}revokeManyOrganizationUsers(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("PUT","/organizations/"+e+"/users/revoke",new Dc(t),!0,!0);return new Tc(i,qc)})}revokeSelf(e){return this.apiService.send("PUT","/organizations/"+e+"/users/revoke-self",null,!0,!1)}restoreOrganizationUser(e,t){return this.apiService.send("PUT","/organizations/"+e+"/users/"+t+"/restore",null,!0,!1)}restoreOrganizationUser_vNext(e,t,i){return this.apiService.send("PUT","/organizations/"+e+"/users/"+t+"/restore/vnext",i,!0,!1)}restoreManyOrganizationUsers(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("PUT","/organizations/"+e+"/users/restore",new Dc(t),!0,!0);return new Tc(i,qc)})}restoreManyOrganizationUsers_vNext(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("PUT","/organizations/"+e+"/users/restore",t,!0,!0);return new Tc(i,qc)})}deleteOrganizationUser(e,t){return this.apiService.send("DELETE","/organizations/"+e+"/users/"+t+"/delete-account",null,!0,!1)}deleteManyOrganizationUsers(e,t){return Mc(this,void 0,void 0,function*(){const i=yield this.apiService.send("DELETE","/organizations/"+e+"/users/delete-account",new Dc(t),!0,!0);return new Tc(i,qc)})}}var $c=function(e){function t(t){var i=e.call(this)||this;return i._value=t,i}return a(t,e),Object.defineProperty(t.prototype,"value",{get:function(){return this.getValue()},enumerable:!1,configurable:!0}),t.prototype._subscribe=function(t){var i=e.prototype._subscribe.call(this,t);return!i.closed&&t.next(this._value),i},t.prototype.getValue=function(){var e=this,t=e.hasError,i=e.thrownError,r=e._value;if(t)throw i;return this._throwIfClosed(),r},t.prototype.next=function(t){e.prototype.next.call(this,this._value=t)},t}(H),Kc=Array.isArray;function Wc(e){return 1===e.length&&Kc(e[0])?e[0]:e}function Hc(){for(var e=[],t=0;tObject.assign(Object.assign({},e),{creationDate:e.creationDate?new Date(e.creationDate):void 0})}),Yc=new fi(Ei,"activeAccountId",{deserializer:e=>e}),Xc=fi.record(Ei,"activity",{deserializer:e=>new Date(e)}),Zc=new wi(Ei,"verifyNewDeviceLogin",{deserializer:e=>e,clearOn:["logout"]}),eu={email:"",emailVerified:!1,name:void 0,creationDate:void 0},tu=X(e=>{if(null==e)throw new Error("Null or undefined account");return e.id}),iu=X(e=>{var t;return null!==(t=null==e?void 0:e.id)&&void 0!==t?t:null});class ru{constructor(e,t,i,r){this.messagingService=e,this.logService=t,this.globalStateProvider=i,this.singleUserStateProvider=r,this._showHeader$=new $c(!0),this.showHeader$=this._showHeader$.asObservable(),this.accountsState=this.globalStateProvider.get(Jc),this.activeAccountIdState=this.globalStateProvider.get(Yc),this.accounts$=this.accountsState.state$.pipe(X(e=>null==e?{}:e)),this.activeAccount$=this.activeAccountIdState.state$.pipe(Gc(this.accounts$),X(([e,t])=>e?Object.assign({id:e},t[e]):null),Zl((e,t)=>(null==e?void 0:e.id)===(null==t?void 0:t.id)&&this.accountInfoEqual(e,t)),Jt({bufferSize:1,refCount:!1})),this.accountActivity$=this.globalStateProvider.get(Xc).state$.pipe(X(e=>null!=e?e:{})),this.sortedUserIds$=this.accountActivity$.pipe(X(e=>Object.entries(e).map(([e,t])=>({userId:e,lastActive:t})).sort((e,t)=>t.lastActive.getTime()-e.lastActive.getTime()).map(e=>e.userId))),this.nextUpAccount$=ai([this.accounts$,this.activeAccount$,this.sortedUserIds$]).pipe(X(([e,t,i])=>{const r=i.find(i=>i!==(null==t?void 0:t.id)&&null!=e[i]);return r?Object.assign({id:r},e[r]):null})),this.accountVerifyNewDeviceLogin$=this.activeAccountIdState.state$.pipe(Le(e=>this.singleUserStateProvider.get(e,Zc).state$))}addAccount(e,t){return Qc(this,void 0,void 0,function*(){if(!Tt.isGuid(e))throw new Error("userId is required");yield this.accountsState.update(i=>(i||(i={}),i[e]=t,i)),yield this.setAccountActivity(e,new Date)})}setAccountName(e,t){return Qc(this,void 0,void 0,function*(){yield this.setAccountInfo(e,{name:t})})}setAccountEmail(e,t){return Qc(this,void 0,void 0,function*(){yield this.setAccountInfo(e,{email:t})})}setAccountEmailVerified(e,t){return Qc(this,void 0,void 0,function*(){yield this.setAccountInfo(e,{emailVerified:t})})}setAccountCreationDate(e,t){return Qc(this,void 0,void 0,function*(){yield this.setAccountInfo(e,{creationDate:t})})}clean(e){return Qc(this,void 0,void 0,function*(){yield this.setAccountInfo(e,eu),yield this.removeAccountActivity(e)})}switchAccount(e){return Qc(this,void 0,void 0,function*(){let t=!1;yield this.activeAccountIdState.update((i,r)=>(t=!0,e),{combineLatestWith:this.accountsState.state$.pipe(Ie(t=>null==e||null!=(null==t?void 0:t[e])),Fe({first:1e3,with:()=>bt({})})),shouldUpdate:(t,i)=>{if(null!=e&&null==(null==i?void 0:i[e]))throw new Error("Account does not exist");return t!==e}}),t&&(yield this.setAccountActivity(e,new Date))})}setAccountActivity(e,t){return Qc(this,void 0,void 0,function*(){Tt.isGuid(e)&&(yield this.globalStateProvider.get(Xc).update(i=>(i||(i={}),i[e]=t,i),{shouldUpdate:i=>{var r;return(null===(r=null==i?void 0:i[e])||void 0===r?void 0:r.getTime())!==(null==t?void 0:t.getTime())}}))})}setAccountVerifyNewDeviceLogin(e,t){return Qc(this,void 0,void 0,function*(){Tt.isGuid(e)&&(yield this.singleUserStateProvider.get(e,Zc).update(()=>t,{shouldUpdate:e=>e!==t}))})}removeAccountActivity(e){return Qc(this,void 0,void 0,function*(){yield this.globalStateProvider.get(Xc).update(t=>(null==t||delete t[e],t),{shouldUpdate:t=>null!=(null==t?void 0:t[e])})})}delete(){return Qc(this,void 0,void 0,function*(){var e;try{null===(e=this.messagingService)||void 0===e||e.send("logout")}catch(e){throw this.logService.error(e),e}})}setShowHeader(e){return Qc(this,void 0,void 0,function*(){this._showHeader$.next(e)})}accountInfoEqual(e,t){var i,r;return null==e&&null==t||null!=e&&null!=t&&e.email===t.email&&e.emailVerified===t.emailVerified&&e.name===t.name&&(null===(i=e.creationDate)||void 0===i?void 0:i.getTime())===(null===(r=t.creationDate)||void 0===r?void 0:r.getTime())}setAccountInfo(e,t){return Qc(this,void 0,void 0,function*(){function i(e){return Object.assign(Object.assign({},e),t)}yield this.accountsState.update(t=>(t[e]=i(t[e]),t),{shouldUpdate:t=>{if(null==(null==t?void 0:t[e]))throw new Error("Account does not exist");return!this.accountInfoEqual(t[e],i(t[e]))}})})}}class nu{constructor(e,t){this.ids=e,this.defaultUserCollectionName=t}}class au{constructor(e){this.defaultUserCollectionName=e}}class su{constructor(e,t,i,r,n){this.keyService=e,this.encryptService=t,this.organizationUserApiService=i,this.accountService=r,this.i18nService=n}orgKey$(e){return this.accountService.activeAccount$.pipe(tu,Le(e=>this.keyService.orgKeys$(e)),Ie(e=>!!e),X(t=>t[e.id]))}buildConfirmRequest(e,t){const i=this.getEncryptedDefaultCollectionName$(e);return ai([this.orgKey$(e).pipe(Le(e=>this.encryptService.encapsulateKeyUnsigned(e,t))),i]).pipe(X(([e,t])=>({key:e.encryptedString,defaultUserCollectionName:t.encryptedString})))}confirmUser(e,t,i){return this.buildConfirmRequest(e,i).pipe(Le(i=>this.organizationUserApiService.postOrganizationUserConfirm(e.id,t,i)))}bulkConfirmUsers(e,t){return this.getEncryptedDefaultCollectionName$(e).pipe(Le(i=>{const r=new ou(t,i.encryptedString);return this.organizationUserApiService.postOrganizationUserBulkConfirm(e.id,r)}))}buildRestoreUserRequest(e){return this.getEncryptedDefaultCollectionName$(e).pipe(X(e=>new au(e.encryptedString)))}restoreUser(e,t){return this.buildRestoreUserRequest(e).pipe(Le(i=>this.organizationUserApiService.restoreOrganizationUser_vNext(e.id,t,i)))}bulkRestoreUsers(e,t){return this.getEncryptedDefaultCollectionName$(e).pipe(Le(i=>{const r=new nu(t,i.encryptedString);return this.organizationUserApiService.restoreManyOrganizationUsers_vNext(e.id,r)}))}getEncryptedDefaultCollectionName$(e){return this.orgKey$(e).pipe(Le(e=>this.encryptService.encryptString(this.i18nService.t("myItems"),e)))}}class ou{constructor(e,t){this.keys=e,this.defaultUserCollectionName=t}}var lu,cu,uu,du;(uu=lu||(lu={}))[uu.Password=0]="Password",uu[uu.Sso=1]="Sso",uu[uu.UserApiKey=2]="UserApiKey",uu[uu.AuthRequest=3]="AuthRequest",uu[uu.WebAuthn=4]="WebAuthn";class hu{constructor(e=null,t=null,i=!1){this.provider=e,this.token=t,this.remember=i}}class pu{constructor(e){this.id=e.id,this.rawId=Tt.fromBufferToUrlB64(e.rawId),this.type=e.type,this.extensions={}}}class mu extends pu{constructor(e){if(super(e),!(e.response instanceof AuthenticatorAssertionResponse))throw new Error("Invalid authenticator response");this.response={authenticatorData:Tt.fromBufferToUrlB64(e.response.authenticatorData),signature:Tt.fromBufferToUrlB64(e.response.signature),clientDataJSON:Tt.fromBufferToUrlB64(e.response.clientDataJSON),userHandle:Tt.fromBufferToUrlB64(e.response.userHandle)}}static fromJSON(e){return Object.assign(Object.create(mu.prototype),e)}}class gu{constructor(e){if(null==e)throw new Error("Must provide key");if(32===e.byteLength)this.innerKey={type:rt.AesCbc256_B64,encryptionKey:e},this.keyB64=this.toBase64();else if(64===e.byteLength)this.innerKey={type:rt.AesCbc256_HmacSha256_B64,encryptionKey:e.slice(0,32),authenticationKey:e.slice(32)},this.keyB64=this.toBase64();else{if(!(e.byteLength>64))throw new Error(`Unsupported encType/key length ${e.byteLength}`);this.innerKey={type:rt.CoseEncrypt0,encryptionKey:e},this.keyB64=this.toBase64()}}toJSON(){return{keyB64:this.keyB64}}inner(){return this.innerKey}toBase64(){return Tt.fromBufferToB64(this.toEncoded())}toEncoded(){if(this.innerKey.type===rt.AesCbc256_B64)return this.innerKey.encryptionKey;if(this.innerKey.type===rt.AesCbc256_HmacSha256_B64){const e=new Uint8Array(64);return e.set(this.innerKey.encryptionKey,0),e.set(this.innerKey.authenticationKey,32),e}if(this.innerKey.type===rt.CoseEncrypt0)return this.innerKey.encryptionKey;throw new Error("Unsupported encryption type.")}static fromString(e){if(null==e)return null;const t=Tt.fromB64ToArray(e);return new gu(t)}static fromJSON(e){return gu.fromString(null==e?void 0:e.keyB64)}}class fu{constructor(e,t,i,r,n){this.email=e,this.accessCode=t,this.authRequestId=i,this.decryptedUserKey=r,this.twoFactor=n,this.type=lu.AuthRequest}static fromJSON(e){return Object.assign(new fu(e.email,e.accessCode,e.authRequestId,null,e.twoFactor?new hu(e.twoFactor.provider,e.twoFactor.token,e.twoFactor.remember):e.twoFactor),{decryptedUserKey:gu.fromJSON(e.decryptedUserKey)})}}class yu{constructor(e,t,i){this.token=e,this.deviceResponse=t,this.prfKey=i,this.type=lu.WebAuthn}static fromJSON(e){return new yu(e.token,Object.assign(Object.create(mu.prototype),e.deviceResponse),gu.fromJSON(e.prfKey))}}class vu{static fromResponse(e){var t;if(null==e)return;const i=new vu;return i.keyConnectorUrl=null!==(t=null==e?void 0:e.keyConnectorUrl)&&void 0!==t?t:null,i}static fromJSON(e){if(null!=e)return Object.assign(new vu,e)}}class bu{static fromResponse(e){if(null==e)return;if(!e.encryptedPrivateKey||!e.encryptedUserKey)return;const t=new bu;return t.encryptedPrivateKey=e.encryptedPrivateKey.encryptedString,t.encryptedUserKey=e.encryptedUserKey.encryptedString,t.credentialId=e.credentialId,t.transports=e.transports||[],t}static fromJSON(e){if(null!=e)return Object.assign(new bu,e)}}class wu{static fromResponse(e){var t,i,r,n;if(null==e)return;const a=new wu;return a.hasAdminApproval=null!==(t=null==e?void 0:e.hasAdminApproval)&&void 0!==t&&t,a.hasLoginApprovingDevice=null!==(i=null==e?void 0:e.hasLoginApprovingDevice)&&void 0!==i&&i,a.hasManageResetPasswordPermission=null!==(r=null==e?void 0:e.hasManageResetPasswordPermission)&&void 0!==r&&r,a.isTdeOffboarding=null!==(n=null==e?void 0:e.isTdeOffboarding)&&void 0!==n&&n,a}static fromJSON(e){if(null!=e)return Object.assign(new wu,e)}}class ku{static fromIdentityTokenResponse(e){if(null==e)throw new Error("User Decryption Options are required for client initialization. Response is nullish.");const t=new ku;if(!e.userDecryptionOptions)throw new Error("User Decryption Options are required for client initialization. userDecryptionOptions is missing in response.");{const i=e.userDecryptionOptions;if(t.hasMasterPassword=i.hasMasterPassword,t.trustedDeviceOption=wu.fromResponse(i.trustedDeviceOption),t.keyConnectorOption=vu.fromResponse(i.keyConnectorOption),i.webAuthnPrfOption){const e=bu.fromResponse(i.webAuthnPrfOption);e&&(t.webAuthnPrfOptions=[e])}}return t}static fromJSON(e){const t=Object.assign(new ku,e);return t.trustedDeviceOption=wu.fromJSON(null==e?void 0:e.trustedDeviceOption),t.keyConnectorOption=vu.fromJSON(null==e?void 0:e.keyConnectorOption),(null==e?void 0:e.webAuthnPrfOptions)&&Array.isArray(e.webAuthnPrfOptions)&&(t.webAuthnPrfOptions=e.webAuthnPrfOptions.map(e=>bu.fromJSON(e)).filter(e=>void 0!==e)),t}}(du=cu||(cu={}))[du.LoggedOut=0]="LoggedOut",du[du.Locked=1]="Locked",du[du.Unlocked=2]="Unlocked",new fi(Ti,"loginEmail",{deserializer:e=>e}),new fi(ji,"storedEmail",{deserializer:e=>e});class Su extends Lt{constructor(e,t,i){super(e);let r=null;if(null!=e){const t=this.getResponseProperty("ErrorModel");r=t&&i?t:e}429===t?this.message="Rate limit exceeded. Try again later.":r&&(this.message=this.getResponseProperty("Message",r),this.validationErrors=this.getResponseProperty("ValidationErrors",r)),this.statusCode=t}getSingleMessage(){if(null==this.validationErrors)return this.message;for(const e in this.validationErrors)if(this.validationErrors.hasOwnProperty(e)&&this.validationErrors[e].length)return this.validationErrors[e][0];return this.message}getAllMessages(){const e=[];if(null==this.validationErrors)return e;for(const t in this.validationErrors)this.validationErrors.hasOwnProperty(t)&&this.validationErrors[t].forEach(i=>{let r="";if(t.indexOf("[")>-1&&t.indexOf("]")>-1){const e=t.lastIndexOf(".");r=t.substr(0,e>-1?e:t.length)+": "}e.push(r+i)});return e}}class _u{constructor(e,t){this.taskSchedulerService=e,this.taskName=t}schedule(e,t,i){return this.taskSchedulerService.setTimeout(this.taskName,null!=t?t:0)}now(){return Te.now()}}class xu{}class Cu extends xu{constructor(e){super(),this.logService=e,this.taskHandlers=new Map}setTimeout(e,t){this.validateRegisteredTask(e);const i=globalThis.setTimeout(()=>this.triggerTask(e),t);return new f(()=>globalThis.clearTimeout(i))}setInterval(e,t,i){this.validateRegisteredTask(e);const r=globalThis.setInterval(()=>this.triggerTask(e),t);return new f(()=>globalThis.clearInterval(r))}registerTaskHandler(e,t){this.taskHandlers.get(e)&&(this.logService.warning(`Task handler for ${e} already exists. Overwriting.`),this.unregisterTaskHandler(e)),this.taskHandlers.set(e,t)}unregisterTaskHandler(e){this.taskHandlers.delete(e)}triggerTask(e,t){return i=this,r=void 0,a=function*(){const t=this.taskHandlers.get(e);t&&t()},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}validateRegisteredTask(e){if(!this.taskHandlers.has(e))throw new Error(`Task handler for ${e} not registered. Unable to schedule task.`)}}const Iu="systemClearClipboardTimeout",Eu="fido2ClientAbortTimeout",zu="scheduleNextSyncInterval",Pu="eventUploadsInterval",Au="vaultTimeoutCheckInterval",ju="clearPopupViewCache",Tu="phishingDomainUpdate",Du=new wi(Cr,"biometricUnlockEnabled",{deserializer:e=>e,clearOn:[]}),Ou=new wi(Cr,"clientKeyHalf",{deserializer:e=>e,clearOn:["logout"]}),Nu=fi.record(Cr,"promptCancelled",{deserializer:e=>e}),Ru=new wi(Cr,"promptAutomatically",{deserializer:e=>e,clearOn:[]}),Uu=new fi(Cr,"fingerprintValidated",{deserializer:e=>e}),Fu=new fi(Cr,"lastProcessReload",{deserializer:e=>new Date(e)});var qu,Lu,Bu=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Mu{constructor(e){this.stateProvider=e,this.biometricUnlockEnabledState=this.stateProvider.getActive(Du),this.encryptedClientKeyHalfState=this.stateProvider.getActive(Ou),this.encryptedClientKeyHalf$=this.encryptedClientKeyHalfState.state$.pipe(X(Vu)),this.promptCancelledState=this.stateProvider.getGlobal(Nu),this.promptCancelled$=ai([this.stateProvider.activeUserId$,this.promptCancelledState.state$]).pipe(X(([e,t])=>{var i;return null!=e&&null!==(i=null==t?void 0:t[e])&&void 0!==i&&i})),this.promptAutomaticallyState=this.stateProvider.getActive(Ru),this.promptAutomatically$=this.promptAutomaticallyState.state$.pipe(X(Boolean)),this.fingerprintValidatedState=this.stateProvider.getGlobal(Uu),this.fingerprintValidated$=this.fingerprintValidatedState.state$.pipe(X(Boolean)),this.lastProcessReloadState=this.stateProvider.getGlobal(Fu),this.lastProcessReload$=this.lastProcessReloadState.state$}setBiometricUnlockEnabled(e){return Bu(this,void 0,void 0,function*(){yield this.biometricUnlockEnabledState.update(()=>e)})}biometricUnlockEnabled$(e){return null!=e?this.stateProvider.getUser(e,Du).state$.pipe(X(Boolean)):this.biometricUnlockEnabledState.state$.pipe(X(Boolean))}getBiometricUnlockEnabled(e){return Bu(this,void 0,void 0,function*(){return yield Ce(this.stateProvider.getUser(e,Du).state$.pipe(X(Boolean)))})}setEncryptedClientKeyHalf(e,t){return Bu(this,void 0,void 0,function*(){var i;const r=null!==(i=null==e?void 0:e.encryptedString)&&void 0!==i?i:null;t?yield this.stateProvider.getUser(t,Ou).update(()=>r):yield this.encryptedClientKeyHalfState.update(()=>r)})}getEncryptedClientKeyHalf(e){return Bu(this,void 0,void 0,function*(){return yield Ce(this.stateProvider.getUser(e,Ou).state$.pipe(X(Vu)))})}logout(e){return Bu(this,void 0,void 0,function*(){yield this.stateProvider.getUser(e,Ou).update(()=>null),yield this.resetUserPromptCancelled(e)})}resetUserPromptCancelled(e){return Bu(this,void 0,void 0,function*(){yield this.stateProvider.getGlobal(Nu).update((t,i)=>(null!=t&&delete t[null!=e?e:i],t),{combineLatestWith:this.stateProvider.activeUserId$,shouldUpdate:(t,i)=>null!=(null==t?void 0:t[null!=e?e:i])})})}setUserPromptCancelled(){return Bu(this,void 0,void 0,function*(){yield this.promptCancelledState.update((e,t)=>(null!=t&&(null!=e||(e={}),e[t]=!0),e),{combineLatestWith:this.stateProvider.activeUserId$,shouldUpdate:(e,t)=>{if(null==t)throw new Error("Cannot update biometric prompt cancelled state without an active user");return!0}})})}resetAllPromptCancelled(){return Bu(this,void 0,void 0,function*(){yield this.promptCancelledState.update(()=>null)})}setPromptAutomatically(e){return Bu(this,void 0,void 0,function*(){yield this.promptAutomaticallyState.update(()=>e)})}setFingerprintValidated(e){return Bu(this,void 0,void 0,function*(){yield this.fingerprintValidatedState.update(()=>e)})}updateLastProcessReload(){return Bu(this,void 0,void 0,function*(){yield this.lastProcessReloadState.update(()=>new Date)})}getLastProcessReload(){return Bu(this,void 0,void 0,function*(){return yield Ce(this.lastProcessReload$)})}}function Vu(e){return null==e?null:new Nt(e)}!function(e){e[e.Available=0]="Available",e[e.UnlockNeeded=1]="UnlockNeeded",e[e.HardwareUnavailable=2]="HardwareUnavailable",e[e.AutoSetupNeeded=3]="AutoSetupNeeded",e[e.ManualSetupNeeded=4]="ManualSetupNeeded",e[e.PlatformUnsupported=5]="PlatformUnsupported",e[e.DesktopDisconnected=6]="DesktopDisconnected",e[e.NotEnabledLocally=7]="NotEnabledLocally",e[e.NotEnabledInConnectedDesktopApp=8]="NotEnabledInConnectedDesktopApp",e[e.NativeMessagingPermissionMissing=9]="NativeMessagingPermissionMissing"}(qu||(qu={})),function(e){e.AuthenticateWithBiometrics="authenticateWithBiometrics",e.GetBiometricsStatus="getBiometricsStatus",e.UnlockWithBiometricsForUser="unlockWithBiometricsForUser",e.GetBiometricsStatusForUser="getBiometricsStatusForUser",e.CanEnableBiometricUnlock="canEnableBiometricUnlock"}(Lu||(Lu={}));class $u{supportsBiometric(){throw new Error("Method not implemented.")}}Error;var Ku,Wu=o(6599);function Hu(e){return Q(function(t,i){var r,n=null,a=!1;n=t.subscribe(J(i,void 0,void 0,function(s){r=le(e(s,Hu(e)(t))),n?(n.unsubscribe(),n=null,r.subscribe(i)):a=!0})),a&&(n.unsubscribe(),n=null,r.subscribe(i))})}function Gu(){for(var e=[],t=0;ttd.fromResponse(e))}}class id extends Rt{constructor(){super(...arguments),this.autoEnrollEnabled=!1}}const rd=wi.record(_i,"policies",{deserializer:e=>e,clearOn:["logout"]});var nd=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ad=X(e=>{var t;return null!==(t=e.at(0))&&void 0!==t?t:void 0});class sd{constructor(e,t,i){this.stateProvider=e,this.organizationService=t,this.accountService=i}policyState(e){return this.stateProvider.getUser(e,rd)}policyData$(e){return this.policyState(e).state$.pipe(X(e=>null!=e?e:{}))}policies$(e){return this.policyData$(e).pipe(X(e=>{return t=e,Object.values(t||{}).map(e=>new td(e));var t}))}policiesByType$(e,t){if(!t)throw new Error("No userId provided");return ai([this.policies$(t),this.organizationService.organizations$(t)]).pipe(X(([e,t])=>this.enforcedPolicyFilter(e,t)),X(t=>t.filter(t=>t.type===e)))}policyAppliesToUser$(e,t){return this.policiesByType$(e,t).pipe(ad,X(e=>!!e))}enforcedPolicyFilter(e,t){const i=Object.fromEntries(t.map(e=>[e.id,e]));return e.filter(t=>{const r=i[t.organizationId];return!r||t.enabled&&r.status>=Qe.Accepted&&r.usePolicies&&!this.isExemptFromPolicy(t.type,r,e)})}masterPasswordPolicyOptions$(e,t){return(t?bt(t):this.policies$(e)).pipe(X(e=>{var t;let i;const r=null!==(t=e.filter(e=>e.type===Ye.MasterPassword))&&void 0!==t?t:[];if(0!==r.length)return r.forEach(e=>{e.enabled&&e.data&&(i||(i=new Zu),null!=e.data.minComplexity&&e.data.minComplexity>i.minComplexity&&(i.minComplexity=e.data.minComplexity),null!=e.data.minLength&&e.data.minLength>i.minLength&&(i.minLength=e.data.minLength),e.data.requireUpper&&(i.requireUpper=!0),e.data.requireLower&&(i.requireLower=!0),e.data.requireNumbers&&(i.requireNumbers=!0),e.data.requireSpecial&&(i.requireSpecial=!0),e.data.enforceOnLogin&&(i.enforceOnLogin=!0))}),i}))}combinePoliciesIntoMasterPasswordPolicyOptions(e){var t;let i;const r=null!==(t=e.filter(e=>e.type===Ye.MasterPassword))&&void 0!==t?t:[];if(0!==r.length)return r.forEach(e=>{e.enabled&&e.data&&(i||(i=new Zu),this.mergeMasterPasswordPolicyOptions(i,e.data))}),i}combineMasterPasswordPolicyOptions(...e){let t;return e.forEach(e=>{t||(t=new Zu),this.mergeMasterPasswordPolicyOptions(t,e)}),t}evaluateMasterPassword(e,t,i){return!(i&&(i.minComplexity>0&&i.minComplexity>e||i.minLength>0&&i.minLength>t.length||i.requireUpper&&t.toLocaleLowerCase()===t||i.requireLower&&t.toLocaleUpperCase()===t||i.requireNumbers&&!/[0-9]/.test(t)||i.requireSpecial&&!/[!@#$%\^&*]/g.test(t)))}getResetPasswordPolicyOptions(e,t){var i,r,n;const a=new id;if(!e||!t)return[a,!1];const s=e.find(e=>e.organizationId===t&&e.type===Ye.ResetPassword&&e.enabled);return a.autoEnrollEnabled=null!==(r=null===(i=null==s?void 0:s.data)||void 0===i?void 0:i.autoEnrollEnabled)&&void 0!==r&&r,[a,null!==(n=null==s?void 0:s.enabled)&&void 0!==n&&n]}upsert(e,t){return nd(this,void 0,void 0,function*(){yield this.policyState(t).update(t=>(null!=t||(t={}),t[e.id]=e,t))})}replace(e,t){return nd(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(rd,e,t)})}isExemptFromPolicy(e,t,i){switch(e){case Ye.MaximumVaultTimeout:return t.isOwner;case Ye.PasswordGenerator:case Ye.FreeFamiliesSponsorshipPolicy:case Ye.RestrictedItemTypes:case Ye.RemoveUnlockWithPin:case Ye.AutoConfirm:return!1;case Ye.OrganizationDataOwnership:return t.isAdmin;case Ye.SingleOrg:return!i.find(e=>e.organizationId===t.id&&e.type===Ye.AutoConfirm&&e.enabled)&&t.canManagePolicies;default:return t.canManagePolicies}}mergeMasterPasswordPolicyOptions(e,t){var i,r;e||(e=new Zu),t&&(e.minComplexity=Math.max(e.minComplexity,null!==(i=t.minComplexity)&&void 0!==i?i:e.minComplexity),e.minLength=Math.max(e.minLength,null!==(r=t.minLength)&&void 0!==r?r:e.minLength),e.requireUpper=Boolean(e.requireUpper||t.requireUpper),e.requireLower=Boolean(e.requireLower||t.requireLower),e.requireNumbers=Boolean(e.requireNumbers||t.requireNumbers),e.requireSpecial=Boolean(e.requireSpecial||t.requireSpecial),e.enforceOnLogin=Boolean(e.enforceOnLogin||t.enforceOnLogin))}syncPolicy(e){return nd(this,void 0,void 0,function*(){yield Ce(this.accountService.activeAccount$.pipe(tu,Le(t=>this.upsert(e,t))))})}}var od;!function(e){e.Lock="lock",e.LogOut="logOut"}(od||(od={}));const ld="never",cd="onRestart",ud="onLocked",dd="onSleep",hd="onIdle";function pd(e){return"number"==typeof e}const md=new wi(Vi,"vaultTimeoutAction",{deserializer:e=>e,clearOn:[]}),gd=new wi(Vi,"vaultTimeout",{deserializer:e=>e,clearOn:[]});var fd=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class yd{constructor(e,t,i,r,n,a,s,o,l,c,u){this.accountService=e,this.pinStateService=t,this.userDecryptionOptionsService=i,this.keyService=r,this.tokenService=n,this.policyService=a,this.biometricStateService=s,this.stateProvider=o,this.logService=l,this.defaultVaultTimeout=c,this.sessionTimeoutTypeService=u}setVaultTimeoutOptions(e,t,i){return fd(this,void 0,void 0,function*(){if(!e)throw new Error("User id required. Cannot set vault timeout settings.");if(null==t)throw new Error("Vault Timeout cannot be null.");if(null==i)throw new Error("Vault Timeout Action cannot be null.");const r=yield this.tokenService.getAccessToken(e),n=yield this.tokenService.getRefreshToken(e),a=yield this.tokenService.getClientId(e),s=yield this.tokenService.getClientSecret(e);yield this.setVaultTimeout(e,t),t!=ld&&i===od.LogOut&&(yield this.tokenService.clearTokens(e)),yield this.setVaultTimeoutAction(e,i),yield this.tokenService.setTokens(r,i,t,n,[a,s]),yield this.keyService.refreshAdditionalKeys(e)})}availableVaultTimeoutActions$(e){return(null!=e?bt(e):tu(this.accountService.activeAccount$)).pipe(Le(e=>ai([this.userDecryptionOptionsService.hasMasterPasswordById$(e),this.biometricStateService.biometricUnlockEnabled$(e),this.pinStateService.pinSet$(e)])),X(([e,t,i])=>e||t||i?[od.LogOut,od.Lock]:[od.LogOut]))}canLock(e){return fd(this,void 0,void 0,function*(){const t=yield Ce(this.availableVaultTimeoutActions$(e));return(null==t?void 0:t.includes(od.Lock))||!1})}isBiometricLockSet(e){return fd(this,void 0,void 0,function*(){return yield Ce(this.biometricStateService.biometricUnlockEnabled$(e))})}setVaultTimeout(e,t){return fd(this,void 0,void 0,function*(){if(!e)throw new Error("User id required. Cannot set vault timeout.");if(null==t)throw new Error("Vault Timeout cannot be null.");yield this.stateProvider.setUserState(gd,t,e)})}getVaultTimeoutByUserId$(e){if(!e)throw new Error("User id required. Cannot get vault timeout.");return ai([this.stateProvider.getUserState$(gd,e),this.getMaxSessionTimeoutPolicyDataByUserId$(e)]).pipe(Le(([t,i])=>(this.logService.debug("[VaultTimeoutSettingsService] Current vault timeout is %o for user id %s, max session policy %o",t,e,i),Se(this.determineVaultTimeout(t,i)).pipe(gc(i=>fd(this,void 0,void 0,function*(){return this.logService.debug("[VaultTimeoutSettingsService] Determined vault timeout is %o for user id %s",i,e),i!==t&&(yield this.stateProvider.setUserState(gd,i,e)),i})),Hu(e=>(this.logService.error(`Error getting vault timeout: ${e}`),pe))))),Zl(),Jt({refCount:!0,bufferSize:1}))}determineVaultTimeout(e,t){return fd(this,void 0,void 0,function*(){const i=yield this.determineVaultTimeoutInternal(e,t);return yield this.sessionTimeoutTypeService.getOrPromoteToAvailable(i)})}determineVaultTimeoutInternal(e,t){return fd(this,void 0,void 0,function*(){if(e=null!=e?e:this.defaultVaultTimeout,null==t)return e;switch(t.type){case"immediately":return 0;case"custom":case null:case void 0:return 0===e?e:pd(e)?Math.min(e,t.minutes):t.minutes;case"onSystemLock":if(e===ld||e===cd||e===ud||e===hd||e===dd)return ud;break;case"onAppRestart":if(e===ld||e===ud||e===hd||e===dd)return cd}return e})}setVaultTimeoutAction(e,t){return fd(this,void 0,void 0,function*(){if(!e)throw new Error("User id required. Cannot set vault timeout action.");if(!t)throw new Error("Vault Timeout Action cannot be null");yield this.stateProvider.setUserState(md,t,e)})}getVaultTimeoutActionByUserId$(e){if(!e)throw new Error("User id required. Cannot get vault timeout action.");return ai([this.stateProvider.getUserState$(md,e),this.getMaxSessionTimeoutPolicyDataByUserId$(e),this.availableVaultTimeoutActions$(e)]).pipe(gc(t=>fd(this,[t],void 0,function*([t,i,r]){const n=this.determineVaultTimeoutAction(r,t,i);return n!==t&&(yield this.stateProvider.setUserState(md,n,e)),n})),Hu(e=>(this.logService.error(`Error getting vault timeout: ${e}`),pe)),Zl(),Jt({refCount:!0,bufferSize:1}))}determineVaultTimeoutAction(e,t,i){return 1===e.length?e[0]:(null==i?void 0:i.action)&&e.includes(i.action)?i.action:null==t&&e.includes(od.Lock)?od.Lock:t}getMaxSessionTimeoutPolicyDataByUserId$(e){if(!e)throw new Error("User id required. Cannot get max session timeout policy.");return this.policyService.policiesByType$(Ye.MaximumVaultTimeout,e).pipe(ad,X(e=>{var t;return null!==(t=null==e?void 0:e.data)&&void 0!==t?t:null}))}}var vd=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class bd{constructor(e,t,i,r,n,a,s,o){this.accountService=e,this.platformUtilsService=t,this.authService=i,this.vaultTimeoutSettingsService=r,this.taskSchedulerService=n,this.logService=a,this.lockService=s,this.logoutService=o,this.inited=!1,this.taskSchedulerService.registerTaskHandler(Au,()=>this.checkVaultTimeout())}init(e){return vd(this,void 0,void 0,function*(){this.inited||(this.inited=!0,e&&this.startCheck())})}startCheck(){this.checkVaultTimeout().catch(e=>this.logService.error(e)),this.taskSchedulerService.setInterval(Au,1e4)}checkVaultTimeout(){return vd(this,void 0,void 0,function*(){const e=yield this.platformUtilsService.isPopupOpen();yield Ce(ai([this.accountService.activeAccount$,this.accountService.accountActivity$]).pipe(gc(t=>vd(this,[t],void 0,function*([t,i]){const r=null==t?void 0:t.id;for(const t in i){const n=t;null!=n&&(yield this.shouldLock(n,i[n],r,e))&&(yield this.executeTimeoutAction(n))}}))))})}shouldLock(e,t,i,r){return vd(this,void 0,void 0,function*(){if(r&&e===i)return!1;const n=yield this.authService.getAuthStatus(e);if(n===cu.Locked||n===cu.LoggedOut)return!1;const a=yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutByUserId$(e));if("string"==typeof a)return!1;if(null==t)return!1;const s=60*a;return((new Date).getTime()-t.getTime())/1e3>=s})}executeTimeoutAction(e){return vd(this,void 0,void 0,function*(){(yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutActionByUserId$(e)))===od.LogOut?yield this.logoutService.logout(e,"vaultTimeout"):yield this.lockService.lock(e)})}}const wd=["abacus","abdomen","abdominal","abide","abiding","ability","ablaze","able","abnormal","abrasion","abrasive","abreast","abridge","abroad","abruptly","absence","absentee","absently","absinthe","absolute","absolve","abstain","abstract","absurd","accent","acclaim","acclimate","accompany","account","accuracy","accurate","accustom","acetone","achiness","aching","acid","acorn","acquaint","acquire","acre","acrobat","acronym","acting","action","activate","activator","active","activism","activist","activity","actress","acts","acutely","acuteness","aeration","aerobics","aerosol","aerospace","afar","affair","affected","affecting","affection","affidavit","affiliate","affirm","affix","afflicted","affluent","afford","affront","aflame","afloat","aflutter","afoot","afraid","afterglow","afterlife","aftermath","aftermost","afternoon","aged","ageless","agency","agenda","agent","aggregate","aghast","agile","agility","aging","agnostic","agonize","agonizing","agony","agreeable","agreeably","agreed","agreeing","agreement","aground","ahead","ahoy","aide","aids","aim","ajar","alabaster","alarm","albatross","album","alfalfa","algebra","algorithm","alias","alibi","alienable","alienate","aliens","alike","alive","alkaline","alkalize","almanac","almighty","almost","aloe","aloft","aloha","alone","alongside","aloof","alphabet","alright","although","altitude","alto","aluminum","alumni","always","amaretto","amaze","amazingly","amber","ambiance","ambiguity","ambiguous","ambition","ambitious","ambulance","ambush","amendable","amendment","amends","amenity","amiable","amicably","amid","amigo","amino","amiss","ammonia","ammonium","amnesty","amniotic","among","amount","amperage","ample","amplifier","amplify","amply","amuck","amulet","amusable","amused","amusement","amuser","amusing","anaconda","anaerobic","anagram","anatomist","anatomy","anchor","anchovy","ancient","android","anemia","anemic","aneurism","anew","angelfish","angelic","anger","angled","angler","angles","angling","angrily","angriness","anguished","angular","animal","animate","animating","animation","animator","anime","animosity","ankle","annex","annotate","announcer","annoying","annually","annuity","anointer","another","answering","antacid","antarctic","anteater","antelope","antennae","anthem","anthill","anthology","antibody","antics","antidote","antihero","antiquely","antiques","antiquity","antirust","antitoxic","antitrust","antiviral","antivirus","antler","antonym","antsy","anvil","anybody","anyhow","anymore","anyone","anyplace","anything","anytime","anyway","anywhere","aorta","apache","apostle","appealing","appear","appease","appeasing","appendage","appendix","appetite","appetizer","applaud","applause","apple","appliance","applicant","applied","apply","appointee","appraisal","appraiser","apprehend","approach","approval","approve","apricot","april","apron","aptitude","aptly","aqua","aqueduct","arbitrary","arbitrate","ardently","area","arena","arguable","arguably","argue","arise","armadillo","armband","armchair","armed","armful","armhole","arming","armless","armoire","armored","armory","armrest","army","aroma","arose","around","arousal","arrange","array","arrest","arrival","arrive","arrogance","arrogant","arson","art","ascend","ascension","ascent","ascertain","ashamed","ashen","ashes","ashy","aside","askew","asleep","asparagus","aspect","aspirate","aspire","aspirin","astonish","astound","astride","astrology","astronaut","astronomy","astute","atlantic","atlas","atom","atonable","atop","atrium","atrocious","atrophy","attach","attain","attempt","attendant","attendee","attention","attentive","attest","attic","attire","attitude","attractor","attribute","atypical","auction","audacious","audacity","audible","audibly","audience","audio","audition","augmented","august","authentic","author","autism","autistic","autograph","automaker","automated","automatic","autopilot","available","avalanche","avatar","avenge","avenging","avenue","average","aversion","avert","aviation","aviator","avid","avoid","await","awaken","award","aware","awhile","awkward","awning","awoke","awry","axis","babble","babbling","babied","baboon","backache","backboard","backboned","backdrop","backed","backer","backfield","backfire","backhand","backing","backlands","backlash","backless","backlight","backlit","backlog","backpack","backpedal","backrest","backroom","backshift","backside","backslid","backspace","backspin","backstab","backstage","backtalk","backtrack","backup","backward","backwash","backwater","backyard","bacon","bacteria","bacterium","badass","badge","badland","badly","badness","baffle","baffling","bagel","bagful","baggage","bagged","baggie","bagginess","bagging","baggy","bagpipe","baguette","baked","bakery","bakeshop","baking","balance","balancing","balcony","balmy","balsamic","bamboo","banana","banish","banister","banjo","bankable","bankbook","banked","banker","banking","banknote","bankroll","banner","bannister","banshee","banter","barbecue","barbed","barbell","barber","barcode","barge","bargraph","barista","baritone","barley","barmaid","barman","barn","barometer","barrack","barracuda","barrel","barrette","barricade","barrier","barstool","bartender","barterer","bash","basically","basics","basil","basin","basis","basket","batboy","batch","bath","baton","bats","battalion","battered","battering","battery","batting","battle","bauble","bazooka","blabber","bladder","blade","blah","blame","blaming","blanching","blandness","blank","blaspheme","blasphemy","blast","blatancy","blatantly","blazer","blazing","bleach","bleak","bleep","blemish","blend","bless","blighted","blimp","bling","blinked","blinker","blinking","blinks","blip","blissful","blitz","blizzard","bloated","bloating","blob","blog","bloomers","blooming","blooper","blot","blouse","blubber","bluff","bluish","blunderer","blunt","blurb","blurred","blurry","blurt","blush","blustery","boaster","boastful","boasting","boat","bobbed","bobbing","bobble","bobcat","bobsled","bobtail","bodacious","body","bogged","boggle","bogus","boil","bok","bolster","bolt","bonanza","bonded","bonding","bondless","boned","bonehead","boneless","bonelike","boney","bonfire","bonnet","bonsai","bonus","bony","boogeyman","boogieman","book","boondocks","booted","booth","bootie","booting","bootlace","bootleg","boots","boozy","borax","boring","borough","borrower","borrowing","boss","botanical","botanist","botany","botch","both","bottle","bottling","bottom","bounce","bouncing","bouncy","bounding","boundless","bountiful","bovine","boxcar","boxer","boxing","boxlike","boxy","breach","breath","breeches","breeching","breeder","breeding","breeze","breezy","brethren","brewery","brewing","briar","bribe","brick","bride","bridged","brigade","bright","brilliant","brim","bring","brink","brisket","briskly","briskness","bristle","brittle","broadband","broadcast","broaden","broadly","broadness","broadside","broadways","broiler","broiling","broken","broker","bronchial","bronco","bronze","bronzing","brook","broom","brought","browbeat","brownnose","browse","browsing","bruising","brunch","brunette","brunt","brush","brussels","brute","brutishly","bubble","bubbling","bubbly","buccaneer","bucked","bucket","buckle","buckshot","buckskin","bucktooth","buckwheat","buddhism","buddhist","budding","buddy","budget","buffalo","buffed","buffer","buffing","buffoon","buggy","bulb","bulge","bulginess","bulgur","bulk","bulldog","bulldozer","bullfight","bullfrog","bullhorn","bullion","bullish","bullpen","bullring","bullseye","bullwhip","bully","bunch","bundle","bungee","bunion","bunkbed","bunkhouse","bunkmate","bunny","bunt","busboy","bush","busily","busload","bust","busybody","buzz","cabana","cabbage","cabbie","cabdriver","cable","caboose","cache","cackle","cacti","cactus","caddie","caddy","cadet","cadillac","cadmium","cage","cahoots","cake","calamari","calamity","calcium","calculate","calculus","caliber","calibrate","calm","caloric","calorie","calzone","camcorder","cameo","camera","camisole","camper","campfire","camping","campsite","campus","canal","canary","cancel","candied","candle","candy","cane","canine","canister","cannabis","canned","canning","cannon","cannot","canola","canon","canopener","canopy","canteen","canyon","capable","capably","capacity","cape","capillary","capital","capitol","capped","capricorn","capsize","capsule","caption","captivate","captive","captivity","capture","caramel","carat","caravan","carbon","cardboard","carded","cardiac","cardigan","cardinal","cardstock","carefully","caregiver","careless","caress","caretaker","cargo","caring","carless","carload","carmaker","carnage","carnation","carnival","carnivore","carol","carpenter","carpentry","carpool","carport","carried","carrot","carrousel","carry","cartel","cartload","carton","cartoon","cartridge","cartwheel","carve","carving","carwash","cascade","case","cash","casing","casino","casket","cassette","casually","casualty","catacomb","catalog","catalyst","catalyze","catapult","cataract","catatonic","catcall","catchable","catcher","catching","catchy","caterer","catering","catfight","catfish","cathedral","cathouse","catlike","catnap","catnip","catsup","cattail","cattishly","cattle","catty","catwalk","caucasian","caucus","causal","causation","cause","causing","cauterize","caution","cautious","cavalier","cavalry","caviar","cavity","cedar","celery","celestial","celibacy","celibate","celtic","cement","census","ceramics","ceremony","certainly","certainty","certified","certify","cesarean","cesspool","chafe","chaffing","chain","chair","chalice","challenge","chamber","chamomile","champion","chance","change","channel","chant","chaos","chaperone","chaplain","chapped","chaps","chapter","character","charbroil","charcoal","charger","charging","chariot","charity","charm","charred","charter","charting","chase","chasing","chaste","chastise","chastity","chatroom","chatter","chatting","chatty","cheating","cheddar","cheek","cheer","cheese","cheesy","chef","chemicals","chemist","chemo","cherisher","cherub","chess","chest","chevron","chevy","chewable","chewer","chewing","chewy","chief","chihuahua","childcare","childhood","childish","childless","childlike","chili","chill","chimp","chip","chirping","chirpy","chitchat","chivalry","chive","chloride","chlorine","choice","chokehold","choking","chomp","chooser","choosing","choosy","chop","chosen","chowder","chowtime","chrome","chubby","chuck","chug","chummy","chump","chunk","churn","chute","cider","cilantro","cinch","cinema","cinnamon","circle","circling","circular","circulate","circus","citable","citadel","citation","citizen","citric","citrus","city","civic","civil","clad","claim","clambake","clammy","clamor","clamp","clamshell","clang","clanking","clapped","clapper","clapping","clarify","clarinet","clarity","clash","clasp","class","clatter","clause","clavicle","claw","clay","clean","clear","cleat","cleaver","cleft","clench","clergyman","clerical","clerk","clever","clicker","client","climate","climatic","cling","clinic","clinking","clip","clique","cloak","clobber","clock","clone","cloning","closable","closure","clothes","clothing","cloud","clover","clubbed","clubbing","clubhouse","clump","clumsily","clumsy","clunky","clustered","clutch","clutter","coach","coagulant","coastal","coaster","coasting","coastland","coastline","coat","coauthor","cobalt","cobbler","cobweb","cocoa","coconut","cod","coeditor","coerce","coexist","coffee","cofounder","cognition","cognitive","cogwheel","coherence","coherent","cohesive","coil","coke","cola","cold","coleslaw","coliseum","collage","collapse","collar","collected","collector","collide","collie","collision","colonial","colonist","colonize","colony","colossal","colt","coma","come","comfort","comfy","comic","coming","comma","commence","commend","comment","commerce","commode","commodity","commodore","common","commotion","commute","commuting","compacted","compacter","compactly","compactor","companion","company","compare","compel","compile","comply","component","composed","composer","composite","compost","composure","compound","compress","comprised","computer","computing","comrade","concave","conceal","conceded","concept","concerned","concert","conch","concierge","concise","conclude","concrete","concur","condense","condiment","condition","condone","conducive","conductor","conduit","cone","confess","confetti","confidant","confident","confider","confiding","configure","confined","confining","confirm","conflict","conform","confound","confront","confused","confusing","confusion","congenial","congested","congrats","congress","conical","conjoined","conjure","conjuror","connected","connector","consensus","consent","console","consoling","consonant","constable","constant","constrain","constrict","construct","consult","consumer","consuming","contact","container","contempt","contend","contented","contently","contents","contest","context","contort","contour","contrite","control","contusion","convene","convent","copartner","cope","copied","copier","copilot","coping","copious","copper","copy","coral","cork","cornball","cornbread","corncob","cornea","corned","corner","cornfield","cornflake","cornhusk","cornmeal","cornstalk","corny","coronary","coroner","corporal","corporate","corral","correct","corridor","corrode","corroding","corrosive","corsage","corset","cortex","cosigner","cosmetics","cosmic","cosmos","cosponsor","cost","cottage","cotton","couch","cough","could","countable","countdown","counting","countless","country","county","courier","covenant","cover","coveted","coveting","coyness","cozily","coziness","cozy","crabbing","crabgrass","crablike","crabmeat","cradle","cradling","crafter","craftily","craftsman","craftwork","crafty","cramp","cranberry","crane","cranial","cranium","crank","crate","crave","craving","crawfish","crawlers","crawling","crayfish","crayon","crazed","crazily","craziness","crazy","creamed","creamer","creamlike","crease","creasing","creatable","create","creation","creative","creature","credible","credibly","credit","creed","creme","creole","crepe","crept","crescent","crested","cresting","crestless","crevice","crewless","crewman","crewmate","crib","cricket","cried","crier","crimp","crimson","cringe","cringing","crinkle","crinkly","crisped","crisping","crisply","crispness","crispy","criteria","critter","croak","crock","crook","croon","crop","cross","crouch","crouton","crowbar","crowd","crown","crucial","crudely","crudeness","cruelly","cruelness","cruelty","crumb","crummiest","crummy","crumpet","crumpled","cruncher","crunching","crunchy","crusader","crushable","crushed","crusher","crushing","crust","crux","crying","cryptic","crystal","cubbyhole","cube","cubical","cubicle","cucumber","cuddle","cuddly","cufflink","culinary","culminate","culpable","culprit","cultivate","cultural","culture","cupbearer","cupcake","cupid","cupped","cupping","curable","curator","curdle","cure","curfew","curing","curled","curler","curliness","curling","curly","curry","curse","cursive","cursor","curtain","curtly","curtsy","curvature","curve","curvy","cushy","cusp","cussed","custard","custodian","custody","customary","customer","customize","customs","cut","cycle","cyclic","cycling","cyclist","cylinder","cymbal","cytoplasm","cytoplast","dab","dad","daffodil","dagger","daily","daintily","dainty","dairy","daisy","dallying","dance","dancing","dandelion","dander","dandruff","dandy","danger","dangle","dangling","daredevil","dares","daringly","darkened","darkening","darkish","darkness","darkroom","darling","darn","dart","darwinism","dash","dastardly","data","datebook","dating","daughter","daunting","dawdler","dawn","daybed","daybreak","daycare","daydream","daylight","daylong","dayroom","daytime","dazzler","dazzling","deacon","deafening","deafness","dealer","dealing","dealmaker","dealt","dean","debatable","debate","debating","debit","debrief","debtless","debtor","debug","debunk","decade","decaf","decal","decathlon","decay","deceased","deceit","deceiver","deceiving","december","decency","decent","deception","deceptive","decibel","decidable","decimal","decimeter","decipher","deck","declared","decline","decode","decompose","decorated","decorator","decoy","decrease","decree","dedicate","dedicator","deduce","deduct","deed","deem","deepen","deeply","deepness","deface","defacing","defame","default","defeat","defection","defective","defendant","defender","defense","defensive","deferral","deferred","defiance","defiant","defile","defiling","define","definite","deflate","deflation","deflator","deflected","deflector","defog","deforest","defraud","defrost","deftly","defuse","defy","degraded","degrading","degrease","degree","dehydrate","deity","dejected","delay","delegate","delegator","delete","deletion","delicacy","delicate","delicious","delighted","delirious","delirium","deliverer","delivery","delouse","delta","deluge","delusion","deluxe","demanding","demeaning","demeanor","demise","democracy","democrat","demote","demotion","demystify","denatured","deniable","denial","denim","denote","dense","density","dental","dentist","denture","deny","deodorant","deodorize","departed","departure","depict","deplete","depletion","deplored","deploy","deport","depose","depraved","depravity","deprecate","depress","deprive","depth","deputize","deputy","derail","deranged","derby","derived","desecrate","deserve","deserving","designate","designed","designer","designing","deskbound","desktop","deskwork","desolate","despair","despise","despite","destiny","destitute","destruct","detached","detail","detection","detective","detector","detention","detergent","detest","detonate","detonator","detoxify","detract","deuce","devalue","deviancy","deviant","deviate","deviation","deviator","device","devious","devotedly","devotee","devotion","devourer","devouring","devoutly","dexterity","dexterous","diabetes","diabetic","diabolic","diagnoses","diagnosis","diagram","dial","diameter","diaper","diaphragm","diary","dice","dicing","dictate","dictation","dictator","difficult","diffused","diffuser","diffusion","diffusive","dig","dilation","diligence","diligent","dill","dilute","dime","diminish","dimly","dimmed","dimmer","dimness","dimple","diner","dingbat","dinghy","dinginess","dingo","dingy","dining","dinner","diocese","dioxide","diploma","dipped","dipper","dipping","directed","direction","directive","directly","directory","direness","dirtiness","disabled","disagree","disallow","disarm","disarray","disaster","disband","disbelief","disburse","discard","discern","discharge","disclose","discolor","discount","discourse","discover","discuss","disdain","disengage","disfigure","disgrace","dish","disinfect","disjoin","disk","dislike","disliking","dislocate","dislodge","disloyal","dismantle","dismay","dismiss","dismount","disobey","disorder","disown","disparate","disparity","dispatch","dispense","dispersal","dispersed","disperser","displace","display","displease","disposal","dispose","disprove","dispute","disregard","disrupt","dissuade","distance","distant","distaste","distill","distinct","distort","distract","distress","district","distrust","ditch","ditto","ditzy","dividable","divided","dividend","dividers","dividing","divinely","diving","divinity","divisible","divisibly","division","divisive","divorcee","dizziness","dizzy","doable","docile","dock","doctrine","document","dodge","dodgy","doily","doing","dole","dollar","dollhouse","dollop","dolly","dolphin","domain","domelike","domestic","dominion","dominoes","donated","donation","donator","donor","donut","doodle","doorbell","doorframe","doorknob","doorman","doormat","doornail","doorpost","doorstep","doorstop","doorway","doozy","dork","dormitory","dorsal","dosage","dose","dotted","doubling","douche","dove","down","dowry","doze","drab","dragging","dragonfly","dragonish","dragster","drainable","drainage","drained","drainer","drainpipe","dramatic","dramatize","drank","drapery","drastic","draw","dreaded","dreadful","dreadlock","dreamboat","dreamily","dreamland","dreamless","dreamlike","dreamt","dreamy","drearily","dreary","drench","dress","drew","dribble","dried","drier","drift","driller","drilling","drinkable","drinking","dripping","drippy","drivable","driven","driver","driveway","driving","drizzle","drizzly","drone","drool","droop","drop-down","dropbox","dropkick","droplet","dropout","dropper","drove","drown","drowsily","drudge","drum","dry","dubbed","dubiously","duchess","duckbill","ducking","duckling","ducktail","ducky","duct","dude","duffel","dugout","duh","duke","duller","dullness","duly","dumping","dumpling","dumpster","duo","dupe","duplex","duplicate","duplicity","durable","durably","duration","duress","during","dusk","dust","dutiful","duty","duvet","dwarf","dweeb","dwelled","dweller","dwelling","dwindle","dwindling","dynamic","dynamite","dynasty","dyslexia","dyslexic","each","eagle","earache","eardrum","earflap","earful","earlobe","early","earmark","earmuff","earphone","earpiece","earplugs","earring","earshot","earthen","earthlike","earthling","earthly","earthworm","earthy","earwig","easeful","easel","easiest","easily","easiness","easing","eastbound","eastcoast","easter","eastward","eatable","eaten","eatery","eating","eats","ebay","ebony","ebook","ecard","eccentric","echo","eclair","eclipse","ecologist","ecology","economic","economist","economy","ecosphere","ecosystem","edge","edginess","edging","edgy","edition","editor","educated","education","educator","eel","effective","effects","efficient","effort","eggbeater","egging","eggnog","eggplant","eggshell","egomaniac","egotism","egotistic","either","eject","elaborate","elastic","elated","elbow","eldercare","elderly","eldest","electable","election","elective","elephant","elevate","elevating","elevation","elevator","eleven","elf","eligible","eligibly","eliminate","elite","elitism","elixir","elk","ellipse","elliptic","elm","elongated","elope","eloquence","eloquent","elsewhere","elude","elusive","elves","email","embargo","embark","embassy","embattled","embellish","ember","embezzle","emblaze","emblem","embody","embolism","emboss","embroider","emcee","emerald","emergency","emission","emit","emote","emoticon","emotion","empathic","empathy","emperor","emphases","emphasis","emphasize","emphatic","empirical","employed","employee","employer","emporium","empower","emptier","emptiness","empty","emu","enable","enactment","enamel","enchanted","enchilada","encircle","enclose","enclosure","encode","encore","encounter","encourage","encroach","encrust","encrypt","endanger","endeared","endearing","ended","ending","endless","endnote","endocrine","endorphin","endorse","endowment","endpoint","endurable","endurance","enduring","energetic","energize","energy","enforced","enforcer","engaged","engaging","engine","engorge","engraved","engraver","engraving","engross","engulf","enhance","enigmatic","enjoyable","enjoyably","enjoyer","enjoying","enjoyment","enlarged","enlarging","enlighten","enlisted","enquirer","enrage","enrich","enroll","enslave","ensnare","ensure","entail","entangled","entering","entertain","enticing","entire","entitle","entity","entomb","entourage","entrap","entree","entrench","entrust","entryway","entwine","enunciate","envelope","enviable","enviably","envious","envision","envoy","envy","enzyme","epic","epidemic","epidermal","epidermis","epidural","epilepsy","epileptic","epilogue","epiphany","episode","equal","equate","equation","equator","equinox","equipment","equity","equivocal","eradicate","erasable","erased","eraser","erasure","ergonomic","errand","errant","erratic","error","erupt","escalate","escalator","escapable","escapade","escapist","escargot","eskimo","esophagus","espionage","espresso","esquire","essay","essence","essential","establish","estate","esteemed","estimate","estimator","estranged","estrogen","etching","eternal","eternity","ethanol","ether","ethically","ethics","euphemism","evacuate","evacuee","evade","evaluate","evaluator","evaporate","evasion","evasive","even","everglade","evergreen","everybody","everyday","everyone","evict","evidence","evident","evil","evoke","evolution","evolve","exact","exalted","example","excavate","excavator","exceeding","exception","excess","exchange","excitable","exciting","exclaim","exclude","excluding","exclusion","exclusive","excretion","excretory","excursion","excusable","excusably","excuse","exemplary","exemplify","exemption","exerciser","exert","exes","exfoliate","exhale","exhaust","exhume","exile","existing","exit","exodus","exonerate","exorcism","exorcist","expand","expanse","expansion","expansive","expectant","expedited","expediter","expel","expend","expenses","expensive","expert","expire","expiring","explain","expletive","explicit","explode","exploit","explore","exploring","exponent","exporter","exposable","expose","exposure","express","expulsion","exquisite","extended","extending","extent","extenuate","exterior","external","extinct","extortion","extradite","extras","extrovert","extrude","extruding","exuberant","fable","fabric","fabulous","facebook","facecloth","facedown","faceless","facelift","faceplate","faceted","facial","facility","facing","facsimile","faction","factoid","factor","factsheet","factual","faculty","fade","fading","failing","falcon","fall","false","falsify","fame","familiar","family","famine","famished","fanatic","fancied","fanciness","fancy","fanfare","fang","fanning","fantasize","fantastic","fantasy","fascism","fastball","faster","fasting","fastness","faucet","favorable","favorably","favored","favoring","favorite","fax","feast","federal","fedora","feeble","feed","feel","feisty","feline","felt-tip","feminine","feminism","feminist","feminize","femur","fence","fencing","fender","ferment","fernlike","ferocious","ferocity","ferret","ferris","ferry","fervor","fester","festival","festive","festivity","fetal","fetch","fever","fiber","fiction","fiddle","fiddling","fidelity","fidgeting","fidgety","fifteen","fifth","fiftieth","fifty","figment","figure","figurine","filing","filled","filler","filling","film","filter","filth","filtrate","finale","finalist","finalize","finally","finance","financial","finch","fineness","finer","finicky","finished","finisher","finishing","finite","finless","finlike","fiscally","fit","five","flaccid","flagman","flagpole","flagship","flagstick","flagstone","flail","flakily","flaky","flame","flammable","flanked","flanking","flannels","flap","flaring","flashback","flashbulb","flashcard","flashily","flashing","flashy","flask","flatbed","flatfoot","flatly","flatness","flatten","flattered","flatterer","flattery","flattop","flatware","flatworm","flavored","flavorful","flavoring","flaxseed","fled","fleshed","fleshy","flick","flier","flight","flinch","fling","flint","flip","flirt","float","flock","flogging","flop","floral","florist","floss","flounder","flyable","flyaway","flyer","flying","flyover","flypaper","foam","foe","fog","foil","folic","folk","follicle","follow","fondling","fondly","fondness","fondue","font","food","fool","footage","football","footbath","footboard","footer","footgear","foothill","foothold","footing","footless","footman","footnote","footpad","footpath","footprint","footrest","footsie","footsore","footwear","footwork","fossil","foster","founder","founding","fountain","fox","foyer","fraction","fracture","fragile","fragility","fragment","fragrance","fragrant","frail","frame","framing","frantic","fraternal","frayed","fraying","frays","freckled","freckles","freebase","freebee","freebie","freedom","freefall","freehand","freeing","freeload","freely","freemason","freeness","freestyle","freeware","freeway","freewill","freezable","freezing","freight","french","frenzied","frenzy","frequency","frequent","fresh","fretful","fretted","friction","friday","fridge","fried","friend","frighten","frightful","frigidity","frigidly","frill","fringe","frisbee","frisk","fritter","frivolous","frolic","from","front","frostbite","frosted","frostily","frosting","frostlike","frosty","froth","frown","frozen","fructose","frugality","frugally","fruit","frustrate","frying","gab","gaffe","gag","gainfully","gaining","gains","gala","gallantly","galleria","gallery","galley","gallon","gallows","gallstone","galore","galvanize","gambling","game","gaming","gamma","gander","gangly","gangrene","gangway","gap","garage","garbage","garden","gargle","garland","garlic","garment","garnet","garnish","garter","gas","gatherer","gathering","gating","gauging","gauntlet","gauze","gave","gawk","gazing","gear","gecko","geek","geiger","gem","gender","generic","generous","genetics","genre","gentile","gentleman","gently","gents","geography","geologic","geologist","geology","geometric","geometry","geranium","gerbil","geriatric","germicide","germinate","germless","germproof","gestate","gestation","gesture","getaway","getting","getup","giant","gibberish","giblet","giddily","giddiness","giddy","gift","gigabyte","gigahertz","gigantic","giggle","giggling","giggly","gigolo","gilled","gills","gimmick","girdle","giveaway","given","giver","giving","gizmo","gizzard","glacial","glacier","glade","gladiator","gladly","glamorous","glamour","glance","glancing","glandular","glare","glaring","glass","glaucoma","glazing","gleaming","gleeful","glider","gliding","glimmer","glimpse","glisten","glitch","glitter","glitzy","gloater","gloating","gloomily","gloomy","glorified","glorifier","glorify","glorious","glory","gloss","glove","glowing","glowworm","glucose","glue","gluten","glutinous","glutton","gnarly","gnat","goal","goatskin","goes","goggles","going","goldfish","goldmine","goldsmith","golf","goliath","gonad","gondola","gone","gong","good","gooey","goofball","goofiness","goofy","google","goon","gopher","gore","gorged","gorgeous","gory","gosling","gossip","gothic","gotten","gout","gown","grab","graceful","graceless","gracious","gradation","graded","grader","gradient","grading","gradually","graduate","graffiti","grafted","grafting","grain","granddad","grandkid","grandly","grandma","grandpa","grandson","granite","granny","granola","grant","granular","grape","graph","grapple","grappling","grasp","grass","gratified","gratify","grating","gratitude","gratuity","gravel","graveness","graves","graveyard","gravitate","gravity","gravy","gray","grazing","greasily","greedily","greedless","greedy","green","greeter","greeting","grew","greyhound","grid","grief","grievance","grieving","grievous","grill","grimace","grimacing","grime","griminess","grimy","grinch","grinning","grip","gristle","grit","groggily","groggy","groin","groom","groove","grooving","groovy","grope","ground","grouped","grout","grove","grower","growing","growl","grub","grudge","grudging","grueling","gruffly","grumble","grumbling","grumbly","grumpily","grunge","grunt","guacamole","guidable","guidance","guide","guiding","guileless","guise","gulf","gullible","gully","gulp","gumball","gumdrop","gumminess","gumming","gummy","gurgle","gurgling","guru","gush","gusto","gusty","gutless","guts","gutter","guy","guzzler","gyration","habitable","habitant","habitat","habitual","hacked","hacker","hacking","hacksaw","had","haggler","haiku","half","halogen","halt","halved","halves","hamburger","hamlet","hammock","hamper","hamster","hamstring","handbag","handball","handbook","handbrake","handcart","handclap","handclasp","handcraft","handcuff","handed","handful","handgrip","handgun","handheld","handiness","handiwork","handlebar","handled","handler","handling","handmade","handoff","handpick","handprint","handrail","handsaw","handset","handsfree","handshake","handstand","handwash","handwork","handwoven","handwrite","handyman","hangnail","hangout","hangover","hangup","hankering","hankie","hanky","haphazard","happening","happier","happiest","happily","happiness","happy","harbor","hardcopy","hardcore","hardcover","harddisk","hardened","hardener","hardening","hardhat","hardhead","hardiness","hardly","hardness","hardship","hardware","hardwired","hardwood","hardy","harmful","harmless","harmonica","harmonics","harmonize","harmony","harness","harpist","harsh","harvest","hash","hassle","haste","hastily","hastiness","hasty","hatbox","hatchback","hatchery","hatchet","hatching","hatchling","hate","hatless","hatred","haunt","haven","hazard","hazelnut","hazily","haziness","hazing","hazy","headache","headband","headboard","headcount","headdress","headed","header","headfirst","headgear","heading","headlamp","headless","headlock","headphone","headpiece","headrest","headroom","headscarf","headset","headsman","headstand","headstone","headway","headwear","heap","heat","heave","heavily","heaviness","heaving","hedge","hedging","heftiness","hefty","helium","helmet","helper","helpful","helping","helpless","helpline","hemlock","hemstitch","hence","henchman","henna","herald","herbal","herbicide","herbs","heritage","hermit","heroics","heroism","herring","herself","hertz","hesitancy","hesitant","hesitate","hexagon","hexagram","hubcap","huddle","huddling","huff","hug","hula","hulk","hull","human","humble","humbling","humbly","humid","humiliate","humility","humming","hummus","humongous","humorist","humorless","humorous","humpback","humped","humvee","hunchback","hundredth","hunger","hungrily","hungry","hunk","hunter","hunting","huntress","huntsman","hurdle","hurled","hurler","hurling","hurray","hurricane","hurried","hurry","hurt","husband","hush","husked","huskiness","hut","hybrid","hydrant","hydrated","hydration","hydrogen","hydroxide","hyperlink","hypertext","hyphen","hypnoses","hypnosis","hypnotic","hypnotism","hypnotist","hypnotize","hypocrisy","hypocrite","ibuprofen","ice","iciness","icing","icky","icon","icy","idealism","idealist","idealize","ideally","idealness","identical","identify","identity","ideology","idiocy","idiom","idly","igloo","ignition","ignore","iguana","illicitly","illusion","illusive","image","imaginary","imagines","imaging","imbecile","imitate","imitation","immature","immerse","immersion","imminent","immobile","immodest","immorally","immortal","immovable","immovably","immunity","immunize","impaired","impale","impart","impatient","impeach","impeding","impending","imperfect","imperial","impish","implant","implement","implicate","implicit","implode","implosion","implosive","imply","impolite","important","importer","impose","imposing","impotence","impotency","impotent","impound","imprecise","imprint","imprison","impromptu","improper","improve","improving","improvise","imprudent","impulse","impulsive","impure","impurity","iodine","iodize","ion","ipad","iphone","ipod","irate","irk","iron","irregular","irrigate","irritable","irritably","irritant","irritate","islamic","islamist","isolated","isolating","isolation","isotope","issue","issuing","italicize","italics","item","itinerary","itunes","ivory","ivy","jab","jackal","jacket","jackknife","jackpot","jailbird","jailbreak","jailer","jailhouse","jalapeno","jam","janitor","january","jargon","jarring","jasmine","jaundice","jaunt","java","jawed","jawless","jawline","jaws","jaybird","jaywalker","jazz","jeep","jeeringly","jellied","jelly","jersey","jester","jet","jiffy","jigsaw","jimmy","jingle","jingling","jinx","jitters","jittery","job","jockey","jockstrap","jogger","jogging","john","joining","jokester","jokingly","jolliness","jolly","jolt","jot","jovial","joyfully","joylessly","joyous","joyride","joystick","jubilance","jubilant","judge","judgingly","judicial","judiciary","judo","juggle","juggling","jugular","juice","juiciness","juicy","jujitsu","jukebox","july","jumble","jumbo","jump","junction","juncture","june","junior","juniper","junkie","junkman","junkyard","jurist","juror","jury","justice","justifier","justify","justly","justness","juvenile","kabob","kangaroo","karaoke","karate","karma","kebab","keenly","keenness","keep","keg","kelp","kennel","kept","kerchief","kerosene","kettle","kick","kiln","kilobyte","kilogram","kilometer","kilowatt","kilt","kimono","kindle","kindling","kindly","kindness","kindred","kinetic","kinfolk","king","kinship","kinsman","kinswoman","kissable","kisser","kissing","kitchen","kite","kitten","kitty","kiwi","kleenex","knapsack","knee","knelt","knickers","knoll","koala","kooky","kosher","krypton","kudos","kung","labored","laborer","laboring","laborious","labrador","ladder","ladies","ladle","ladybug","ladylike","lagged","lagging","lagoon","lair","lake","lance","landed","landfall","landfill","landing","landlady","landless","landline","landlord","landmark","landmass","landmine","landowner","landscape","landside","landslide","language","lankiness","lanky","lantern","lapdog","lapel","lapped","lapping","laptop","lard","large","lark","lash","lasso","last","latch","late","lather","latitude","latrine","latter","latticed","launch","launder","laundry","laurel","lavender","lavish","laxative","lazily","laziness","lazy","lecturer","left","legacy","legal","legend","legged","leggings","legible","legibly","legislate","lego","legroom","legume","legwarmer","legwork","lemon","lend","length","lens","lent","leotard","lesser","letdown","lethargic","lethargy","letter","lettuce","level","leverage","levers","levitate","levitator","liability","liable","liberty","librarian","library","licking","licorice","lid","life","lifter","lifting","liftoff","ligament","likely","likeness","likewise","liking","lilac","lilly","lily","limb","limeade","limelight","limes","limit","limping","limpness","line","lingo","linguini","linguist","lining","linked","linoleum","linseed","lint","lion","lip","liquefy","liqueur","liquid","lisp","list","litigate","litigator","litmus","litter","little","livable","lived","lively","liver","livestock","lividly","living","lizard","lubricant","lubricate","lucid","luckily","luckiness","luckless","lucrative","ludicrous","lugged","lukewarm","lullaby","lumber","luminance","luminous","lumpiness","lumping","lumpish","lunacy","lunar","lunchbox","luncheon","lunchroom","lunchtime","lung","lurch","lure","luridness","lurk","lushly","lushness","luster","lustfully","lustily","lustiness","lustrous","lusty","luxurious","luxury","lying","lyrically","lyricism","lyricist","lyrics","macarena","macaroni","macaw","mace","machine","machinist","magazine","magenta","maggot","magical","magician","magma","magnesium","magnetic","magnetism","magnetize","magnifier","magnify","magnitude","magnolia","mahogany","maimed","majestic","majesty","majorette","majority","makeover","maker","makeshift","making","malformed","malt","mama","mammal","mammary","mammogram","manager","managing","manatee","mandarin","mandate","mandatory","mandolin","manger","mangle","mango","mangy","manhandle","manhole","manhood","manhunt","manicotti","manicure","manifesto","manila","mankind","manlike","manliness","manly","manmade","manned","mannish","manor","manpower","mantis","mantra","manual","many","map","marathon","marauding","marbled","marbles","marbling","march","mardi","margarine","margarita","margin","marigold","marina","marine","marital","maritime","marlin","marmalade","maroon","married","marrow","marry","marshland","marshy","marsupial","marvelous","marxism","mascot","masculine","mashed","mashing","massager","masses","massive","mastiff","matador","matchbook","matchbox","matcher","matching","matchless","material","maternal","maternity","math","mating","matriarch","matrimony","matrix","matron","matted","matter","maturely","maturing","maturity","mauve","maverick","maximize","maximum","maybe","mayday","mayflower","moaner","moaning","mobile","mobility","mobilize","mobster","mocha","mocker","mockup","modified","modify","modular","modulator","module","moisten","moistness","moisture","molar","molasses","mold","molecular","molecule","molehill","mollusk","mom","monastery","monday","monetary","monetize","moneybags","moneyless","moneywise","mongoose","mongrel","monitor","monkhood","monogamy","monogram","monologue","monopoly","monorail","monotone","monotype","monoxide","monsieur","monsoon","monstrous","monthly","monument","moocher","moodiness","moody","mooing","moonbeam","mooned","moonlight","moonlike","moonlit","moonrise","moonscape","moonshine","moonstone","moonwalk","mop","morale","morality","morally","morbidity","morbidly","morphine","morphing","morse","mortality","mortally","mortician","mortified","mortify","mortuary","mosaic","mossy","most","mothball","mothproof","motion","motivate","motivator","motive","motocross","motor","motto","mountable","mountain","mounted","mounting","mourner","mournful","mouse","mousiness","moustache","mousy","mouth","movable","move","movie","moving","mower","mowing","much","muck","mud","mug","mulberry","mulch","mule","mulled","mullets","multiple","multiply","multitask","multitude","mumble","mumbling","mumbo","mummified","mummify","mummy","mumps","munchkin","mundane","municipal","muppet","mural","murkiness","murky","murmuring","muscular","museum","mushily","mushiness","mushroom","mushy","music","musket","muskiness","musky","mustang","mustard","muster","mustiness","musty","mutable","mutate","mutation","mute","mutilated","mutilator","mutiny","mutt","mutual","muzzle","myself","myspace","mystified","mystify","myth","nacho","nag","nail","name","naming","nanny","nanometer","nape","napkin","napped","napping","nappy","narrow","nastily","nastiness","national","native","nativity","natural","nature","naturist","nautical","navigate","navigator","navy","nearby","nearest","nearly","nearness","neatly","neatness","nebula","nebulizer","nectar","negate","negation","negative","neglector","negligee","negligent","negotiate","nemeses","nemesis","neon","nephew","nerd","nervous","nervy","nest","net","neurology","neuron","neurosis","neurotic","neuter","neutron","never","next","nibble","nickname","nicotine","niece","nifty","nimble","nimbly","nineteen","ninetieth","ninja","nintendo","ninth","nuclear","nuclei","nucleus","nugget","nullify","number","numbing","numbly","numbness","numeral","numerate","numerator","numeric","numerous","nuptials","nursery","nursing","nurture","nutcase","nutlike","nutmeg","nutrient","nutshell","nuttiness","nutty","nuzzle","nylon","oaf","oak","oasis","oat","obedience","obedient","obituary","object","obligate","obliged","oblivion","oblivious","oblong","obnoxious","oboe","obscure","obscurity","observant","observer","observing","obsessed","obsession","obsessive","obsolete","obstacle","obstinate","obstruct","obtain","obtrusive","obtuse","obvious","occultist","occupancy","occupant","occupier","occupy","ocean","ocelot","octagon","octane","october","octopus","ogle","oil","oink","ointment","okay","old","olive","olympics","omega","omen","ominous","omission","omit","omnivore","onboard","oncoming","ongoing","onion","online","onlooker","only","onscreen","onset","onshore","onslaught","onstage","onto","onward","onyx","oops","ooze","oozy","opacity","opal","open","operable","operate","operating","operation","operative","operator","opium","opossum","opponent","oppose","opposing","opposite","oppressed","oppressor","opt","opulently","osmosis","other","otter","ouch","ought","ounce","outage","outback","outbid","outboard","outbound","outbreak","outburst","outcast","outclass","outcome","outdated","outdoors","outer","outfield","outfit","outflank","outgoing","outgrow","outhouse","outing","outlast","outlet","outline","outlook","outlying","outmatch","outmost","outnumber","outplayed","outpost","outpour","output","outrage","outrank","outreach","outright","outscore","outsell","outshine","outshoot","outsider","outskirts","outsmart","outsource","outspoken","outtakes","outthink","outward","outweigh","outwit","oval","ovary","oven","overact","overall","overarch","overbid","overbill","overbite","overblown","overboard","overbook","overbuilt","overcast","overcoat","overcome","overcook","overcrowd","overdraft","overdrawn","overdress","overdrive","overdue","overeager","overeater","overexert","overfed","overfeed","overfill","overflow","overfull","overgrown","overhand","overhang","overhaul","overhead","overhear","overheat","overhung","overjoyed","overkill","overlabor","overlaid","overlap","overlay","overload","overlook","overlord","overlying","overnight","overpass","overpay","overplant","overplay","overpower","overprice","overrate","overreach","overreact","override","overripe","overrule","overrun","overshoot","overshot","oversight","oversized","oversleep","oversold","overspend","overstate","overstay","overstep","overstock","overstuff","oversweet","overtake","overthrow","overtime","overtly","overtone","overture","overturn","overuse","overvalue","overview","overwrite","owl","oxford","oxidant","oxidation","oxidize","oxidizing","oxygen","oxymoron","oyster","ozone","paced","pacemaker","pacific","pacifier","pacifism","pacifist","pacify","padded","padding","paddle","paddling","padlock","pagan","pager","paging","pajamas","palace","palatable","palm","palpable","palpitate","paltry","pampered","pamperer","pampers","pamphlet","panama","pancake","pancreas","panda","pandemic","pang","panhandle","panic","panning","panorama","panoramic","panther","pantomime","pantry","pants","pantyhose","paparazzi","papaya","paper","paprika","papyrus","parabola","parachute","parade","paradox","paragraph","parakeet","paralegal","paralyses","paralysis","paralyze","paramedic","parameter","paramount","parasail","parasite","parasitic","parcel","parched","parchment","pardon","parish","parka","parking","parkway","parlor","parmesan","parole","parrot","parsley","parsnip","partake","parted","parting","partition","partly","partner","partridge","party","passable","passably","passage","passcode","passenger","passerby","passing","passion","passive","passivism","passover","passport","password","pasta","pasted","pastel","pastime","pastor","pastrami","pasture","pasty","patchwork","patchy","paternal","paternity","path","patience","patient","patio","patriarch","patriot","patrol","patronage","patronize","pauper","pavement","paver","pavestone","pavilion","paving","pawing","payable","payback","paycheck","payday","payee","payer","paying","payment","payphone","payroll","pebble","pebbly","pecan","pectin","peculiar","peddling","pediatric","pedicure","pedigree","pedometer","pegboard","pelican","pellet","pelt","pelvis","penalize","penalty","pencil","pendant","pending","penholder","penknife","pennant","penniless","penny","penpal","pension","pentagon","pentagram","pep","perceive","percent","perch","percolate","perennial","perfected","perfectly","perfume","periscope","perish","perjurer","perjury","perkiness","perky","perm","peroxide","perpetual","perplexed","persecute","persevere","persuaded","persuader","pesky","peso","pessimism","pessimist","pester","pesticide","petal","petite","petition","petri","petroleum","petted","petticoat","pettiness","petty","petunia","phantom","phobia","phoenix","phonebook","phoney","phonics","phoniness","phony","phosphate","photo","phrase","phrasing","placard","placate","placidly","plank","planner","plant","plasma","plaster","plastic","plated","platform","plating","platinum","platonic","platter","platypus","plausible","plausibly","playable","playback","player","playful","playgroup","playhouse","playing","playlist","playmaker","playmate","playoff","playpen","playroom","playset","plaything","playtime","plaza","pleading","pleat","pledge","plentiful","plenty","plethora","plexiglas","pliable","plod","plop","plot","plow","ploy","pluck","plug","plunder","plunging","plural","plus","plutonium","plywood","poach","pod","poem","poet","pogo","pointed","pointer","pointing","pointless","pointy","poise","poison","poker","poking","polar","police","policy","polio","polish","politely","polka","polo","polyester","polygon","polygraph","polymer","poncho","pond","pony","popcorn","pope","poplar","popper","poppy","popsicle","populace","popular","populate","porcupine","pork","porous","porridge","portable","portal","portfolio","porthole","portion","portly","portside","poser","posh","posing","possible","possibly","possum","postage","postal","postbox","postcard","posted","poster","posting","postnasal","posture","postwar","pouch","pounce","pouncing","pound","pouring","pout","powdered","powdering","powdery","power","powwow","pox","praising","prance","prancing","pranker","prankish","prankster","prayer","praying","preacher","preaching","preachy","preamble","precinct","precise","precision","precook","precut","predator","predefine","predict","preface","prefix","preflight","preformed","pregame","pregnancy","pregnant","preheated","prelaunch","prelaw","prelude","premiere","premises","premium","prenatal","preoccupy","preorder","prepaid","prepay","preplan","preppy","preschool","prescribe","preseason","preset","preshow","president","presoak","press","presume","presuming","preteen","pretended","pretender","pretense","pretext","pretty","pretzel","prevail","prevalent","prevent","preview","previous","prewar","prewashed","prideful","pried","primal","primarily","primary","primate","primer","primp","princess","print","prior","prism","prison","prissy","pristine","privacy","private","privatize","prize","proactive","probable","probably","probation","probe","probing","probiotic","problem","procedure","process","proclaim","procreate","procurer","prodigal","prodigy","produce","product","profane","profanity","professed","professor","profile","profound","profusely","progeny","prognosis","program","progress","projector","prologue","prolonged","promenade","prominent","promoter","promotion","prompter","promptly","prone","prong","pronounce","pronto","proofing","proofread","proofs","propeller","properly","property","proponent","proposal","propose","props","prorate","protector","protegee","proton","prototype","protozoan","protract","protrude","proud","provable","proved","proven","provided","provider","providing","province","proving","provoke","provoking","provolone","prowess","prowler","prowling","proximity","proxy","prozac","prude","prudishly","prune","pruning","pry","psychic","public","publisher","pucker","pueblo","pug","pull","pulmonary","pulp","pulsate","pulse","pulverize","puma","pumice","pummel","punch","punctual","punctuate","punctured","pungent","punisher","punk","pupil","puppet","puppy","purchase","pureblood","purebred","purely","pureness","purgatory","purge","purging","purifier","purify","purist","puritan","purity","purple","purplish","purposely","purr","purse","pursuable","pursuant","pursuit","purveyor","pushcart","pushchair","pusher","pushiness","pushing","pushover","pushpin","pushup","pushy","putdown","putt","puzzle","puzzling","pyramid","pyromania","python","quack","quadrant","quail","quaintly","quake","quaking","qualified","qualifier","qualify","quality","qualm","quantum","quarrel","quarry","quartered","quarterly","quarters","quartet","quench","query","quicken","quickly","quickness","quicksand","quickstep","quiet","quill","quilt","quintet","quintuple","quirk","quit","quiver","quizzical","quotable","quotation","quote","rabid","race","racing","racism","rack","racoon","radar","radial","radiance","radiantly","radiated","radiation","radiator","radio","radish","raffle","raft","rage","ragged","raging","ragweed","raider","railcar","railing","railroad","railway","raisin","rake","raking","rally","ramble","rambling","ramp","ramrod","ranch","rancidity","random","ranged","ranger","ranging","ranked","ranking","ransack","ranting","rants","rare","rarity","rascal","rash","rasping","ravage","raven","ravine","raving","ravioli","ravishing","reabsorb","reach","reacquire","reaction","reactive","reactor","reaffirm","ream","reanalyze","reappear","reapply","reappoint","reapprove","rearrange","rearview","reason","reassign","reassure","reattach","reawake","rebalance","rebate","rebel","rebirth","reboot","reborn","rebound","rebuff","rebuild","rebuilt","reburial","rebuttal","recall","recant","recapture","recast","recede","recent","recess","recharger","recipient","recital","recite","reckless","reclaim","recliner","reclining","recluse","reclusive","recognize","recoil","recollect","recolor","reconcile","reconfirm","reconvene","recopy","record","recount","recoup","recovery","recreate","rectal","rectangle","rectified","rectify","recycled","recycler","recycling","reemerge","reenact","reenter","reentry","reexamine","referable","referee","reference","refill","refinance","refined","refinery","refining","refinish","reflected","reflector","reflex","reflux","refocus","refold","reforest","reformat","reformed","reformer","reformist","refract","refrain","refreeze","refresh","refried","refueling","refund","refurbish","refurnish","refusal","refuse","refusing","refutable","refute","regain","regalia","regally","reggae","regime","region","register","registrar","registry","regress","regretful","regroup","regular","regulate","regulator","rehab","reheat","rehire","rehydrate","reimburse","reissue","reiterate","rejoice","rejoicing","rejoin","rekindle","relapse","relapsing","relatable","related","relation","relative","relax","relay","relearn","release","relenting","reliable","reliably","reliance","reliant","relic","relieve","relieving","relight","relish","relive","reload","relocate","relock","reluctant","rely","remake","remark","remarry","rematch","remedial","remedy","remember","reminder","remindful","remission","remix","remnant","remodeler","remold","remorse","remote","removable","removal","removed","remover","removing","rename","renderer","rendering","rendition","renegade","renewable","renewably","renewal","renewed","renounce","renovate","renovator","rentable","rental","rented","renter","reoccupy","reoccur","reopen","reorder","repackage","repacking","repaint","repair","repave","repaying","repayment","repeal","repeated","repeater","repent","rephrase","replace","replay","replica","reply","reporter","repose","repossess","repost","repressed","reprimand","reprint","reprise","reproach","reprocess","reproduce","reprogram","reps","reptile","reptilian","repugnant","repulsion","repulsive","repurpose","reputable","reputably","request","require","requisite","reroute","rerun","resale","resample","rescuer","reseal","research","reselect","reseller","resemble","resend","resent","reset","reshape","reshoot","reshuffle","residence","residency","resident","residual","residue","resigned","resilient","resistant","resisting","resize","resolute","resolved","resonant","resonate","resort","resource","respect","resubmit","result","resume","resupply","resurface","resurrect","retail","retainer","retaining","retake","retaliate","retention","rethink","retinal","retired","retiree","retiring","retold","retool","retorted","retouch","retrace","retract","retrain","retread","retreat","retrial","retrieval","retriever","retry","return","retying","retype","reunion","reunite","reusable","reuse","reveal","reveler","revenge","revenue","reverb","revered","reverence","reverend","reversal","reverse","reversing","reversion","revert","revisable","revise","revision","revisit","revivable","revival","reviver","reviving","revocable","revoke","revolt","revolver","revolving","reward","rewash","rewind","rewire","reword","rework","rewrap","rewrite","rhyme","ribbon","ribcage","rice","riches","richly","richness","rickety","ricotta","riddance","ridden","ride","riding","rifling","rift","rigging","rigid","rigor","rimless","rimmed","rind","rink","rinse","rinsing","riot","ripcord","ripeness","ripening","ripping","ripple","rippling","riptide","rise","rising","risk","risotto","ritalin","ritzy","rival","riverbank","riverbed","riverboat","riverside","riveter","riveting","roamer","roaming","roast","robbing","robe","robin","robotics","robust","rockband","rocker","rocket","rockfish","rockiness","rocking","rocklike","rockslide","rockstar","rocky","rogue","roman","romp","rope","roping","roster","rosy","rotten","rotting","rotunda","roulette","rounding","roundish","roundness","roundup","roundworm","routine","routing","rover","roving","royal","rubbed","rubber","rubbing","rubble","rubdown","ruby","ruckus","rudder","rug","ruined","rule","rumble","rumbling","rummage","rumor","runaround","rundown","runner","running","runny","runt","runway","rupture","rural","ruse","rush","rust","rut","sabbath","sabotage","sacrament","sacred","sacrifice","sadden","saddlebag","saddled","saddling","sadly","sadness","safari","safeguard","safehouse","safely","safeness","saffron","saga","sage","sagging","saggy","said","saint","sake","salad","salami","salaried","salary","saline","salon","saloon","salsa","salt","salutary","salute","salvage","salvaging","salvation","same","sample","sampling","sanction","sanctity","sanctuary","sandal","sandbag","sandbank","sandbar","sandblast","sandbox","sanded","sandfish","sanding","sandlot","sandpaper","sandpit","sandstone","sandstorm","sandworm","sandy","sanitary","sanitizer","sank","santa","sapling","sappiness","sappy","sarcasm","sarcastic","sardine","sash","sasquatch","sassy","satchel","satiable","satin","satirical","satisfied","satisfy","saturate","saturday","sauciness","saucy","sauna","savage","savanna","saved","savings","savior","savor","saxophone","say","scabbed","scabby","scalded","scalding","scale","scaling","scallion","scallop","scalping","scam","scandal","scanner","scanning","scant","scapegoat","scarce","scarcity","scarecrow","scared","scarf","scarily","scariness","scarring","scary","scavenger","scenic","schedule","schematic","scheme","scheming","schilling","schnapps","scholar","science","scientist","scion","scoff","scolding","scone","scoop","scooter","scope","scorch","scorebook","scorecard","scored","scoreless","scorer","scoring","scorn","scorpion","scotch","scoundrel","scoured","scouring","scouting","scouts","scowling","scrabble","scraggly","scrambled","scrambler","scrap","scratch","scrawny","screen","scribble","scribe","scribing","scrimmage","script","scroll","scrooge","scrounger","scrubbed","scrubber","scruffy","scrunch","scrutiny","scuba","scuff","sculptor","sculpture","scurvy","scuttle","secluded","secluding","seclusion","second","secrecy","secret","sectional","sector","secular","securely","security","sedan","sedate","sedation","sedative","sediment","seduce","seducing","segment","seismic","seizing","seldom","selected","selection","selective","selector","self","seltzer","semantic","semester","semicolon","semifinal","seminar","semisoft","semisweet","senate","senator","send","senior","senorita","sensation","sensitive","sensitize","sensually","sensuous","sepia","september","septic","septum","sequel","sequence","sequester","series","sermon","serotonin","serpent","serrated","serve","service","serving","sesame","sessions","setback","setting","settle","settling","setup","sevenfold","seventeen","seventh","seventy","severity","shabby","shack","shaded","shadily","shadiness","shading","shadow","shady","shaft","shakable","shakily","shakiness","shaking","shaky","shale","shallot","shallow","shame","shampoo","shamrock","shank","shanty","shape","shaping","share","sharpener","sharper","sharpie","sharply","sharpness","shawl","sheath","shed","sheep","sheet","shelf","shell","shelter","shelve","shelving","sherry","shield","shifter","shifting","shiftless","shifty","shimmer","shimmy","shindig","shine","shingle","shininess","shining","shiny","ship","shirt","shivering","shock","shone","shoplift","shopper","shopping","shoptalk","shore","shortage","shortcake","shortcut","shorten","shorter","shorthand","shortlist","shortly","shortness","shorts","shortwave","shorty","shout","shove","showbiz","showcase","showdown","shower","showgirl","showing","showman","shown","showoff","showpiece","showplace","showroom","showy","shrank","shrapnel","shredder","shredding","shrewdly","shriek","shrill","shrimp","shrine","shrink","shrivel","shrouded","shrubbery","shrubs","shrug","shrunk","shucking","shudder","shuffle","shuffling","shun","shush","shut","shy","siamese","siberian","sibling","siding","sierra","siesta","sift","sighing","silenced","silencer","silent","silica","silicon","silk","silliness","silly","silo","silt","silver","similarly","simile","simmering","simple","simplify","simply","sincere","sincerity","singer","singing","single","singular","sinister","sinless","sinner","sinuous","sip","siren","sister","sitcom","sitter","sitting","situated","situation","sixfold","sixteen","sixth","sixties","sixtieth","sixtyfold","sizable","sizably","size","sizing","sizzle","sizzling","skater","skating","skedaddle","skeletal","skeleton","skeptic","sketch","skewed","skewer","skid","skied","skier","skies","skiing","skilled","skillet","skillful","skimmed","skimmer","skimming","skimpily","skincare","skinhead","skinless","skinning","skinny","skintight","skipper","skipping","skirmish","skirt","skittle","skydiver","skylight","skyline","skype","skyrocket","skyward","slab","slacked","slacker","slacking","slackness","slacks","slain","slam","slander","slang","slapping","slapstick","slashed","slashing","slate","slather","slaw","sled","sleek","sleep","sleet","sleeve","slept","sliceable","sliced","slicer","slicing","slick","slider","slideshow","sliding","slighted","slighting","slightly","slimness","slimy","slinging","slingshot","slinky","slip","slit","sliver","slobbery","slogan","sloped","sloping","sloppily","sloppy","slot","slouching","slouchy","sludge","slug","slum","slurp","slush","sly","small","smartly","smartness","smasher","smashing","smashup","smell","smelting","smile","smilingly","smirk","smite","smith","smitten","smock","smog","smoked","smokeless","smokiness","smoking","smoky","smolder","smooth","smother","smudge","smudgy","smuggler","smuggling","smugly","smugness","snack","snagged","snaking","snap","snare","snarl","snazzy","sneak","sneer","sneeze","sneezing","snide","sniff","snippet","snipping","snitch","snooper","snooze","snore","snoring","snorkel","snort","snout","snowbird","snowboard","snowbound","snowcap","snowdrift","snowdrop","snowfall","snowfield","snowflake","snowiness","snowless","snowman","snowplow","snowshoe","snowstorm","snowsuit","snowy","snub","snuff","snuggle","snugly","snugness","speak","spearfish","spearhead","spearman","spearmint","species","specimen","specked","speckled","specks","spectacle","spectator","spectrum","speculate","speech","speed","spellbind","speller","spelling","spendable","spender","spending","spent","spew","sphere","spherical","sphinx","spider","spied","spiffy","spill","spilt","spinach","spinal","spindle","spinner","spinning","spinout","spinster","spiny","spiral","spirited","spiritism","spirits","spiritual","splashed","splashing","splashy","splatter","spleen","splendid","splendor","splice","splicing","splinter","splotchy","splurge","spoilage","spoiled","spoiler","spoiling","spoils","spoken","spokesman","sponge","spongy","sponsor","spoof","spookily","spooky","spool","spoon","spore","sporting","sports","sporty","spotless","spotlight","spotted","spotter","spotting","spotty","spousal","spouse","spout","sprain","sprang","sprawl","spray","spree","sprig","spring","sprinkled","sprinkler","sprint","sprite","sprout","spruce","sprung","spry","spud","spur","sputter","spyglass","squabble","squad","squall","squander","squash","squatted","squatter","squatting","squeak","squealer","squealing","squeamish","squeegee","squeeze","squeezing","squid","squiggle","squiggly","squint","squire","squirt","squishier","squishy","stability","stabilize","stable","stack","stadium","staff","stage","staging","stagnant","stagnate","stainable","stained","staining","stainless","stalemate","staleness","stalling","stallion","stamina","stammer","stamp","stand","stank","staple","stapling","starboard","starch","stardom","stardust","starfish","stargazer","staring","stark","starless","starlet","starlight","starlit","starring","starry","starship","starter","starting","startle","startling","startup","starved","starving","stash","state","static","statistic","statue","stature","status","statute","statutory","staunch","stays","steadfast","steadier","steadily","steadying","steam","steed","steep","steerable","steering","steersman","stegosaur","stellar","stem","stench","stencil","step","stereo","sterile","sterility","sterilize","sterling","sternness","sternum","stew","stick","stiffen","stiffly","stiffness","stifle","stifling","stillness","stilt","stimulant","stimulate","stimuli","stimulus","stinger","stingily","stinging","stingray","stingy","stinking","stinky","stipend","stipulate","stir","stitch","stock","stoic","stoke","stole","stomp","stonewall","stoneware","stonework","stoning","stony","stood","stooge","stool","stoop","stoplight","stoppable","stoppage","stopped","stopper","stopping","stopwatch","storable","storage","storeroom","storewide","storm","stout","stove","stowaway","stowing","straddle","straggler","strained","strainer","straining","strangely","stranger","strangle","strategic","strategy","stratus","straw","stray","streak","stream","street","strength","strenuous","strep","stress","stretch","strewn","stricken","strict","stride","strife","strike","striking","strive","striving","strobe","strode","stroller","strongbox","strongly","strongman","struck","structure","strudel","struggle","strum","strung","strut","stubbed","stubble","stubbly","stubborn","stucco","stuck","student","studied","studio","study","stuffed","stuffing","stuffy","stumble","stumbling","stump","stung","stunned","stunner","stunning","stunt","stupor","sturdily","sturdy","styling","stylishly","stylist","stylized","stylus","suave","subarctic","subatomic","subdivide","subdued","subduing","subfloor","subgroup","subheader","subject","sublease","sublet","sublevel","sublime","submarine","submerge","submersed","submitter","subpanel","subpar","subplot","subprime","subscribe","subscript","subsector","subside","subsiding","subsidize","subsidy","subsoil","subsonic","substance","subsystem","subtext","subtitle","subtly","subtotal","subtract","subtype","suburb","subway","subwoofer","subzero","succulent","such","suction","sudden","sudoku","suds","sufferer","suffering","suffice","suffix","suffocate","suffrage","sugar","suggest","suing","suitable","suitably","suitcase","suitor","sulfate","sulfide","sulfite","sulfur","sulk","sullen","sulphate","sulphuric","sultry","superbowl","superglue","superhero","superior","superjet","superman","supermom","supernova","supervise","supper","supplier","supply","support","supremacy","supreme","surcharge","surely","sureness","surface","surfacing","surfboard","surfer","surgery","surgical","surging","surname","surpass","surplus","surprise","surreal","surrender","surrogate","surround","survey","survival","survive","surviving","survivor","sushi","suspect","suspend","suspense","sustained","sustainer","swab","swaddling","swagger","swampland","swan","swapping","swarm","sway","swear","sweat","sweep","swell","swept","swerve","swifter","swiftly","swiftness","swimmable","swimmer","swimming","swimsuit","swimwear","swinger","swinging","swipe","swirl","switch","swivel","swizzle","swooned","swoop","swoosh","swore","sworn","swung","sycamore","sympathy","symphonic","symphony","symptom","synapse","syndrome","synergy","synopses","synopsis","synthesis","synthetic","syrup","system","t-shirt","tabasco","tabby","tableful","tables","tablet","tableware","tabloid","tackiness","tacking","tackle","tackling","tacky","taco","tactful","tactical","tactics","tactile","tactless","tadpole","taekwondo","tag","tainted","take","taking","talcum","talisman","tall","talon","tamale","tameness","tamer","tamper","tank","tanned","tannery","tanning","tantrum","tapeless","tapered","tapering","tapestry","tapioca","tapping","taps","tarantula","target","tarmac","tarnish","tarot","tartar","tartly","tartness","task","tassel","taste","tastiness","tasting","tasty","tattered","tattle","tattling","tattoo","taunt","tavern","thank","that","thaw","theater","theatrics","thee","theft","theme","theology","theorize","thermal","thermos","thesaurus","these","thesis","thespian","thicken","thicket","thickness","thieving","thievish","thigh","thimble","thing","think","thinly","thinner","thinness","thinning","thirstily","thirsting","thirsty","thirteen","thirty","thong","thorn","those","thousand","thrash","thread","threaten","threefold","thrift","thrill","thrive","thriving","throat","throbbing","throng","throttle","throwaway","throwback","thrower","throwing","thud","thumb","thumping","thursday","thus","thwarting","thyself","tiara","tibia","tidal","tidbit","tidiness","tidings","tidy","tiger","tighten","tightly","tightness","tightrope","tightwad","tigress","tile","tiling","till","tilt","timid","timing","timothy","tinderbox","tinfoil","tingle","tingling","tingly","tinker","tinkling","tinsel","tinsmith","tint","tinwork","tiny","tipoff","tipped","tipper","tipping","tiptoeing","tiptop","tiring","tissue","trace","tracing","track","traction","tractor","trade","trading","tradition","traffic","tragedy","trailing","trailside","train","traitor","trance","tranquil","transfer","transform","translate","transpire","transport","transpose","trapdoor","trapeze","trapezoid","trapped","trapper","trapping","traps","trash","travel","traverse","travesty","tray","treachery","treading","treadmill","treason","treat","treble","tree","trekker","tremble","trembling","tremor","trench","trend","trespass","triage","trial","triangle","tribesman","tribunal","tribune","tributary","tribute","triceps","trickery","trickily","tricking","trickle","trickster","tricky","tricolor","tricycle","trident","tried","trifle","trifocals","trillion","trilogy","trimester","trimmer","trimming","trimness","trinity","trio","tripod","tripping","triumph","trivial","trodden","trolling","trombone","trophy","tropical","tropics","trouble","troubling","trough","trousers","trout","trowel","truce","truck","truffle","trump","trunks","trustable","trustee","trustful","trusting","trustless","truth","try","tubby","tubeless","tubular","tucking","tuesday","tug","tuition","tulip","tumble","tumbling","tummy","turban","turbine","turbofan","turbojet","turbulent","turf","turkey","turmoil","turret","turtle","tusk","tutor","tutu","tux","tweak","tweed","tweet","tweezers","twelve","twentieth","twenty","twerp","twice","twiddle","twiddling","twig","twilight","twine","twins","twirl","twistable","twisted","twister","twisting","twisty","twitch","twitter","tycoon","tying","tyke","udder","ultimate","ultimatum","ultra","umbilical","umbrella","umpire","unabashed","unable","unadorned","unadvised","unafraid","unaired","unaligned","unaltered","unarmored","unashamed","unaudited","unawake","unaware","unbaked","unbalance","unbeaten","unbend","unbent","unbiased","unbitten","unblended","unblessed","unblock","unbolted","unbounded","unboxed","unbraided","unbridle","unbroken","unbuckled","unbundle","unburned","unbutton","uncanny","uncapped","uncaring","uncertain","unchain","unchanged","uncharted","uncheck","uncivil","unclad","unclaimed","unclamped","unclasp","uncle","unclip","uncloak","unclog","unclothed","uncoated","uncoiled","uncolored","uncombed","uncommon","uncooked","uncork","uncorrupt","uncounted","uncouple","uncouth","uncover","uncross","uncrown","uncrushed","uncured","uncurious","uncurled","uncut","undamaged","undated","undaunted","undead","undecided","undefined","underage","underarm","undercoat","undercook","undercut","underdog","underdone","underfed","underfeed","underfoot","undergo","undergrad","underhand","underline","underling","undermine","undermost","underpaid","underpass","underpay","underrate","undertake","undertone","undertook","undertow","underuse","underwear","underwent","underwire","undesired","undiluted","undivided","undocked","undoing","undone","undrafted","undress","undrilled","undusted","undying","unearned","unearth","unease","uneasily","uneasy","uneatable","uneaten","unedited","unelected","unending","unengaged","unenvied","unequal","unethical","uneven","unexpired","unexposed","unfailing","unfair","unfasten","unfazed","unfeeling","unfiled","unfilled","unfitted","unfitting","unfixable","unfixed","unflawed","unfocused","unfold","unfounded","unframed","unfreeze","unfrosted","unfrozen","unfunded","unglazed","ungloved","unglue","ungodly","ungraded","ungreased","unguarded","unguided","unhappily","unhappy","unharmed","unhealthy","unheard","unhearing","unheated","unhelpful","unhidden","unhinge","unhitched","unholy","unhook","unicorn","unicycle","unified","unifier","uniformed","uniformly","unify","unimpeded","uninjured","uninstall","uninsured","uninvited","union","uniquely","unisexual","unison","unissued","unit","universal","universe","unjustly","unkempt","unkind","unknotted","unknowing","unknown","unlaced","unlatch","unlawful","unleaded","unlearned","unleash","unless","unleveled","unlighted","unlikable","unlimited","unlined","unlinked","unlisted","unlit","unlivable","unloaded","unloader","unlocked","unlocking","unlovable","unloved","unlovely","unloving","unluckily","unlucky","unmade","unmanaged","unmanned","unmapped","unmarked","unmasked","unmasking","unmatched","unmindful","unmixable","unmixed","unmolded","unmoral","unmovable","unmoved","unmoving","unnamable","unnamed","unnatural","unneeded","unnerve","unnerving","unnoticed","unopened","unopposed","unpack","unpadded","unpaid","unpainted","unpaired","unpaved","unpeeled","unpicked","unpiloted","unpinned","unplanned","unplanted","unpleased","unpledged","unplowed","unplug","unpopular","unproven","unquote","unranked","unrated","unraveled","unreached","unread","unreal","unreeling","unrefined","unrelated","unrented","unrest","unretired","unrevised","unrigged","unripe","unrivaled","unroasted","unrobed","unroll","unruffled","unruly","unrushed","unsaddle","unsafe","unsaid","unsalted","unsaved","unsavory","unscathed","unscented","unscrew","unsealed","unseated","unsecured","unseeing","unseemly","unseen","unselect","unselfish","unsent","unsettled","unshackle","unshaken","unshaved","unshaven","unsheathe","unshipped","unsightly","unsigned","unskilled","unsliced","unsmooth","unsnap","unsocial","unsoiled","unsold","unsolved","unsorted","unspoiled","unspoken","unstable","unstaffed","unstamped","unsteady","unsterile","unstirred","unstitch","unstopped","unstuck","unstuffed","unstylish","unsubtle","unsubtly","unsuited","unsure","unsworn","untagged","untainted","untaken","untamed","untangled","untapped","untaxed","unthawed","unthread","untidy","untie","until","untimed","untimely","untitled","untoasted","untold","untouched","untracked","untrained","untreated","untried","untrimmed","untrue","untruth","unturned","untwist","untying","unusable","unused","unusual","unvalued","unvaried","unvarying","unveiled","unveiling","unvented","unviable","unvisited","unvocal","unwanted","unwarlike","unwary","unwashed","unwatched","unweave","unwed","unwelcome","unwell","unwieldy","unwilling","unwind","unwired","unwitting","unwomanly","unworldly","unworn","unworried","unworthy","unwound","unwoven","unwrapped","unwritten","unzip","upbeat","upchuck","upcoming","upcountry","update","upfront","upgrade","upheaval","upheld","uphill","uphold","uplifted","uplifting","upload","upon","upper","upright","uprising","upriver","uproar","uproot","upscale","upside","upstage","upstairs","upstart","upstate","upstream","upstroke","upswing","uptake","uptight","uptown","upturned","upward","upwind","uranium","urban","urchin","urethane","urgency","urgent","urging","urologist","urology","usable","usage","useable","used","uselessly","user","usher","usual","utensil","utility","utilize","utmost","utopia","utter","vacancy","vacant","vacate","vacation","vagabond","vagrancy","vagrantly","vaguely","vagueness","valiant","valid","valium","valley","valuables","value","vanilla","vanish","vanity","vanquish","vantage","vaporizer","variable","variably","varied","variety","various","varmint","varnish","varsity","varying","vascular","vaseline","vastly","vastness","veal","vegan","veggie","vehicular","velcro","velocity","velvet","vendetta","vending","vendor","veneering","vengeful","venomous","ventricle","venture","venue","venus","verbalize","verbally","verbose","verdict","verify","verse","version","versus","vertebrae","vertical","vertigo","very","vessel","vest","veteran","veto","vexingly","viability","viable","vibes","vice","vicinity","victory","video","viewable","viewer","viewing","viewless","viewpoint","vigorous","village","villain","vindicate","vineyard","vintage","violate","violation","violator","violet","violin","viper","viral","virtual","virtuous","virus","visa","viscosity","viscous","viselike","visible","visibly","vision","visiting","visitor","visor","vista","vitality","vitalize","vitally","vitamins","vivacious","vividly","vividness","vixen","vocalist","vocalize","vocally","vocation","voice","voicing","void","volatile","volley","voltage","volumes","voter","voting","voucher","vowed","vowel","voyage","wackiness","wad","wafer","waffle","waged","wager","wages","waggle","wagon","wake","waking","walk","walmart","walnut","walrus","waltz","wand","wannabe","wanted","wanting","wasabi","washable","washbasin","washboard","washbowl","washcloth","washday","washed","washer","washhouse","washing","washout","washroom","washstand","washtub","wasp","wasting","watch","water","waviness","waving","wavy","whacking","whacky","wham","wharf","wheat","whenever","whiff","whimsical","whinny","whiny","whisking","whoever","whole","whomever","whoopee","whooping","whoops","why","wick","widely","widen","widget","widow","width","wieldable","wielder","wife","wifi","wikipedia","wildcard","wildcat","wilder","wildfire","wildfowl","wildland","wildlife","wildly","wildness","willed","willfully","willing","willow","willpower","wilt","wimp","wince","wincing","wind","wing","winking","winner","winnings","winter","wipe","wired","wireless","wiring","wiry","wisdom","wise","wish","wisplike","wispy","wistful","wizard","wobble","wobbling","wobbly","wok","wolf","wolverine","womanhood","womankind","womanless","womanlike","womanly","womb","woof","wooing","wool","woozy","word","work","worried","worrier","worrisome","worry","worsening","worshiper","worst","wound","woven","wow","wrangle","wrath","wreath","wreckage","wrecker","wrecking","wrench","wriggle","wriggly","wrinkle","wrinkly","wrist","writing","written","wrongdoer","wronged","wrongful","wrongly","wrongness","wrought","xbox","xerox","yahoo","yam","yanking","yapping","yard","yarn","yeah","yearbook","yearling","yearly","yearning","yeast","yelling","yelp","yen","yesterday","yiddish","yield","yin","yippee","yo-yo","yodel","yoga","yogurt","yonder","yoyo","yummy","zap","zealous","zebra","zen","zeppelin","zero","zestfully","zesty","zigzagged","zipfile","zipping","zippy","zips","zit","zodiac","zombie","zone","zoning","zookeeper","zoologist","zoology","zoom"],kd=wi.record(zr,"organizationKeys",{deserializer:e=>e,clearOn:["logout"]}),Sd=wi.record(zr,"providerKeys",{deserializer:e=>e,clearOn:["logout"]}),_d=new wi(zr,"everHadUserKey",{deserializer:e=>e,clearOn:["logout"]}),xd=new wi(Pr,"userKey",{deserializer:e=>gu.fromJSON(e),clearOn:["logout","lock"]});var Cd,Id=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Ed{constructor(e,t,i,r,n,a,s,o,l,c,u){this.masterPasswordService=e,this.keyGenerationService=t,this.cryptoFunctionService=i,this.encryptService=r,this.platformUtilService=n,this.logService=a,this.stateService=s,this.accountService=o,this.stateProvider=l,this.kdfConfigService=c,this.accountCryptographyStateService=u,this.activeUserOrgKeys$=this.stateProvider.activeUserId$.pipe(Le(e=>null!=e?this.orgKeys$(e):Wt),Ie(e=>null!=e),Zl(),Jt({bufferSize:1,refCount:!1}))}setUserKey(e,t){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("No key provided. Lock the user to clear the key");if(null==t)throw new Error("No userId provided.");if(yield this.stateProvider.setUserState(xd,e,t),yield this.stateProvider.setUserState(_d,!0,t),yield this.storeAdditionalKeys(e,t),null==(yield Ce(this.userKey$(t).pipe(Ie(e=>null!=e)))))throw new Error("Failed to set user key")})}refreshAdditionalKeys(e){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("UserId is required.");const t=yield Ce(this.userKey$(e));if(null==t)throw new Error("No user key found for: "+e);yield this.setUserKey(t,e)})}everHadUserKey$(e){return this.stateProvider.getUser(e,_d).state$.pipe(X(e=>null!=e&&e))}getInMemoryUserKeyFor$(e){return this.stateProvider.getUserState$(xd,e)}getUserKey(e){return Id(this,void 0,void 0,function*(){return yield Ce(this.stateProvider.getUserState$(xd,e))})}getUserKeyFromStorage(e,t){return Id(this,void 0,void 0,function*(){if(null==t)throw new Error("UserId is required");const i=yield this.getKeyFromStorage(e,t);return null==i?null:((yield this.validateUserKey(i,t))||(this.logService.warning("Invalid key, throwing away stored keys"),yield this.clearAllStoredUserKeys(t)),i)})}hasUserKey(e){return Id(this,void 0,void 0,function*(){return null!=e&&null!=(yield Ce(this.stateProvider.getUserState$(xd,e)))})}makeUserKey(e){return Id(this,void 0,void 0,function*(){if(!e)throw new Error("MasterKey is required");const t=yield this.keyGenerationService.createKey(512);return this.buildProtectedSymmetricKey(e,t)})}clearUserKey(e){return Id(this,void 0,void 0,function*(){null!=e&&(yield this.stateProvider.setUserState(xd,null,e),yield this.clearAllStoredUserKeys(e))})}clearStoredUserKey(e){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("UserId is required");yield this.stateService.setUserKeyAutoUnlock(null,{userId:e})})}getOrDeriveMasterKey(e,t){return Id(this,void 0,void 0,function*(){if(null==t)throw new Error("User ID is required.");const i=yield Ce(this.masterPasswordService.masterKey$(t));if(null!=i)return i;const r=yield Ce(this.accountService.accounts$.pipe(X(e=>{var i;return null===(i=e[t])||void 0===i?void 0:i.email})));if(null==r)throw new Error("No email found for user "+t);const n=yield Ce(this.kdfConfigService.getKdfConfig$(t));if(null==n)throw new Error("No kdf found for user "+t);return yield this.makeMasterKey(e,r,n)})}makeMasterKey(e,t,i){return Id(this,void 0,void 0,function*(){const r=(new Date).getTime();t=t.trim().toLowerCase();const n=yield this.keyGenerationService.deriveKeyFromPassword(e,t,i),a=(new Date).getTime();return this.logService.info(`[KeyService] Deriving master key took ${a-r}ms`),n})}encryptUserKeyWithMasterKey(e,t){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("masterKey is required.");if(null==t)throw new Error("userKey is required.");return yield this.buildProtectedSymmetricKey(e,t)})}hashMasterKey(e,t,i){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("password is required.");if(null==t)throw new Error("key is required.");const r=i===lt.LocalAuthorization?2:1,n=yield this.cryptoFunctionService.pbkdf2(t.inner().encryptionKey,e,"sha256",r);return Tt.fromBufferToB64(n)})}compareKeyHash(e,t,i){return Id(this,void 0,void 0,function*(){if(null==t)throw new Error("'masterKey' is required to be non-null.");if(null==e)return!1;const r=yield Ce(this.masterPasswordService.masterKeyHash$(i));if(null==r)return!1;const n=yield this.hashMasterKey(e,t,lt.LocalAuthorization);return null!=n&&r===n})}setOrgKeys(e,t,i){return Id(this,void 0,void 0,function*(){yield this.stateProvider.getUser(i,kd).update(()=>{const i={};for(const t of e)i[t.id]={type:"organization",key:t.key};for(const e of t)i[e.id]={type:"provider",providerId:e.providerId,key:e.key};return i})})}getOrgKey(e){return Id(this,void 0,void 0,function*(){return yield Ce(this.activeUserOrgKeys$.pipe(X(t=>{var i;return null!==(i=t[e])&&void 0!==i?i:null})))})}makeDataEncKey(e){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("No key provided");const t=yield this.keyGenerationService.createKey(512);return[t,yield this.encryptService.wrapSymmetricKey(t,e)]})}clearOrgKeys(e){return Id(this,void 0,void 0,function*(){null!=e&&(yield this.stateProvider.setUserState(kd,null,e))})}setProviderKeys(e,t){return Id(this,void 0,void 0,function*(){yield this.stateProvider.getUser(t,Sd).update(()=>{const t={};return e.forEach(e=>{t[e.id]=e.key}),t})})}providerKeys$(e){return this.userPrivateKey$(e).pipe(Le(t=>null==t?bt(null):this.providerKeysHelper$(e,t)))}clearProviderKeys(e){return Id(this,void 0,void 0,function*(){null!=e&&(yield this.stateProvider.setUserState(Sd,null,e))})}makeOrgKey(e){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("UserId is required");const t=yield Ce(this.userPublicKey$(e));if(null==t)throw new Error("No public key found for user "+e);const i=yield this.keyGenerationService.createKey(512);return[yield this.encryptService.encapsulateKeyUnsigned(i,t),i]})}getFingerprint(e,t){return Id(this,void 0,void 0,function*(){if(null==t)throw new Error("Public key is required to generate a fingerprint.");const i=yield this.cryptoFunctionService.hash(t,"sha256"),r=yield this.cryptoFunctionService.hkdfExpand(i,e,32,"sha256");return this.hashPhrase(r)})}makeKeyPair(e){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("'key' is a required parameter and must be non-null.");const t=yield this.cryptoFunctionService.rsaGenerateKeyPair(2048);return[Tt.fromBufferToB64(t[0]),yield this.encryptService.wrapDecapsulationKey(t[1],e)]})}makeSendKey(e){return Id(this,void 0,void 0,function*(){return yield this.keyGenerationService.deriveKeyFromMaterial(e,"bitwarden-send","send")})}makeCipherKey(){return Id(this,void 0,void 0,function*(){return yield this.keyGenerationService.createKey(512)})}clearKeys(e){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("UserId is required");yield this.masterPasswordService.clearMasterKeyHash(e),yield this.clearUserKey(e),yield this.clearOrgKeys(e),yield this.clearProviderKeys(e),yield this.stateProvider.setUserState(_d,null,e),yield this.accountCryptographyStateService.clearAccountCryptographicState(e)})}validateUserKey(e,t){return Id(this,void 0,void 0,function*(){if(null==e)return!1;try{const i=yield Ce(this.userEncryptedPrivateKey$(t));if(null==i)return!1;const r=yield this.decryptPrivateKey(i,e);if(null==r)return!1;if(null==(yield this.derivePublicKey(r)))return!1}catch(e){return!1}return!0})}initAccount(e){return Id(this,void 0,void 0,function*(){if(null==e)throw new Error("UserId is required.");if(null!=(yield Ce(this.userKey$(e))))throw this.logService.error("Tried to initialize account with existing user key."),new Error("Cannot initialize account, keys already exist.");const t=yield this.keyGenerationService.createKey(512),[i,r]=yield this.makeKeyPair(t);if(null==r.encryptedString)throw new Error("Failed to create valid private key.");return yield this.setUserKey(t,e),yield this.accountCryptographyStateService.setAccountCryptographicState({V1:{private_key:r.encryptedString}},e),{userKey:t,publicKey:i,privateKey:r}})}storeAdditionalKeys(e,t){return Id(this,void 0,void 0,function*(){(yield this.shouldStoreKey(ht.Auto,t))?yield this.stateService.setUserKeyAutoUnlock(e.keyB64,{userId:t}):yield this.stateService.setUserKeyAutoUnlock(null,{userId:t})})}shouldStoreKey(e,t){return Id(this,void 0,void 0,function*(){if(e===ht.Auto){if(this.platformUtilService.getClientType()==Ku.Cli)return!0;const e=yield Ce(this.stateProvider.getUserState$(gd,t).pipe(Ie(e=>null!=e)));return this.logService.debug(`[KeyService] Should store auto key for vault timeout ${e}`),e==ld}return!1})}getKeyFromStorage(e,t){return Id(this,void 0,void 0,function*(){if(e===ht.Auto){const e=yield this.stateService.getUserKeyAutoUnlock({userId:t});if(e)return new gu(Tt.fromB64ToArray(e))}return null})}clearAllStoredUserKeys(e){return Id(this,void 0,void 0,function*(){yield this.stateService.setUserKeyAutoUnlock(null,{userId:e})})}hashPhrase(e){return Id(this,arguments,void 0,function*(e,t=64){const i=Math.log(wd.length)/Math.log(2);let r=Math.ceil(t/i);const n=Array.from(new Uint8Array(e));if(r*i>4*n.length)throw new Error("Output entropy of hash function is too small");const a=[];let s=Wu.fromArray(n,256);for(;r--;){const e=s.mod(wd.length);s=s.divide(wd.length),a.push(wd[e])}return a})}buildProtectedSymmetricKey(e,t){return Id(this,void 0,void 0,function*(){let i;if(e.inner().type===rt.AesCbc256_B64){const r=yield this.keyGenerationService.stretchKey(e);i=yield this.encryptService.wrapSymmetricKey(t,r)}else{if(e.inner().type!==rt.AesCbc256_HmacSha256_B64)throw new Error("Invalid key size.");i=yield this.encryptService.wrapSymmetricKey(t,e)}return[t,i]})}userKey$(e){return this.stateProvider.getUser(e,xd).state$}userPublicKey$(e){return this.userPrivateKey$(e).pipe(Le(e=>Id(this,void 0,void 0,function*(){return yield this.derivePublicKey(e)})))}derivePublicKey(e){return Id(this,void 0,void 0,function*(){return null==e?null:yield this.cryptoFunctionService.rsaExtractPublicKey(e)})}userPrivateKey$(e){return this.userPrivateKeyHelper$(e).pipe(X(e=>{var t;return null!==(t=null==e?void 0:e.userPrivateKey)&&void 0!==t?t:null}))}userEncryptionKeyPair$(e){return this.userPrivateKey$(e).pipe(Le(e=>Id(this,void 0,void 0,function*(){if(null==e)return null;const t=yield this.derivePublicKey(e);return{privateKey:e,publicKey:t}})))}userEncryptedPrivateKey$(e){return this.accountCryptographyStateService.accountCryptographicState$(e).pipe(X(e=>null==e?null:"V2"in e?e.V2.private_key:"V1"in e?e.V1.private_key:null))}userPrivateKeyHelper$(e){return this.userKey$(e).pipe(Le(t=>null==t?bt(null):this.userEncryptedPrivateKey$(e).pipe(Le(e=>Id(this,void 0,void 0,function*(){return yield this.decryptPrivateKey(e,t)})),X(e=>({userKey:t,userPrivateKey:e})),Hu(i=>(this.logService.error(`Failed to decrypt private key for user ${e}`),bt({userKey:t,userPrivateKey:null}))))))}decryptPrivateKey(e,t){return Id(this,void 0,void 0,function*(){return null==e?null:yield this.encryptService.unwrapDecapsulationKey(new Nt(e),t)})}providerKeysHelper$(e,t){return this.stateProvider.getUser(e,Sd).state$.pipe((i=(e,i)=>Id(this,void 0,void 0,function*(){return yield this.encryptService.decapsulateKeyUnsigned(new Nt(i),t)}),X(e=>{if(null==e)return null;const t={};for(const[r,n]of Object.entries(e))t[r]=i(0,n);return t})),Le(e=>null==e?bt(null):0===Object.keys(e).length?bt({}):Gu(e)));var i}userSigningKey$(e){return this.accountCryptographyStateService.accountCryptographicState$(e).pipe(X(e=>null==e?null:"V2"in e?e.V2.signing_key:null))}orgKeys$(e){return this.cipherDecryptionKeys$(e).pipe(X(e=>{var t;return null!==(t=null==e?void 0:e.orgKeys)&&void 0!==t?t:null}))}encryptedOrgKeys$(e){var t;return null===(t=this.userPrivateKey$(e))||void 0===t?void 0:t.pipe(Le(t=>null==t?bt({}):ai([this.stateProvider.getUser(e,kd).state$,this.providerKeysHelper$(e,t)]).pipe(Le(e=>Id(this,[e],void 0,function*([e,i]){const r=yield this.derivePublicKey(t),n={};e=null!=e?e:{};for(const t of Object.keys(e)){if(null!=n[t])continue;const a=Ju.fromData(e[t]);if(null==a)continue;let s;if(Ju.isProviderEncrypted(a)){if(null==i)continue;s=yield this.encryptService.encapsulateKeyUnsigned(yield a.decrypt(this.encryptService,i),r)}else s=a.encryptedOrganizationKey;n[t]=s}return n})),Hu(t=>(this.logService.error(`Failed to get encrypted organization keys for user ${e}`,t),bt({}))))))}cipherDecryptionKeys$(e){var t;return null===(t=this.userPrivateKeyHelper$(e))||void 0===t?void 0:t.pipe(Le(t=>{if(null==t)return bt(null);const i=t.userPrivateKey;return null==i?bt({userKey:t.userKey,orgKeys:null}):ai([this.stateProvider.getUser(e,kd).state$,this.providerKeysHelper$(e,i)]).pipe(Le(e=>Id(this,[e],void 0,function*([e,t]){const r={};e=null!=e?e:{};for(const n of Object.keys(e)){if(null!=r[n])continue;const a=Ju.fromData(e[n]);if(null==a)continue;let s;if(Ju.isProviderEncrypted(a)){if(null==t)continue;s=yield a.decrypt(this.encryptService,t)}else s=yield a.decrypt(this.encryptService,i);r[n]=s}return r})),X(e=>({userKey:t.userKey,orgKeys:e})))}))}userSignedPublicKey$(e){return this.accountCryptographyStateService.accountCryptographicState$(e).pipe(X(e=>null==e?null:"V2"in e?e.V2.signed_public_key:null))}}class zd{constructor(e,t,i){if(this.min=e,this.max=t,this.defaultValue=i,e>t)throw new Error(`${e} is greater than ${t}.`);if(!1===this.inRange(i))throw new Error("Default value is not in range.")}inRange(e){return e>=this.min&&e<=this.max}}!function(e){e[e.PBKDF2_SHA256=0]="PBKDF2_SHA256",e[e.Argon2id=1]="Argon2id"}(Cd||(Cd={}));class Pd{constructor(e){this.kdfType=Cd.PBKDF2_SHA256,this.iterations=null!=e?e:Pd.ITERATIONS.defaultValue}validateKdfConfigForSetting(){if(!Pd.ITERATIONS.inRange(this.iterations))throw new Error(`PBKDF2 iterations must be between ${Pd.ITERATIONS.min} and ${Pd.ITERATIONS.max}`)}validateKdfConfigForPrelogin(){if(Pd.PRELOGIN_ITERATIONS_MIN>this.iterations)throw new Error(`PBKDF2 iterations must be at least ${Pd.PRELOGIN_ITERATIONS_MIN}, but was ${this.iterations}; possible pre-login downgrade attack detected.`)}static fromJSON(e){return new Pd(e.iterations)}toSdkConfig(){return{pBKDF2:{iterations:this.iterations}}}}Pd.ITERATIONS=new zd(6e5,2e6,6e5),Pd.PRELOGIN_ITERATIONS_MIN=5e3;class Ad{constructor(e,t,i){this.kdfType=Cd.Argon2id,this.iterations=null!=e?e:Ad.ITERATIONS.defaultValue,this.memory=null!=t?t:Ad.MEMORY.defaultValue,this.parallelism=null!=i?i:Ad.PARALLELISM.defaultValue}validateKdfConfigForSetting(){if(!Ad.ITERATIONS.inRange(this.iterations))throw new Error(`Argon2 iterations must be between ${Ad.ITERATIONS.min} and ${Ad.ITERATIONS.max}`);if(!Ad.MEMORY.inRange(this.memory))throw new Error(`Argon2 memory must be between ${Ad.MEMORY.min} MiB and ${Ad.MEMORY.max} MiB`);if(!Ad.PARALLELISM.inRange(this.parallelism))throw new Error(`Argon2 parallelism must be between ${Ad.PARALLELISM.min} and ${Ad.PARALLELISM.max}.`)}validateKdfConfigForPrelogin(){if(Ad.PRELOGIN_ITERATIONS_MIN>this.iterations)throw new Error(`Argon2 iterations must be at least ${Ad.PRELOGIN_ITERATIONS_MIN}, but was ${this.iterations}; possible pre-login downgrade attack detected.`);if(Ad.PRELOGIN_MEMORY_MIN>this.memory)throw new Error(`Argon2 memory must be at least ${Ad.PRELOGIN_MEMORY_MIN} MiB, but was ${this.memory} MiB; possible pre-login downgrade attack detected.`);if(Ad.PRELOGIN_PARALLELISM_MIN>this.parallelism)throw new Error(`Argon2 parallelism must be at least ${Ad.PRELOGIN_PARALLELISM_MIN}, but was ${this.parallelism}; possible pre-login downgrade attack detected.`)}static fromJSON(e){return new Ad(e.iterations,e.memory,e.parallelism)}toSdkConfig(){return{argon2id:{iterations:this.iterations,memory:this.memory,parallelism:this.parallelism}}}}Ad.MEMORY=new zd(16,1024,64),Ad.PARALLELISM=new zd(1,16,4),Ad.ITERATIONS=new zd(2,10,3),Ad.PRELOGIN_MEMORY_MIN=16,Ad.PRELOGIN_PARALLELISM_MIN=1,Ad.PRELOGIN_ITERATIONS_MIN=2,new Pd(Pd.ITERATIONS.defaultValue);var jd=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Td=new wi(Ar,"kdfConfig",{deserializer:e=>null==e?null:e.kdfType===Cd.PBKDF2_SHA256?Pd.fromJSON(e):Ad.fromJSON(e),clearOn:["logout"]});class Dd{constructor(e){this.stateProvider=e}setKdfConfig(e,t){return jd(this,void 0,void 0,function*(){if(null==e)throw new Error("userId cannot be null");if(null==t)throw new Error("kdfConfig cannot be null");yield this.stateProvider.setUserState(Td,t,e)})}getKdfConfig(e){return jd(this,void 0,void 0,function*(){if(null==e)throw new Error("userId cannot be null");const t=yield Ce(this.stateProvider.getUser(e,Td).state$);if(null==t)throw new Error("KdfConfig for user "+e+" is null");return t})}getKdfConfig$(e){if(null==e)throw new Error("userId cannot be null");return this.stateProvider.getUser(e,Td).state$}}var Od,Nd,Rd;class Ud{constructor(e,t){this.type=t.getDevice(),this.name=t.getDeviceString(),this.identifier=e,this.pushToken=null}static fromJSON(e){return Object.assign(Object.create(Ud.prototype),e)}}class Fd{constructor(e,t){this.twoFactor=e,this.device=null!=t?t:null}setTwoFactor(e){this.twoFactor=e}setAuthRequestAccessCode(e){this.authRequest=e}toIdentityToken(e){const t={scope:"api offline_access",client_id:e};return this.device&&(t.deviceType=this.device.type,t.deviceIdentifier=this.device.identifier,t.deviceName=this.device.name),this.authRequest&&(t.authRequest=this.authRequest),this.twoFactor&&this.twoFactor.token&&null!=this.twoFactor.provider&&(t.twoFactorToken=this.twoFactor.token,t.twoFactorProvider=this.twoFactor.provider,t.twoFactorRemember=this.twoFactor.remember?"1":"0"),t}}class qd extends Fd{constructor(e,t,i,r,n){super(i,r),this.email=e,this.masterPasswordHash=t,this.twoFactor=i,this.newDeviceOtp=n}toIdentityToken(e){const t=super.toIdentityToken(e);return t.grant_type="password",t.username=this.email,t.password=this.masterPasswordHash,this.newDeviceOtp&&(t.newDeviceOtp=this.newDeviceOtp),t}static fromJSON(e){return Object.assign(Object.create(qd.prototype),e,{device:e.device?Ud.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new hu,e.twoFactor):void 0})}}!function(e){e[e.Authenticator=0]="Authenticator",e[e.Email=1]="Email",e[e.Duo=2]="Duo",e[e.Yubikey=3]="Yubikey",e[e.U2f=4]="U2f",e[e.Remember=5]="Remember",e[e.OrganizationDuo=6]="OrganizationDuo",e[e.WebAuthn=7]="WebAuthn",e[e.RecoveryCode=8]="RecoveryCode"}(Od||(Od={})),function(e){e[e.None=0]="None",e[e.SsoNewJitProvisionedUser=1]="SsoNewJitProvisionedUser",e[e.TdeUserWithoutPasswordHasPasswordResetPermission=2]="TdeUserWithoutPasswordHasPasswordResetPermission",e[e.TdeOffboarding=3]="TdeOffboarding",e[e.TdeOffboardingUntrustedDevice=4]="TdeOffboardingUntrustedDevice",e[e.AdminForcePasswordReset=5]="AdminForcePasswordReset",e[e.WeakMasterPassword=6]="WeakMasterPassword"}(Nd||(Nd={}));class Ld extends Lt{constructor(e){var t;super(e),this.deviceVerified=null!==(t=this.getResponseProperty("DeviceVerified"))&&void 0!==t&&t}}class Bd extends Lt{constructor(e){super(e),this.ssoOrganizationIdentifier=this.getResponseProperty("SsoOrganizationIdentifier")}}class Md{constructor(e){if(this.securityState=null,"object"!=typeof e||null==e)throw new TypeError("Response must be an object");if(!("securityState"in e)||"string"!=typeof e.securityState)throw new TypeError("Response must contain a valid securityState");this.securityState=e.securityState}}class Vd{constructor(e){if(this.signedPublicKey=null,"object"!=typeof e||null==e)throw new TypeError("Response must be an object");if(!("publicKey"in e)||"string"!=typeof e.publicKey)throw new TypeError("Response must contain a valid publicKey");if(this.publicKey=Tt.fromB64ToArray(e.publicKey),!("wrappedPrivateKey"in e)||"string"!=typeof e.wrappedPrivateKey)throw new TypeError("Response must contain a valid wrappedPrivateKey");this.wrappedPrivateKey=e.wrappedPrivateKey,"signedPublicKey"in e&&"string"==typeof e.signedPublicKey?this.signedPublicKey=e.signedPublicKey:this.signedPublicKey=null}}class $d{constructor(e){if("object"!=typeof e||null==e)throw new TypeError("Response must be an object");if(!("wrappedSigningKey"in e)||"string"!=typeof e.wrappedSigningKey)throw new TypeError("Response must contain a valid wrappedSigningKey");if(this.wrappedSigningKey=e.wrappedSigningKey,!("verifyingKey"in e)||"string"!=typeof e.verifyingKey)throw new TypeError("Response must contain a valid verifyingKey");this.verifyingKey=e.verifyingKey}}class Kd{constructor(e){if(this.signatureKeyPair=null,this.securityState=null,"object"!=typeof e||null==e)throw new TypeError("Response must be an object");if(!("publicKeyEncryptionKeyPair"in e)||"object"!=typeof e.publicKeyEncryptionKeyPair)throw new TypeError("Response must contain a valid publicKeyEncryptionKeyPair");if(this.publicKeyEncryptionKeyPair=new Vd(e.publicKeyEncryptionKeyPair),"signatureKeyPair"in e&&"object"==typeof e.signatureKeyPair&&null!=e.signatureKeyPair&&(this.signatureKeyPair=new $d(e.signatureKeyPair)),"securityState"in e&&"object"==typeof e.securityState&&null!=e.securityState&&(this.securityState=new Md(e.securityState)),null!==this.signatureKeyPair&&null===this.securityState||null===this.signatureKeyPair&&null!==this.securityState)throw new TypeError("Both signatureKeyPair and securityState must be present or absent together")}toWrappedAccountCryptographicState(){if(null===this.signatureKeyPair&&null===this.securityState)return{V1:{private_key:this.publicKeyEncryptionKeyPair.wrappedPrivateKey}};if(null!==this.signatureKeyPair&&null!==this.securityState)return{V2:{private_key:this.publicKeyEncryptionKeyPair.wrappedPrivateKey,signing_key:this.signatureKeyPair.wrappedSigningKey,signed_public_key:this.publicKeyEncryptionKeyPair.signedPublicKey,security_state:this.securityState.securityState}};throw new Error("Both signatureKeyPair and securityState must be present or absent together")}isV2Encryption(){return null!==this.signatureKeyPair&&null!==this.securityState}}class Wd extends Lt{constructor(e){super(e),this.minComplexity=this.getResponseProperty("MinComplexity"),this.minLength=this.getResponseProperty("MinLength"),this.requireUpper=this.getResponseProperty("RequireUpper"),this.requireLower=this.getResponseProperty("RequireLower"),this.requireNumbers=this.getResponseProperty("RequireNumbers"),this.requireSpecial=this.getResponseProperty("RequireSpecial"),this.enforceOnLogin=this.getResponseProperty("EnforceOnLogin")}}class Hd extends Lt{constructor(e){super(e);const t=this.getResponseProperty("KdfType");if(null==t||"number"!=typeof t)throw new Error("KDF config response does not contain a valid KDF type");this.kdfType=t;const i=this.getResponseProperty("Iterations");if(null==i||"number"!=typeof i)throw new Error("KDF config response does not contain a valid number of iterations");if(this.iterations=i,this.kdfType===Cd.Argon2id){const e=this.getResponseProperty("Memory");if(null==e||"number"!=typeof e)throw new Error("KDF config response does not contain a valid memory size for Argon2id");const t=this.getResponseProperty("Parallelism");if(null==t||"number"!=typeof t)throw new Error("KDF config response does not contain a valid parallelism for Argon2id");this.memory=e,this.parallelism=t}}toKdfConfig(){switch(this.kdfType){case Cd.Argon2id:return new Ad(this.iterations,this.memory,this.parallelism);case Cd.PBKDF2_SHA256:return new Pd(this.iterations)}}}class Gd{constructor(e,t,i){this.salt=e,this.kdf=t,this.masterKeyWrappedUserKey=i}static fromSdk(e){return new Gd(e.salt,function(e){if("pBKDF2"in e)return new Pd(e.pBKDF2.iterations);if("argon2id"in e)return new Ad(e.argon2id.iterations,e.argon2id.memory,e.argon2id.parallelism);throw new Error("Unsupported KDF type")}(e.kdf),e.masterKeyWrappedUserKey)}toJSON(){return{salt:this.salt,kdf:this.kdf,masterKeyWrappedUserKey:this.masterKeyWrappedUserKey}}static fromJSON(e){return null==e?null:new Gd(e.salt,e.kdf.kdfType===Cd.PBKDF2_SHA256?Pd.fromJSON(e.kdf):Ad.fromJSON(e.kdf),e.masterKeyWrappedUserKey)}}class Qd extends Lt{constructor(e){super(e);const t=this.getResponseProperty("Salt");if(null==t||"string"!=typeof t)throw new Error("MasterPasswordUnlockResponse does not contain a valid salt");this.salt=t,this.kdf=new Hd(this.getResponseProperty("Kdf"));const i=this.getResponseProperty("MasterKeyEncryptedUserKey");if(null==i||"string"!=typeof i)throw new Error("MasterPasswordUnlockResponse does not contain a valid master key encrypted user key");this.masterKeyWrappedUserKey=i}toMasterPasswordUnlockData(){return new Gd(this.salt,this.kdf.toKdfConfig(),this.masterKeyWrappedUserKey)}}class Jd extends Lt{constructor(e){super(e),this.keyConnectorUrl=this.getResponseProperty("KeyConnectorUrl")}}class Yd extends Lt{constructor(e){super(e),this.hasAdminApproval=this.getResponseProperty("HasAdminApproval"),this.hasLoginApprovingDevice=this.getResponseProperty("HasLoginApprovingDevice"),this.hasManageResetPasswordPermission=this.getResponseProperty("HasManageResetPasswordPermission"),this.isTdeOffboarding=this.getResponseProperty("IsTdeOffboarding"),e.EncryptedPrivateKey&&(this.encryptedPrivateKey=new Nt(this.getResponseProperty("EncryptedPrivateKey"))),e.EncryptedUserKey&&(this.encryptedUserKey=new Nt(this.getResponseProperty("EncryptedUserKey")))}}class Xd extends Lt{constructor(e){super(e);const t=this.getResponseProperty("EncryptedPrivateKey");t&&(this.encryptedPrivateKey=new Nt(t));const i=this.getResponseProperty("EncryptedUserKey");i&&(this.encryptedUserKey=new Nt(i)),this.credentialId=this.getResponseProperty("CredentialId"),this.transports=this.getResponseProperty("Transports")||[]}}class Zd extends Lt{constructor(e){super(e),this.hasMasterPassword=this.getResponseProperty("HasMasterPassword");const t=this.getResponseProperty("MasterPasswordUnlock");null!=t&&"object"==typeof t&&(this.masterPasswordUnlock=new Qd(t)),e.TrustedDeviceOption&&(this.trustedDeviceOption=new Yd(this.getResponseProperty("TrustedDeviceOption"))),e.KeyConnectorOption&&(this.keyConnectorOption=new Jd(this.getResponseProperty("KeyConnectorOption"))),e.WebAuthnPrfOption&&(this.webAuthnPrfOption=new Xd(this.getResponseProperty("WebAuthnPrfOption")))}}class eh extends Lt{constructor(e){super(e),this.accountKeysResponseModel=null;const t=this.getResponseProperty("access_token");if(null==t||"string"!=typeof t)throw new Error("Identity response does not contain a valid access token");const i=this.getResponseProperty("token_type");if(null==i||"string"!=typeof i)throw new Error("Identity response does not contain a valid token type");this.accessToken=t,this.tokenType=i;const r=this.getResponseProperty("expires_in");null!=r&&"number"==typeof r&&(this.expiresIn=r);const n=this.getResponseProperty("refresh_token");null!=n&&"string"==typeof n&&(this.refreshToken=n),this.privateKey=this.getResponseProperty("PrivateKey"),null!=this.getResponseProperty("AccountKeys")&&(this.accountKeysResponseModel=new Kd(this.getResponseProperty("AccountKeys")));const a=this.getResponseProperty("Key");a&&(this.key=new Nt(a)),this.twoFactorToken=this.getResponseProperty("TwoFactorToken");const s=this.getResponseProperty("Kdf"),o=this.getResponseProperty("KdfIterations"),l=this.getResponseProperty("KdfMemory"),c=this.getResponseProperty("KdfParallelism");this.kdfConfig=s==Cd.PBKDF2_SHA256?new Pd(o):new Ad(o,l,c),this.forcePasswordReset=this.getResponseProperty("ForcePasswordReset"),this.apiUseKeyConnector=this.getResponseProperty("ApiUseKeyConnector"),this.masterPasswordPolicy=new Wd(this.getResponseProperty("MasterPasswordPolicy"));const u=this.getResponseProperty("UserDecryptionOptions");null!=u&&"object"==typeof u&&(this.userDecryptionOptions=new Zd(u))}hasMasterKeyEncryptedUserKey(){return Boolean(this.key)}}class th extends Lt{constructor(e){super(e),this.twoFactorProviders=this.getResponseProperty("TwoFactorProviders"),this.twoFactorProviders2=this.getResponseProperty("TwoFactorProviders2"),this.masterPasswordPolicy=new Wd(this.getResponseProperty("MasterPasswordPolicy")),this.ssoEmail2faSessionToken=this.getResponseProperty("SsoEmail2faSessionToken"),this.email=this.getResponseProperty("Email")}}class ih{static fromJSON(e){return Object.assign(new ih,e,{tokenRequest:qd.fromJSON(e.tokenRequest),authRequestCredentials:fu.fromJSON(e.authRequestCredentials)})}}class rh{constructor(){this.forcePasswordResetReason=Nd.None}static fromJSON(e){return Object.assign(new rh,e,{tokenRequest:qd.fromJSON(e.tokenRequest),masterKey:gu.fromJSON(e.masterKey)})}}class nh extends Fd{constructor(e,t,i,r,n){super(r,n),this.code=e,this.codeVerifier=t,this.redirectUri=i,this.twoFactor=r}toIdentityToken(e){const t=super.toIdentityToken(e);return t.grant_type="authorization_code",t.code=this.code,t.code_verifier=this.codeVerifier,t.redirect_uri=this.redirectUri,t}static fromJSON(e){return Object.assign(Object.create(nh.prototype),e,{device:e.device?Ud.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new hu,e.twoFactor):void 0})}}!function(e){e[e.Android=0]="Android",e[e.iOS=1]="iOS",e[e.ChromeExtension=2]="ChromeExtension",e[e.FirefoxExtension=3]="FirefoxExtension",e[e.OperaExtension=4]="OperaExtension",e[e.EdgeExtension=5]="EdgeExtension",e[e.WindowsDesktop=6]="WindowsDesktop",e[e.MacOsDesktop=7]="MacOsDesktop",e[e.LinuxDesktop=8]="LinuxDesktop",e[e.ChromeBrowser=9]="ChromeBrowser",e[e.FirefoxBrowser=10]="FirefoxBrowser",e[e.OperaBrowser=11]="OperaBrowser",e[e.EdgeBrowser=12]="EdgeBrowser",e[e.IEBrowser=13]="IEBrowser",e[e.UnknownBrowser=14]="UnknownBrowser",e[e.AndroidAmazon=15]="AndroidAmazon",e[e.UWP=16]="UWP",e[e.SafariBrowser=17]="SafariBrowser",e[e.VivaldiBrowser=18]="VivaldiBrowser",e[e.VivaldiExtension=19]="VivaldiExtension",e[e.SafariExtension=20]="SafariExtension",e[e.SDK=21]="SDK",e[e.Server=22]="Server",e[e.WindowsCLI=23]="WindowsCLI",e[e.MacOsCLI=24]="MacOsCLI",e[e.LinuxCLI=25]="LinuxCLI",e[e.DuckDuckGoBrowser=26]="DuckDuckGoBrowser"}(Rd||(Rd={}));const ah={[Rd.Android]:{category:"mobile",platform:"Android"},[Rd.iOS]:{category:"mobile",platform:"iOS"},[Rd.AndroidAmazon]:{category:"mobile",platform:"Amazon"},[Rd.ChromeExtension]:{category:"extension",platform:"Chrome"},[Rd.FirefoxExtension]:{category:"extension",platform:"Firefox"},[Rd.OperaExtension]:{category:"extension",platform:"Opera"},[Rd.EdgeExtension]:{category:"extension",platform:"Edge"},[Rd.VivaldiExtension]:{category:"extension",platform:"Vivaldi"},[Rd.SafariExtension]:{category:"extension",platform:"Safari"},[Rd.ChromeBrowser]:{category:"webApp",platform:"Chrome"},[Rd.FirefoxBrowser]:{category:"webApp",platform:"Firefox"},[Rd.OperaBrowser]:{category:"webApp",platform:"Opera"},[Rd.EdgeBrowser]:{category:"webApp",platform:"Edge"},[Rd.IEBrowser]:{category:"webApp",platform:"IE"},[Rd.SafariBrowser]:{category:"webApp",platform:"Safari"},[Rd.VivaldiBrowser]:{category:"webApp",platform:"Vivaldi"},[Rd.DuckDuckGoBrowser]:{category:"webApp",platform:"DuckDuckGo"},[Rd.UnknownBrowser]:{category:"webApp",platform:"Unknown"},[Rd.WindowsDesktop]:{category:"desktop",platform:"Windows"},[Rd.MacOsDesktop]:{category:"desktop",platform:"macOS"},[Rd.LinuxDesktop]:{category:"desktop",platform:"Linux"},[Rd.UWP]:{category:"desktop",platform:"Windows UWP"},[Rd.WindowsCLI]:{category:"cli",platform:"Windows"},[Rd.MacOsCLI]:{category:"cli",platform:"macOS"},[Rd.LinuxCLI]:{category:"cli",platform:"Linux"},[Rd.SDK]:{category:"sdk",platform:""},[Rd.Server]:{category:"server",platform:""}};var sh,oh,lh,ch,uh,dh;!function(e){e[e.SCIM=1]="SCIM",e[e.DomainVerification=2]="DomainVerification",e[e.PublicApi=3]="PublicApi",e[e.BitwardenPortal=5]="BitwardenPortal"}(sh||(sh={})),function(e){e[e.User_LoggedIn=1e3]="User_LoggedIn",e[e.User_ChangedPassword=1001]="User_ChangedPassword",e[e.User_Updated2fa=1002]="User_Updated2fa",e[e.User_Disabled2fa=1003]="User_Disabled2fa",e[e.User_Recovered2fa=1004]="User_Recovered2fa",e[e.User_FailedLogIn=1005]="User_FailedLogIn",e[e.User_FailedLogIn2fa=1006]="User_FailedLogIn2fa",e[e.User_ClientExportedVault=1007]="User_ClientExportedVault",e[e.User_UpdatedTempPassword=1008]="User_UpdatedTempPassword",e[e.User_MigratedKeyToKeyConnector=1009]="User_MigratedKeyToKeyConnector",e[e.User_RequestedDeviceApproval=1010]="User_RequestedDeviceApproval",e[e.User_TdeOffboardingPasswordSet=1011]="User_TdeOffboardingPasswordSet",e[e.Cipher_Created=1100]="Cipher_Created",e[e.Cipher_Updated=1101]="Cipher_Updated",e[e.Cipher_Deleted=1102]="Cipher_Deleted",e[e.Cipher_AttachmentCreated=1103]="Cipher_AttachmentCreated",e[e.Cipher_AttachmentDeleted=1104]="Cipher_AttachmentDeleted",e[e.Cipher_Shared=1105]="Cipher_Shared",e[e.Cipher_UpdatedCollections=1106]="Cipher_UpdatedCollections",e[e.Cipher_ClientViewed=1107]="Cipher_ClientViewed",e[e.Cipher_ClientToggledPasswordVisible=1108]="Cipher_ClientToggledPasswordVisible",e[e.Cipher_ClientToggledHiddenFieldVisible=1109]="Cipher_ClientToggledHiddenFieldVisible",e[e.Cipher_ClientToggledCardCodeVisible=1110]="Cipher_ClientToggledCardCodeVisible",e[e.Cipher_ClientCopiedPassword=1111]="Cipher_ClientCopiedPassword",e[e.Cipher_ClientCopiedHiddenField=1112]="Cipher_ClientCopiedHiddenField",e[e.Cipher_ClientCopiedCardCode=1113]="Cipher_ClientCopiedCardCode",e[e.Cipher_ClientAutofilled=1114]="Cipher_ClientAutofilled",e[e.Cipher_SoftDeleted=1115]="Cipher_SoftDeleted",e[e.Cipher_Restored=1116]="Cipher_Restored",e[e.Cipher_ClientToggledCardNumberVisible=1117]="Cipher_ClientToggledCardNumberVisible",e[e.Cipher_ClientToggledTOTPSeedVisible=1118]="Cipher_ClientToggledTOTPSeedVisible",e[e.Collection_Created=1300]="Collection_Created",e[e.Collection_Updated=1301]="Collection_Updated",e[e.Collection_Deleted=1302]="Collection_Deleted",e[e.Group_Created=1400]="Group_Created",e[e.Group_Updated=1401]="Group_Updated",e[e.Group_Deleted=1402]="Group_Deleted",e[e.OrganizationUser_Invited=1500]="OrganizationUser_Invited",e[e.OrganizationUser_Confirmed=1501]="OrganizationUser_Confirmed",e[e.OrganizationUser_Updated=1502]="OrganizationUser_Updated",e[e.OrganizationUser_Removed=1503]="OrganizationUser_Removed",e[e.OrganizationUser_UpdatedGroups=1504]="OrganizationUser_UpdatedGroups",e[e.OrganizationUser_UnlinkedSso=1505]="OrganizationUser_UnlinkedSso",e[e.OrganizationUser_ResetPassword_Enroll=1506]="OrganizationUser_ResetPassword_Enroll",e[e.OrganizationUser_ResetPassword_Withdraw=1507]="OrganizationUser_ResetPassword_Withdraw",e[e.OrganizationUser_AdminResetPassword=1508]="OrganizationUser_AdminResetPassword",e[e.OrganizationUser_ResetSsoLink=1509]="OrganizationUser_ResetSsoLink",e[e.OrganizationUser_FirstSsoLogin=1510]="OrganizationUser_FirstSsoLogin",e[e.OrganizationUser_Revoked=1511]="OrganizationUser_Revoked",e[e.OrganizationUser_Restored=1512]="OrganizationUser_Restored",e[e.OrganizationUser_ApprovedAuthRequest=1513]="OrganizationUser_ApprovedAuthRequest",e[e.OrganizationUser_RejectedAuthRequest=1514]="OrganizationUser_RejectedAuthRequest",e[e.OrganizationUser_Deleted=1515]="OrganizationUser_Deleted",e[e.OrganizationUser_Left=1516]="OrganizationUser_Left",e[e.OrganizationUser_AutomaticallyConfirmed=1517]="OrganizationUser_AutomaticallyConfirmed",e[e.Organization_Updated=1600]="Organization_Updated",e[e.Organization_PurgedVault=1601]="Organization_PurgedVault",e[e.Organization_ClientExportedVault=1602]="Organization_ClientExportedVault",e[e.Organization_VaultAccessed=1603]="Organization_VaultAccessed",e[e.Organization_EnabledSso=1604]="Organization_EnabledSso",e[e.Organization_DisabledSso=1605]="Organization_DisabledSso",e[e.Organization_EnabledKeyConnector=1606]="Organization_EnabledKeyConnector",e[e.Organization_DisabledKeyConnector=1607]="Organization_DisabledKeyConnector",e[e.Organization_SponsorshipsSynced=1608]="Organization_SponsorshipsSynced",e[e.Organization_CollectionManagementUpdated=1609]="Organization_CollectionManagementUpdated",e[e.Organization_CollectionManagement_LimitCollectionCreationEnabled=1610]="Organization_CollectionManagement_LimitCollectionCreationEnabled",e[e.Organization_CollectionManagement_LimitCollectionCreationDisabled=1611]="Organization_CollectionManagement_LimitCollectionCreationDisabled",e[e.Organization_CollectionManagement_LimitCollectionDeletionEnabled=1612]="Organization_CollectionManagement_LimitCollectionDeletionEnabled",e[e.Organization_CollectionManagement_LimitCollectionDeletionDisabled=1613]="Organization_CollectionManagement_LimitCollectionDeletionDisabled",e[e.Organization_CollectionManagement_LimitItemDeletionEnabled=1614]="Organization_CollectionManagement_LimitItemDeletionEnabled",e[e.Organization_CollectionManagement_LimitItemDeletionDisabled=1615]="Organization_CollectionManagement_LimitItemDeletionDisabled",e[e.Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsEnabled=1616]="Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsEnabled",e[e.Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsDisabled=1617]="Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsDisabled",e[e.Organization_ItemOrganization_Accepted=1618]="Organization_ItemOrganization_Accepted",e[e.Organization_ItemOrganization_Declined=1619]="Organization_ItemOrganization_Declined",e[e.Organization_AutoConfirmEnabled_Admin=1620]="Organization_AutoConfirmEnabled_Admin",e[e.Organization_AutoConfirmDisabled_Admin=1621]="Organization_AutoConfirmDisabled_Admin",e[e.Organization_AutoConfirmEnabled_Portal=1622]="Organization_AutoConfirmEnabled_Portal",e[e.Organization_AutoConfirmDisabled_Portal=1623]="Organization_AutoConfirmDisabled_Portal",e[e.Policy_Updated=1700]="Policy_Updated",e[e.ProviderUser_Invited=1800]="ProviderUser_Invited",e[e.ProviderUser_Confirmed=1801]="ProviderUser_Confirmed",e[e.ProviderUser_Updated=1802]="ProviderUser_Updated",e[e.ProviderUser_Removed=1803]="ProviderUser_Removed",e[e.ProviderOrganization_Created=1900]="ProviderOrganization_Created",e[e.ProviderOrganization_Added=1901]="ProviderOrganization_Added",e[e.ProviderOrganization_Removed=1902]="ProviderOrganization_Removed",e[e.ProviderOrganization_VaultAccessed=1903]="ProviderOrganization_VaultAccessed",e[e.OrganizationDomain_Added=2e3]="OrganizationDomain_Added",e[e.OrganizationDomain_Removed=2001]="OrganizationDomain_Removed",e[e.OrganizationDomain_Verified=2002]="OrganizationDomain_Verified",e[e.OrganizationDomain_NotVerified=2003]="OrganizationDomain_NotVerified",e[e.Secret_Retrieved=2100]="Secret_Retrieved",e[e.Secret_Created=2101]="Secret_Created",e[e.Secret_Edited=2102]="Secret_Edited",e[e.Secret_Deleted=2103]="Secret_Deleted",e[e.Secret_Permanently_Deleted=2104]="Secret_Permanently_Deleted",e[e.Secret_Restored=2105]="Secret_Restored",e[e.Project_Retrieved=2200]="Project_Retrieved",e[e.Project_Created=2201]="Project_Created",e[e.Project_Edited=2202]="Project_Edited",e[e.Project_Deleted=2203]="Project_Deleted",e[e.ServiceAccount_UserAdded=2300]="ServiceAccount_UserAdded",e[e.ServiceAccount_UserRemoved=2301]="ServiceAccount_UserRemoved",e[e.ServiceAccount_GroupAdded=2302]="ServiceAccount_GroupAdded",e[e.ServiceAccount_GroupRemoved=2303]="ServiceAccount_GroupRemoved",e[e.ServiceAccount_Created=2304]="ServiceAccount_Created",e[e.ServiceAccount_Deleted=2305]="ServiceAccount_Deleted"}(oh||(oh={})),function(e){e[e.Continue=100]="Continue",e[e.SwitchingProtocols=101]="SwitchingProtocols",e[e.Processing=102]="Processing",e[e.Ok=200]="Ok",e[e.Created=201]="Created",e[e.Accepted=202]="Accepted",e[e.NonAuthoritativeInformation=203]="NonAuthoritativeInformation",e[e.NoContent=204]="NoContent",e[e.ResetContent=205]="ResetContent",e[e.PartialContent=206]="PartialContent",e[e.MultiStatus=207]="MultiStatus",e[e.AlreadyReported=208]="AlreadyReported",e[e.ImUsed=226]="ImUsed",e[e.MultipleChoices=300]="MultipleChoices",e[e.MovedPermanently=301]="MovedPermanently",e[e.Found=302]="Found",e[e.SeeOther=303]="SeeOther",e[e.NotModified=304]="NotModified",e[e.UseProxy=305]="UseProxy",e[e.SwitchProxy=306]="SwitchProxy",e[e.TemporaryRedirect=307]="TemporaryRedirect",e[e.PermanentRedirect=308]="PermanentRedirect",e[e.BadRequest=400]="BadRequest",e[e.Unauthorized=401]="Unauthorized",e[e.PaymentRequired=402]="PaymentRequired",e[e.Forbidden=403]="Forbidden",e[e.NotFound=404]="NotFound",e[e.MethodNotAllowed=405]="MethodNotAllowed",e[e.NotAcceptable=406]="NotAcceptable",e[e.ProxyAuthenticationRequired=407]="ProxyAuthenticationRequired",e[e.RequestTimeout=408]="RequestTimeout",e[e.Conflict=409]="Conflict",e[e.Gone=410]="Gone",e[e.LengthRequired=411]="LengthRequired",e[e.PreconditionFailed=412]="PreconditionFailed",e[e.PayloadTooLarge=413]="PayloadTooLarge",e[e.UriTooLong=414]="UriTooLong",e[e.UnsupportedMediaType=415]="UnsupportedMediaType",e[e.RangeNotSatisfiable=416]="RangeNotSatisfiable",e[e.ExpectationFailed=417]="ExpectationFailed",e[e.IAmATeapot=418]="IAmATeapot",e[e.MisdirectedRequest=421]="MisdirectedRequest",e[e.UnprocessableEntity=422]="UnprocessableEntity",e[e.Locked=423]="Locked",e[e.FailedDependency=424]="FailedDependency",e[e.UpgradeRequired=426]="UpgradeRequired",e[e.PreconditionRequired=428]="PreconditionRequired",e[e.TooManyRequests=429]="TooManyRequests",e[e.RequestHeaderFieldsTooLarge=431]="RequestHeaderFieldsTooLarge",e[e.UnavailableForLegalReasons=451]="UnavailableForLegalReasons",e[e.InternalServerError=500]="InternalServerError",e[e.NotImplemented=501]="NotImplemented",e[e.BadGateway=502]="BadGateway",e[e.ServiceUnavailable=503]="ServiceUnavailable",e[e.GatewayTimeout=504]="GatewayTimeout",e[e.HttpVersionNotSupported=505]="HttpVersionNotSupported",e[e.VariantAlsoNegotiates=506]="VariantAlsoNegotiates",e[e.InsufficientStorage=507]="InsufficientStorage",e[e.LoopDetected=508]="LoopDetected",e[e.NotExtended=510]="NotExtended",e[e.NetworkAuthenticationRequired=511]="NetworkAuthenticationRequired"}(lh||(lh={})),function(e){e.Integration="integration",e.SDK="sdk",e.SSO="sso",e.SCIM="scim",e.BWDC="bwdc",e.EVENT="event",e.DEVICE="device"}(ch||(ch={})),function(e){e[e.One=1]="One",e[e.Latest=1]="Latest"}(uh||(uh={})),function(e){e[e.SyncCipherUpdate=0]="SyncCipherUpdate",e[e.SyncCipherCreate=1]="SyncCipherCreate",e[e.SyncLoginDelete=2]="SyncLoginDelete",e[e.SyncFolderDelete=3]="SyncFolderDelete",e[e.SyncCiphers=4]="SyncCiphers",e[e.SyncVault=5]="SyncVault",e[e.SyncOrgKeys=6]="SyncOrgKeys",e[e.SyncFolderCreate=7]="SyncFolderCreate",e[e.SyncFolderUpdate=8]="SyncFolderUpdate",e[e.SyncCipherDelete=9]="SyncCipherDelete",e[e.SyncSettings=10]="SyncSettings",e[e.LogOut=11]="LogOut",e[e.SyncSendCreate=12]="SyncSendCreate",e[e.SyncSendUpdate=13]="SyncSendUpdate",e[e.SyncSendDelete=14]="SyncSendDelete",e[e.AuthRequest=15]="AuthRequest",e[e.AuthRequestResponse=16]="AuthRequestResponse",e[e.SyncOrganizations=17]="SyncOrganizations",e[e.SyncOrganizationStatusChanged=18]="SyncOrganizationStatusChanged",e[e.SyncOrganizationCollectionSettingChanged=19]="SyncOrganizationCollectionSettingChanged",e[e.Notification=20]="Notification",e[e.NotificationStatus=21]="NotificationStatus",e[e.RefreshSecurityTasks=22]="RefreshSecurityTasks",e[e.OrganizationBankAccountVerified=23]="OrganizationBankAccountVerified",e[e.ProviderBankAccountVerified=24]="ProviderBankAccountVerified",e[e.SyncPolicy=25]="SyncPolicy",e[e.AutoConfirmMember=26]="AutoConfirmMember"}(dh||(dh={}));const hh=Object.freeze({KdfChange:0});class ph{static fromJSON(e){return Object.assign(new ph,e,{tokenRequest:nh.fromJSON(e.tokenRequest)})}}class mh extends Fd{constructor(e,t,i,r){super(i,r),this.clientId=e,this.clientSecret=t,this.twoFactor=i}toIdentityToken(){const e=super.toIdentityToken(this.clientId);return e.scope=this.clientId.startsWith("organization")?"api.organization":"api",e.grant_type="client_credentials",e.client_secret=this.clientSecret,e}static fromJSON(e){return Object.assign(Object.create(mh.prototype),e,{device:e.device?Ud.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new hu,e.twoFactor):void 0})}}class gh{static fromJSON(e){return Object.assign(new gh,e,{tokenRequest:mh.fromJSON(e.tokenRequest)})}}class fh extends Fd{constructor(e,t,i){super(void 0,i),this.token=e,this.deviceResponse=t}toIdentityToken(e){const t=super.toIdentityToken(e);return t.grant_type="webauthn",t.token=this.token,t.deviceResponse=JSON.stringify(this.deviceResponse),t}static fromJSON(e){return Object.assign(Object.create(fh.prototype),e,{deviceResponse:mu.fromJSON(e.deviceResponse),device:e.device?Ud.fromJSON(e.device):void 0,twoFactor:e.twoFactor?Object.assign(new hu,e.twoFactor):void 0})}}class yh{static fromJSON(e){return Object.assign(new yh,e,{tokenRequest:fh.fromJSON(e.tokenRequest),credentials:yu.fromJSON(e.credentials)})}}new fi(Di,"currentLoginStrategy",{deserializer:e=>e}),new fi(Di,"loginStrategyCacheExpiration",{deserializer:e=>e?null:new Date(e)}),new fi(Di,"authRequestPushNotification",{deserializer:e=>e}),new fi(Di,"loginStrategyCache",{deserializer:e=>null==e?null:{password:e.password?rh.fromJSON(e.password):void 0,sso:e.sso?ph.fromJSON(e.sso):void 0,userApiKey:e.userApiKey?gh.fromJSON(e.userApiKey):void 0,authRequest:e.authRequest?ih.fromJSON(e.authRequest):void 0,webAuthn:e.webAuthn?yh.fromJSON(e.webAuthn):void 0}});const vh=new wi(Mi,"decryptionOptions",{deserializer:e=>ku.fromJSON(e),clearOn:["logout"]});class bh{constructor(e){this.singleUserStateProvider=e}userDecryptionOptionsById$(e){return this.singleUserStateProvider.get(e,vh).state$.pipe(Ie(e=>null!=e))}hasMasterPasswordById$(e){return this.userDecryptionOptionsById$(e).pipe(X(e=>{var t;return null!==(t=e.hasMasterPassword)&&void 0!==t&&t}))}setUserDecryptionOptionsById(e,t){return i=this,r=void 0,a=function*(){yield this.singleUserStateProvider.get(e,vh).update(e=>t)},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}}class wh{constructor(e){e&&Object.assign(this,e)}toJSON(){return{id:this.id,privateKey:Tt.fromBufferToByteString(this.privateKey)}}static fromJSON(e){if(null==e)return null;let t=null;return e.privateKey&&(t=Tt.fromByteStringToArray(e.privateKey)),new wh({id:e.id,privateKey:t})}}class kh{constructor(e,t,i,r){this.key=e,this.masterPasswordHash=t,this.deviceIdentifier=i,this.requestApproved=r}}class Sh extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.publicKey=this.getResponseProperty("PublicKey"),this.requestDeviceType=this.getResponseProperty("RequestDeviceType"),this.requestDeviceTypeValue=this.getResponseProperty("RequestDeviceTypeValue"),this.requestDeviceIdentifier=this.getResponseProperty("RequestDeviceIdentifier"),this.requestIpAddress=this.getResponseProperty("RequestIpAddress"),this.requestCountryName=this.getResponseProperty("RequestCountryName"),this.key=this.getResponseProperty("Key"),this.creationDate=this.getResponseProperty("CreationDate"),this.requestApproved=this.getResponseProperty("RequestApproved"),this.responseDate=this.getResponseProperty("ResponseDate"),this.deviceId=this.getResponseProperty("RequestDeviceId");const t=new Date(this.creationDate),i=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds(),t.getUTCMilliseconds()),r=new Date(Date.now()),n=Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds());this.isExpired=n-i>=9e5,this.isAnswered=null!=this.requestApproved&&null!=this.responseDate}}var _h=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const xh=new wi(zi,"adminAuthRequest",{deserializer:e=>e,clearOn:[]});class Ch{constructor(e,t,i,r,n,a,s,o){this.appIdService=e,this.masterPasswordService=t,this.keyService=i,this.encryptService=r,this.apiService=n,this.stateProvider=a,this.authRequestApiService=s,this.accountService=o,this.authRequestPushNotificationSubject=new H,this.adminLoginApprovedSubject=new H,this.authRequestPushNotification$=this.authRequestPushNotificationSubject.asObservable(),this.adminLoginApproved$=this.adminLoginApprovedSubject.asObservable()}getAdminAuthRequest(e){return _h(this,void 0,void 0,function*(){if(null==e)throw new Error("User ID is required");const t=yield Ce(this.stateProvider.getUser(e,xh).state$);return wh.fromJSON(t)})}setAdminAuthRequest(e,t){return _h(this,void 0,void 0,function*(){if(null==t)throw new Error("User ID is required");if(null==e)throw new Error("Auth request is required");yield this.stateProvider.setUserState(xh,e.toJSON(),t)})}clearAdminAuthRequest(e){return _h(this,void 0,void 0,function*(){if(null==e)throw new Error("User ID is required");yield this.stateProvider.setUserState(xh,null,e)})}getPendingAuthRequests$(){return nc(()=>this.authRequestApiService.getPendingAuthRequests()).pipe(X(e=>e.data.map(e=>new Sh(e))))}getLatestPendingAuthRequest$(){return this.getPendingAuthRequests$().pipe(X(e=>0===e.length?null:e.sort((e,t)=>{const i=new Date(e.creationDate).getTime();return new Date(t.creationDate).getTime()-i})[0]))}approveOrDenyAuthRequest(e,t){return _h(this,void 0,void 0,function*(){const i=yield Ce(this.accountService.activeAccount$.pipe(tu));if(!t.id)throw new Error("Auth request has no id");if(!t.publicKey)throw new Error("Auth request has no public key");if(null==i)throw new Error("User ID is required");const r=Tt.fromB64ToArray(t.publicKey),n=yield Ce(this.keyService.userKey$(i)),a=yield this.encryptService.encapsulateKeyUnsigned(n,r),s=new kh(a.encryptedString,void 0,yield this.appIdService.getAppId(),e);return yield this.apiService.putAuthRequest(t.id,s)})}setUserKeyAfterDecryptingSharedUserKey(e,t,i){return _h(this,void 0,void 0,function*(){const r=yield this.decryptPubKeyEncryptedUserKey(e.key,t);yield this.keyService.setUserKey(r,i)})}decryptPubKeyEncryptedUserKey(e,t){return _h(this,void 0,void 0,function*(){return yield this.encryptService.decapsulateKeyUnsigned(new Nt(e),t)})}sendAuthRequestPushNotification(e){null!=e.id&&this.authRequestPushNotificationSubject.next(e.id)}getFingerprintPhrase(e,t){return _h(this,void 0,void 0,function*(){return(yield this.keyService.getFingerprint(e.toLowerCase(),t)).join("-")})}emitAdminLoginApproved(){this.adminLoginApprovedSubject.next()}}var Ih=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Eh{constructor(e,t){this.apiService=e,this.logService=t}getPendingAuthRequests(){return Ih(this,void 0,void 0,function*(){const e=yield this.apiService.send("GET","/auth-requests/pending",null,!0,!0);return new Tc(e,Sh)})}getAuthRequest(e){return Ih(this,void 0,void 0,function*(){try{const t=`/auth-requests/${e}`,i=yield this.apiService.send("GET",t,null,!0,!0);return new Sh(i)}catch(e){throw this.logService.error(e),e}})}getAuthResponse(e,t){return Ih(this,void 0,void 0,function*(){try{const i=`/auth-requests/${e}/response?code=${t}`,r=yield this.apiService.send("GET",i,null,!1,!0);return new Sh(r)}catch(e){throw this.logService.error(e),e}})}postAdminAuthRequest(e){return Ih(this,void 0,void 0,function*(){try{const t=yield this.apiService.send("POST","/auth-requests/admin-request",e,!0,!0);return new Sh(t)}catch(e){throw this.logService.error(e),e}})}postAuthRequest(e){return Ih(this,void 0,void 0,function*(){try{const t=yield this.apiService.send("POST","/auth-requests/",e,!1,!0,null,t=>{t.set("Device-Identifier",e.deviceIdentifier)});return new Sh(t)}catch(e){throw this.logService.error(e),e}})}}function zh(e,t,i){if(null==e)throw new Error(`${t} is null or undefined.${i?` ${i}`:""}`)}var Ph=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Ah{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m){this.accountService=e,this.biometricService=t,this.vaultTimeoutSettingsService=i,this.logoutService=r,this.messagingService=n,this.searchService=a,this.folderService=s,this.masterPasswordService=o,this.stateEventRunnerService=l,this.cipherService=c,this.authService=u,this.systemService=d,this.processReloadService=h,this.logService=p,this.keyService=m}lockAll(){return Ph(this,void 0,void 0,function*(){const e=yield Ce(ai([this.accountService.activeAccount$,this.accountService.accounts$]).pipe(X(([e,t])=>{const i=Object.keys(t);return null==e?{activeAccount:null,otherAccounts:i}:{activeAccount:e.id,otherAccounts:i.filter(t=>t!==e.id)}})));for(const t of e.otherAccounts)yield this.lock(t);null!=e.activeAccount&&(yield this.lock(e.activeAccount))})}lock(e){return Ph(this,void 0,void 0,function*(){if(zh(e,"userId","LockService"),this.logService.info(`[LockService] Locking user ${e}`),(yield Ce(this.authService.authStatusFor$(e)))!==cu.LoggedOut){if(!(yield this.vaultTimeoutSettingsService.canLock(e)))return yield this.logoutService.logout(e,"vaultTimeout"),void this.logService.info(`[LockService] User ${e} cannot lock, logging out instead.`);yield this.wipeDecryptedState(e),yield this.waitForLockedStatus(e),yield this.systemService.clearPendingClipboard(),yield this.runPlatformOnLockActions(),this.logService.info(`[LockService] Locked user ${e}`),yield this.biometricService.setShouldAutopromptNow(!1),this.messagingService.send("locked",{userId:e}),yield this.processReloadService.startProcessReload()}})}wipeDecryptedState(e){return Ph(this,void 0,void 0,function*(){yield this.searchService.clearIndex(e),yield this.folderService.clearDecryptedFolderState(e),yield this.masterPasswordService.clearMasterKey(e),yield this.cipherService.clearCache(e),yield this.keyService.clearStoredUserKey(e),yield this.stateEventRunnerService.handleEvent("lock",e)})}waitForLockedStatus(e){return Ph(this,void 0,void 0,function*(){yield Ce(this.authService.authStatusFor$(e).pipe(Ie(e=>e===cu.Locked),Fe({first:5e3,with:()=>{throw new Error("The lock process did not complete in a reasonable amount of time.")}})))})}runPlatformOnLockActions(){return Ph(this,void 0,void 0,function*(){})}}class jh{constructor(e){this.messagingService=e}logout(e,t){return i=this,r=void 0,a=function*(){this.messagingService.send("logout",{userId:e,logoutReason:t})},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}}class Th{constructor(){this.enabled=!1,this.showSetupDialog=!0}}const Dh=wi.record(Ci,"autoConfirm",{deserializer:e=>e,clearOn:[]}),Oh=e=>X(t=>t.find(t=>t.id===e));var Nh,Rh,Uh,Fh,qh,Lh,Bh,Mh,Vh,$h,Kh,Wh,Hh,Gh=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Qh{constructor(e,t,i,r,n,a,s){this.configService=e,this.apiService=t,this.organizationUserService=i,this.stateProvider=r,this.organizationService=n,this.organizationUserApiService=a,this.policyService=s}autoConfirmState(e){return this.stateProvider.getUser(e,Dh)}configuration$(e){return this.autoConfirmState(e).state$.pipe(X(t=>{var i;return null!==(i=null==t?void 0:t[e])&&void 0!==i?i:new Th}))}upsert(e,t){return Gh(this,void 0,void 0,function*(){yield this.autoConfirmState(e).update(i=>Object.assign(Object.assign({},i),{[e]:t}))})}canManageAutoConfirm$(e){return ai([this.configService.getFeatureFlag$(Ne.AutoConfirm),this.organizationService.organizations$(e).pipe(X(e=>e[0])),this.policyService.policyAppliesToUser$(Ye.AutoConfirm,e)]).pipe(X(([e,t,i])=>{var r;return e&&i&&null!==(r=null==t?void 0:t.canManageAutoConfirm)&&void 0!==r&&r}))}autoConfirmUser(e,t,i){return Gh(this,void 0,void 0,function*(){if(!(yield Ce(this.canManageAutoConfirm$(e))))return;if(!(yield Ce(this.configuration$(e).pipe(X(e=>e.enabled)))))return;const r=this.organizationService.organizations$(e).pipe(Oh(i),X(e=>{if(null==e)throw new Error("Organization not found");return e})),n=yield this.apiService.getUserPublicKey(e),a=Tt.fromB64ToArray(n.publicKey);yield Ce(r.pipe(Le(e=>this.organizationUserService.buildConfirmRequest(e,a)),Le(e=>this.organizationUserApiService.postOrganizationUserAutoConfirm(i,t,e))))})}}!function(e){e[e.None=0]="None",e[e.OpenIdConnect=1]="OpenIdConnect",e[e.Saml2=2]="Saml2"}(Nh||(Nh={})),function(e){e[e.MasterPassword=0]="MasterPassword",e[e.KeyConnector=1]="KeyConnector",e[e.TrustedDeviceEncryption=2]="TrustedDeviceEncryption"}(Rh||(Rh={})),function(e){e[e.RedirectGet=0]="RedirectGet",e[e.FormPost=1]="FormPost"}(Uh||(Uh={})),function(e){e[e.HttpRedirect=1]="HttpRedirect",e[e.HttpPost=2]="HttpPost"}(Fh||(Fh={})),function(e){e[e.NotConfigured=0]="NotConfigured",e[e.Unspecified=1]="Unspecified",e[e.EmailAddress=2]="EmailAddress",e[e.X509SubjectName=3]="X509SubjectName",e[e.WindowsDomainQualifiedName=4]="WindowsDomainQualifiedName",e[e.KerberosPrincipalName=5]="KerberosPrincipalName",e[e.EntityIdentifier=6]="EntityIdentifier",e[e.Persistent=7]="Persistent",e[e.Transient=8]="Transient"}(qh||(qh={})),function(e){e[e.IfIdpWantAuthnRequestsSigned=0]="IfIdpWantAuthnRequestsSigned",e[e.Always=1]="Always",e[e.Never=3]="Never"}(Lh||(Lh={})),function(e){e[e.Card=0]="Card",e[e.BankAccount=1]="BankAccount",e[e.PayPal=2]="PayPal",e[e.BitPay=3]="BitPay",e[e.Credit=4]="Credit",e[e.WireTransfer=5]="WireTransfer",e[e.Check=8]="Check"}(Bh||(Bh={})),function(e){e[e.FamiliesForEnterprise=0]="FamiliesForEnterprise"}(Mh||(Mh={})),function(e){e[e.Free=0]="Free",e[e.FamiliesAnnually2019=1]="FamiliesAnnually2019",e[e.TeamsMonthly2019=2]="TeamsMonthly2019",e[e.TeamsAnnually2019=3]="TeamsAnnually2019",e[e.EnterpriseMonthly2019=4]="EnterpriseMonthly2019",e[e.EnterpriseAnnually2019=5]="EnterpriseAnnually2019",e[e.Custom=6]="Custom",e[e.FamiliesAnnually2025=7]="FamiliesAnnually2025",e[e.TeamsMonthly2020=8]="TeamsMonthly2020",e[e.TeamsAnnually2020=9]="TeamsAnnually2020",e[e.EnterpriseMonthly2020=10]="EnterpriseMonthly2020",e[e.EnterpriseAnnually2020=11]="EnterpriseAnnually2020",e[e.TeamsMonthly2023=12]="TeamsMonthly2023",e[e.TeamsAnnually2023=13]="TeamsAnnually2023",e[e.EnterpriseMonthly2023=14]="EnterpriseMonthly2023",e[e.EnterpriseAnnually2023=15]="EnterpriseAnnually2023",e[e.TeamsStarter2023=16]="TeamsStarter2023",e[e.TeamsMonthly=17]="TeamsMonthly",e[e.TeamsAnnually=18]="TeamsAnnually",e[e.EnterpriseMonthly=19]="EnterpriseMonthly",e[e.EnterpriseAnnually=20]="EnterpriseAnnually",e[e.TeamsStarter=21]="TeamsStarter",e[e.FamiliesAnnually=22]="FamiliesAnnually"}(Vh||(Vh={})),function(e){e[e.Charge=0]="Charge",e[e.Credit=1]="Credit",e[e.PromotionalCredit=2]="PromotionalCredit",e[e.ReferralCredit=3]="ReferralCredit",e[e.Refund=4]="Refund"}($h||($h={})),function(e){e[e.Free=0]="Free",e[e.Families=1]="Families",e[e.Teams=2]="Teams",e[e.Enterprise=3]="Enterprise",e[e.TeamsStarter=4]="TeamsStarter"}(Kh||(Kh={})),function(e){e[e.PasswordManager=0]="PasswordManager",e[e.SecretsManager=1]="SecretsManager"}(Wh||(Wh={})),function(e){e[e.Monthly=0]="Monthly",e[e.Annually=1]="Annually"}(Hh||(Hh={}));class Jh{constructor(e){var t;null!=e&&(this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.usePolicies=e.usePolicies,this.useGroups=e.useGroups,this.useDirectory=e.useDirectory,this.useEvents=e.useEvents,this.useTotp=e.useTotp,this.use2fa=e.use2fa,this.useApi=e.useApi,this.useSso=e.useSso,this.useOrganizationDomains=e.useOrganizationDomains,this.useKeyConnector=e.useKeyConnector,this.useScim=e.useScim,this.useCustomPermissions=e.useCustomPermissions,this.useResetPassword=e.useResetPassword,this.useSecretsManager=e.useSecretsManager,this.usePasswordManager=e.usePasswordManager,this.useActivateAutofillPolicy=e.useActivateAutofillPolicy,this.useAutomaticUserConfirmation=e.useAutomaticUserConfirmation,this.selfHost=e.selfHost,this.usersGetPremium=e.usersGetPremium,this.seats=e.seats,this.maxCollections=e.maxCollections,this.maxStorageGb=e.maxStorageGb,this.ssoBound=e.ssoBound,this.identifier=e.identifier,this.permissions=e.permissions,this.resetPasswordEnrolled=e.resetPasswordEnrolled,this.userId=e.userId,this.organizationUserId=e.organizationUserId,this.hasPublicAndPrivateKeys=e.hasPublicAndPrivateKeys,this.providerId=e.providerId,this.providerName=e.providerName,this.providerType=e.providerType,this.isProviderUser=e.isProviderUser,this.isMember=e.isMember,this.familySponsorshipFriendlyName=e.familySponsorshipFriendlyName,this.familySponsorshipAvailable=e.familySponsorshipAvailable,this.productTierType=e.productTierType,this.keyConnectorEnabled=e.keyConnectorEnabled,this.keyConnectorUrl=e.keyConnectorUrl,this.familySponsorshipLastSyncDate=e.familySponsorshipLastSyncDate,this.familySponsorshipValidUntil=e.familySponsorshipValidUntil,this.familySponsorshipToDelete=e.familySponsorshipToDelete,this.accessSecretsManager=e.accessSecretsManager,this.limitCollectionCreation=e.limitCollectionCreation,this.limitCollectionDeletion=e.limitCollectionDeletion,this.limitItemDeletion=e.limitItemDeletion,this.allowAdminAccessToAllCollectionItems=e.allowAdminAccessToAllCollectionItems,this.userIsManagedByOrganization=e.userIsManagedByOrganization,this.useAccessIntelligence=e.useAccessIntelligence,this.useAdminSponsoredFamilies=e.useAdminSponsoredFamilies,this.useDisableSMAdsForUsers=null!==(t=e.useDisableSMAdsForUsers)&&void 0!==t&&t,this.isAdminInitiated=e.isAdminInitiated,this.ssoEnabled=e.ssoEnabled,this.ssoMemberDecryptionType=e.ssoMemberDecryptionType,this.usePhishingBlocker=e.usePhishingBlocker)}get canAccess(){return!!this.isOwner||this.enabled&&this.status===Qe.Confirmed}get isAdmin(){return this.type===Je.Admin||this.isOwner}get isOwner(){return this.type===Je.Owner||this.isProviderUser}get canAccessEventLogs(){return(this.isAdmin||this.permissions.accessEventLogs)&&this.useEvents}get canAccessImport(){return this.isProviderUser||this.type===Je.Owner||this.type===Je.Admin||this.permissions.accessImportExport}get canAccessExport(){return this.isMember&&(this.type===Je.Owner||this.type===Je.Admin||this.permissions.accessImportExport)}get canAccessReports(){return this.isAdmin||this.permissions.accessReports}get canCreateNewCollections(){return!this.limitCollectionCreation||this.isAdmin||this.permissions.createNewCollections}get canEditAnyCollection(){return this.isProviderUser||this.type===Je.Custom&&this.permissions.editAnyCollection||this.allowAdminAccessToAllCollectionItems&&this.isAdmin}get canEditUnmanagedCollections(){return this.isAdmin||this.permissions.editAnyCollection}get canEditUnassignedCiphers(){return this.type===Je.Admin||this.type===Je.Owner||this.permissions.editAnyCollection}get canEditAllCiphers(){return this.type===Je.Custom&&this.permissions.editAnyCollection||this.allowAdminAccessToAllCollectionItems&&(this.type===Je.Admin||this.type===Je.Owner)}get canDeleteAnyCollection(){return!(!this.isProviderUser&&!this.permissions.deleteAnyCollection&&(!this.allowAdminAccessToAllCollectionItems||this.type!=Je.Owner&&this.type!=Je.Admin))}get canViewAllCollections(){return this.isAdmin||this.permissions.editAnyCollection||this.permissions.deleteAnyCollection}get canManageGroups(){return(this.isAdmin||this.permissions.manageGroups)&&this.useGroups}get canManageSso(){return(this.isAdmin||this.permissions.manageSso)&&this.useSso}get canManageDomainVerification(){return(this.isAdmin||this.permissions.manageSso)&&this.useOrganizationDomains}get canManageScim(){return(this.isAdmin||this.permissions.manageScim)&&this.useScim}get canManagePolicies(){return(this.isAdmin||this.permissions.managePolicies)&&this.usePolicies}get canManageUsers(){return this.isAdmin||this.permissions.manageUsers}get canManageUsersPassword(){return this.isAdmin||this.permissions.manageResetPassword}get canEnableAutoConfirmPolicy(){return(this.canManageUsers||this.canManagePolicies)&&this.useAutomaticUserConfirmation&&!this.isProviderUser}get canManageDeviceApprovals(){return(this.isAdmin||this.permissions.manageResetPassword)&&this.useSso&&this.ssoEnabled&&this.ssoMemberDecryptionType===Rh.TrustedDeviceEncryption}get isExemptFromPolicies(){return this.canManagePolicies}get canViewSubscription(){return!!this.canEditSubscription||(this.hasBillableProvider?this.isProviderUser:this.isOwner)}get canEditSubscription(){return this.hasProvider?this.isProviderUser:this.isOwner}get canEditPaymentMethods(){return this.canEditSubscription}get canViewBillingHistory(){return this.canEditSubscription}get hasProvider(){return null!=this.providerId||null!=this.providerName}get hasBillableProvider(){return this.hasProvider&&(this.providerType===Xe.Msp||this.providerType===Xe.BusinessUnit)}get hasReseller(){return this.hasProvider&&this.providerType===Xe.Reseller}get canAccessSecretsManager(){return this.useSecretsManager&&this.accessSecretsManager}get isFreeOrg(){return!this.useTotp}get canManageSponsorships(){return this.familySponsorshipAvailable||null!==this.familySponsorshipFriendlyName}get canManageAutoConfirm(){return this.isMember&&this.canManageUsers&&this.useAutomaticUserConfirmation}static fromJSON(e){return null==e?null:Object.assign(new Jh,e,{familySponsorshipLastSyncDate:new Date(e.familySponsorshipLastSyncDate),familySponsorshipValidUntil:new Date(e.familySponsorshipValidUntil)})}get canAccessIntegrations(){return(this.productTierType===Kh.Teams||this.productTierType===Kh.Enterprise)&&(this.isAdmin||this.permissions.manageUsers||this.permissions.manageGroups||this.permissions.accessEventLogs)}get canUseAccessIntelligence(){return this.productTierType===Kh.Enterprise}}class Yh{constructor(e,t){var i;null!=e&&(this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.usePolicies=e.usePolicies,this.useGroups=e.useGroups,this.useDirectory=e.useDirectory,this.useEvents=e.useEvents,this.useTotp=e.useTotp,this.use2fa=e.use2fa,this.useApi=e.useApi,this.useSso=e.useSso,this.useOrganizationDomains=e.useOrganizationDomains,this.useKeyConnector=e.useKeyConnector,this.useScim=e.useScim,this.useCustomPermissions=e.useCustomPermissions,this.useResetPassword=e.useResetPassword,this.useSecretsManager=e.useSecretsManager,this.usePasswordManager=e.usePasswordManager,this.useActivateAutofillPolicy=e.useActivateAutofillPolicy,this.useAutomaticUserConfirmation=e.useAutomaticUserConfirmation,this.selfHost=e.selfHost,this.usersGetPremium=e.usersGetPremium,this.seats=e.seats,this.maxCollections=e.maxCollections,this.maxStorageGb=e.maxStorageGb,this.ssoBound=e.ssoBound,this.identifier=e.identifier,this.permissions=e.permissions,this.resetPasswordEnrolled=e.resetPasswordEnrolled,this.userId=e.userId,this.organizationUserId=e.organizationUserId,this.hasPublicAndPrivateKeys=e.hasPublicAndPrivateKeys,this.providerId=e.providerId,this.providerName=e.providerName,this.providerType=e.providerType,this.familySponsorshipFriendlyName=e.familySponsorshipFriendlyName,this.familySponsorshipAvailable=e.familySponsorshipAvailable,this.productTierType=e.productTierType,this.keyConnectorEnabled=e.keyConnectorEnabled,this.keyConnectorUrl=e.keyConnectorUrl,this.familySponsorshipLastSyncDate=e.familySponsorshipLastSyncDate,this.familySponsorshipValidUntil=e.familySponsorshipValidUntil,this.familySponsorshipToDelete=e.familySponsorshipToDelete,this.accessSecretsManager=e.accessSecretsManager,this.limitCollectionCreation=e.limitCollectionCreation,this.limitCollectionDeletion=e.limitCollectionDeletion,this.limitItemDeletion=e.limitItemDeletion,this.allowAdminAccessToAllCollectionItems=e.allowAdminAccessToAllCollectionItems,this.userIsManagedByOrganization=e.userIsManagedByOrganization,this.useAccessIntelligence=e.useAccessIntelligence,this.useAdminSponsoredFamilies=e.useAdminSponsoredFamilies,this.useDisableSMAdsForUsers=null!==(i=e.useDisableSMAdsForUsers)&&void 0!==i&&i,this.isAdminInitiated=e.isAdminInitiated,this.ssoEnabled=e.ssoEnabled,this.ssoMemberDecryptionType=e.ssoMemberDecryptionType,this.usePhishingBlocker=e.usePhishingBlocker,this.isMember=t.isMember,this.isProviderUser=t.isProviderUser)}static fromJSON(e){return Object.assign(new Yh,e,{familySponsorshipLastSyncDate:null!=e.familySponsorshipLastSyncDate?new Date(e.familySponsorshipLastSyncDate):e.familySponsorshipLastSyncDate,familySponsorshipValidUntil:null!=e.familySponsorshipValidUntil?new Date(e.familySponsorshipValidUntil):e.familySponsorshipValidUntil})}}const Xh=wi.record(Si,"organizations",{deserializer:e=>Yh.fromJSON(e),clearOn:["logout"]});var Zh=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};function ep(){return X(e=>e.length>0)}class tp{memberOrganizations$(e){return this.organizations$(e).pipe(X(e=>e.filter(e=>e.isMember)))}constructor(e){this.stateProvider=e}canManageSponsorships$(e){return this.organizations$(e).pipe(X(e=>e.filter(e=>e.canManageSponsorships)),ep())}familySponsorshipAvailable$(e){return this.organizations$(e).pipe(X(e=>e.some(e=>e.familySponsorshipAvailable)))}hasOrganizations(e){return this.organizations$(e).pipe(ep())}upsert(e,t){return Zh(this,void 0,void 0,function*(){yield this.organizationState(t).update(t=>{const i=null!=t?t:{};return i[e.id]=e,i})})}replace(e,t){return Zh(this,void 0,void 0,function*(){yield this.organizationState(t).update(()=>e)})}organizations$(e){return this.organizationState(e).state$.pipe(this.mapOrganizationRecordToArray())}organizationState(e){return this.stateProvider.getUser(e,Xh)}mapOrganizationRecordToArray(){return X(e=>{var t;return null===(t=Object.values(null!=e?e:{}))||void 0===t?void 0:t.map(e=>new Jh(e))})}}class ip extends Lt{constructor(e){var t;super(e),this.id=this.getResponseProperty("Id"),this.organizationId=this.getResponseProperty("OrganizationId"),this.type=this.getResponseProperty("Type"),this.data=this.getResponseProperty("Data"),this.enabled=this.getResponseProperty("Enabled"),this.canToggleState=null===(t=this.getResponseProperty("CanToggleState"))||void 0===t||t,this.revisionDate=this.getResponseProperty("RevisionDate")}}var rp=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class np{constructor(e,t,i){this.policyService=e,this.apiService=t,this.accountService=i}getPolicy(e,t){return rp(this,void 0,void 0,function*(){const i=yield this.apiService.send("GET","/organizations/"+e+"/policies/"+t,null,!0,!0);return new ip(i)})}getPolicies(e){return rp(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET","/organizations/"+e+"/policies",null,!0,!0);return new Tc(t,ip)})}getPoliciesByToken(e,t,i,r){return rp(this,void 0,void 0,function*(){const n=yield this.apiService.send("GET","/organizations/"+e+"/policies/token?token="+encodeURIComponent(t)+"&email="+Tt.encodeRFC3986URIComponent(i)+"&organizationUserId="+r,null,!1,!0);return td.fromListResponse(new Tc(n,ip))})}getMasterPasswordPolicyResponseForOrgUser(e){return rp(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET","/organizations/"+e+"/policies/master-password",null,!0,!0);return new ip(t)})}getMasterPasswordPolicyOptsForOrgUser(e){return rp(this,void 0,void 0,function*(){try{const t=yield this.getMasterPasswordPolicyResponseForOrgUser(e),i=td.fromResponse(t);return i?Ce(this.accountService.activeAccount$.pipe(tu,Le(e=>this.policyService.masterPasswordPolicyOptions$(e,[i])),X(e=>null!=e?e:null))):null}catch(e){if(e instanceof Su&&e.statusCode===lh.NotFound)return null;throw e}})}putPolicy(e,t,i){return rp(this,void 0,void 0,function*(){const r=yield this.apiService.send("PUT","/organizations/"+e+"/policies/"+t,i,!0,!0);yield this.handleResponse(r)})}putPolicyVNext(e,t,i){return rp(this,void 0,void 0,function*(){const r=yield this.apiService.send("PUT",`/organizations/${e}/policies/${t}/vnext`,i,!0,!0);yield this.handleResponse(r)})}handleResponse(e){return rp(this,void 0,void 0,function*(){const t=yield Ce(this.accountService.activeAccount$.pipe(tu)),i=new ip(e),r=new ed(i);yield this.policyService.upsert(r,t)})}}class ap{constructor(e){null!=e&&(this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.userId=e.userId,this.useEvents=e.useEvents,this.providerStatus=e.providerStatus,this.providerType=e.providerType)}get canAccess(){return!!this.isProviderAdmin||this.enabled&&this.status===Ze.Confirmed}get canCreateOrganizations(){return this.enabled&&this.isProviderAdmin}get canManageUsers(){return this.isProviderAdmin}get canAccessEventLogs(){return this.isProviderAdmin}get isProviderAdmin(){return this.type===et.ProviderAdmin}}const sp=wi.record(xi,"providers",{deserializer:e=>e,clearOn:["logout"]});class op{constructor(e){this.stateProvider=e}providers$(e){return this.stateProvider.getUser(e,sp).state$.pipe(this.mapProviderRecordToArray())}mapProviderRecordToArray(){return X(e=>Object.values(null!=e?e:{}).map(e=>new ap(e)))}get$(e,t){return this.providers$(t).pipe(Oh(e))}save(e,t){return i=this,r=void 0,a=function*(){yield this.stateProvider.setUserState(sp,e,t)},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}}const lp=Object.freeze({AuthRequest:"authRequest"});var cp=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const up=fi.array(zi,"pendingAuthRequests",{deserializer:e=>e});class dp{constructor(e){this.stateProvider=e,this.state=this.stateProvider.getGlobal(up)}getAll$(){return this.state.state$}add(e){return cp(this,void 0,void 0,function*(){const t=Date.now();yield this.stateProvider.getGlobal(up).update(i=>[...(null!=i?i:[]).filter(t=>t.userId!==e),{userId:e,receivedAtMs:t}])})}pruneOlderThan(e){return cp(this,void 0,void 0,function*(){const t=Date.now()-e;yield this.stateProvider.getGlobal(up).update(e=>(null!=e?e:[]).filter(e=>e.receivedAtMs>=t))})}clear(e){return cp(this,void 0,void 0,function*(){yield this.stateProvider.getGlobal(up).update(t=>(null!=t?t:[]).filter(t=>t.userId!==e))})}}class hp{constructor(e,t,i,r,n,a){this.accountService=e,this.messageSender=t,this.keyService=i,this.apiService=r,this.stateService=n,this.tokenService=a,this.activeAccountStatus$=this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id),Le(e=>this.authStatusFor$(e))),this.authStatuses$=this.accountService.accounts$.pipe(X(e=>Object.keys(e)),Le(e=>0===e.length?bt([]):ai(e.map(e=>this.authStatusFor$(e).pipe(X(t=>({userId:e,status:t})))))),X(e=>e.reduce((e,{userId:t,status:i})=>(e[t]=i,e),{})))}authStatusFor$(e){return Tt.isGuid(e)?ai([this.keyService.getInMemoryUserKeyFor$(e),this.tokenService.hasAccessToken$(e)]).pipe(X(([e,t])=>t?e?cu.Unlocked:cu.Locked:cu.LoggedOut),Zl(),Jt({bufferSize:1,refCount:!1})):bt(cu.LoggedOut)}getAuthStatus(e){return t=this,i=void 0,n=function*(){return null!=e||(e=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id)))),yield Ce(this.authStatusFor$(e))},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}logOut(e,t){e(),this.messageSender.send("loggedOut",{userId:t})}}class pp{constructor(e){this.avatarColor=e}}var mp=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const gp=new wi(Pi,"avatarColor",{deserializer:e=>e,clearOn:[]});class fp{constructor(e,t){this.apiService=e,this.stateProvider=t,this.avatarColor$=this.stateProvider.getActive(gp).state$}setAvatarColor(e){return mp(this,void 0,void 0,function*(){const{avatarColor:t}=yield this.apiService.putAvatar(new pp(e));yield this.stateProvider.setUserState(gp,t)})}setSyncAvatarColor(e,t){return mp(this,void 0,void 0,function*(){yield this.stateProvider.getUser(e,gp).update(()=>t)})}getUserAvatarColor$(e){return this.stateProvider.getUser(e,gp).state$}}class yp{constructor(e){this.accountService=e,this.activeUserId$=this.accountService.activeAccount$.pipe(X(e=>null!=e?e.id:null))}}class vp{constructor(e){Object.assign(this,e),this.response=e}}class bp{constructor(e,t,i){this.appIdService=e,this.devicesApiService=t,this.i18nService=i}getDevices$(){return nc(()=>this.devicesApiService.getDevices()).pipe(X(e=>e.data.map(e=>new vp(e))))}getDeviceByIdentifier$(e){return nc(()=>this.devicesApiService.getDeviceByIdentifier(e)).pipe(X(e=>new vp(e)))}isDeviceKnownForUser$(e,t){return nc(()=>this.devicesApiService.getKnownDevice(e,t))}updateTrustedDeviceKeys$(e,t,i,r){return nc(()=>this.devicesApiService.updateTrustedDeviceKeys(e,t,i,r)).pipe(X(e=>new vp(e)))}deactivateDevice$(e){return nc(()=>this.devicesApiService.deactivateDevice(e))}getCurrentDevice$(){return nc(()=>{return e=this,t=void 0,r=function*(){const e=yield this.appIdService.getAppId();return this.devicesApiService.getDeviceByIdentifier(e)},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r})}getReadableDeviceTypeName(e){if(void 0===e)return this.i18nService.t("unknownDevice");const t=ah[e];if(!t)return this.i18nService.t("unknownDevice");const i="Unknown"===t.platform?this.i18nService.t("unknown"):t.platform,r=this.i18nService.t(t.category);return i?`${r} - ${i}`:r}}class wp extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.name=this.getResponseProperty("Name"),this.identifier=this.getResponseProperty("Identifier"),this.type=this.getResponseProperty("Type"),this.creationDate=this.getResponseProperty("CreationDate"),this.revisionDate=this.getResponseProperty("RevisionDate"),this.isTrusted=this.getResponseProperty("IsTrusted"),this.encryptedUserKey=this.getResponseProperty("EncryptedUserKey"),this.encryptedPublicKey=this.getResponseProperty("EncryptedPublicKey"),this.devicePendingAuthRequest=this.getResponseProperty("DevicePendingAuthRequest")}}class kp{constructor(e){this.devices=e}}class Sp{constructor(e,t,i){this.encapsulatedDownstreamKey=e,this.encryptedPublicKey=t,this.encryptedPrivateKey=i}}class _p extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("id"),this.name=this.getResponseProperty("name"),this.identifier=this.getResponseProperty("identifier"),this.type=this.getResponseProperty("type"),this.creationDate=new Date(this.getResponseProperty("creationDate")),e.encryptedUserKey&&(this.encryptedUserKey=new Nt(this.getResponseProperty("encryptedUserKey"))),e.encryptedPublicKey&&(this.encryptedPublicKey=new Nt(this.getResponseProperty("encryptedPublicKey")))}getRotateableKeyset(){return new Sp(this.encryptedUserKey,this.encryptedPublicKey)}isTrusted(){return null!=this.encryptedUserKey&&null!=this.encryptedPublicKey}}class xp{constructor(e,t,i){this.encryptedUserKey=e,this.encryptedPublicKey=t,this.encryptedPrivateKey=i}}var Cp=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Ip{constructor(e){this.apiService=e}getKnownDevice(e,t){return Cp(this,void 0,void 0,function*(){return yield this.apiService.send("GET","/devices/knowndevice",null,!1,!0,null,i=>{i.set("X-Device-Identifier",t),i.set("X-Request-Email",Tt.fromUtf8ToUrlB64(e))})})}getDeviceByIdentifier(e){return Cp(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET",`/devices/identifier/${e}`,null,!0,!0);return new wp(t)})}getDevices(){return Cp(this,void 0,void 0,function*(){const e=yield this.apiService.send("GET","/devices",null,!0,!0,null);return new Tc(e,wp)})}updateTrustedDeviceKeys(e,t,i,r){return Cp(this,void 0,void 0,function*(){const n=new xp(t,i,r),a=yield this.apiService.send("PUT",`/devices/${e}/keys`,n,!0,!0);return new wp(a)})}updateTrust(e,t){return Cp(this,void 0,void 0,function*(){yield this.apiService.send("POST","/devices/update-trust",e,!0,!1,null,e=>{e.set("Device-Identifier",t)})})}getDeviceKeys(e){return Cp(this,void 0,void 0,function*(){const t=yield this.apiService.send("POST",`/devices/${e}/retrieve-keys`,null,!0,!0);return new _p(t)})}postDeviceTrustLoss(e){return Cp(this,void 0,void 0,function*(){yield this.apiService.send("POST","/devices/lost-trust",null,!0,!1,null,t=>{t.set("Device-Identifier",e)})})}deactivateDevice(e){return Cp(this,void 0,void 0,function*(){yield this.apiService.send("POST",`/devices/${e}/deactivate`,null,!0,!1)})}untrustDevices(e){return Cp(this,void 0,void 0,function*(){yield this.apiService.send("POST","/devices/untrust",new kp(e),!0,!1)})}}var Ep=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const zp=new fi(Ui,"ssoCodeVerifier",{deserializer:e=>e}),Pp=new fi(Ui,"ssoState",{deserializer:e=>e}),Ap=new wi(Ui,"organizationSsoIdentifier",{deserializer:e=>e,clearOn:["logout"]}),jp=new fi(Ui,"organizationSsoIdentifier",{deserializer:e=>e}),Tp=new fi(Ui,"ssoEmail",{deserializer:e=>e}),Dp=new fi(Fi,"ssoRequiredCache",{deserializer:e=>e});class Op{constructor(e,t,i){this.stateProvider=e,this.logService=t,this.policyService=i,this.codeVerifierState=this.stateProvider.getGlobal(zp),this.ssoState=this.stateProvider.getGlobal(Pp),this.orgSsoIdentifierState=this.stateProvider.getGlobal(jp),this.ssoEmailState=this.stateProvider.getGlobal(Tp),this.ssoRequiredCacheState=this.stateProvider.getGlobal(Dp),this.ssoRequiredCache$=this.ssoRequiredCacheState.state$.pipe(X(e=>new Set(e)))}getCodeVerifier(){return Ce(this.codeVerifierState.state$)}setCodeVerifier(e){return Ep(this,void 0,void 0,function*(){yield this.codeVerifierState.update(t=>e)})}getSsoState(){return Ce(this.ssoState.state$)}setSsoState(e){return Ep(this,void 0,void 0,function*(){yield this.ssoState.update(t=>e)})}getOrganizationSsoIdentifier(){return Ce(this.orgSsoIdentifierState.state$)}setOrganizationSsoIdentifier(e){return Ep(this,void 0,void 0,function*(){yield this.orgSsoIdentifierState.update(t=>e)})}getSsoEmail(){return Ce(this.ssoEmailState.state$)}setSsoEmail(e){return Ep(this,void 0,void 0,function*(){yield this.ssoEmailState.update(t=>e)})}clearSsoEmail(){return Ep(this,void 0,void 0,function*(){yield this.ssoEmailState.update(e=>null)})}getActiveUserOrganizationSsoIdentifier(e){return Ce(this.userOrgSsoIdentifierState(e).state$)}setActiveUserOrganizationSsoIdentifier(e,t){return Ep(this,void 0,void 0,function*(){void 0!==t?yield this.userOrgSsoIdentifierState(t).update(t=>e):this.logService.error("Tried to set a user organization sso identifier with an undefined user id.")})}userOrgSsoIdentifierState(e){return this.stateProvider.getUser(e,Ap)}addToSsoRequiredCache(e){return Ep(this,void 0,void 0,function*(){yield this.ssoRequiredCacheState.update(t=>null==t?[e]:[...t,e],{shouldUpdate:t=>null==t||!t.includes(e)})})}removeFromSsoRequiredCacheIfPresent(e){return Ep(this,void 0,void 0,function*(){yield this.ssoRequiredCacheState.update(t=>{var i;return null!==(i=null==t?void 0:t.filter(t=>t!==e))&&void 0!==i?i:t},{shouldUpdate:t=>null!=t&&t.includes(e)})})}updateSsoRequiredCache(e,t){return Ep(this,void 0,void 0,function*(){(yield Ce(this.policyService.policyAppliesToUser$(Ye.RequireSso,t)))?yield this.addToSsoRequiredCache(e.toLowerCase()):yield this.removeFromSsoRequiredCacheIfPresent(e.toLowerCase())})}}class Np{constructor(e,t,i){this.accessToken=e,this.refreshToken=t,this.clientIdSecretPair=i}}const Rp=new wi(qi,"accessToken",{deserializer:e=>e,clearOn:[]}),Up=new wi(Bi,"accessToken",{deserializer:e=>e,clearOn:[]}),Fp=new wi(qi,"refreshToken",{deserializer:e=>e,clearOn:[]}),qp=new wi(Bi,"refreshToken",{deserializer:e=>e,clearOn:[]}),Lp=fi.record(Li,"emailTwoFactorTokenRecord",{deserializer:e=>e}),Bp=new wi(qi,"apiKeyClientId",{deserializer:e=>e,clearOn:[]}),Mp=new wi(Bi,"apiKeyClientId",{deserializer:e=>e,clearOn:[]}),Vp=new wi(qi,"apiKeyClientSecret",{deserializer:e=>e,clearOn:[]}),$p=new wi(Bi,"apiKeyClientSecret",{deserializer:e=>e,clearOn:[]}),Kp=new wi(Bi,"securityStamp",{deserializer:e=>e,clearOn:["logout"]});var Wp,Hp=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};!function(e){e.Disk="disk",e.SecureStorage="secureStorage",e.Memory="memory"}(Wp||(Wp={}));class Gp{constructor(e,t,i,r,n,a,s,o){this.singleUserStateProvider=e,this.globalStateProvider=t,this.platformSupportsSecureStorage=i,this.secureStorageService=r,this.keyGenerationService=n,this.encryptService=a,this.logService=s,this.logoutCallback=o,this.accessTokenKeySecureStorageKey="_accessTokenKey",this.refreshTokenSecureStorageKey="_refreshToken",this.initializeState()}hasAccessToken$(e){return ai([this.singleUserStateProvider.get(e,Rp).state$,this.singleUserStateProvider.get(e,Up).state$]).pipe(X(([e,t])=>Boolean(e||t)))}initializeState(){this.emailTwoFactorTokenRecordGlobalState=this.globalStateProvider.get(Lp),this.activeUserIdGlobalState=this.globalStateProvider.get(Yc)}setTokens(e,t,i,r,n){return Hp(this,void 0,void 0,function*(){if(!e)throw new Error("Access token is required.");if(null==i)throw new Error("Vault Timeout is required.");if(null==t)throw new Error("Vault Timeout Action is required.");const a=yield this.getUserIdFromAccessToken(e);if(!a)throw new Error("User id not found. Cannot set tokens.");const s=yield this._setAccessToken(e,t,i,a),o=new Np(s);if(r&&(o.refreshToken=yield this.setRefreshToken(r,t,i,a)),null!=n){const e=yield this.setClientId(n[0],t,i,a),r=yield this.setClientSecret(n[1],t,i,a);o.clientIdSecretPair=[e,r]}return o})}getAccessTokenKey(e){return Hp(this,void 0,void 0,function*(){const t=yield this.secureStorageService.get(`${e}${this.accessTokenKeySecureStorageKey}`,this.getSecureStorageOptions(e));return t?gu.fromJSON(t):null})}createAndSaveAccessTokenKey(e){return Hp(this,void 0,void 0,function*(){const t=yield this.keyGenerationService.createKey(512);if(yield this.secureStorageService.save(`${e}${this.accessTokenKeySecureStorageKey}`,t,this.getSecureStorageOptions(e)),!(yield this.getAccessTokenKey(e)))throw new Error("New Access token key unable to be retrieved from secure storage.");return t})}clearAccessTokenKey(e){return Hp(this,void 0,void 0,function*(){yield this.secureStorageService.remove(`${e}${this.accessTokenKeySecureStorageKey}`,this.getSecureStorageOptions(e))})}getOrCreateAccessTokenKey(e){return Hp(this,void 0,void 0,function*(){if(!this.platformSupportsSecureStorage)throw new Error("Platform does not support secure storage. Cannot obtain access token key.");if(!e)throw new Error("User id not found. Cannot obtain access token key.");let t=yield this.getAccessTokenKey(e);return t||(t=yield this.createAndSaveAccessTokenKey(e)),t})}encryptAccessToken(e,t){return Hp(this,void 0,void 0,function*(){const i=yield this.getOrCreateAccessTokenKey(t);return yield this.encryptService.encryptString(e,i)})}decryptAccessToken(e,t){return Hp(this,void 0,void 0,function*(){if(!e)throw new Error("decryptAccessToken: Access token key required. Cannot decrypt access token.");try{return yield this.encryptService.decryptString(t,e)}catch(e){throw this.logService.error("[TokenService] Error decrypting access token",e),e}})}_setAccessToken(e,t,i,r){return Hp(this,void 0,void 0,function*(){switch(yield this.determineStorageLocation(t,i,!0)){case Wp.SecureStorage:{let t=null;try{const i=yield this.encryptAccessToken(e,r);yield this.singleUserStateProvider.get(r,Rp).update(e=>i.encryptedString,{shouldUpdate:e=>e!==i.encryptedString}),t=e,yield this.singleUserStateProvider.get(r,Up).update(e=>null)}catch(i){this.logService.error("SetAccessToken: storing encrypted access token in secure storage failed. Falling back to disk storage.",i),t=yield this.singleUserStateProvider.get(r,Rp).update(t=>e,{shouldUpdate:t=>t!==e})}return t}case Wp.Disk:return yield this.singleUserStateProvider.get(r,Rp).update(t=>e,{shouldUpdate:t=>t!==e});case Wp.Memory:return yield this.singleUserStateProvider.get(r,Up).update(t=>e)}})}setAccessToken(e,t,i){return Hp(this,void 0,void 0,function*(){if(!e)throw new Error("Access token is required.");const r=yield this.getUserIdFromAccessToken(e);if(!r)throw new Error("User id not found. Cannot save access token.");if(null==i)throw new Error("Vault Timeout is required.");if(null==t)throw new Error("Vault Timeout Action is required.");return yield this._setAccessToken(e,t,i,r)})}clearAccessToken(e){return Hp(this,void 0,void 0,function*(){if(null!=e||(e=yield Ce(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear access token.");this.platformSupportsSecureStorage&&(yield this.clearAccessTokenKey(e)),yield this.singleUserStateProvider.get(e,Rp).update(e=>null,{shouldUpdate:e=>null!==e}),yield this.singleUserStateProvider.get(e,Up).update(e=>null)})}getAccessToken(e){return Hp(this,void 0,void 0,function*(){if(!e)return null;const t=yield this.getStateValueByUserIdAndKeyDef(e,Up);if(null!=t)return t;const i=yield this.getStateValueByUserIdAndKeyDef(e,Rp);if(!i)return null;if(this.platformSupportsSecureStorage){let t;try{t=yield this.getAccessTokenKey(e)}catch(t){return Nt.isSerializedEncString(i)?(this.logService.error("Access token key retrieval failed. Unable to decrypt encrypted access token. Logging user out.",t),yield this.logoutCallback("accessTokenUnableToBeDecrypted",e),null):i}if(!t)return Nt.isSerializedEncString(i)?(this.logService.error("Access token key not found to decrypt encrypted access token. Logging user out."),yield this.logoutCallback("accessTokenUnableToBeDecrypted",e),null):i;try{const e=new Nt(i);return yield this.decryptAccessToken(t,e)}catch(t){return this.logService.error("Failed to decrypt access token",t),yield this.logoutCallback("accessTokenUnableToBeDecrypted",e),null}}return i})}setRefreshToken(e,t,i,r){return Hp(this,void 0,void 0,function*(){if(!r)throw new Error("User id not found. Cannot save refresh token.");if(null==i)throw new Error("Vault Timeout is required.");if(null==t)throw new Error("Vault Timeout Action is required.");switch(yield this.determineStorageLocation(t,i,!0)){case Wp.SecureStorage:{let t=null;try{yield this.saveStringToSecureStorage(r,this.refreshTokenSecureStorageKey,e);const i=yield this.getStringFromSecureStorage(r,this.refreshTokenSecureStorageKey);if(null!==e&&!i)throw new Error("Refresh token failed to save to secure storage.");t=e,yield this.singleUserStateProvider.get(r,Fp).update(e=>null,{shouldUpdate:e=>null!==e}),yield this.singleUserStateProvider.get(r,qp).update(e=>null)}catch(i){this.logService.error("SetRefreshToken: storing refresh token in secure storage failed. Falling back to disk storage.",i),t=yield this.singleUserStateProvider.get(r,Fp).update(t=>e,{shouldUpdate:t=>t!==e})}return t}case Wp.Disk:return yield this.singleUserStateProvider.get(r,Fp).update(t=>e,{shouldUpdate:t=>t!==e});case Wp.Memory:return yield this.singleUserStateProvider.get(r,qp).update(t=>e)}})}getRefreshToken(e){return Hp(this,void 0,void 0,function*(){if(!e)return null;const t=yield this.getStateValueByUserIdAndKeyDef(e,qp);if(null!=t)return t;const i=yield this.getStateValueByUserIdAndKeyDef(e,Fp);if(null!=i)return i;if(this.platformSupportsSecureStorage)try{const t=yield this.getStringFromSecureStorage(e,this.refreshTokenSecureStorageKey);if(null!=t)return t;this.logService.error("Refresh token not found in secure storage. Access token will fail to refresh upon expiration or manual refresh.")}catch(t){this.logService.error("Failed to retrieve refresh token from secure storage",t),yield this.logoutCallback("refreshTokenSecureStorageRetrievalFailure",e)}return null})}clearRefreshToken(e){return Hp(this,void 0,void 0,function*(){if(!e)throw new Error("User id not found. Cannot clear refresh token.");this.platformSupportsSecureStorage&&(yield this.secureStorageService.remove(`${e}${this.refreshTokenSecureStorageKey}`,this.getSecureStorageOptions(e))),yield this.singleUserStateProvider.get(e,qp).update(e=>null),yield this.singleUserStateProvider.get(e,Fp).update(e=>null,{shouldUpdate:e=>null!==e})})}setClientId(e,t,i,r){return Hp(this,void 0,void 0,function*(){if(null!=r||(r=yield Ce(this.activeUserIdGlobalState.state$)),!r)throw new Error("User id not found. Cannot save client id.");if(null==i)throw new Error("Vault Timeout is required.");if(null==t)throw new Error("Vault Timeout Action is required.");const n=yield this.determineStorageLocation(t,i,!1);return n===Wp.Disk?yield this.singleUserStateProvider.get(r,Bp).update(t=>e):n===Wp.Memory?yield this.singleUserStateProvider.get(r,Mp).update(t=>e):void 0})}getClientId(e){return Hp(this,void 0,void 0,function*(){if(!e)return;const t=yield this.getStateValueByUserIdAndKeyDef(e,Mp);return null!=t?t:yield this.getStateValueByUserIdAndKeyDef(e,Bp)})}clearClientId(e){return Hp(this,void 0,void 0,function*(){if(null!=e||(e=yield Ce(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear client id.");yield this.singleUserStateProvider.get(e,Mp).update(e=>null),yield this.singleUserStateProvider.get(e,Bp).update(e=>null)})}setClientSecret(e,t,i,r){return Hp(this,void 0,void 0,function*(){if(null!=r||(r=yield Ce(this.activeUserIdGlobalState.state$)),!r)throw new Error("User id not found. Cannot save client secret.");if(null==i)throw new Error("Vault Timeout is required.");if(null==t)throw new Error("Vault Timeout Action is required.");const n=yield this.determineStorageLocation(t,i,!1);return n===Wp.Disk?yield this.singleUserStateProvider.get(r,Vp).update(t=>e):n===Wp.Memory?yield this.singleUserStateProvider.get(r,$p).update(t=>e):void 0})}getClientSecret(e){return Hp(this,void 0,void 0,function*(){if(!e)return;const t=yield this.getStateValueByUserIdAndKeyDef(e,$p);return null!=t?t:yield this.getStateValueByUserIdAndKeyDef(e,Vp)})}clearClientSecret(e){return Hp(this,void 0,void 0,function*(){if(null!=e||(e=yield Ce(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear client secret.");yield this.singleUserStateProvider.get(e,$p).update(e=>null),yield this.singleUserStateProvider.get(e,Vp).update(e=>null)})}setTwoFactorToken(e,t){return Hp(this,void 0,void 0,function*(){yield this.emailTwoFactorTokenRecordGlobalState.update(i=>(null!=i||(i={}),i[e]=t,i))})}getTwoFactorToken(e){return Hp(this,void 0,void 0,function*(){const t=yield Ce(this.emailTwoFactorTokenRecordGlobalState.state$);return t?t[e]:null})}clearTwoFactorToken(e){return Hp(this,void 0,void 0,function*(){yield this.emailTwoFactorTokenRecordGlobalState.update(t=>(null!=t||(t={}),delete t[e],t))})}clearTokens(e){return Hp(this,void 0,void 0,function*(){if(null!=e||(e=yield Ce(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot clear tokens.");yield Promise.all([this.clearAccessToken(e),this.clearRefreshToken(e),this.clearClientId(e),this.clearClientSecret(e)])})}decodeAccessToken(e){return Hp(this,void 0,void 0,function*(){let t=e;if(Tt.isGuid(e)?t=yield this.getAccessToken(e):null!=t||(t=yield this.getAccessToken(yield Ce(this.activeUserIdGlobalState.state$))),null==t)throw new Error("Access token not found.");return function(e){if(null==e)throw new Error("JWT token not found");const t=e.split(".");if(3!==t.length)throw new Error("JWT must have 3 parts");const i=t[1];let r;try{r=Tt.fromUrlB64ToUtf8(i)}catch(e){throw new Error("Cannot decode the token")}try{return JSON.parse(r)}catch(e){throw new Error("Cannot parse the token's payload into JSON")}}(t)})}getTokenExpirationDate(e){return Hp(this,void 0,void 0,function*(){let t;try{t=yield this.decodeAccessToken(e)}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!t||"number"!=typeof t.exp)return null;const i=new Date(0);return i.setUTCSeconds(t.exp),i})}tokenSecondsRemaining(e){return Hp(this,arguments,void 0,function*(e,t=0){const i=yield this.getTokenExpirationDate(e);if(null==i)return 0;const r=i.valueOf()-((new Date).valueOf()+1e3*t);return Math.round(r/1e3)})}tokenNeedsRefresh(e){return Hp(this,arguments,void 0,function*(e,t=5){return(yield this.tokenSecondsRemaining(e))<60*t})}getUserId(){return Hp(this,void 0,void 0,function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"string"!=typeof e.sub)throw new Error("No user id found");return e.sub})}getUserIdFromAccessToken(e){return Hp(this,void 0,void 0,function*(){let t;try{t=yield this.decodeAccessToken(e)}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!t||"string"!=typeof t.sub)throw new Error("No user id found");return t.sub})}getEmail(){return Hp(this,void 0,void 0,function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"string"!=typeof e.email)throw new Error("No email found");return e.email})}getEmailVerified(){return Hp(this,void 0,void 0,function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"boolean"!=typeof e.email_verified)throw new Error("No email verification found");return e.email_verified})}getName(){return Hp(this,void 0,void 0,function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}return e&&"string"==typeof e.name?e.name:null})}getIssuer(){return Hp(this,void 0,void 0,function*(){let e;try{e=yield this.decodeAccessToken()}catch(e){throw new Error("Failed to decode access token: "+e.message)}if(!e||"string"!=typeof e.iss)throw new Error("No issuer found");return e.iss})}getIsExternal(e){return Hp(this,void 0,void 0,function*(){let t;try{t=yield this.decodeAccessToken(e)}catch(e){throw new Error("Failed to decode access token: "+e.message)}return Array.isArray(t.amr)&&t.amr.includes("external")})}getSecurityStamp(e){return Hp(this,void 0,void 0,function*(){if(null!=e||(e=yield Ce(this.activeUserIdGlobalState.state$)),!e)throw new Error("User id not found. Cannot get security stamp.");return yield this.getStateValueByUserIdAndKeyDef(e,Kp)})}setSecurityStamp(e,t){return Hp(this,void 0,void 0,function*(){if(null!=t||(t=yield Ce(this.activeUserIdGlobalState.state$)),!t)throw new Error("User id not found. Cannot set security stamp.");yield this.singleUserStateProvider.get(t,Kp).update(t=>e)})}getStateValueByUserIdAndKeyDef(e,t){return Hp(this,void 0,void 0,function*(){return yield Ce(this.singleUserStateProvider.get(e,t).state$)})}determineStorageLocation(e,t,i){return Hp(this,void 0,void 0,function*(){if(null==e)throw new Error("TokenService - determineStorageLocation: We expect the vault timeout action to always exist at this point.");if(null==t)throw new Error("TokenService - determineStorageLocation: We expect the vault timeout to always exist at this point.");return e===od.LogOut&&t!==ld?Wp.Memory:i&&this.platformSupportsSecureStorage?Wp.SecureStorage:Wp.Disk})}saveStringToSecureStorage(e,t,i){return Hp(this,void 0,void 0,function*(){yield this.secureStorageService.save(`${e}${t}`,i,this.getSecureStorageOptions(e))})}getStringFromSecureStorage(e,t){return Hp(this,void 0,void 0,function*(){return yield this.secureStorageService.get(`${e}${t}`,this.getSecureStorageOptions(e))})}getSecureStorageOptions(e){return{storageLocation:dt.Disk,useSecureStorage:!0,userId:e}}}var Qp;class Jp{constructor(e){this.apiService=e}postAccountVerifyOTP(e){return this.apiService.send("POST","/accounts/verify-otp",e,!0,!1)}postAccountRequestOTP(){return e=this,t=void 0,r=function*(){return this.apiService.send("POST","/accounts/request-otp",null,!0,!1)},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r}postAccountVerifyPassword(e){return this.apiService.send("POST","/accounts/verify-password",e,!0,!0)}}!function(e){e[e.MasterPassword=0]="MasterPassword",e[e.OTP=1]="OTP",e[e.PIN=2]="PIN",e[e.Biometrics=3]="Biometrics"}(Qp||(Qp={}));class Yp{authenticateWith(e){return this.masterPasswordHash=e.masterPasswordAuthenticationHash,this}}class Xp{constructor(e){this.OTP=e}}var Zp=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class em{constructor(e,t,i,r,n,a,s,o,l){this.keyService=e,this.accountService=t,this.masterPasswordService=i,this.i18nService=r,this.userVerificationApiService=n,this.userDecryptionOptionsService=a,this.pinService=s,this.kdfConfigService=o,this.biometricsService=l}getAvailableVerificationOptions(e){return Zp(this,void 0,void 0,function*(){var t;const i=null===(t=yield Ce(this.accountService.activeAccount$))||void 0===t?void 0:t.id;if("client"===e){const[e,t,r]=yield Promise.all([this.hasMasterPasswordAndMasterKeyHash(i),this.pinService.isPinDecryptionAvailable(i),this.biometricsService.getBiometricsStatus()]);return{client:{masterPassword:e,pin:t,biometrics:r===qu.Available},server:{masterPassword:!1,otp:!1}}}{const e=yield this.hasMasterPassword(i);return{client:{masterPassword:!1,pin:!1,biometrics:!1},server:{masterPassword:e,otp:!e}}}})}buildRequest(e,t){return Zp(this,void 0,void 0,function*(){this.validateSecretInput(e);const i=null!=t?new t:new Yp;if(e.type===Qp.OTP)i.otp=e.secret;else{const t=yield Ce(this.accountService.activeAccount$.pipe(tu)),r=yield this.kdfConfigService.getKdfConfig(t),n=yield Ce(this.masterPasswordService.saltForUser$(t)),a=yield this.masterPasswordService.makeMasterPasswordAuthenticationData(e.secret,r,n);i.authenticateWith(a)}return i})}verifyUser(e){return Zp(this,void 0,void 0,function*(){if(null==e)throw new Error("Verification is required.");const[t,i]=yield Ce(this.accountService.activeAccount$.pipe(X(e=>[null==e?void 0:e.id,null==e?void 0:e.email])));switch(function(e){return"secret"in e}(e)&&this.validateSecretInput(e),e.type){case Qp.OTP:return this.verifyUserByOTP(e);case Qp.MasterPassword:return yield this.verifyUserByMasterPassword(e,t,i),!0;case Qp.PIN:return this.verifyUserByPIN(e,t);case Qp.Biometrics:return this.verifyUserByBiometrics();default:return e}})}verifyUserByOTP(e){return Zp(this,void 0,void 0,function*(){const t=new Xp(e.secret);try{yield this.userVerificationApiService.postAccountVerifyOTP(t)}catch(e){throw new Error(this.i18nService.t("invalidVerificationCode"))}return!0})}verifyUserByMasterPassword(e,t,i){return Zp(this,void 0,void 0,function*(){if(!e.secret)throw new Error("Master Password is required. Cannot verify user without a master password.");if(!t)throw new Error("User ID is required. Cannot verify user by master password.");if(!i)throw new Error("Email is required. Cannot verify user by master password.");const r=yield this.kdfConfigService.getKdfConfig(t);if(!r)throw new Error("KDF config is required. Cannot verify user by master password.");let n,a=yield Ce(this.masterPasswordService.masterKey$(t));if(a||(a=yield this.keyService.makeMasterKey(e.secret,i,r)),!a)throw new Error("Master key could not be created to verify the master password.");if(yield this.hasMasterPasswordAndMasterKeyHash(t)){if(!(yield this.keyService.compareKeyHash(e.secret,a,t)))throw new Error(this.i18nService.t("invalidMasterPassword"));n=null}else{const t=new Yp,i=yield this.keyService.hashMasterKey(e.secret,a,lt.ServerAuthorization);t.masterPasswordHash=i;try{n=yield this.userVerificationApiService.postAccountVerifyPassword(t)}catch(e){throw new Error(this.i18nService.t("invalidMasterPassword"))}}const s=yield this.keyService.hashMasterKey(e.secret,a,lt.LocalAuthorization);return yield this.masterPasswordService.setMasterKeyHash(s,t),yield this.masterPasswordService.setMasterKey(a,t),{policyOptions:n,masterKey:a,email:i}})}verifyUserByPIN(e,t){return Zp(this,void 0,void 0,function*(){if(!t)throw new Error("User ID is required. Cannot verify user by PIN.");return null!=(yield this.pinService.decryptUserKeyWithPin(e.secret,t))})}verifyUserByBiometrics(){return Zp(this,void 0,void 0,function*(){return this.biometricsService.authenticateWithBiometrics()})}requestOTP(){return Zp(this,void 0,void 0,function*(){yield this.userVerificationApiService.postAccountRequestOTP()})}hasMasterPassword(e){return Zp(this,void 0,void 0,function*(){var t;const i=null!=e?e:null===(t=yield Ce(this.accountService.activeAccount$))||void 0===t?void 0:t.id;return!!i&&(yield Ce(this.userDecryptionOptionsService.hasMasterPasswordById$(i)))})}hasMasterPasswordAndMasterKeyHash(e){return Zp(this,void 0,void 0,function*(){var t;return null!=e||(e=null===(t=yield Ce(this.accountService.activeAccount$))||void 0===t?void 0:t.id),(yield this.hasMasterPassword(e))&&null!=(yield Ce(this.masterPasswordService.masterKeyHash$(e)))})}validateSecretInput(e){if(null==(null==e?void 0:e.secret)||""===e.secret)switch(e.type){case Qp.OTP:throw new Error(this.i18nService.t("verificationCodeRequired"));case Qp.MasterPassword:throw new Error(this.i18nService.t("masterPasswordRequired"));case Qp.PIN:throw new Error(this.i18nService.t("pinRequired"))}}}const tm={None:0,Password:1};function im(e){switch(e){case tm.None:case tm.Password:return e;default:return tm.None}}const rm=Object.freeze({Login:1,SecureNote:2,Card:3,Identity:4,SshKey:5}),nm=Object.freeze(Object.fromEntries(Object.entries(rm).map(([e,t])=>[t,e]))),am=Object.freeze({Text:0,Hidden:1,Boolean:2,Linked:3});function sm(e){switch(e){case am.Text:case am.Hidden:case am.Boolean:case am.Linked:return e;default:return am.Text}}const om={Username:100,Password:101},lm={CardholderName:300,ExpMonth:301,ExpYear:302,Code:303,Brand:304,Number:305},cm={Title:400,MiddleName:401,Address1:402,Address2:403,Address3:404,City:405,State:406,PostalCode:407,Country:408,Company:409,Email:410,Phone:411,Ssn:412,Username:413,PassportNumber:414,LicenseNumber:415,FirstName:416,LastName:417,FullName:418};function um(e){if(null!=e)return[...Object.values(om),...Object.values(lm),...Object.values(cm)].includes(e)?e:void 0}const dm={Index:"popup/index.html#/",AtRiskPasswords:"popup/index.html#/at-risk-passwords"},hm=["/","-","."," "],pm="\\"+hm.join("\\").replace(" ","s"),mm="2[0-1]{1}\\d{2}",gm=new RegExp(`[${pm}]`,"g"),fm=new RegExp(`[^\\d${pm}]`,"g"),ym=new RegExp("^(([1]{1}[0-2]{1})|(0?[1-9]{1}))$"),vm=new RegExp(`^${mm}$`),bm="autofill-card",wm="autofill",km="autofill-identity",Sm="copy-identifier",_m="copy-password",xm="copy-username",Cm="copy-totp",Im="create-card",Em="create-identity",zm="create-login",Pm="generate-password",Am="noop",jm="root",Tm="separator",Dm=15e4,Om="autofill_cmd",Nm="autofill_card",Rm="autofill_identity",Um="autofill_login";var Fm=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const qm=new wi(Hi,"autofillOnPageLoad",{deserializer:e=>null!=e&&e,clearOn:[]}),Lm=new wi(Hi,"autofillOnPageLoadDefault",{deserializer:e=>null!=e&&e,clearOn:[]}),Bm=new wi(Hi,"autofillOnPageLoadCalloutIsDismissed",{deserializer:e=>null!=e&&e,clearOn:[]}),Mm=new wi(Hi,"autofillOnPageLoadPolicyToastHasDisplayed",{deserializer:e=>null!=e&&e,clearOn:[]}),Vm=new wi(Hi,"autoCopyTotp",{deserializer:e=>null==e||e,clearOn:[]}),$m=new fi(Gi,"inlineMenuVisibility",{deserializer:e=>null!=e?e:0}),Km=new wi(Hi,"showInlineMenuIdentities",{deserializer:e=>null==e||e,clearOn:[]}),Wm=new wi(Hi,"showInlineMenuCards",{deserializer:e=>null==e||e,clearOn:[]}),Hm=new fi(Hi,"enableContextMenu",{deserializer:e=>null==e||e}),Gm=new wi(Gi,"clearClipboardDelay",{deserializer:e=>null!=e?e:null,clearOn:[]});class Qm{constructor(e,t,i,r){this.stateProvider=e,this.policyService=t,this.accountService=i,this.restrictedItemTypesService=r,this.autofillOnPageLoadState=this.stateProvider.getActive(qm),this.autofillOnPageLoad$=this.autofillOnPageLoadState.state$.pipe(X(e=>null!=e&&e)),this.autofillOnPageLoadDefaultState=this.stateProvider.getActive(Lm),this.autofillOnPageLoadDefault$=this.autofillOnPageLoadDefaultState.state$.pipe(X(e=>null==e||e)),this.autofillOnPageLoadCalloutIsDismissedState=this.stateProvider.getActive(Bm),this.autofillOnPageLoadCalloutIsDismissed$=this.autofillOnPageLoadCalloutIsDismissedState.state$.pipe(X(e=>null!=e&&e)),this.activateAutofillOnPageLoadFromPolicy$=this.accountService.activeAccount$.pipe(tu,Le(e=>this.policyService.policyAppliesToUser$(Ye.ActivateAutofill,e))),this.autofillOnPageLoadPolicyToastHasDisplayedState=this.stateProvider.getActive(Mm),this.autofillOnPageLoadPolicyToastHasDisplayed$=this.autofillOnPageLoadPolicyToastHasDisplayedState.state$.pipe(X(e=>null!=e&&e)),this.autoCopyTotpState=this.stateProvider.getActive(Vm),this.autoCopyTotp$=this.autoCopyTotpState.state$.pipe(X(e=>null==e||e)),this.inlineMenuVisibilityState=this.stateProvider.getGlobal($m),this.inlineMenuVisibility$=this.inlineMenuVisibilityState.state$.pipe(X(e=>null!=e?e:0)),this.showInlineMenuIdentitiesState=this.stateProvider.getActive(Km),this.showInlineMenuIdentities$=this.showInlineMenuIdentitiesState.state$.pipe(X(e=>null==e||e)),this.showInlineMenuCardsState=this.stateProvider.getActive(Wm),this.showInlineMenuCards$=ai([this.showInlineMenuCardsState.state$.pipe(X(e=>null==e||e)),this.restrictedItemTypesService.restricted$]).pipe(X(([e,t])=>e&&!t.some(e=>e.cipherType===rm.Card))),this.enableContextMenuState=this.stateProvider.getGlobal(Hm),this.enableContextMenu$=this.enableContextMenuState.state$.pipe(X(e=>null==e||e)),this.clearClipboardDelayState=this.stateProvider.getActive(Gm),this.clearClipboardDelay$=this.clearClipboardDelayState.state$.pipe(X(e=>null!=e?e:null))}setAutofillOnPageLoad(e){return Fm(this,void 0,void 0,function*(){yield this.autofillOnPageLoadState.update(()=>e)})}setAutofillOnPageLoadDefault(e){return Fm(this,void 0,void 0,function*(){yield this.autofillOnPageLoadDefaultState.update(()=>e)})}setAutofillOnPageLoadCalloutIsDismissed(e){return Fm(this,void 0,void 0,function*(){yield this.autofillOnPageLoadCalloutIsDismissedState.update(()=>e)})}setAutofillOnPageLoadPolicyToastHasDisplayed(e){return Fm(this,void 0,void 0,function*(){yield this.autofillOnPageLoadPolicyToastHasDisplayedState.update(()=>e)})}setAutoCopyTotp(e){return Fm(this,void 0,void 0,function*(){yield this.autoCopyTotpState.update(()=>e)})}setInlineMenuVisibility(e){return Fm(this,void 0,void 0,function*(){yield this.inlineMenuVisibilityState.update(()=>e)})}setShowInlineMenuIdentities(e){return Fm(this,void 0,void 0,function*(){yield this.showInlineMenuIdentitiesState.update(()=>e)})}setShowInlineMenuCards(e){return Fm(this,void 0,void 0,function*(){yield this.showInlineMenuCardsState.update(()=>e)})}setEnableContextMenu(e){return Fm(this,void 0,void 0,function*(){yield this.enableContextMenuState.update(()=>e)})}setClearClipboardDelay(e){return Fm(this,void 0,void 0,function*(){yield this.clearClipboardDelayState.update(()=>e)})}}const Jm=new wi($i,"enableBadgeCounter",{deserializer:e=>null==e||e,clearOn:[]});class Ym{constructor(e){this.stateProvider=e,this.enableBadgeCounterState=this.stateProvider.getActive(Jm),this.enableBadgeCounter$=this.enableBadgeCounterState.state$.pipe(X(e=>null==e||e))}setEnableBadgeCounter(e){return t=this,i=void 0,n=function*(){yield this.enableBadgeCounterState.update(()=>e)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}const Xm={Domain:0,Host:1,StartsWith:2,Exact:3,RegularExpression:4,Never:5};function Zm(e){if(null!=e)switch(e){case 0:case 1:case 2:case 3:case 4:case 5:return e;default:return}}var eg=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const tg=new fi(Wi,"showFavicons",{deserializer:e=>null==e||e}),ig=new fi(Wi,"neverDomains",{deserializer:e=>null!=e?e:null}),rg=new fi(Wi,"blockedInteractionsUris",{deserializer:e=>null!=e?e:{}}),ng=new wi(Wi,"equivalentDomains",{deserializer:e=>null!=e?e:null,clearOn:["logout"]}),ag=new wi(Wi,"defaultUriMatchStrategy",{deserializer:e=>null!=e?e:Xm.Domain,clearOn:[]});class sg{constructor(e,t,i){this.stateProvider=e,this.policyService=t,this.accountService=i,this.showFaviconsState=this.stateProvider.getGlobal(tg),this.showFavicons$=this.showFaviconsState.state$.pipe(X(e=>null==e||e)),this.neverDomainsState=this.stateProvider.getGlobal(ig),this.neverDomains$=this.neverDomainsState.state$.pipe(X(e=>null!=e?e:null)),this.blockedInteractionsUrisState=this.stateProvider.getGlobal(rg),this.blockedInteractionsUris$=this.blockedInteractionsUrisState.state$.pipe(X(e=>null!=e?e:{})),this.equivalentDomainsState=this.stateProvider.getActive(ng),this.equivalentDomains$=this.equivalentDomainsState.state$.pipe(X(e=>null!=e?e:null)),this.defaultUriMatchStrategyState=this.stateProvider.getActive(ag),this.defaultUriMatchStrategy$=this.defaultUriMatchStrategyState.state$.pipe(X(e=>null!=e?e:Xm.Domain)),this.defaultUriMatchStrategyPolicy$=this.accountService.activeAccount$.pipe(tu,Le(e=>this.policyService.policiesByType$(Ye.UriMatchDefaults,e)),ad,X(e=>{var t;if(!(null==e?void 0:e.enabled)||null==(null==e?void 0:e.data))return null;const i=null===(t=e.data)||void 0===t?void 0:t.uriMatchDetection;return Object.values(Xm).includes(i)?i:null}),Jt({bufferSize:1,refCount:!0})),this.resolvedDefaultUriMatchStrategy$=ai([this.defaultUriMatchStrategy$,this.defaultUriMatchStrategyPolicy$]).pipe(X(([e,t])=>t||e),Jt({bufferSize:1,refCount:!0}))}setShowFavicons(e){return eg(this,void 0,void 0,function*(){yield this.showFaviconsState.update(()=>e)})}setNeverDomains(e){return eg(this,void 0,void 0,function*(){yield this.neverDomainsState.update(()=>e)})}setBlockedInteractionsUris(e){return eg(this,void 0,void 0,function*(){yield this.blockedInteractionsUrisState.update(()=>e)})}setEquivalentDomains(e,t){return eg(this,void 0,void 0,function*(){yield this.stateProvider.getUser(t,ng).update(()=>e)})}setDefaultUriMatchStrategy(e){return eg(this,void 0,void 0,function*(){yield this.defaultUriMatchStrategyState.update(()=>e)})}getUrlEquivalentDomains(e){return this.equivalentDomains$.pipe(X(t=>{const i=Tt.getDomain(e);if(null==i||null==t)return new Set;const r=t.filter(e=>e.includes(i)).flat();return new Set(r)}))}}var og=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const lg=new fi(Ki,"enableAddedLoginPrompt",{deserializer:e=>null==e||e}),cg=new fi(Ki,"enableChangedPasswordPrompt",{deserializer:e=>null==e||e});class ug{constructor(e){this.stateProvider=e,this.enableAddedLoginPromptState=this.stateProvider.getGlobal(lg),this.enableAddedLoginPrompt$=this.enableAddedLoginPromptState.state$.pipe(X(e=>null==e||e)),this.enableChangedPasswordPromptState=this.stateProvider.getGlobal(cg),this.enableChangedPasswordPrompt$=this.enableChangedPasswordPromptState.state$.pipe(X(e=>null==e||e))}setEnableAddedLoginPrompt(e){return og(this,void 0,void 0,function*(){yield this.enableAddedLoginPromptState.update(()=>e)})}setEnableChangedPasswordPrompt(e){return og(this,void 0,void 0,function*(){yield this.enableChangedPasswordPromptState.update(()=>e)})}}function dg(e){const t=null==e||""===e;let i=t?null:`${e}`;if(t||i&&/^[1-9]{1}\d{3}$/.test(i))return i;if(i=(i||"").replace(/[^\d]/g,"").replace(/^[0]+(?=.)/,""),""===i&&(i=null),i&&4!==i.length){const e=("00"+i).slice(-2);i=`${(new Date).getFullYear()}`.slice(0,2)+e}return i}function hg(e="",t={}){const i=t&&Object.keys(t);if(i.length&&(null==e?void 0:e.length)){let t;try{t=Tt.getHostname(e)}catch(e){return!1}if(t)return i.some(e=>t.endsWith(e))}return!1}const pg=new wi(Ii,"accountProfile",{deserializer:e=>e,clearOn:["logout"]});class mg{constructor(e){this.stateProvider=e}hasPremiumFromAnyOrganization$(e){return this.stateProvider.getUser(e,pg).state$.pipe(X(e=>!!(null==e?void 0:e.hasPremiumFromAnyOrganization)))}hasPremiumPersonally$(e){return this.stateProvider.getUser(e,pg).state$.pipe(X(e=>!!(null==e?void 0:e.hasPremiumPersonally)))}hasPremiumFromAnySource$(e){return this.stateProvider.getUser(e,pg).state$.pipe(X(e=>!0===(null==e?void 0:e.hasPremiumFromAnyOrganization)||!0===(null==e?void 0:e.hasPremiumPersonally)))}setHasPremium(e,t,i){return r=this,n=void 0,s=function*(){yield this.stateProvider.getUser(i,pg).update(i=>({hasPremiumPersonally:e,hasPremiumFromAnyOrganization:t}),{shouldUpdate:i=>null==i||i.hasPremiumFromAnyOrganization!==t||i.hasPremiumPersonally!==e})},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}}class gg extends Lt{constructor(e){super(e),this.addedDate=this.getResponseProperty("AddedDate"),this.breachDate=this.getResponseProperty("BreachDate"),this.dataClasses=this.getResponseProperty("DataClasses"),this.description=this.getResponseProperty("Description"),this.domain=this.getResponseProperty("Domain"),this.isActive=this.getResponseProperty("IsActive"),this.isVerified=this.getResponseProperty("IsVerified"),this.logoPath=this.getResponseProperty("LogoPath"),this.modifiedDate=this.getResponseProperty("ModifiedDate"),this.name=this.getResponseProperty("Name"),this.pwnCount=this.getResponseProperty("PwnCount"),this.title=this.getResponseProperty("Title")}}class fg{constructor(e){this.apiService=e}getHibpBreach(e){return t=this,i=void 0,n=function*(){const t=encodeURIComponent(e);return(yield this.apiService.send("GET","/hibp/breach?username="+t,null,!0,!0)).map(e=>new gg(e))},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}const yg=new wi(Qi,"enablePhishingDetection",{deserializer:e=>null==e||e,clearOn:[]});class vg{constructor(e,t,i,r,n,a,s){this.accountService=e,this.billingService=t,this.configService=i,this.logService=r,this.organizationService=n,this.platformService=a,this.stateProvider=s,this.logService.debug("[PhishingDetectionSettingsService] Initializing service..."),this.available$=this.buildAvailablePipeline$().pipe(Zl(),ac(e=>this.logService.debug(`[PhishingDetectionSettingsService] Phishing detection available: ${e}`)),Jt({bufferSize:1,refCount:!0})),this.enabled$=this.buildEnabledPipeline$().pipe(Zl(),ac(e=>this.logService.debug(`[PhishingDetectionSettingsService] Phishing detection enabled: ${{enabled:e}}`)),Jt({bufferSize:1,refCount:!0})),this.on$=ai([this.available$,this.enabled$]).pipe(X(([e,t])=>e&&t),Zl(),ac(e=>this.logService.debug(`[PhishingDetectionSettingsService] Phishing detection is on: ${{on:e}}`)),Jt({bufferSize:1,refCount:!1}))}setEnabled(e,t){return i=this,r=void 0,a=function*(){this.logService.debug(`[PhishingDetectionSettingsService] Setting phishing detection enabled: ${{enabled:t,userId:e}}`),yield this.stateProvider.getUser(e,yg).update(()=>t)},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}buildAvailablePipeline$(){return this.platformService.isSafari()?(this.logService.warning("[PhishingDetectionSettingsService] Phishing detection is unavailable on Safari due to platform limitations"),bt(!1)):ai([this.accountService.activeAccount$,this.configService.getFeatureFlag$(Ne.PhishingDetection)]).pipe(Le(([e,t])=>e&&t?ai([this.billingService.hasPremiumPersonally$(e.id).pipe(Hu(()=>bt(!1))),this.organizationService.organizations$(e.id).pipe(Hu(()=>bt([])))]).pipe(X(([e,t])=>e||this.orgGrantsAccess(t)),Hu(()=>bt(!1))):bt(!1)))}buildEnabledPipeline$(){return this.accountService.activeAccount$.pipe(Le(e=>e?(this.logService.debug("[PhishingDetectionSettingsService] Refreshing phishing detection enabled state"),this.stateProvider.getUserState$(yg,e.id)):bt(!1)),X(e=>null==e||e))}orgGrantsAccess(e){return e.some(e=>!!(e.canAccess&&e.isMember&&e.usersGetPremium)&&(e.productTierType===Kh.Families||e.productTierType===Kh.Enterprise&&e.usePhishingBlocker))}}var bg=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const wg=new wi(zr,"accountCryptographicState",{deserializer:e=>e,clearOn:["logout"]});class kg{constructor(e){this.stateProvider=e}accountCryptographicState$(e){return this.stateProvider.getUserState$(wg,e)}setAccountCryptographicState(e,t){return bg(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(wg,e,t)})}clearAccountCryptographicState(e){return bg(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(wg,null,e)})}}var Sg=o(6414);class _g extends Error{constructor(e){super(`SDK loading failed: ${e}`)}}class xg{loadAndInit(){return e=this,t=void 0,r=function*(){try{yield this.load(),(0,Sg.Geh)(xg.logLevel),xg.markAsReady()}catch(e){xg.markAsFailed(e)}},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r}}xg.logLevel=Sg.$bb.Info,xg.Ready=new Promise((e,t)=>{xg.markAsReady=e,xg.markAsFailed=e=>t(new _g(e))});var Cg=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Ig{constructor(e){this.cryptoFunctionService=e}createKey(e){return Cg(this,void 0,void 0,function*(){const t=yield this.cryptoFunctionService.aesGenerateKey(e);return new gu(t)})}createKeyWithPurpose(e,t,i){return Cg(this,void 0,void 0,function*(){if(null==i){const e=yield this.cryptoFunctionService.randomBytes(32);i=Tt.fromBufferToUtf8(e.buffer)}const r=yield this.cryptoFunctionService.aesGenerateKey(e),n=yield this.cryptoFunctionService.hkdf(r,i,t,64,"sha256");return{salt:i,material:r,derivedKey:new gu(n)}})}deriveKeyFromMaterial(e,t,i){return Cg(this,void 0,void 0,function*(){const r=yield this.cryptoFunctionService.hkdf(e,t,i,64,"sha256");return new gu(r)})}deriveKeyFromPassword(e,t,i){return Cg(this,void 0,void 0,function*(){return"string"==typeof e&&(e=(new TextEncoder).encode(e)),"string"==typeof t&&(t=(new TextEncoder).encode(t)),yield xg.Ready,new gu(Sg.IEs.derive_kdf_material(e,t,i.toSdkConfig()))})}stretchKey(e){return Cg(this,void 0,void 0,function*(){if(e.inner().type!=rt.AesCbc256_B64)throw new Error("Key passed into stretchKey is not a 256-bit key.");const t=new Uint8Array(64),i=yield this.cryptoFunctionService.hkdfExpand(e.inner().encryptionKey,"enc",32,"sha256"),r=yield this.cryptoFunctionService.hkdfExpand(e.inner().encryptionKey,"mac",32,"sha256");return t.set(new Uint8Array(i)),t.set(new Uint8Array(r),32),new gu(t)})}deriveVaultExportKey(e,t,i){return Cg(this,void 0,void 0,function*(){return yield this.stretchKey(yield this.deriveKeyFromPassword(e,t,i))})}}class Eg{constructor(e){this.buffer=e,this.encryptionType=null,this.dataBytes=null,this.ivBytes=null,this.macBytes=null;const t=e,i=t[0];switch(i){case rt.AesCbc256_HmacSha256_B64:{const e=50;t.length255*n)throw new Error("outputByteSize is too large.");if(new Uint8Array(e).length=i)break}return u.slice(0,i)})}hash(e,t){return jg(this,void 0,void 0,function*(){if("md5"===t){const t=Ag.md.md5.create(),i=this.toByteString(e);return t.update(i,"raw"),Tt.fromByteStringToArray(t.digest().data)}const i=this.toBuf(e),r=yield this.subtle.digest({name:this.toWebCryptoAlgorithm(t)},i);return new Uint8Array(r)})}hmac(e,t,i){return jg(this,void 0,void 0,function*(){const r={name:"HMAC",hash:{name:this.toWebCryptoAlgorithm(i)}},n=yield this.subtle.importKey("raw",t,r,!1,["sign"]),a=yield this.subtle.sign(r,n,e);return new Uint8Array(a)})}hmacFast(e,t,i){const r=Ag.hmac.create();r.start(i,t),r.update(e);const n=r.digest().getBytes();return Promise.resolve(n)}compareFast(e,t){return jg(this,void 0,void 0,function*(){const i=yield this.randomBytes(32),r=new Uint32Array(i),n=Ag.util.createBuffer();for(let e=0;ee?gu.fromJSON(e):null,clearOn:[],cleanupDelayMs:0,debug:{enableRetrievalLogging:!0,enableUpdateLogging:!0}}),Fg=new wi(Ai,"shouldTrustDevice",{deserializer:e=>e,clearOn:[]});class qg{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p){this.keyGenerationService=e,this.cryptoFunctionService=t,this.keyService=i,this.encryptService=r,this.appIdService=n,this.devicesApiService=a,this.i18nService=s,this.platformUtilsService=o,this.stateProvider=l,this.secureStorageService=c,this.userDecryptionOptionsService=u,this.logService=d,this.configService=h,this.accountService=p,this.platformSupportsSecureStorage=this.platformUtilsService.supportsSecureStorage(),this.deviceKeySecureStorageKey="_deviceKey",this.deviceTrustedSubject=new H,this.deviceTrusted$=this.deviceTrustedSubject.asObservable(),this.supportsDeviceTrust$=this.accountService.activeAccount$.pipe(Le(e=>null==e?[!1]:this.userDecryptionOptionsService.userDecryptionOptionsById$(e.id).pipe(X(e=>null!=(null==e?void 0:e.trustedDeviceOption)))))}supportsDeviceTrustByUserId$(e){return this.userDecryptionOptionsService.userDecryptionOptionsById$(e).pipe(X(e=>null!=(null==e?void 0:e.trustedDeviceOption)))}getShouldTrustDevice(e){return Rg(this,void 0,void 0,function*(){if(!e)throw new Error("UserId is required. Cannot get should trust device.");return yield Ce(this.stateProvider.getUserState$(Fg,e))})}setShouldTrustDevice(e,t){return Rg(this,void 0,void 0,function*(){if(!e)throw new Error("UserId is required. Cannot set should trust device.");yield this.stateProvider.setUserState(Fg,t,e)})}trustDeviceIfRequired(e){return Rg(this,void 0,void 0,function*(){if(!e)throw new Error("UserId is required. Cannot trust device if required.");(yield this.getShouldTrustDevice(e))&&(yield this.trustDevice(e),yield this.setShouldTrustDevice(e,null))})}trustDevice(e){return Rg(this,void 0,void 0,function*(){if(!e)throw new Error("UserId is required. Cannot trust device.");const t=yield Ce(this.keyService.userKey$(e));if(!t)throw new Error("User symmetric key not found");const i=yield this.makeDeviceKey(),[r,n]=yield this.cryptoFunctionService.rsaGenerateKeyPair(2048),[a,s,o]=yield Promise.all([this.encryptService.encapsulateKeyUnsigned(t,r),this.encryptService.wrapEncapsulationKey(r,t),this.encryptService.wrapDecapsulationKey(n,i)]),l=yield this.appIdService.getAppId(),c=yield this.devicesApiService.updateTrustedDeviceKeys(l,a.encryptedString,s.encryptedString,o.encryptedString);return yield this.setDeviceKey(e,i),this.deviceTrustedSubject.next(),c})}getRotatedData(e,t,i){return Rg(this,void 0,void 0,function*(){if(!i)throw new Error("UserId is required. Cannot get rotated data.");if(!e)throw new Error("Old user key is required. Cannot get rotated data.");if(!t)throw new Error("New user key is required. Cannot get rotated data.");const r=yield this.devicesApiService.getDevices(),n=[],a=yield Promise.all(r.data.filter(e=>e.isTrusted).map(i=>Rg(this,void 0,void 0,function*(){const r=yield this.encryptService.unwrapEncapsulationKey(new Nt(i.encryptedPublicKey),e);if(!r)return n.push(i.id),null;const a=yield this.encryptService.wrapEncapsulationKey(r,t),s=yield this.encryptService.encapsulateKeyUnsigned(t,r),o=new Sp(s,a),l=new Ng;return l.encryptedPublicKey=o.encryptedPublicKey.encryptedString,l.encryptedUserKey=o.encapsulatedDownstreamKey.encryptedString,l.deviceId=i.id,l})).filter(e=>null!=e));return a.length>0&&(this.logService.info("[Device trust rotation] Distrusting devices that failed to decrypt."),yield this.devicesApiService.untrustDevices(n)),a})}rotateDevicesTrust(e,t,i){return Rg(this,void 0,void 0,function*(){if(this.logService.info("[Device trust rotation] Rotating device trust..."),!e)throw new Error("UserId is required. Cannot rotate device's trust.");if(null==(yield this.getDeviceKey(e)))return void this.logService.info("[Device trust rotation] No device key available to rotate trust!");const r=yield Ce(this.keyService.userKey$(e));r==t&&this.logService.info("[Device trust rotation] Old user key is the same as the new user key.");const n=yield this.appIdService.getAppId();(new Yp).masterPasswordHash=i;const a=yield this.devicesApiService.getDeviceKeys(n),s=yield this.encryptService.unwrapEncapsulationKey(a.encryptedPublicKey,r),o=yield this.encryptService.encapsulateKeyUnsigned(t,s),l=yield this.encryptService.wrapEncapsulationKey(s,t),c=new Og;c.encryptedUserKey=o.encryptedString,c.encryptedPublicKey=l.encryptedString;const u=new Dg;u.masterPasswordHash=i,u.currentDevice=c,u.otherDevices=[],this.logService.info("[Device trust rotation] Posting device trust update with current device:",n),yield this.devicesApiService.updateTrust(u,n),this.logService.info("[Device trust rotation] Device trust update posted successfully.")})}getDeviceKey(e){return Rg(this,void 0,void 0,function*(){if(!e)throw new Error("UserId is required. Cannot get device key.");try{if(this.platformSupportsSecureStorage){const t=yield this.secureStorageService.get(`${e}${this.deviceKeySecureStorageKey}`,this.getSecureStorageOptions(e));return gu.fromJSON(t)}return yield Ce(this.stateProvider.getUserState$(Ug,e))}catch(e){this.logService.error("Failed to get device key",e)}})}setDeviceKey(e,t){return Rg(this,void 0,void 0,function*(){if(!e)throw new Error("UserId is required. Cannot set device key.");try{if(this.platformSupportsSecureStorage)return void(yield this.secureStorageService.save(`${e}${this.deviceKeySecureStorageKey}`,t,this.getSecureStorageOptions(e)));yield this.stateProvider.setUserState(Ug,null==t?void 0:t.toJSON(),e)}catch(e){this.logService.error("Failed to set device key",e)}})}makeDeviceKey(){return Rg(this,void 0,void 0,function*(){return yield this.keyGenerationService.createKey(512)})}decryptUserKeyWithDeviceKey(e,t,i,r){return Rg(this,void 0,void 0,function*(){if(!e)throw new Error("UserId is required. Cannot decrypt user key with device key.");if(!t)throw new Error("Encrypted device private key is required. Cannot decrypt user key with device key.");if(!i)throw new Error("Encrypted user key is required. Cannot decrypt user key with device key.");if(!r)return null;try{const e=yield this.encryptService.unwrapDecapsulationKey(t,r);return yield this.encryptService.decapsulateKeyUnsigned(new Nt(i.encryptedString),e)}catch(t){return this.logService.error("Failed to decrypt using device key. Removing device key."),yield this.setDeviceKey(e,null),null}})}recordDeviceTrustLoss(){return Rg(this,void 0,void 0,function*(){const e=yield this.appIdService.getAppId();yield this.devicesApiService.postDeviceTrustLoss(e)})}getSecureStorageOptions(e){return{storageLocation:dt.Disk,useSecureStorage:!0,userId:e}}}class Lg{constructor(e,t){this.publicKey=e,this.encryptedPrivateKey=t}}class Bg extends Error{constructor(e){super(`User (${e}) is not logged in`)}}class Mg extends Error{constructor(e){super(`Invalid UUID: ${e}`)}}function Vg(e){switch(e){case Rd.Android:return"Android";case Rd.iOS:return"iOS";case Rd.ChromeExtension:return"ChromeExtension";case Rd.FirefoxExtension:return"FirefoxExtension";case Rd.OperaExtension:return"OperaExtension";case Rd.EdgeExtension:return"EdgeExtension";case Rd.WindowsDesktop:return"WindowsDesktop";case Rd.MacOsDesktop:return"MacOsDesktop";case Rd.LinuxDesktop:return"LinuxDesktop";case Rd.ChromeBrowser:return"ChromeBrowser";case Rd.FirefoxBrowser:return"FirefoxBrowser";case Rd.OperaBrowser:return"OperaBrowser";case Rd.EdgeBrowser:return"EdgeBrowser";case Rd.IEBrowser:return"IEBrowser";case Rd.UnknownBrowser:return"UnknownBrowser";case Rd.AndroidAmazon:return"AndroidAmazon";case Rd.UWP:return"UWP";case Rd.SafariBrowser:return"SafariBrowser";case Rd.VivaldiBrowser:return"VivaldiBrowser";case Rd.VivaldiExtension:return"VivaldiExtension";case Rd.SafariExtension:return"SafariExtension";case Rd.Server:return"Server";case Rd.WindowsCLI:return"WindowsCLI";case Rd.MacOsCLI:return"MacOsCLI";case Rd.LinuxCLI:return"LinuxCLI";default:return"SDK"}}function $g(e){if(Tt.isGuid(e))return e;throw new Mg(e)}function Kg(e){return e}class Wg{constructor(e){this.key=e}}class Hg{constructor(e,t,i,r){this.key=e,this.kdf=t.kdfType,this.kdfIterations=t.iterations,t.kdfType===Cd.Argon2id&&(this.kdfMemory=t.memory,this.kdfParallelism=t.parallelism),this.orgIdentifier=i,this.keys=r}}var Gg=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})},Qg=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===n)return n=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(a).then(e,function(t){return i(t),e()})}else n|=1}catch(e){i(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const Jg=new wi(jr,"usesKeyConnector",{deserializer:e=>e,clearOn:["logout"],cleanupDelayMs:0}),Yg=new wi(jr,"newSsoUserKeyConnectorConversion",{deserializer:e=>null==e?null:{kdfConfig:e.kdfConfig.kdfType===Cd.PBKDF2_SHA256?Pd.fromJSON(e.kdfConfig):Ad.fromJSON(e.kdfConfig),keyConnectorUrl:e.keyConnectorUrl,organizationId:e.organizationId},clearOn:["logout"],cleanupDelayMs:0});class Xg{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p){this.masterPasswordService=t,this.keyService=i,this.apiService=r,this.tokenService=n,this.logService=a,this.organizationService=s,this.keyGenerationService=o,this.logoutCallback=l,this.stateProvider=c,this.configService=u,this.registerSdkService=d,this.securityStateService=h,this.accountCryptographicStateService=p,this.convertAccountRequired$=e.activeAccount$.pipe(Ie(e=>null!=e),Le(e=>ai([bt(e.id),this.organizationService.organizations$(e.id).pipe(Ie(e=>null!=e)),this.stateProvider.getUserState$(Jg,e.id).pipe(Ie(e=>null!=e)),n.hasAccessToken$(e.id).pipe(Ie(e=>e))])),Le(e=>Gg(this,[e],void 0,function*([e,t,i]){const r=yield this.tokenService.getIsExternal(e),n=null!=this.findManagingOrganization(t);return r&&n&&!i})))}setUsesKeyConnector(e,t){return Gg(this,void 0,void 0,function*(){yield this.stateProvider.getUser(t,Jg).update(()=>e)})}getUsesKeyConnector(e){return Gg(this,void 0,void 0,function*(){var t;return null!==(t=yield Ce(this.stateProvider.getUserState$(Jg,e)))&&void 0!==t&&t})}migrateUser(e,t){return Gg(this,void 0,void 0,function*(){const i=yield Ce(this.masterPasswordService.masterKey$(t)),r=new Wg(Tt.fromBufferToB64(i.inner().encryptionKey));try{yield this.apiService.postUserKeyToKeyConnector(e,r)}catch(e){this.handleKeyConnectorError(e)}yield this.apiService.postConvertToKeyConnector(),yield this.setUsesKeyConnector(!0,t)})}setMasterKeyFromUrl(e,t){return Gg(this,void 0,void 0,function*(){try{const i=yield this.apiService.getMasterKeyFromKeyConnector(e),r=Tt.fromB64ToArray(i.key),n=new gu(r);yield this.masterPasswordService.setMasterKey(n,t)}catch(e){this.handleKeyConnectorError(e)}})}getManagingOrganization(e){return Gg(this,void 0,void 0,function*(){const t=yield Ce(this.organizationService.organizations$(e));return this.findManagingOrganization(t)})}convertNewSsoUserToKeyConnector(e){return Gg(this,void 0,void 0,function*(){const t=yield Ce(this.stateProvider.getUserState$(Yg,e));if(null==t)throw new Error("Key Connector conversion not found");const{kdfConfig:i,keyConnectorUrl:r,organizationId:n}=t;(yield Ce(this.configService.getFeatureFlag$(Ne.EnableAccountEncryptionV2KeyConnectorRegistration)))?yield this.convertNewSsoUserToKeyConnectorV2(e,r,n):yield this.convertNewSsoUserToKeyConnectorV1(e,i,r,n),yield this.stateProvider.getUser(e,Yg).update(()=>null)})}convertNewSsoUserToKeyConnectorV2(e,t,i){return Gg(this,void 0,void 0,function*(){const r=yield Ce(this.registerSdkService.registerClient$(e).pipe(X(r=>{const n={stack:[],error:void 0,hasError:!1};try{if(!r)throw new Error("SDK not available");return function(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(n,r.take(),!1).value.auth().registration().post_keys_for_key_connector_registration(t,i,$g(e))}catch(e){n.error=e,n.hasError=!0}finally{Qg(n)}})));if(!("V2"in r.account_cryptographic_state)){const e=Object.keys(r.account_cryptographic_state);throw new Error(`Unexpected account cryptographic state version ${e}`)}yield this.masterPasswordService.setMasterKey(gu.fromString(r.key_connector_key),e),yield this.keyService.setUserKey(gu.fromString(r.user_key),e),yield this.masterPasswordService.setMasterKeyEncryptedUserKey(new Nt(r.key_connector_key_wrapped_user_key),e),yield this.accountCryptographicStateService.setAccountCryptographicState(r.account_cryptographic_state,e)})}convertNewSsoUserToKeyConnectorV1(e,t,i,r){return Gg(this,void 0,void 0,function*(){const n=yield this.keyGenerationService.createKey(512),a=yield this.keyService.makeMasterKey(n.keyB64,yield this.tokenService.getEmail(),t),s=new Wg(Tt.fromBufferToB64(a.inner().encryptionKey));yield this.masterPasswordService.setMasterKey(a,e);const o=yield this.keyService.makeUserKey(a);yield this.keyService.setUserKey(o[0],e),yield this.masterPasswordService.setMasterKeyEncryptedUserKey(o[1],e);const[l,c]=yield this.keyService.makeKeyPair(o[0]);try{yield this.apiService.postUserKeyToKeyConnector(i,s)}catch(e){this.handleKeyConnectorError(e)}const u=new Lg(l,c.encryptedString),d=new Hg(o[1].encryptedString,t,r,u);yield this.apiService.postSetKeyConnectorKey(d)})}setNewSsoUserKeyConnectorConversionData(e,t){return Gg(this,void 0,void 0,function*(){yield this.stateProvider.getUser(t,Yg).update(()=>e)})}requiresDomainConfirmation$(e){return this.stateProvider.getUserState$(Yg,e).pipe(X(e=>null!=e?{keyConnectorUrl:e.keyConnectorUrl,organizationSsoIdentifier:e.organizationId}:null))}handleKeyConnectorError(e){throw this.logService.error(e),null!=this.logoutCallback&&this.logoutCallback("keyConnectorError"),new Error("Key Connector error")}findManagingOrganization(e){return e.find(e=>e.keyConnectorEnabled&&e.type!==Je.Admin&&e.type!==Je.Owner&&!e.isProviderUser)}}function Zg(e,t,i){return nc(function(){return e()?t:i})}function ef(){for(var e=[],t=0;tnull==e?null:sf.fromJSON(e),clearOn:["logout"]}),gf=fi.record(Yi,"byServer",{deserializer:e=>null==e?null:sf.fromJSON(e)}),ff=(e,t)=>e.getApiUrl()===t.getApiUrl();class yf{constructor(e,t,i,r,n){this.configApiService=e,this.environmentService=t,this.logService=i,this.stateProvider=r,this.authService=n,this.failedFetchFallbackSubject=new H;const a=this.environmentService.globalEnvironment$.pipe(Zl(ff),Le(e=>this.globalConfigFor$(e.getApiUrl()).pipe(X(t=>[t,null,e,t]))));this.serverConfig$=this.stateProvider.activeUserId$.pipe(Zl(),Le(e=>null==e?a:this.authService.authStatusFor$(e).pipe(X(e=>e===cu.Unlocked),Zl(),Le(t=>t?ai([this.environmentService.getEnvironment$(e).pipe(Zl(ff)),this.userConfigFor$(e)]).pipe(Le(([t,i])=>null==i?this.globalConfigFor$(t.getApiUrl()).pipe(X(i=>[null,e,t,i])):bt([i,e,t,i]))):a))),ac(e=>pf(this,void 0,void 0,function*(){const[t,i,r,n]=e;t&&!this.olderThanRetrievalInterval(t.utcDate)||(yield this.renewConfig(t,i,r,n))})),Le(([e])=>!e||this.olderThanRetrievalInterval(e.utcDate)?Wt:bt(e)),tf(this.failedFetchFallbackSubject),Gt({connector:()=>new Ht(1),resetOnRefCountZero:()=>sc(1e3)})),this.cloudRegion$=this.serverConfig$.pipe(X(e=>{var t,i;return null!==(i=null===(t=null==e?void 0:e.environment)||void 0===t?void 0:t.cloudRegion)&&void 0!==i?i:nf.US})),this.serverSettings$=this.serverConfig$.pipe(X(e=>{var t;return null!==(t=null==e?void 0:e.settings)&&void 0!==t?t:new lf}))}getFeatureFlag$(e){return this.serverConfig$.pipe(X(t=>We(t,e)))}userCachedFeatureFlag$(e,t){return this.stateProvider.getUser(t,mf).state$.pipe(X(t=>We(t,e)))}getFeatureFlag(e){return pf(this,void 0,void 0,function*(){return yield Ce(this.getFeatureFlag$(e))})}checkServerMeetsVersionRequirement$(e){return this.serverConfig$.pipe(X(t=>null!=t&&new af.SemVer(t.version).compare(e)>=0))}ensureConfigFetched(){return pf(this,void 0,void 0,function*(){yield Ce(this.serverConfig$)})}olderThanRetrievalInterval(e){return(new Date).getTime()-e.getTime()>36e5}renewConfig(e,t,i,r){return pf(this,void 0,void 0,function*(){var n,a,s;try{const o=setTimeout(()=>{this.logService.info("Environment did not respond in time, emitting previous config."),this.failedFetchFallbackSubject.next(r)},800),l=yield this.configApiService.get(t);clearTimeout(o);const c=new sf(new cf(l));null!=(null===(n=null==c?void 0:c.environment)||void 0===n?void 0:n.cloudRegion)&&(null===(a=null==e?void 0:e.environment)||void 0===a?void 0:a.cloudRegion)!=c.environment.cloudRegion&&(yield this.environmentService.setCloudRegion(t,null===(s=null==c?void 0:c.environment)||void 0===s?void 0:s.cloudRegion)),null==t?yield this.stateProvider.getGlobal(gf).update(e=>Object.assign(Object.assign({},e),{[i.getApiUrl()]:c})):yield this.stateProvider.setUserState(mf,c,t)}catch(e){this.logService.error(`Unable to fetch ServerConfig from ${i.getApiUrl()}`,e),this.failedFetchFallbackSubject.next(r)}})}globalConfigFor$(e){return this.stateProvider.getGlobal(gf).state$.pipe(X(t=>{var i;return null!==(i=null==t?void 0:t[e])&&void 0!==i?i:null}))}userConfigFor$(e){return this.stateProvider.getUser(e,mf).state$}}var vf=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const bf=new wi(Ni,"masterKey",{deserializer:e=>gu.fromJSON(e),clearOn:["lock","logout"]}),wf=new wi(Oi,"masterKeyHash",{deserializer:e=>e,clearOn:["logout"]}),kf=new wi(Oi,"masterKeyEncryptedUserKey",{deserializer:e=>e,clearOn:["logout"]}),Sf=new wi(Oi,"forceSetPasswordReason",{deserializer:e=>e,clearOn:["logout"]}),_f=new wi(Ri,"masterPasswordUnlockKey",{deserializer:e=>Gd.fromJSON(e),clearOn:["logout"]});class xf{constructor(e,t,i,r,n){this.stateProvider=e,this.keyGenerationService=t,this.logService=i,this.cryptoFunctionService=r,this.accountService=n}userHasMasterPassword(e){return vf(this,void 0,void 0,function*(){zh(e,"userId");const t=yield Ce(this.stateProvider.getUser(e,Jg).state$);return(yield Ce(this.stateProvider.getUser(e,kf).state$))&&!t})}saltForUser$(e){return zh(e,"userId"),this.stateProvider.getUser(e,mf).state$.pipe(X(e=>We(e,Ne.PM31088_MasterPasswordServiceEmitSalt)),Le(t=>Zg(()=>t,this.masterPasswordUnlockData$(e).pipe(X(e=>{if(null==e)throw new Error("Master password unlock data not found for user.");return e.salt})),this.accountService.accounts$.pipe(X(t=>t[e].email),X(e=>this.emailToSalt(e))))))}masterKey$(e){if(null==e)throw new Error("User ID is required.");return this.stateProvider.getUser(e,bf).state$}masterKeyHash$(e){if(null==e)throw new Error("User ID is required.");return this.stateProvider.getUser(e,wf).state$}forceSetPasswordReason$(e){if(null==e)throw new Error("User ID is required.");return this.stateProvider.getUser(e,Sf).state$.pipe(X(e=>null!=e?e:Nd.None))}getMasterKeyEncryptedUserKey(e){return vf(this,void 0,void 0,function*(){if(null==e)throw new Error("User ID is required.");const t=yield Ce(this.stateProvider.getUser(e,kf).state$);return Nt.fromJSON(t)})}emailToSalt(e){return e.toLowerCase().trim()}setMasterKey(e,t){return vf(this,void 0,void 0,function*(){if(null==e)throw new Error("Master key is required.");if(null==t)throw new Error("User ID is required.");yield this.stateProvider.getUser(t,bf).update(t=>e)})}clearMasterKey(e){return vf(this,void 0,void 0,function*(){if(null==e)throw new Error("User ID is required.");yield this.stateProvider.getUser(e,bf).update(e=>null)})}setMasterKeyHash(e,t){return vf(this,void 0,void 0,function*(){if(null==e)throw new Error("Master key hash is required.");if(null==t)throw new Error("User ID is required.");yield this.stateProvider.getUser(t,wf).update(t=>e,{shouldUpdate:t=>t!==e})})}clearMasterKeyHash(e){return vf(this,void 0,void 0,function*(){if(null==e)throw new Error("User ID is required.");yield this.stateProvider.getUser(e,wf).update(e=>null,{shouldUpdate:e=>null!==e})})}setMasterKeyEncryptedUserKey(e,t){return vf(this,void 0,void 0,function*(){if(null==e||null==e.encryptedString)throw new Error("Encrypted Key is required.");if(null==t)throw new Error("User ID is required.");yield this.stateProvider.getUser(t,kf).update(t=>e.toJSON())})}setForceSetPasswordReason(e,t){return vf(this,void 0,void 0,function*(){if(null==e)throw new Error("Reason is required.");if(null==t)throw new Error("User ID is required.");(yield Ce(this.forceSetPasswordReason$(t)))===Nd.AdminForcePasswordReset&&e!==Nd.None||(yield this.stateProvider.getUser(t,Sf).update(t=>e))})}decryptUserKeyWithMasterKey(e,t,i){return vf(this,void 0,void 0,function*(){if(null!=i||(i=yield this.getMasterKeyEncryptedUserKey(t)),null!=e||(e=yield Ce(this.masterKey$(t))),null==e)throw new Error("No master key found.");yield xg.Ready;try{return new gu(Sg.IEs.decrypt_user_key_with_master_key(i.toSdk(),e.toEncoded()))}catch(e){return this.logService.warning("Failed to decrypt user key with master key."),null}})}makeMasterPasswordAuthenticationData(e,t,i){return vf(this,void 0,void 0,function*(){if(zh(e,"password"),zh(t,"kdf"),zh(i,"salt"),""===e)throw new Error("Master password cannot be empty.");i=i.toLowerCase().trim();const r=yield this.keyGenerationService.deriveKeyFromPassword(e,i,t),n=Tt.fromBufferToB64(yield this.cryptoFunctionService.pbkdf2(r.toEncoded(),e,"sha256",1));return{salt:i,kdf:t,masterPasswordAuthenticationHash:n}})}makeMasterPasswordUnlockData(e,t,i,r){return vf(this,void 0,void 0,function*(){if(zh(e,"password"),zh(t,"kdf"),zh(i,"salt"),zh(r,"userKey"),""===e)throw new Error("Master password cannot be empty.");i=i.toLowerCase().trim(),yield xg.Ready;const n=Sg.IEs.encrypt_user_key_with_master_password(r.toEncoded(),e,i,t.toSdkConfig());return new Gd(i,t,n)})}unwrapUserKeyFromMasterPasswordUnlockData(e,t){return vf(this,void 0,void 0,function*(){return zh(e,"password"),zh(t,"masterPasswordUnlockData"),yield xg.Ready,new gu(Sg.IEs.decrypt_user_key_with_master_password(t.masterKeyWrappedUserKey,e,t.salt,t.kdf.toSdkConfig()))})}setMasterPasswordUnlockData(e,t){return vf(this,void 0,void 0,function*(){zh(e,"masterPasswordUnlockData"),zh(t,"userId"),yield this.stateProvider.getUser(t,_f).update(()=>e.toJSON())})}masterPasswordUnlockData$(e){return zh(e,"userId"),this.stateProvider.getUser(e,_f).state$}setLegacyMasterKeyFromUnlockData(e,t,i){return vf(this,void 0,void 0,function*(){zh(e,"password"),zh(t,"masterPasswordUnlockData"),zh(i,"userId");const r=yield this.keyGenerationService.deriveKeyFromPassword(e,t.salt,t.kdf),n=yield this.hashMasterKey(e,r,lt.LocalAuthorization);yield this.setMasterKey(r,i),yield this.setMasterKeyHash(n,i)})}hashMasterKey(e,t,i){return vf(this,void 0,void 0,function*(){if(null==e)throw new Error("password is required.");if(null==t)throw new Error("key is required.");const r=i===lt.LocalAuthorization?2:1,n=yield this.cryptoFunctionService.pbkdf2(t.inner().encryptionKey,e,"sha256",r);return Tt.fromBufferToB64(n)})}}const Cf=new wi(Ir,"pinProtectedUserKeyEnvelopePersistent",{deserializer:e=>e,clearOn:["logout"]}),If=new wi(Er,"pinProtectedUserKeyEnvelopeEphemeral",{deserializer:e=>e,clearOn:["logout"]}),Ef=new wi(Ir,"userKeyEncryptedPin",{deserializer:e=>e,clearOn:["logout"]});var zf=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Pf{constructor(e){this.stateProvider=e}userKeyEncryptedPin$(e){return zh(e,"userId"),this.stateProvider.getUserState$(Ef,e).pipe(X(e=>e?new Nt(e):null))}pinSet$(e){return zh(e,"userId"),this.pinLockType$(e).pipe(X(e=>"DISABLED"!==e))}pinLockType$(e){return zh(e,"userId"),ai([this.pinProtectedUserKeyEnvelope$(e,"PERSISTENT").pipe(X(e=>null!=e)),this.stateProvider.getUserState$(Ef,e).pipe(X(e=>null!=e))]).pipe(X(([e,t])=>e?"PERSISTENT":t?"EPHEMERAL":"DISABLED"))}getPinLockType(e){return zf(this,void 0,void 0,function*(){return zh(e,"userId"),yield Ce(this.pinLockType$(e))})}getPinProtectedUserKeyEnvelope(e,t){return zf(this,void 0,void 0,function*(){return zh(e,"userId"),yield Ce(this.pinProtectedUserKeyEnvelope$(e,t))})}setPinState(e,t,i,r){return zf(this,void 0,void 0,function*(){if(zh(e,"userId"),zh(t,"pinProtectedUserKeyEnvelope"),zh(r,"pinLockType"),"EPHEMERAL"===r)yield this.stateProvider.setUserState(If,t,e);else{if("PERSISTENT"!==r)throw new Error(`Cannot set up PIN with pin lock type ${r}`);yield this.stateProvider.setUserState(Cf,t,e)}yield this.stateProvider.setUserState(Ef,i,e)})}clearPinState(e){return zf(this,void 0,void 0,function*(){zh(e,"userId"),yield this.stateProvider.setUserState(Ef,null,e),yield this.stateProvider.setUserState(If,null,e),yield this.stateProvider.setUserState(Cf,null,e)})}clearEphemeralPinState(e){return zf(this,void 0,void 0,function*(){zh(e,"userId"),yield this.stateProvider.setUserState(If,null,e)})}pinProtectedUserKeyEnvelope$(e,t){if(zh(e,"userId"),"EPHEMERAL"===t)return this.stateProvider.getUserState$(If,e);if("PERSISTENT"===t)return this.stateProvider.getUserState$(Cf,e);throw new Error(`Unsupported PinLockType: ${t}`)}}function Af(e,t){return i=this,r=void 0,a=function*(){const i=yield Ce(e);if(null==i)throw new Error(`Failed to get ${t}`);return i},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}var jf=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})},Tf=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===n)return n=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(a).then(e,function(t){return i(t),e()})}else n|=1}catch(e){i(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});class Df{constructor(e,t,i,r,n){this.encryptService=e,this.logService=t,this.keyService=i,this.sdkService=r,this.pinStateService=n}getPinLockType(e){return zh(e,"userId"),this.pinStateService.getPinLockType(e)}isPinSet(e){return jf(this,void 0,void 0,function*(){return zh(e,"userId"),"DISABLED"!==(yield this.pinStateService.getPinLockType(e))})}logout(e){return jf(this,void 0,void 0,function*(){zh(e,"userId"),yield this.pinStateService.clearPinState(e)})}userUnlocked(e){return jf(this,void 0,void 0,function*(){if("EPHEMERAL"===(yield this.pinStateService.getPinLockType(e))&&!(yield this.isPinDecryptionAvailable(e))){this.logService.info("[Pin Service] On first unlock: Setting up ephemeral PIN");const t=yield this.getPin(e);yield this.setPin(t,"EPHEMERAL",e)}})}getPin(e){return jf(this,void 0,void 0,function*(){zh(e,"userId");const t=yield Af(this.keyService.userKey$(e),"userKey"),i=yield Af(this.pinStateService.userKeyEncryptedPin$(e),"userKeyEncryptedPin");return this.encryptService.decryptString(i,t)})}setPin(e,t,i){return jf(this,void 0,void 0,function*(){zh(e,"pin"),zh(t,"pinLockType"),zh(i,"userId");const{pinProtectedUserKeyEnvelope:r,userKeyEncryptedPin:n}=yield Ce(this.sdkService.userClient$(i).pipe(X(t=>{const i={stack:[],error:void 0,hasError:!1};try{return function(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(i,t.take(),!1).value.crypto().enroll_pin(e)}catch(e){i.error=e,i.hasError=!0}finally{Tf(i)}})));yield this.pinStateService.setPinState(i,r,n,t)})}unsetPin(e){return jf(this,void 0,void 0,function*(){zh(e,"userId"),yield this.pinStateService.clearPinState(e)})}isPinDecryptionAvailable(e){return jf(this,void 0,void 0,function*(){zh(e,"userId");const t=yield this.pinStateService.getPinLockType(e);switch(t){case"DISABLED":return!1;case"PERSISTENT":return!0;case"EPHEMERAL":return null!=(yield this.pinStateService.getPinProtectedUserKeyEnvelope(e,"EPHEMERAL"));default:throw new Error(`Unexpected pinLockType: ${t}`)}})}decryptUserKeyWithPin(e,t){return jf(this,void 0,void 0,function*(){zh(e,"pin"),zh(t,"userId"),this.logService.info("[Pin Service] Pin-unlock via PinProtectedUserKeyEnvelope");const i=yield this.pinStateService.getPinLockType(t),r=yield this.pinStateService.getPinProtectedUserKeyEnvelope(t,i);try{const t=performance.now(),i=yield Ce(this.sdkService.client$.pipe(X(t=>{if(!t)throw new Error("SDK not available");return t.crypto().unseal_password_protected_key_envelope(e,r)})));return this.logService.measure(t,"Crypto","PinService","UnsealPinEnvelope"),new gu(i)}catch(e){return this.logService.error(`Failed to unseal pin: ${e}`),null}})}}class Of{constructor(e){this.accountCryptographicStateService=e}accountSecurityState$(e){return this.accountCryptographicStateService.accountCryptographicState$(e).pipe(X(e=>null==e?null:"V2"in e?e.V2.security_state:null))}}var Nf=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Rf{constructor(e,t,i=null,r,n,a,s,o){this.pinService=e,this.messagingService=t,this.reloadCallback=i,this.vaultTimeoutSettingsService=r,this.biometricStateService=n,this.accountService=a,this.logService=s,this.authService=o,this.reloadInterval=null}startProcessReload(){return Nf(this,void 0,void 0,function*(){var e;const t=yield Ce(this.accountService.accounts$);if(null!=t){const e=Object.keys(t);if(e.length>0)for(const t of e){let e=yield Ce(this.authService.authStatusFor$(t));if(e=yield this.authService.getAuthStatus(t),e===cu.Unlocked)return void this.logService.info("[Process Reload Service] User unlocked, preventing process reload")}}if(null!=this.reloadInterval)return;const i=null===(e=yield Ce(this.accountService.activeAccount$))||void 0===e?void 0:e.id;null==i||"EPHEMERAL"!==(yield this.pinService.getPinLockType(i))?(this.cancelProcessReload(),yield this.executeProcessReload()):this.logService.info("[Process Reload Service] Ephemeral pin active, preventing process reload")})}executeProcessReload(){return Nf(this,void 0,void 0,function*(){if(!(yield Ce(this.biometricStateService.fingerprintValidated$))){clearInterval(this.reloadInterval),this.reloadInterval=null;const e=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id),Fe(500)));if(null!=e&&(yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutActionByUserId$(e).pipe(Fe(500))))===od.LogOut){const e=yield Ce(this.accountService.nextUpAccount$.pipe(X(e=>{var t;return null!==(t=null==e?void 0:e.id)&&void 0!==t?t:null})));yield this.accountService.switchAccount(e)}return this.messagingService.send("reloadProcess"),void(null!=this.reloadCallback&&(yield this.reloadCallback()))}this.logService.info("[Process Reload Service] Desktop ipc fingerprint validated, preventing process reload"),null==this.reloadInterval&&(this.reloadInterval=setInterval(()=>Nf(this,void 0,void 0,function*(){return yield this.executeProcessReload()}),1e3))})}cancelProcessReload(){null!=this.reloadInterval&&(clearInterval(this.reloadInterval),this.reloadInterval=null)}}var Uf=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Ff{get client(){if(!this._client)throw new Error("IpcService not initialized. Call init() first.");return this._client}get messages$(){if(!this._messages$)throw new Error("IpcService not initialized. Call init() first.");return this._messages$}initWithClient(e){return Uf(this,void 0,void 0,function*(){this._client=e,yield this._client.start(),this._messages$=new $(e=>{let t=!0;return(()=>{Uf(this,void 0,void 0,function*(){const i=yield this.client.subscribe();for(;t;)try{const t=yield i.receive();e.next(t)}catch(t){e.error(t);break}})})(),()=>{t=!1}}).pipe(Jt({bufferSize:0,refCount:!0}))})}send(e){return Uf(this,void 0,void 0,function*(){yield this.client.send(e)})}}var qf=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Lf=fi.record(er,"ipcSessions",{deserializer:e=>e});class Bf{constructor(e){this.stateProvider=e,this.states=this.stateProvider.getGlobal(Lf)}get(e){return Ce(this.states.state$.pipe(X(t=>null==t?void 0:t[Mf(e)])))}save(e,t){return qf(this,void 0,void 0,function*(){yield this.states.update(i=>Object.assign(Object.assign({},i),{[Mf(e)]:t}))})}remove(e){return qf(this,void 0,void 0,function*(){yield this.states.update(t=>{const i=Object.assign({},t);return delete i[Mf(e)],i})})}}function Mf(e){return"object"==typeof e&&"Web"in e?`Web(${e.Web.id})`:e}class Vf{constructor(e){this.messageStream=e,this.allMessages$=this.messageStream}messages$(e){return this.allMessages$.pipe(Ie(t=>(null==t?void 0:t.command)===e.command))}}Vf.EMPTY=new Vf(pe);class $f{constructor(e){this.innerMessageSenders=e}send(e,t={}){for(const i of this.innerMessageSenders)i.send(e,t)}}class Kf{static combine(...e){return new $f(e)}}Kf.EMPTY=new $f([]);class Wf{constructor(e){this.command=e}}const Hf=Symbol("externalSource"),Gf=e=>!0===(null==e?void 0:e[Hf]),Qf=e=>"string"==typeof e?e:e.command;class Jf{constructor(e){this.messagesSubject=e}send(e,t={}){const i=Qf(e);this.messagesSubject.next(Object.assign(null!=t?t:{},{command:i}))}}var Yf=["addListener","removeListener"],Xf=["addEventListener","removeEventListener"],Zf=["on","off"];function ey(e,t,i,r){if(h(i)&&(r=i,i=void 0),r)return ey(e,t,i).pipe(ri(r));var n=c(function(e){return h(e.addEventListener)&&h(e.removeEventListener)}(e)?Xf.map(function(r){return function(n){return e[r](t,n,i)}}):function(e){return h(e.addListener)&&h(e.removeListener)}(e)?Yf.map(ty(e,t)):function(e){return h(e.on)&&h(e.off)}(e)?Zf.map(ty(e,t)):[],2),a=n[0],s=n[1];if(!a&&Z(e))return de(function(e){return ey(e,t,i)})(le(e));if(!a)throw new TypeError("Invalid event target");return new $(function(e){var t=function(){for(var t=[],i=0;i{this.pushEvent.complete(),this.pushChangeEvent.complete(),this.pushEvent=new H,this.pushChangeEvent=new H}),t=ey(self,"push").subscribe(this.pushEvent),i=ey(self,"pushsubscriptionchange").subscribe(this.pushChangeEvent);return e.add(t),e.add(i),e}supportStatus$(e){return this.configService.serverConfig$.pipe(X(e=>{var t;return(null===(t=null==e?void 0:e.push)||void 0===t?void 0:t.pushTechnology)===rf.WebPush?e.push.vapidPublicKey:null}),Zl(),X(t=>null==t?{type:"not-supported",reason:"server-not-configured"}:{type:"supported",service:new ky(t,e,this.webPushApiService,this.serviceWorkerRegistration,this.pushEvent,this.pushChangeEvent,this.stateProvider)}))}}class ky{constructor(e,t,i,r,n,a,s){this.vapidPublicKey=e,this.userId=t,this.webPushApiService=i,this.serviceWorkerRegistration=r,this.pushEvent$=n,this.pushChangeEvent$=a,this.stateProvider=s;const o=this.stateProvider.getGlobal(Sy);this.notifications$=this.getOrCreateSubscription$(this.vapidPublicKey).pipe(iy(o.state$.pipe(X(e=>null!=e?e:{}))),gc(e=>by(this,[e],void 0,function*([[e,t],i]){var r,n,a;if(null==t)throw new Error("Expected a non-null subscription.");e||(i={}),(null===(r=i[t.endpoint])||void 0===r?void 0:r.includes(this.userId))||(null!==(n=i[a=t.endpoint])&&void 0!==n||(i[a]=[]),i[t.endpoint].push(this.userId),yield o.update(()=>i),yield this.webPushApiService.putSubscription(t.toJSON(),this.userId))})),Le(()=>this.pushEvent$),X(e=>new sy(e.data.json().data)))}pushManagerSubscribe(e){return by(this,void 0,void 0,function*(){return yield this.serviceWorkerRegistration.pushManager.subscribe({userVisibleOnly:!1,applicationServerKey:e})})}getOrCreateSubscription$(e){return li(nc(()=>by(this,void 0,void 0,function*(){var t;const i=yield this.serviceWorkerRegistration.pushManager.getSubscription();return null==i?[!1,yield this.pushManagerSubscribe(e)]:Tt.fromBufferToUrlB64(null===(t=i.options)||void 0===t?void 0:t.applicationServerKey)!==e?(yield i.unsubscribe(),[!1,yield this.pushManagerSubscribe(e)]):[!0,i]})),this.pushChangeEvent$.pipe(X(e=>[!1,e.newSubscription])))}}const Sy=new fi(or,"subUsers",{deserializer:e=>{if(null==e)return{};const t={};for(const[i,r]of Object.entries(e))t[i]=Array.isArray(r)?r:[];return t}});var _y;!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Information=2]="Information",e[e.Warning=3]="Warning",e[e.Error=4]="Error",e[e.Critical=5]="Critical",e[e.None=6]="None"}(_y||(_y={}));const xy=[0,2e3,1e4,3e4,null];class Cy{constructor(e){this._retryDelays=void 0!==e?[...e,null]:xy}nextRetryDelayInMilliseconds(e){return this._retryDelays[e.previousRetryCount]}}class Iy{}Iy.Authorization="Authorization",Iy.Cookie="Cookie";class Ey{constructor(e,t,i){this.statusCode=e,this.statusText=t,this.content=i}}class zy{get(e,t){return this.send({...t,method:"GET",url:e})}post(e,t){return this.send({...t,method:"POST",url:e})}delete(e,t){return this.send({...t,method:"DELETE",url:e})}getCookieString(e){return""}}class Py extends zy{constructor(e,t){super(),this._innerClient=e,this._accessTokenFactory=t}async send(e){let t=!0;this._accessTokenFactory&&(!this._accessToken||e.url&&e.url.indexOf("/negotiate?")>0)&&(t=!1,this._accessToken=await this._accessTokenFactory()),this._setAuthorizationHeader(e);const i=await this._innerClient.send(e);return t&&401===i.statusCode&&this._accessTokenFactory?(this._accessToken=await this._accessTokenFactory(),this._setAuthorizationHeader(e),await this._innerClient.send(e)):i}_setAuthorizationHeader(e){e.headers||(e.headers={}),this._accessToken?e.headers[Iy.Authorization]=`Bearer ${this._accessToken}`:this._accessTokenFactory&&e.headers[Iy.Authorization]&&delete e.headers[Iy.Authorization]}getCookieString(e){return this._innerClient.getCookieString(e)}}class Ay extends Error{constructor(e,t){const i=new.target.prototype;super(`${e}: Status code '${t}'`),this.statusCode=t,this.__proto__=i}}class jy extends Error{constructor(e="A timeout occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Ty extends Error{constructor(e="An abort occurred."){const t=new.target.prototype;super(e),this.__proto__=t}}class Dy extends Error{constructor(e,t){const i=new.target.prototype;super(e),this.transport=t,this.errorType="UnsupportedTransportError",this.__proto__=i}}class Oy extends Error{constructor(e,t){const i=new.target.prototype;super(e),this.transport=t,this.errorType="DisabledTransportError",this.__proto__=i}}class Ny extends Error{constructor(e,t){const i=new.target.prototype;super(e),this.transport=t,this.errorType="FailedToStartTransportError",this.__proto__=i}}class Ry extends Error{constructor(e){const t=new.target.prototype;super(e),this.errorType="FailedToNegotiateWithServerError",this.__proto__=t}}class Uy extends Error{constructor(e,t){const i=new.target.prototype;super(e),this.innerErrors=t,this.__proto__=i}}class Fy{constructor(){}log(e,t){}}Fy.instance=new Fy;class qy{static isRequired(e,t){if(null==e)throw new Error(`The '${t}' argument is required.`)}static isNotEmpty(e,t){if(!e||e.match(/^\s*$/))throw new Error(`The '${t}' argument should not be empty.`)}static isIn(e,t,i){if(!(e in t))throw new Error(`Unknown ${i} value: ${e}.`)}}class Ly{static get isBrowser(){return!Ly.isNode&&"object"==typeof window&&"object"==typeof window.document}static get isWebWorker(){return!Ly.isNode&&"object"==typeof self&&"importScripts"in self}static get isReactNative(){return!Ly.isNode&&"object"==typeof window&&void 0===window.document}static get isNode(){return"undefined"!=typeof process&&process.release&&"node"===process.release.name}}function By(e,t){let i="";return My(e)?(i=`Binary data of length ${e.byteLength}`,t&&(i+=`. Content: '${function(e){const t=new Uint8Array(e);let i="";return t.forEach(e=>{i+=`0x${e<16?"0":""}${e.toString(16)} `}),i.substr(0,i.length-1)}(e)}'`)):"string"==typeof e&&(i=`String data of length ${e.length}`,t&&(i+=`. Content: '${e}'`)),i}function My(e){return e&&"undefined"!=typeof ArrayBuffer&&(e instanceof ArrayBuffer||e.constructor&&"ArrayBuffer"===e.constructor.name)}async function Vy(e,t,i,r,n,a){const s={},[o,l]=Wy();s[o]=l,e.log(_y.Trace,`(${t} transport) sending data. ${By(n,a.logMessageContent)}.`);const c=My(n)?"arraybuffer":"text",u=await i.post(r,{content:n,headers:{...s,...a.headers},responseType:c,timeout:a.timeout,withCredentials:a.withCredentials});e.log(_y.Trace,`(${t} transport) request complete. Response status: ${u.statusCode}.`)}class $y{constructor(e,t){this._subject=e,this._observer=t}dispose(){const e=this._subject.observers.indexOf(this._observer);e>-1&&this._subject.observers.splice(e,1),0===this._subject.observers.length&&this._subject.cancelCallback&&this._subject.cancelCallback().catch(e=>{})}}class Ky{constructor(e){this._minLevel=e,this.out=console}log(e,t){if(e>=this._minLevel){const i=`[${(new Date).toISOString()}] ${_y[e]}: ${t}`;switch(e){case _y.Critical:case _y.Error:this.out.error(i);break;case _y.Warning:this.out.warn(i);break;case _y.Information:this.out.info(i);break;default:this.out.log(i)}}}}function Wy(){let e="X-SignalR-User-Agent";return Ly.isNode&&(e="User-Agent"),[e,Hy("8.0.7",Gy(),Ly.isNode?"NodeJS":"Browser",Qy())]}function Hy(e,t,i,r){let n="Microsoft SignalR/";const a=e.split(".");return n+=`${a[0]}.${a[1]}`,n+=` (${e}; `,n+=t&&""!==t?`${t}; `:"Unknown OS; ",n+=`${i}`,n+=r?`; ${r}`:"; Unknown Runtime Version",n+=")",n}function Gy(){if(!Ly.isNode)return"";switch(process.platform){case"win32":return"Windows NT";case"darwin":return"macOS";case"linux":return"Linux";default:return process.platform}}function Qy(){if(Ly.isNode)return process.versions.node}function Jy(e){return e.stack?e.stack:e.message?e.message:`${e}`}class Yy extends zy{constructor(e){if(super(),this._logger=e,"undefined"==typeof fetch||Ly.isNode){const e=require;this._jar=new(e("tough-cookie").CookieJar),"undefined"==typeof fetch?this._fetchType=e("node-fetch"):this._fetchType=fetch,this._fetchType=e("fetch-cookie")(this._fetchType,this._jar)}else this._fetchType=fetch.bind(function(){if("undefined"!=typeof globalThis)return globalThis;if("undefined"!=typeof self)return self;if("undefined"!=typeof window)return window;if(void 0!==o.g)return o.g;throw new Error("could not find global")}());if("undefined"==typeof AbortController){const e=require;this._abortControllerType=e("abort-controller")}else this._abortControllerType=AbortController}async send(e){if(e.abortSignal&&e.abortSignal.aborted)throw new Ty;if(!e.method)throw new Error("No method defined.");if(!e.url)throw new Error("No url defined.");const t=new this._abortControllerType;let i;e.abortSignal&&(e.abortSignal.onabort=()=>{t.abort(),i=new Ty});let r,n=null;if(e.timeout){const r=e.timeout;n=setTimeout(()=>{t.abort(),this._logger.log(_y.Warning,"Timeout from HTTP request."),i=new jy},r)}""===e.content&&(e.content=void 0),e.content&&(e.headers=e.headers||{},My(e.content)?e.headers["Content-Type"]="application/octet-stream":e.headers["Content-Type"]="text/plain;charset=UTF-8");try{r=await this._fetchType(e.url,{body:e.content,cache:"no-cache",credentials:!0===e.withCredentials?"include":"same-origin",headers:{"X-Requested-With":"XMLHttpRequest",...e.headers},method:e.method,mode:"cors",redirect:"follow",signal:t.signal})}catch(e){if(i)throw i;throw this._logger.log(_y.Warning,`Error from HTTP request. ${e}.`),e}finally{n&&clearTimeout(n),e.abortSignal&&(e.abortSignal.onabort=null)}if(!r.ok){const e=await Xy(r,"text");throw new Ay(e||r.statusText,r.status)}const a=Xy(r,e.responseType),s=await a;return new Ey(r.status,r.statusText,s)}getCookieString(e){let t="";return Ly.isNode&&this._jar&&this._jar.getCookies(e,(e,i)=>t=i.join("; ")),t}}function Xy(e,t){let i;switch(t){case"arraybuffer":i=e.arrayBuffer();break;case"text":default:i=e.text();break;case"blob":case"document":case"json":throw new Error(`${t} is not supported.`)}return i}class Zy extends zy{constructor(e){super(),this._logger=e}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Ty):e.method?e.url?new Promise((t,i)=>{const r=new XMLHttpRequest;r.open(e.method,e.url,!0),r.withCredentials=void 0===e.withCredentials||e.withCredentials,r.setRequestHeader("X-Requested-With","XMLHttpRequest"),""===e.content&&(e.content=void 0),e.content&&(My(e.content)?r.setRequestHeader("Content-Type","application/octet-stream"):r.setRequestHeader("Content-Type","text/plain;charset=UTF-8"));const n=e.headers;n&&Object.keys(n).forEach(e=>{r.setRequestHeader(e,n[e])}),e.responseType&&(r.responseType=e.responseType),e.abortSignal&&(e.abortSignal.onabort=()=>{r.abort(),i(new Ty)}),e.timeout&&(r.timeout=e.timeout),r.onload=()=>{e.abortSignal&&(e.abortSignal.onabort=null),r.status>=200&&r.status<300?t(new Ey(r.status,r.statusText,r.response||r.responseText)):i(new Ay(r.response||r.responseText||r.statusText,r.status))},r.onerror=()=>{this._logger.log(_y.Warning,`Error from HTTP request. ${r.status}: ${r.statusText}.`),i(new Ay(r.statusText,r.status))},r.ontimeout=()=>{this._logger.log(_y.Warning,"Timeout from HTTP request."),i(new jy)},r.send(e.content)}):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}}class ev extends zy{constructor(e){if(super(),"undefined"!=typeof fetch||Ly.isNode)this._httpClient=new Yy(e);else{if("undefined"==typeof XMLHttpRequest)throw new Error("No usable HttpClient found.");this._httpClient=new Zy(e)}}send(e){return e.abortSignal&&e.abortSignal.aborted?Promise.reject(new Ty):e.method?e.url?this._httpClient.send(e):Promise.reject(new Error("No url defined.")):Promise.reject(new Error("No method defined."))}getCookieString(e){return this._httpClient.getCookieString(e)}}var tv,iv,rv,nv;!function(e){e[e.None=0]="None",e[e.WebSockets=1]="WebSockets",e[e.ServerSentEvents=2]="ServerSentEvents",e[e.LongPolling=4]="LongPolling"}(tv||(tv={})),function(e){e[e.Text=1]="Text",e[e.Binary=2]="Binary"}(iv||(iv={}));class av{constructor(){this._isAborted=!1,this.onabort=null}abort(){this._isAborted||(this._isAborted=!0,this.onabort&&this.onabort())}get signal(){return this}get aborted(){return this._isAborted}}class sv{get pollAborted(){return this._pollAbort.aborted}constructor(e,t,i){this._httpClient=e,this._logger=t,this._pollAbort=new av,this._options=i,this._running=!1,this.onreceive=null,this.onclose=null}async connect(e,t){if(qy.isRequired(e,"url"),qy.isRequired(t,"transferFormat"),qy.isIn(t,iv,"transferFormat"),this._url=e,this._logger.log(_y.Trace,"(LongPolling transport) Connecting."),t===iv.Binary&&"undefined"!=typeof XMLHttpRequest&&"string"!=typeof(new XMLHttpRequest).responseType)throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");const[i,r]=Wy(),n={[i]:r,...this._options.headers},a={abortSignal:this._pollAbort.signal,headers:n,timeout:1e5,withCredentials:this._options.withCredentials};t===iv.Binary&&(a.responseType="arraybuffer");const s=`${e}&_=${Date.now()}`;this._logger.log(_y.Trace,`(LongPolling transport) polling: ${s}.`);const o=await this._httpClient.get(s,a);200!==o.statusCode?(this._logger.log(_y.Error,`(LongPolling transport) Unexpected response code: ${o.statusCode}.`),this._closeError=new Ay(o.statusText||"",o.statusCode),this._running=!1):this._running=!0,this._receiving=this._poll(this._url,a)}async _poll(e,t){try{for(;this._running;)try{const i=`${e}&_=${Date.now()}`;this._logger.log(_y.Trace,`(LongPolling transport) polling: ${i}.`);const r=await this._httpClient.get(i,t);204===r.statusCode?(this._logger.log(_y.Information,"(LongPolling transport) Poll terminated by server."),this._running=!1):200!==r.statusCode?(this._logger.log(_y.Error,`(LongPolling transport) Unexpected response code: ${r.statusCode}.`),this._closeError=new Ay(r.statusText||"",r.statusCode),this._running=!1):r.content?(this._logger.log(_y.Trace,`(LongPolling transport) data received. ${By(r.content,this._options.logMessageContent)}.`),this.onreceive&&this.onreceive(r.content)):this._logger.log(_y.Trace,"(LongPolling transport) Poll timed out, reissuing.")}catch(e){this._running?e instanceof jy?this._logger.log(_y.Trace,"(LongPolling transport) Poll timed out, reissuing."):(this._closeError=e,this._running=!1):this._logger.log(_y.Trace,`(LongPolling transport) Poll errored after shutdown: ${e.message}`)}}finally{this._logger.log(_y.Trace,"(LongPolling transport) Polling complete."),this.pollAborted||this._raiseOnClose()}}async send(e){return this._running?Vy(this._logger,"LongPolling",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}async stop(){this._logger.log(_y.Trace,"(LongPolling transport) Stopping polling."),this._running=!1,this._pollAbort.abort();try{await this._receiving,this._logger.log(_y.Trace,`(LongPolling transport) sending DELETE request to ${this._url}.`);const e={},[t,i]=Wy();e[t]=i;const r={headers:{...e,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials};let n;try{await this._httpClient.delete(this._url,r)}catch(e){n=e}n?n instanceof Ay&&(404===n.statusCode?this._logger.log(_y.Trace,"(LongPolling transport) A 404 response was returned from sending a DELETE request."):this._logger.log(_y.Trace,`(LongPolling transport) Error sending a DELETE request: ${n}`)):this._logger.log(_y.Trace,"(LongPolling transport) DELETE request accepted.")}finally{this._logger.log(_y.Trace,"(LongPolling transport) Stop finished."),this._raiseOnClose()}}_raiseOnClose(){if(this.onclose){let e="(LongPolling transport) Firing onclose event.";this._closeError&&(e+=" Error: "+this._closeError),this._logger.log(_y.Trace,e),this.onclose(this._closeError)}}}class ov{constructor(e,t,i,r){this._httpClient=e,this._accessToken=t,this._logger=i,this._options=r,this.onreceive=null,this.onclose=null}async connect(e,t){return qy.isRequired(e,"url"),qy.isRequired(t,"transferFormat"),qy.isIn(t,iv,"transferFormat"),this._logger.log(_y.Trace,"(SSE transport) Connecting."),this._url=e,this._accessToken&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(this._accessToken)}`),new Promise((i,r)=>{let n,a=!1;if(t===iv.Text){if(Ly.isBrowser||Ly.isWebWorker)n=new this._options.EventSource(e,{withCredentials:this._options.withCredentials});else{const t=this._httpClient.getCookieString(e),i={};i.Cookie=t;const[r,a]=Wy();i[r]=a,n=new this._options.EventSource(e,{withCredentials:this._options.withCredentials,headers:{...i,...this._options.headers}})}try{n.onmessage=e=>{if(this.onreceive)try{this._logger.log(_y.Trace,`(SSE transport) data received. ${By(e.data,this._options.logMessageContent)}.`),this.onreceive(e.data)}catch(e){return void this._close(e)}},n.onerror=e=>{a?this._close():r(new Error("EventSource failed to connect. The connection could not be found on the server, either the connection ID is not present on the server, or a proxy is refusing/buffering the connection. If you have multiple servers check that sticky sessions are enabled."))},n.onopen=()=>{this._logger.log(_y.Information,`SSE connected to ${this._url}`),this._eventSource=n,a=!0,i()}}catch(e){return void r(e)}}else r(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"))})}async send(e){return this._eventSource?Vy(this._logger,"SSE",this._httpClient,this._url,e,this._options):Promise.reject(new Error("Cannot send until the transport is connected"))}stop(){return this._close(),Promise.resolve()}_close(e){this._eventSource&&(this._eventSource.close(),this._eventSource=void 0,this.onclose&&this.onclose(e))}}class lv{constructor(e,t,i,r,n,a){this._logger=i,this._accessTokenFactory=t,this._logMessageContent=r,this._webSocketConstructor=n,this._httpClient=e,this.onreceive=null,this.onclose=null,this._headers=a}async connect(e,t){let i;return qy.isRequired(e,"url"),qy.isRequired(t,"transferFormat"),qy.isIn(t,iv,"transferFormat"),this._logger.log(_y.Trace,"(WebSockets transport) Connecting."),this._accessTokenFactory&&(i=await this._accessTokenFactory()),new Promise((r,n)=>{let a;e=e.replace(/^http/,"ws");const s=this._httpClient.getCookieString(e);let o=!1;if(Ly.isNode||Ly.isReactNative){const t={},[r,n]=Wy();t[r]=n,i&&(t[Iy.Authorization]=`Bearer ${i}`),s&&(t[Iy.Cookie]=s),a=new this._webSocketConstructor(e,void 0,{headers:{...t,...this._headers}})}else i&&(e+=(e.indexOf("?")<0?"?":"&")+`access_token=${encodeURIComponent(i)}`);a||(a=new this._webSocketConstructor(e)),t===iv.Binary&&(a.binaryType="arraybuffer"),a.onopen=t=>{this._logger.log(_y.Information,`WebSocket connected to ${e}.`),this._webSocket=a,o=!0,r()},a.onerror=e=>{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"There was an error with the transport",this._logger.log(_y.Information,`(WebSockets transport) ${t}.`)},a.onmessage=e=>{if(this._logger.log(_y.Trace,`(WebSockets transport) data received. ${By(e.data,this._logMessageContent)}.`),this.onreceive)try{this.onreceive(e.data)}catch(e){return void this._close(e)}},a.onclose=e=>{if(o)this._close(e);else{let t=null;t="undefined"!=typeof ErrorEvent&&e instanceof ErrorEvent?e.error:"WebSocket failed to connect. The connection could not be found on the server, either the endpoint may not be a SignalR endpoint, the connection ID is not present on the server, or there is a proxy blocking WebSockets. If you have multiple servers check that sticky sessions are enabled.",n(new Error(t))}}})}send(e){return this._webSocket&&this._webSocket.readyState===this._webSocketConstructor.OPEN?(this._logger.log(_y.Trace,`(WebSockets transport) sending data. ${By(e,this._logMessageContent)}.`),this._webSocket.send(e),Promise.resolve()):Promise.reject("WebSocket is not in the OPEN state")}stop(){return this._webSocket&&this._close(void 0),Promise.resolve()}_close(e){this._webSocket&&(this._webSocket.onclose=()=>{},this._webSocket.onmessage=()=>{},this._webSocket.onerror=()=>{},this._webSocket.close(),this._webSocket=void 0),this._logger.log(_y.Trace,"(WebSockets transport) socket closed."),this.onclose&&(!this._isCloseEvent(e)||!1!==e.wasClean&&1e3===e.code?e instanceof Error?this.onclose(e):this.onclose():this.onclose(new Error(`WebSocket closed with status code: ${e.code} (${e.reason||"no reason given"}).`)))}_isCloseEvent(e){return e&&"boolean"==typeof e.wasClean&&"number"==typeof e.code}}class cv{constructor(e,t={}){var i;if(this._stopPromiseResolver=()=>{},this.features={},this._negotiateVersion=1,qy.isRequired(e,"url"),this._logger=void 0===(i=t.logger)?new Ky(_y.Information):null===i?Fy.instance:void 0!==i.log?i:new Ky(i),this.baseUrl=this._resolveUrl(e),(t=t||{}).logMessageContent=void 0!==t.logMessageContent&&t.logMessageContent,"boolean"!=typeof t.withCredentials&&void 0!==t.withCredentials)throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");t.withCredentials=void 0===t.withCredentials||t.withCredentials,t.timeout=void 0===t.timeout?1e5:t.timeout;let r=null,n=null;if(Ly.isNode){const e=require;r=e("ws"),n=e("eventsource")}Ly.isNode||"undefined"==typeof WebSocket||t.WebSocket?Ly.isNode&&!t.WebSocket&&r&&(t.WebSocket=r):t.WebSocket=WebSocket,Ly.isNode||"undefined"==typeof EventSource||t.EventSource?Ly.isNode&&!t.EventSource&&void 0!==n&&(t.EventSource=n):t.EventSource=EventSource,this._httpClient=new Py(t.httpClient||new ev(this._logger),t.accessTokenFactory),this._connectionState="Disconnected",this._connectionStarted=!1,this._options=t,this.onreceive=null,this.onclose=null}async start(e){if(e=e||iv.Binary,qy.isIn(e,iv,"transferFormat"),this._logger.log(_y.Debug,`Starting connection with transfer format '${iv[e]}'.`),"Disconnected"!==this._connectionState)return Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."));if(this._connectionState="Connecting",this._startInternalPromise=this._startInternal(e),await this._startInternalPromise,"Disconnecting"===this._connectionState){const e="Failed to start the HttpConnection before stop() was called.";return this._logger.log(_y.Error,e),await this._stopPromise,Promise.reject(new Ty(e))}if("Connected"!==this._connectionState){const e="HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";return this._logger.log(_y.Error,e),Promise.reject(new Ty(e))}this._connectionStarted=!0}send(e){return"Connected"!==this._connectionState?Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State.")):(this._sendQueue||(this._sendQueue=new uv(this.transport)),this._sendQueue.send(e))}async stop(e){return"Disconnected"===this._connectionState?(this._logger.log(_y.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnected state.`),Promise.resolve()):"Disconnecting"===this._connectionState?(this._logger.log(_y.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise):(this._connectionState="Disconnecting",this._stopPromise=new Promise(e=>{this._stopPromiseResolver=e}),await this._stopInternal(e),void await this._stopPromise)}async _stopInternal(e){this._stopError=e;try{await this._startInternalPromise}catch(e){}if(this.transport){try{await this.transport.stop()}catch(e){this._logger.log(_y.Error,`HttpConnection.transport.stop() threw error '${e}'.`),this._stopConnection()}this.transport=void 0}else this._logger.log(_y.Debug,"HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.")}async _startInternal(e){let t=this.baseUrl;this._accessTokenFactory=this._options.accessTokenFactory,this._httpClient._accessTokenFactory=this._accessTokenFactory;try{if(this._options.skipNegotiation){if(this._options.transport!==tv.WebSockets)throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");this.transport=this._constructTransport(tv.WebSockets),await this._startTransport(t,e)}else{let i=null,r=0;do{if(i=await this._getNegotiationResponse(t),"Disconnecting"===this._connectionState||"Disconnected"===this._connectionState)throw new Ty("The connection was stopped during negotiation.");if(i.error)throw new Error(i.error);if(i.ProtocolVersion)throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");if(i.url&&(t=i.url),i.accessToken){const e=i.accessToken;this._accessTokenFactory=()=>e,this._httpClient._accessToken=e,this._httpClient._accessTokenFactory=void 0}r++}while(i.url&&r<100);if(100===r&&i.url)throw new Error("Negotiate redirection limit exceeded.");await this._createTransport(t,this._options.transport,i,e)}this.transport instanceof sv&&(this.features.inherentKeepAlive=!0),"Connecting"===this._connectionState&&(this._logger.log(_y.Debug,"The HttpConnection connected successfully."),this._connectionState="Connected")}catch(e){return this._logger.log(_y.Error,"Failed to start the connection: "+e),this._connectionState="Disconnected",this.transport=void 0,this._stopPromiseResolver(),Promise.reject(e)}}async _getNegotiationResponse(e){const t={},[i,r]=Wy();t[i]=r;const n=this._resolveNegotiateUrl(e);this._logger.log(_y.Debug,`Sending negotiation request: ${n}.`);try{const e=await this._httpClient.post(n,{content:"",headers:{...t,...this._options.headers},timeout:this._options.timeout,withCredentials:this._options.withCredentials});if(200!==e.statusCode)return Promise.reject(new Error(`Unexpected status code returned from negotiate '${e.statusCode}'`));const i=JSON.parse(e.content);return(!i.negotiateVersion||i.negotiateVersion<1)&&(i.connectionToken=i.connectionId),i.useStatefulReconnect&&!0!==this._options._useStatefulReconnect?Promise.reject(new Ry("Client didn't negotiate Stateful Reconnect but the server did.")):i}catch(e){let t="Failed to complete negotiation with the server: "+e;return e instanceof Ay&&404===e.statusCode&&(t+=" Either this is not a SignalR endpoint or there is a proxy blocking the connection."),this._logger.log(_y.Error,t),Promise.reject(new Ry(t))}}_createConnectUrl(e,t){return t?e+(-1===e.indexOf("?")?"?":"&")+`id=${t}`:e}async _createTransport(e,t,i,r){let n=this._createConnectUrl(e,i.connectionToken);if(this._isITransport(t))return this._logger.log(_y.Debug,"Connection was provided an instance of ITransport, using that directly."),this.transport=t,await this._startTransport(n,r),void(this.connectionId=i.connectionId);const a=[],s=i.availableTransports||[];let o=i;for(const i of s){const s=this._resolveTransportOrError(i,t,r,!0===(null==o?void 0:o.useStatefulReconnect));if(s instanceof Error)a.push(`${i.transport} failed:`),a.push(s);else if(this._isITransport(s)){if(this.transport=s,!o){try{o=await this._getNegotiationResponse(e)}catch(e){return Promise.reject(e)}n=this._createConnectUrl(e,o.connectionToken)}try{return await this._startTransport(n,r),void(this.connectionId=o.connectionId)}catch(e){if(this._logger.log(_y.Error,`Failed to start the transport '${i.transport}': ${e}`),o=void 0,a.push(new Ny(`${i.transport} failed: ${e}`,tv[i.transport])),"Connecting"!==this._connectionState){const e="Failed to select transport before stop() was called.";return this._logger.log(_y.Debug,e),Promise.reject(new Ty(e))}}}}return a.length>0?Promise.reject(new Uy(`Unable to connect to the server with any of the available transports. ${a.join(" ")}`,a)):Promise.reject(new Error("None of the transports supported by the client are supported by the server."))}_constructTransport(e){switch(e){case tv.WebSockets:if(!this._options.WebSocket)throw new Error("'WebSocket' is not supported in your environment.");return new lv(this._httpClient,this._accessTokenFactory,this._logger,this._options.logMessageContent,this._options.WebSocket,this._options.headers||{});case tv.ServerSentEvents:if(!this._options.EventSource)throw new Error("'EventSource' is not supported in your environment.");return new ov(this._httpClient,this._httpClient._accessToken,this._logger,this._options);case tv.LongPolling:return new sv(this._httpClient,this._logger,this._options);default:throw new Error(`Unknown transport: ${e}.`)}}_startTransport(e,t){return this.transport.onreceive=this.onreceive,this.features.reconnect?this.transport.onclose=async i=>{let r=!1;if(this.features.reconnect){try{this.features.disconnected(),await this.transport.connect(e,t),await this.features.resend()}catch{r=!0}r&&this._stopConnection(i)}else this._stopConnection(i)}:this.transport.onclose=e=>this._stopConnection(e),this.transport.connect(e,t)}_resolveTransportOrError(e,t,i,r){const n=tv[e.transport];if(null==n)return this._logger.log(_y.Debug,`Skipping transport '${e.transport}' because it is not supported by this client.`),new Error(`Skipping transport '${e.transport}' because it is not supported by this client.`);if(!function(e,t){return!e||0!==(t&e)}(t,n))return this._logger.log(_y.Debug,`Skipping transport '${tv[n]}' because it was disabled by the client.`),new Oy(`'${tv[n]}' is disabled by the client.`,n);if(!(e.transferFormats.map(e=>iv[e]).indexOf(i)>=0))return this._logger.log(_y.Debug,`Skipping transport '${tv[n]}' because it does not support the requested transfer format '${iv[i]}'.`),new Error(`'${tv[n]}' does not support ${iv[i]}.`);if(n===tv.WebSockets&&!this._options.WebSocket||n===tv.ServerSentEvents&&!this._options.EventSource)return this._logger.log(_y.Debug,`Skipping transport '${tv[n]}' because it is not supported in your environment.'`),new Dy(`'${tv[n]}' is not supported in your environment.`,n);this._logger.log(_y.Debug,`Selecting transport '${tv[n]}'.`);try{return this.features.reconnect=n===tv.WebSockets?r:void 0,this._constructTransport(n)}catch(e){return e}}_isITransport(e){return e&&"object"==typeof e&&"connect"in e}_stopConnection(e){if(this._logger.log(_y.Debug,`HttpConnection.stopConnection(${e}) called while in state ${this._connectionState}.`),this.transport=void 0,e=this._stopError||e,this._stopError=void 0,"Disconnected"!==this._connectionState){if("Connecting"===this._connectionState)throw this._logger.log(_y.Warning,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is still in the connecting state.`),new Error(`HttpConnection.stopConnection(${e}) was called while the connection is still in the connecting state.`);if("Disconnecting"===this._connectionState&&this._stopPromiseResolver(),e?this._logger.log(_y.Error,`Connection disconnected with error '${e}'.`):this._logger.log(_y.Information,"Connection disconnected."),this._sendQueue&&(this._sendQueue.stop().catch(e=>{this._logger.log(_y.Error,`TransportSendQueue.stop() threw error '${e}'.`)}),this._sendQueue=void 0),this.connectionId=void 0,this._connectionState="Disconnected",this._connectionStarted){this._connectionStarted=!1;try{this.onclose&&this.onclose(e)}catch(t){this._logger.log(_y.Error,`HttpConnection.onclose(${e}) threw error '${t}'.`)}}}else this._logger.log(_y.Debug,`Call to HttpConnection.stopConnection(${e}) was ignored because the connection is already in the disconnected state.`)}_resolveUrl(e){if(0===e.lastIndexOf("https://",0)||0===e.lastIndexOf("http://",0))return e;if(!Ly.isBrowser)throw new Error(`Cannot resolve '${e}'.`);const t=window.document.createElement("a");return t.href=e,this._logger.log(_y.Information,`Normalizing '${e}' to '${t.href}'.`),t.href}_resolveNegotiateUrl(e){const t=new URL(e);t.pathname.endsWith("/")?t.pathname+="negotiate":t.pathname+="/negotiate";const i=new URLSearchParams(t.searchParams);return i.has("negotiateVersion")||i.append("negotiateVersion",this._negotiateVersion.toString()),i.has("useStatefulReconnect")?"true"===i.get("useStatefulReconnect")&&(this._options._useStatefulReconnect=!0):!0===this._options._useStatefulReconnect&&i.append("useStatefulReconnect","true"),t.search=i.toString(),t.toString()}}class uv{constructor(e){this._transport=e,this._buffer=[],this._executing=!0,this._sendBufferedData=new dv,this._transportResult=new dv,this._sendLoopPromise=this._sendLoop()}send(e){return this._bufferData(e),this._transportResult||(this._transportResult=new dv),this._transportResult.promise}stop(){return this._executing=!1,this._sendBufferedData.resolve(),this._sendLoopPromise}_bufferData(e){if(this._buffer.length&&typeof this._buffer[0]!=typeof e)throw new Error(`Expected data to be of type ${typeof this._buffer} but was of type ${typeof e}`);this._buffer.push(e),this._sendBufferedData.resolve()}async _sendLoop(){for(;;){if(await this._sendBufferedData.promise,!this._executing){this._transportResult&&this._transportResult.reject("Connection stopped.");break}this._sendBufferedData=new dv;const e=this._transportResult;this._transportResult=void 0;const t="string"==typeof this._buffer[0]?this._buffer.join(""):uv._concatBuffers(this._buffer);this._buffer.length=0;try{await this._transport.send(t),e.resolve()}catch(t){e.reject(t)}}}static _concatBuffers(e){const t=e.map(e=>e.byteLength).reduce((e,t)=>e+t),i=new Uint8Array(t);let r=0;for(const t of e)i.set(new Uint8Array(t),r),r+=t.byteLength;return i.buffer}}class dv{constructor(){this.promise=new Promise((e,t)=>[this._resolver,this._rejecter]=[e,t])}resolve(){this._resolver()}reject(e){this._rejecter(e)}}class hv{static write(e){return`${e}${hv.RecordSeparator}`}static parse(e){if(e[e.length-1]!==hv.RecordSeparator)throw new Error("Message is incomplete.");const t=e.split(hv.RecordSeparator);return t.pop(),t}}hv.RecordSeparatorCode=30,hv.RecordSeparator=String.fromCharCode(hv.RecordSeparatorCode);class pv{writeHandshakeRequest(e){return hv.write(JSON.stringify(e))}parseHandshakeResponse(e){let t,i;if(My(e)){const r=new Uint8Array(e),n=r.indexOf(hv.RecordSeparatorCode);if(-1===n)throw new Error("Message is incomplete.");const a=n+1;t=String.fromCharCode.apply(null,Array.prototype.slice.call(r.slice(0,a))),i=r.byteLength>a?r.slice(a).buffer:null}else{const r=e,n=r.indexOf(hv.RecordSeparator);if(-1===n)throw new Error("Message is incomplete.");const a=n+1;t=r.substring(0,a),i=r.length>a?r.substring(a):null}const r=hv.parse(t),n=JSON.parse(r[0]);if(n.type)throw new Error("Expected a handshake response from the server.");return[i,n]}}!function(e){e[e.Invocation=1]="Invocation",e[e.StreamItem=2]="StreamItem",e[e.Completion=3]="Completion",e[e.StreamInvocation=4]="StreamInvocation",e[e.CancelInvocation=5]="CancelInvocation",e[e.Ping=6]="Ping",e[e.Close=7]="Close",e[e.Ack=8]="Ack",e[e.Sequence=9]="Sequence"}(rv||(rv={}));class mv{constructor(){this.observers=[]}next(e){for(const t of this.observers)t.next(e)}error(e){for(const t of this.observers)t.error&&t.error(e)}complete(){for(const e of this.observers)e.complete&&e.complete()}subscribe(e){return this.observers.push(e),new $y(this,e)}}class gv{constructor(e,t,i){this._bufferSize=1e5,this._messages=[],this._totalMessageCount=0,this._waitForSequenceMessage=!1,this._nextReceivingSequenceId=1,this._latestReceivedSequenceId=0,this._bufferedByteCount=0,this._reconnectInProgress=!1,this._protocol=e,this._connection=t,this._bufferSize=i}async _send(e){const t=this._protocol.writeMessage(e);let i=Promise.resolve();if(this._isInvocationMessage(e)){this._totalMessageCount++;let e=()=>{},r=()=>{};My(t)?this._bufferedByteCount+=t.byteLength:this._bufferedByteCount+=t.length,this._bufferedByteCount>=this._bufferSize&&(i=new Promise((t,i)=>{e=t,r=i})),this._messages.push(new fv(t,this._totalMessageCount,e,r))}try{this._reconnectInProgress||await this._connection.send(t)}catch{this._disconnected()}await i}_ack(e){let t=-1;for(let i=0;ithis._nextReceivingSequenceId?this._connection.stop(new Error("Sequence ID greater than amount of messages we've received.")):this._nextReceivingSequenceId=e.sequenceId}_disconnected(){this._reconnectInProgress=!0,this._waitForSequenceMessage=!0}async _resend(){const e=0!==this._messages.length?this._messages[0]._id:this._totalMessageCount+1;await this._connection.send(this._protocol.writeMessage({type:rv.Sequence,sequenceId:e}));const t=this._messages;for(const e of t)await this._connection.send(e._message);this._reconnectInProgress=!1}_dispose(e){null!=e||(e=new Error("Unable to reconnect to server."));for(const t of this._messages)t._rejector(e)}_isInvocationMessage(e){switch(e.type){case rv.Invocation:case rv.StreamItem:case rv.Completion:case rv.StreamInvocation:case rv.CancelInvocation:return!0;case rv.Close:case rv.Sequence:case rv.Ping:case rv.Ack:return!1}}_ackTimer(){void 0===this._ackTimerHandle&&(this._ackTimerHandle=setTimeout(async()=>{try{this._reconnectInProgress||await this._connection.send(this._protocol.writeMessage({type:rv.Ack,sequenceId:this._latestReceivedSequenceId}))}catch{}clearTimeout(this._ackTimerHandle),this._ackTimerHandle=void 0},1e3))}}class fv{constructor(e,t,i,r){this._message=e,this._id=t,this._resolver=i,this._rejector=r}}!function(e){e.Disconnected="Disconnected",e.Connecting="Connecting",e.Connected="Connected",e.Disconnecting="Disconnecting",e.Reconnecting="Reconnecting"}(nv||(nv={}));class yv{static create(e,t,i,r,n,a,s){return new yv(e,t,i,r,n,a,s)}constructor(e,t,i,r,n,a,s){this._nextKeepAlive=0,this._freezeEventListener=()=>{this._logger.log(_y.Warning,"The page is being frozen, this will likely lead to the connection being closed and messages being lost. For more information see the docs at https://learn.microsoft.com/aspnet/core/signalr/javascript-client#bsleep")},qy.isRequired(e,"connection"),qy.isRequired(t,"logger"),qy.isRequired(i,"protocol"),this.serverTimeoutInMilliseconds=null!=n?n:3e4,this.keepAliveIntervalInMilliseconds=null!=a?a:15e3,this._statefulReconnectBufferSize=null!=s?s:1e5,this._logger=t,this._protocol=i,this.connection=e,this._reconnectPolicy=r,this._handshakeProtocol=new pv,this.connection.onreceive=e=>this._processIncomingData(e),this.connection.onclose=e=>this._connectionClosed(e),this._callbacks={},this._methods={},this._closedCallbacks=[],this._reconnectingCallbacks=[],this._reconnectedCallbacks=[],this._invocationId=0,this._receivedHandshakeResponse=!1,this._connectionState=nv.Disconnected,this._connectionStarted=!1,this._cachedPingMessage=this._protocol.writeMessage({type:rv.Ping})}get state(){return this._connectionState}get connectionId(){return this.connection&&this.connection.connectionId||null}get baseUrl(){return this.connection.baseUrl||""}set baseUrl(e){if(this._connectionState!==nv.Disconnected&&this._connectionState!==nv.Reconnecting)throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");if(!e)throw new Error("The HubConnection url must be a valid url.");this.connection.baseUrl=e}start(){return this._startPromise=this._startWithStateTransitions(),this._startPromise}async _startWithStateTransitions(){if(this._connectionState!==nv.Disconnected)return Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."));this._connectionState=nv.Connecting,this._logger.log(_y.Debug,"Starting HubConnection.");try{await this._startInternal(),Ly.isBrowser&&window.document.addEventListener("freeze",this._freezeEventListener),this._connectionState=nv.Connected,this._connectionStarted=!0,this._logger.log(_y.Debug,"HubConnection connected successfully.")}catch(e){return this._connectionState=nv.Disconnected,this._logger.log(_y.Debug,`HubConnection failed to start successfully because of error '${e}'.`),Promise.reject(e)}}async _startInternal(){this._stopDuringStartError=void 0,this._receivedHandshakeResponse=!1;const e=new Promise((e,t)=>{this._handshakeResolver=e,this._handshakeRejecter=t});await this.connection.start(this._protocol.transferFormat);try{let t=this._protocol.version;this.connection.features.reconnect||(t=1);const i={protocol:this._protocol.name,version:t};if(this._logger.log(_y.Debug,"Sending handshake request."),await this._sendMessage(this._handshakeProtocol.writeHandshakeRequest(i)),this._logger.log(_y.Information,`Using HubProtocol '${this._protocol.name}'.`),this._cleanupTimeout(),this._resetTimeoutPeriod(),this._resetKeepAliveInterval(),await e,this._stopDuringStartError)throw this._stopDuringStartError;!!this.connection.features.reconnect&&(this._messageBuffer=new gv(this._protocol,this.connection,this._statefulReconnectBufferSize),this.connection.features.disconnected=this._messageBuffer._disconnected.bind(this._messageBuffer),this.connection.features.resend=()=>{if(this._messageBuffer)return this._messageBuffer._resend()}),this.connection.features.inherentKeepAlive||await this._sendMessage(this._cachedPingMessage)}catch(e){throw this._logger.log(_y.Debug,`Hub handshake failed with error '${e}' during start(). Stopping HubConnection.`),this._cleanupTimeout(),this._cleanupPingTimer(),await this.connection.stop(e),e}}async stop(){const e=this._startPromise;this.connection.features.reconnect=!1,this._stopPromise=this._stopInternal(),await this._stopPromise;try{await e}catch(e){}}_stopInternal(e){if(this._connectionState===nv.Disconnected)return this._logger.log(_y.Debug,`Call to HubConnection.stop(${e}) ignored because it is already in the disconnected state.`),Promise.resolve();if(this._connectionState===nv.Disconnecting)return this._logger.log(_y.Debug,`Call to HttpConnection.stop(${e}) ignored because the connection is already in the disconnecting state.`),this._stopPromise;const t=this._connectionState;return this._connectionState=nv.Disconnecting,this._logger.log(_y.Debug,"Stopping HubConnection."),this._reconnectDelayHandle?(this._logger.log(_y.Debug,"Connection stopped during reconnect delay. Done reconnecting."),clearTimeout(this._reconnectDelayHandle),this._reconnectDelayHandle=void 0,this._completeClose(),Promise.resolve()):(t===nv.Connected&&this._sendCloseMessage(),this._cleanupTimeout(),this._cleanupPingTimer(),this._stopDuringStartError=e||new Ty("The connection was stopped before the hub handshake could complete."),this.connection.stop(e))}async _sendCloseMessage(){try{await this._sendWithProtocol(this._createCloseMessage())}catch{}}stream(e,...t){const[i,r]=this._replaceStreamingParams(t),n=this._createStreamInvocation(e,t,r);let a;const s=new mv;return s.cancelCallback=()=>{const e=this._createCancelInvocation(n.invocationId);return delete this._callbacks[n.invocationId],a.then(()=>this._sendWithProtocol(e))},this._callbacks[n.invocationId]=(e,t)=>{t?s.error(t):e&&(e.type===rv.Completion?e.error?s.error(new Error(e.error)):s.complete():s.next(e.item))},a=this._sendWithProtocol(n).catch(e=>{s.error(e),delete this._callbacks[n.invocationId]}),this._launchStreams(i,a),s}_sendMessage(e){return this._resetKeepAliveInterval(),this.connection.send(e)}_sendWithProtocol(e){return this._messageBuffer?this._messageBuffer._send(e):this._sendMessage(this._protocol.writeMessage(e))}send(e,...t){const[i,r]=this._replaceStreamingParams(t),n=this._sendWithProtocol(this._createInvocation(e,t,!0,r));return this._launchStreams(i,n),n}invoke(e,...t){const[i,r]=this._replaceStreamingParams(t),n=this._createInvocation(e,t,!1,r);return new Promise((e,t)=>{this._callbacks[n.invocationId]=(i,r)=>{r?t(r):i&&(i.type===rv.Completion?i.error?t(new Error(i.error)):e(i.result):t(new Error(`Unexpected message type: ${i.type}`)))};const r=this._sendWithProtocol(n).catch(e=>{t(e),delete this._callbacks[n.invocationId]});this._launchStreams(i,r)})}on(e,t){e&&t&&(e=e.toLowerCase(),this._methods[e]||(this._methods[e]=[]),-1===this._methods[e].indexOf(t)&&this._methods[e].push(t))}off(e,t){if(!e)return;e=e.toLowerCase();const i=this._methods[e];if(i)if(t){const r=i.indexOf(t);-1!==r&&(i.splice(r,1),0===i.length&&delete this._methods[e])}else delete this._methods[e]}onclose(e){e&&this._closedCallbacks.push(e)}onreconnecting(e){e&&this._reconnectingCallbacks.push(e)}onreconnected(e){e&&this._reconnectedCallbacks.push(e)}_processIncomingData(e){if(this._cleanupTimeout(),this._receivedHandshakeResponse||(e=this._processHandshakeResponse(e),this._receivedHandshakeResponse=!0),e){const t=this._protocol.parseMessages(e,this._logger);for(const e of t)if(!this._messageBuffer||this._messageBuffer._shouldProcessMessage(e))switch(e.type){case rv.Invocation:this._invokeClientMethod(e).catch(e=>{this._logger.log(_y.Error,`Invoke client method threw error: ${Jy(e)}`)});break;case rv.StreamItem:case rv.Completion:{const t=this._callbacks[e.invocationId];if(t){e.type===rv.Completion&&delete this._callbacks[e.invocationId];try{t(e)}catch(e){this._logger.log(_y.Error,`Stream callback threw error: ${Jy(e)}`)}}break}case rv.Ping:break;case rv.Close:{this._logger.log(_y.Information,"Close message received from server.");const t=e.error?new Error("Server returned an error on close: "+e.error):void 0;!0===e.allowReconnect?this.connection.stop(t):this._stopPromise=this._stopInternal(t);break}case rv.Ack:this._messageBuffer&&this._messageBuffer._ack(e);break;case rv.Sequence:this._messageBuffer&&this._messageBuffer._resetSequence(e);break;default:this._logger.log(_y.Warning,`Invalid message type: ${e.type}.`)}}this._resetTimeoutPeriod()}_processHandshakeResponse(e){let t,i;try{[i,t]=this._handshakeProtocol.parseHandshakeResponse(e)}catch(e){const t="Error parsing handshake response: "+e;this._logger.log(_y.Error,t);const i=new Error(t);throw this._handshakeRejecter(i),i}if(t.error){const e="Server returned handshake error: "+t.error;this._logger.log(_y.Error,e);const i=new Error(e);throw this._handshakeRejecter(i),i}return this._logger.log(_y.Debug,"Server handshake complete."),this._handshakeResolver(),i}_resetKeepAliveInterval(){this.connection.features.inherentKeepAlive||(this._nextKeepAlive=(new Date).getTime()+this.keepAliveIntervalInMilliseconds,this._cleanupPingTimer())}_resetTimeoutPeriod(){if(!(this.connection.features&&this.connection.features.inherentKeepAlive||(this._timeoutHandle=setTimeout(()=>this.serverTimeout(),this.serverTimeoutInMilliseconds),void 0!==this._pingServerHandle))){let e=this._nextKeepAlive-(new Date).getTime();e<0&&(e=0),this._pingServerHandle=setTimeout(async()=>{if(this._connectionState===nv.Connected)try{await this._sendMessage(this._cachedPingMessage)}catch{this._cleanupPingTimer()}},e)}}serverTimeout(){this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."))}async _invokeClientMethod(e){const t=e.target.toLowerCase(),i=this._methods[t];if(!i)return this._logger.log(_y.Warning,`No client method with the name '${t}' found.`),void(e.invocationId&&(this._logger.log(_y.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),await this._sendWithProtocol(this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null))));const r=i.slice(),n=!!e.invocationId;let a,s,o;for(const i of r)try{const r=a;a=await i.apply(this,e.arguments),n&&a&&r&&(this._logger.log(_y.Error,`Multiple results provided for '${t}'. Sending error to server.`),o=this._createCompletionMessage(e.invocationId,"Client provided multiple results.",null)),s=void 0}catch(e){s=e,this._logger.log(_y.Error,`A callback for the method '${t}' threw error '${e}'.`)}o?await this._sendWithProtocol(o):n?(s?o=this._createCompletionMessage(e.invocationId,`${s}`,null):void 0!==a?o=this._createCompletionMessage(e.invocationId,null,a):(this._logger.log(_y.Warning,`No result given for '${t}' method and invocation ID '${e.invocationId}'.`),o=this._createCompletionMessage(e.invocationId,"Client didn't provide a result.",null)),await this._sendWithProtocol(o)):a&&this._logger.log(_y.Error,`Result given for '${t}' method but server is not expecting a result.`)}_connectionClosed(e){this._logger.log(_y.Debug,`HubConnection.connectionClosed(${e}) called while in state ${this._connectionState}.`),this._stopDuringStartError=this._stopDuringStartError||e||new Ty("The underlying connection was closed before the hub handshake could complete."),this._handshakeResolver&&this._handshakeResolver(),this._cancelCallbacksWithError(e||new Error("Invocation canceled due to the underlying connection being closed.")),this._cleanupTimeout(),this._cleanupPingTimer(),this._connectionState===nv.Disconnecting?this._completeClose(e):this._connectionState===nv.Connected&&this._reconnectPolicy?this._reconnect(e):this._connectionState===nv.Connected&&this._completeClose(e)}_completeClose(e){if(this._connectionStarted){this._connectionState=nv.Disconnected,this._connectionStarted=!1,this._messageBuffer&&(this._messageBuffer._dispose(null!=e?e:new Error("Connection closed.")),this._messageBuffer=void 0),Ly.isBrowser&&window.document.removeEventListener("freeze",this._freezeEventListener);try{this._closedCallbacks.forEach(t=>t.apply(this,[e]))}catch(t){this._logger.log(_y.Error,`An onclose callback called with error '${e}' threw error '${t}'.`)}}}async _reconnect(e){const t=Date.now();let i=0,r=void 0!==e?e:new Error("Attempting to reconnect due to a unknown error."),n=this._getNextRetryDelay(i++,0,r);if(null===n)return this._logger.log(_y.Debug,"Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt."),void this._completeClose(e);if(this._connectionState=nv.Reconnecting,e?this._logger.log(_y.Information,`Connection reconnecting because of error '${e}'.`):this._logger.log(_y.Information,"Connection reconnecting."),0!==this._reconnectingCallbacks.length){try{this._reconnectingCallbacks.forEach(t=>t.apply(this,[e]))}catch(t){this._logger.log(_y.Error,`An onreconnecting callback called with error '${e}' threw error '${t}'.`)}if(this._connectionState!==nv.Reconnecting)return void this._logger.log(_y.Debug,"Connection left the reconnecting state in onreconnecting callback. Done reconnecting.")}for(;null!==n;){if(this._logger.log(_y.Information,`Reconnect attempt number ${i} will start in ${n} ms.`),await new Promise(e=>{this._reconnectDelayHandle=setTimeout(e,n)}),this._reconnectDelayHandle=void 0,this._connectionState!==nv.Reconnecting)return void this._logger.log(_y.Debug,"Connection left the reconnecting state during reconnect delay. Done reconnecting.");try{if(await this._startInternal(),this._connectionState=nv.Connected,this._logger.log(_y.Information,"HubConnection reconnected successfully."),0!==this._reconnectedCallbacks.length)try{this._reconnectedCallbacks.forEach(e=>e.apply(this,[this.connection.connectionId]))}catch(e){this._logger.log(_y.Error,`An onreconnected callback called with connectionId '${this.connection.connectionId}; threw error '${e}'.`)}return}catch(e){if(this._logger.log(_y.Information,`Reconnect attempt failed because of error '${e}'.`),this._connectionState!==nv.Reconnecting)return this._logger.log(_y.Debug,`Connection moved to the '${this._connectionState}' from the reconnecting state during reconnect attempt. Done reconnecting.`),void(this._connectionState===nv.Disconnecting&&this._completeClose());r=e instanceof Error?e:new Error(e.toString()),n=this._getNextRetryDelay(i++,Date.now()-t,r)}}this._logger.log(_y.Information,`Reconnect retries have been exhausted after ${Date.now()-t} ms and ${i} failed attempts. Connection disconnecting.`),this._completeClose()}_getNextRetryDelay(e,t,i){try{return this._reconnectPolicy.nextRetryDelayInMilliseconds({elapsedMilliseconds:t,previousRetryCount:e,retryReason:i})}catch(i){return this._logger.log(_y.Error,`IRetryPolicy.nextRetryDelayInMilliseconds(${e}, ${t}) threw error '${i}'.`),null}}_cancelCallbacksWithError(e){const t=this._callbacks;this._callbacks={},Object.keys(t).forEach(i=>{const r=t[i];try{r(null,e)}catch(t){this._logger.log(_y.Error,`Stream 'error' callback called with '${e}' threw error: ${Jy(t)}`)}})}_cleanupPingTimer(){this._pingServerHandle&&(clearTimeout(this._pingServerHandle),this._pingServerHandle=void 0)}_cleanupTimeout(){this._timeoutHandle&&clearTimeout(this._timeoutHandle)}_createInvocation(e,t,i,r){if(i)return 0!==r.length?{arguments:t,streamIds:r,target:e,type:rv.Invocation}:{arguments:t,target:e,type:rv.Invocation};{const i=this._invocationId;return this._invocationId++,0!==r.length?{arguments:t,invocationId:i.toString(),streamIds:r,target:e,type:rv.Invocation}:{arguments:t,invocationId:i.toString(),target:e,type:rv.Invocation}}}_launchStreams(e,t){if(0!==e.length){t||(t=Promise.resolve());for(const i in e)e[i].subscribe({complete:()=>{t=t.then(()=>this._sendWithProtocol(this._createCompletionMessage(i)))},error:e=>{let r;r=e instanceof Error?e.message:e&&e.toString?e.toString():"Unknown error",t=t.then(()=>this._sendWithProtocol(this._createCompletionMessage(i,r)))},next:e=>{t=t.then(()=>this._sendWithProtocol(this._createStreamItemMessage(i,e)))}})}}_replaceStreamingParams(e){const t=[],i=[];for(let r=0;r=55296&&n<=56319&&r65535&&(u-=65536,a.push(u>>>10&1023|55296),u=56320|1023&u),a.push(u)}else a.push(o);else a.push(o);a.length>=4096&&(s+=String.fromCharCode.apply(String,a),a.length=0)}return a.length>0&&(s+=String.fromCharCode.apply(String,a)),s}var Dv=Ev?new TextDecoder:null,Ov=Ev?"undefined"!=typeof process&&"force"!==(null===(_v=null===process||void 0===process?void 0:{ENV:"production"})||void 0===_v?void 0:_v.TEXT_DECODER)?200:0:xv,Nv=function(e,t){this.type=e,this.data=t},Rv=function(){var e=function(t,i){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])},e(t,i)};return function(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function r(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(r.prototype=i.prototype,new r)}}(),Uv=function(e){function t(i){var r=e.call(this,i)||this,n=Object.create(t.prototype);return Object.setPrototypeOf(r,n),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:t.name}),r}return Rv(t,e),t}(Error),Fv={type:-1,encode:function(e){var t,i,r,n;return e instanceof Date?function(e){var t,i=e.sec,r=e.nsec;if(i>=0&&r>=0&&i<=17179869183){if(0===r&&i<=4294967295){var n=new Uint8Array(4);return(t=new DataView(n.buffer)).setUint32(0,i),n}var a=i/4294967296,s=4294967295&i;return n=new Uint8Array(8),(t=new DataView(n.buffer)).setUint32(0,r<<2|3&a),t.setUint32(4,s),n}return n=new Uint8Array(12),(t=new DataView(n.buffer)).setUint32(0,r),Cv(t,4,i),n}((r=1e6*((t=e.getTime())-1e3*(i=Math.floor(t/1e3))),{sec:i+(n=Math.floor(r/1e9)),nsec:r-1e9*n})):null},decode:function(e){var t=function(e){var t=new DataView(e.buffer,e.byteOffset,e.byteLength);switch(e.byteLength){case 4:return{sec:t.getUint32(0),nsec:0};case 8:var i=t.getUint32(0);return{sec:4294967296*(3&i)+t.getUint32(4),nsec:i>>>2};case 12:return{sec:Iv(t,4),nsec:t.getUint32(0)};default:throw new Uv("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(e.length))}}(e);return new Date(1e3*t.sec+t.nsec/1e6)}},qv=function(){function e(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Fv)}return e.prototype.register=function(e){var t=e.type,i=e.encode,r=e.decode;if(t>=0)this.encoders[t]=i,this.decoders[t]=r;else{var n=1+t;this.builtInEncoders[n]=i,this.builtInDecoders[n]=r}},e.prototype.tryToEncode=function(e,t){for(var i=0;ithis.maxDepth)throw new Error("Too deep objects in depth ".concat(t));null==e?this.encodeNil():"boolean"==typeof e?this.encodeBoolean(e):"number"==typeof e?this.encodeNumber(e):"string"==typeof e?this.encodeString(e):this.encodeObject(e,t)},e.prototype.ensureBufferSizeToWrite=function(e){var t=this.pos+e;this.view.byteLength=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):(this.writeU8(211),this.writeI64(e)):this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))},e.prototype.writeStringHeader=function(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else{if(!(e<4294967296))throw new Error("Too long string: ".concat(e," bytes in UTF-8"));this.writeU8(219),this.writeU32(e)}},e.prototype.encodeString=function(e){if(e.length>Av){var t=zv(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),jv(e,this.bytes,this.pos),this.pos+=t}else t=zv(e),this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),function(e,t,i){for(var r=e.length,n=i,a=0;a=55296&&s<=56319&&a>18&7|240,t[n++]=s>>12&63|128,t[n++]=s>>6&63|128):(t[n++]=s>>12&15|224,t[n++]=s>>6&63|128)}else t[n++]=s>>6&31|192;t[n++]=63&s|128}else t[n++]=s}}(e,this.bytes,this.pos),this.pos+=t},e.prototype.encodeObject=function(e,t){var i=this.extensionCodec.tryToEncode(e,this.context);if(null!=i)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else{if("object"!=typeof e)throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(e)));this.encodeMap(e,t)}},e.prototype.encodeBinary=function(e){var t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else{if(!(t<4294967296))throw new Error("Too large binary: ".concat(t));this.writeU8(198),this.writeU32(t)}var i=Lv(e);this.writeU8a(i)},e.prototype.encodeArray=function(e,t){var i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else{if(!(i<4294967296))throw new Error("Too large array: ".concat(i));this.writeU8(221),this.writeU32(i)}for(var r=0,n=e;r0&&e<=this.maxKeyLength},e.prototype.find=function(e,t,i){e:for(var r=0,n=this.caches[i-1];r=this.maxLengthPerKey?i[Math.random()*i.length|0]=r:i.push(r)},e.prototype.decode=function(e,t,i){var r=this.find(e,t,i);if(null!=r)return this.hit++,r;this.miss++;var n=Tv(e,t,i),a=Uint8Array.prototype.slice.call(e,t,t+i);return this.store(a,n),n},e}(),$v=function(e,t){var i,r,n,a,s={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(a){return function(o){return function(a){if(i)throw new TypeError("Generator is already executing.");for(;s;)try{if(i=1,r&&(n=2&a[0]?r.return:a[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,a[1])).done)return n;switch(r=0,n&&(a=[2&a[0],n.value]),a[0]){case 0:case 1:n=a;break;case 4:return s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!((n=(n=s.trys).length>0&&n[n.length-1])||6!==a[0]&&2!==a[0])){s=0;continue}if(3===a[0]&&(!n||a[1]>n[0]&&a[1]=e},e.prototype.createExtraByteError=function(e){var t=this.view,i=this.pos;return new RangeError("Extra ".concat(t.byteLength-i," of ").concat(t.byteLength," byte(s) found at buffer[").concat(e,"]"))},e.prototype.decode=function(e){this.reinitializeState(),this.setBuffer(e);var t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t},e.prototype.decodeMulti=function(e){return $v(this,function(t){switch(t.label){case 0:this.reinitializeState(),this.setBuffer(e),t.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return t.sent(),[3,1];case 3:return[2]}})},e.prototype.decodeAsync=function(e){var t,i,r,n,a,s,o,l;return a=this,s=void 0,l=function(){var a,s,o,l,c,u,d,h;return $v(this,function(p){switch(p.label){case 0:a=!1,p.label=1;case 1:p.trys.push([1,6,7,12]),t=Kv(e),p.label=2;case 2:return[4,t.next()];case 3:if((i=p.sent()).done)return[3,5];if(o=i.value,a)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o);try{s=this.doDecodeSync(),a=!0}catch(e){if(!(e instanceof Jv))throw e}this.totalPos+=this.pos,p.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=p.sent(),r={error:l},[3,12];case 7:return p.trys.push([7,,10,11]),i&&!i.done&&(n=t.return)?[4,n.call(t)]:[3,9];case 8:p.sent(),p.label=9;case 9:return[3,11];case 10:if(r)throw r.error;return[7];case 11:return[7];case 12:if(a){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,s]}throw u=(c=this).headByte,d=c.pos,h=c.totalPos,new RangeError("Insufficient data in parsing ".concat(Mv(u)," at ").concat(h," (").concat(d," in the current buffer)"))}})},new((o=void 0)||(o=Promise))(function(e,t){function i(e){try{n(l.next(e))}catch(e){t(e)}}function r(e){try{n(l.throw(e))}catch(e){t(e)}}function n(t){var n;t.done?e(t.value):(n=t.value,n instanceof o?n:new o(function(e){e(n)})).then(i,r)}n((l=l.apply(a,s||[])).next())})},e.prototype.decodeArrayStream=function(e){return this.decodeMultiAsync(e,!0)},e.prototype.decodeStream=function(e){return this.decodeMultiAsync(e,!1)},e.prototype.decodeMultiAsync=function(e,t){return function(e,t,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,n=i.apply(e,t||[]),a=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){n[e]&&(r[e]=function(t){return new Promise(function(i,r){a.push([e,t,i,r])>1||o(e,t)})})}function o(e,t){try{(i=n[e](t)).value instanceof Wv?Promise.resolve(i.value.v).then(l,c):u(a[0][2],i)}catch(e){u(a[0][3],e)}var i}function l(e){o("next",e)}function c(e){o("throw",e)}function u(e,t){e(t),a.shift(),a.length&&o(a[0][0],a[0][1])}}(this,arguments,function(){var i,r,n,a,s,o,l,c,u;return $v(this,function(d){switch(d.label){case 0:i=t,r=-1,d.label=1;case 1:d.trys.push([1,13,14,19]),n=Kv(e),d.label=2;case 2:return[4,Wv(n.next())];case 3:if((a=d.sent()).done)return[3,12];if(s=a.value,t&&0===r)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(r=this.readArraySize(),i=!1,this.complete()),d.label=4;case 4:d.trys.push([4,9,,10]),d.label=5;case 5:return[4,Wv(this.doDecodeSync())];case 6:return[4,d.sent()];case 7:return d.sent(),0===--r?[3,8]:[3,5];case 8:return[3,10];case 9:if(!((o=d.sent())instanceof Jv))throw o;return[3,10];case 10:this.totalPos+=this.pos,d.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return l=d.sent(),c={error:l},[3,19];case 14:return d.trys.push([14,,17,18]),a&&!a.done&&(u=n.return)?[4,Wv(u.call(n))]:[3,16];case 15:d.sent(),d.label=16;case 16:return[3,18];case 17:if(c)throw c.error;return[7];case 18:return[7];case 19:return[2]}})})},e.prototype.doDecodeSync=function(){e:for(;;){var e=this.readHeadByte(),t=void 0;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){if(0!=(r=e-128)){this.pushMapState(r),this.complete();continue e}t={}}else if(e<160){if(0!=(r=e-144)){this.pushArrayState(r),this.complete();continue e}t=[]}else{var i=e-160;t=this.decodeUtf8String(i,0)}else if(192===e)t=null;else if(194===e)t=!1;else if(195===e)t=!0;else if(202===e)t=this.readF32();else if(203===e)t=this.readF64();else if(204===e)t=this.readU8();else if(205===e)t=this.readU16();else if(206===e)t=this.readU32();else if(207===e)t=this.readU64();else if(208===e)t=this.readI8();else if(209===e)t=this.readI16();else if(210===e)t=this.readI32();else if(211===e)t=this.readI64();else if(217===e)i=this.lookU8(),t=this.decodeUtf8String(i,1);else if(218===e)i=this.lookU16(),t=this.decodeUtf8String(i,2);else if(219===e)i=this.lookU32(),t=this.decodeUtf8String(i,4);else if(220===e){if(0!==(r=this.readU16())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(221===e){if(0!==(r=this.readU32())){this.pushArrayState(r),this.complete();continue e}t=[]}else if(222===e){if(0!==(r=this.readU16())){this.pushMapState(r),this.complete();continue e}t={}}else if(223===e){if(0!==(r=this.readU32())){this.pushMapState(r),this.complete();continue e}t={}}else if(196===e){var r=this.lookU8();t=this.decodeBinary(r,1)}else if(197===e)r=this.lookU16(),t=this.decodeBinary(r,2);else if(198===e)r=this.lookU32(),t=this.decodeBinary(r,4);else if(212===e)t=this.decodeExtension(1,0);else if(213===e)t=this.decodeExtension(2,0);else if(214===e)t=this.decodeExtension(4,0);else if(215===e)t=this.decodeExtension(8,0);else if(216===e)t=this.decodeExtension(16,0);else if(199===e)r=this.lookU8(),t=this.decodeExtension(r,1);else if(200===e)r=this.lookU16(),t=this.decodeExtension(r,2);else{if(201!==e)throw new Uv("Unrecognized type byte: ".concat(Mv(e)));r=this.lookU32(),t=this.decodeExtension(r,4)}this.complete();for(var n=this.stack;n.length>0;){var a=n[n.length-1];if(0===a.type){if(a.array[a.position]=t,a.position++,a.position!==a.size)continue e;n.pop(),t=a.array}else{if(1===a.type){if(!Hv(t))throw new Uv("The type of key must be string or number but "+typeof t);if("__proto__"===t)throw new Uv("The key __proto__ is not allowed");a.key=t,a.type=2;continue e}if(a.map[a.key]=t,a.readCount++,a.readCount!==a.size){a.key=null,a.type=1;continue e}n.pop(),t=a.map}}return t}},e.prototype.readHeadByte=function(){return-1===this.headByte&&(this.headByte=this.readU8()),this.headByte},e.prototype.complete=function(){this.headByte=-1},e.prototype.readArraySize=function(){var e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:if(e<160)return e-144;throw new Uv("Unrecognized array type byte: ".concat(Mv(e)))}},e.prototype.pushMapState=function(e){if(e>this.maxMapLength)throw new Uv("Max length exceeded: map length (".concat(e,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:e,key:null,readCount:0,map:{}})},e.prototype.pushArrayState=function(e){if(e>this.maxArrayLength)throw new Uv("Max length exceeded: array length (".concat(e,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:e,array:new Array(e),position:0})},e.prototype.decodeUtf8String=function(e,t){var i;if(e>this.maxStrLength)throw new Uv("Max length exceeded: UTF-8 byte length (".concat(e,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLengthOv?function(e,t,i){var r=e.subarray(t,t+i);return Dv.decode(r)}(this.bytes,n,e):Tv(this.bytes,n,e),this.pos+=t+e,r},e.prototype.stateIsMapKey=function(){return this.stack.length>0&&1===this.stack[this.stack.length-1].type},e.prototype.decodeBinary=function(e,t){if(e>this.maxBinLength)throw new Uv("Max length exceeded: bin length (".concat(e,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(e+t))throw Yv;var i=this.pos+t,r=this.bytes.subarray(i,i+e);return this.pos+=t+e,r},e.prototype.decodeExtension=function(e,t){if(e>this.maxExtLength)throw new Uv("Max length exceeded: ext length (".concat(e,") > maxExtLength (").concat(this.maxExtLength,")"));var i=this.view.getInt8(this.pos+t),r=this.decodeBinary(e,t+1);return this.extensionCodec.decode(r,i,this.context)},e.prototype.lookU8=function(){return this.view.getUint8(this.pos)},e.prototype.lookU16=function(){return this.view.getUint16(this.pos)},e.prototype.lookU32=function(){return this.view.getUint32(this.pos)},e.prototype.readU8=function(){var e=this.view.getUint8(this.pos);return this.pos++,e},e.prototype.readI8=function(){var e=this.view.getInt8(this.pos);return this.pos++,e},e.prototype.readU16=function(){var e=this.view.getUint16(this.pos);return this.pos+=2,e},e.prototype.readI16=function(){var e=this.view.getInt16(this.pos);return this.pos+=2,e},e.prototype.readU32=function(){var e=this.view.getUint32(this.pos);return this.pos+=4,e},e.prototype.readI32=function(){var e=this.view.getInt32(this.pos);return this.pos+=4,e},e.prototype.readU64=function(){var e,t,i=(e=this.view,t=this.pos,4294967296*e.getUint32(t)+e.getUint32(t+4));return this.pos+=8,i},e.prototype.readI64=function(){var e=Iv(this.view,this.pos);return this.pos+=8,e},e.prototype.readF32=function(){var e=this.view.getFloat32(this.pos);return this.pos+=4,e},e.prototype.readF64=function(){var e=this.view.getFloat64(this.pos);return this.pos+=8,e},e}();class eb{static write(e){let t=e.byteLength||e.length;const i=[];do{let e=127&t;t>>=7,t>0&&(e|=128),i.push(e)}while(t>0);t=e.byteLength||e.length;const r=new Uint8Array(i.length+t);return r.set(i,0),r.set(e,i.length),r.buffer}static parse(e){const t=[],i=new Uint8Array(e),r=[0,7,14,21,28];for(let n=0;n7)throw new Error("Messages bigger than 2GB are not supported.");if(!(i.byteLength>=n+s+o))throw new Error("Incomplete message.");t.push(i.slice?i.slice(n+s,n+s+o):i.subarray(n+s,n+s+o)),n=n+s+o}return t}}const tb=new Uint8Array([145,rv.Ping]);class ib{constructor(e){this.name="messagepack",this.version=2,this.transferFormat=iv.Binary,this._errorResult=1,this._voidResult=2,this._nonVoidResult=3,e=e||{},this._encoder=new Bv(e.extensionCodec,e.context,e.maxDepth,e.initialBufferSize,e.sortKeys,e.forceFloat32,e.ignoreUndefined,e.forceIntegerToFloat),this._decoder=new Zv(e.extensionCodec,e.context,e.maxStrLength,e.maxBinLength,e.maxArrayLength,e.maxMapLength,e.maxExtLength)}parseMessages(e,t){if(!(i=e)||"undefined"==typeof ArrayBuffer||!(i instanceof ArrayBuffer||i.constructor&&"ArrayBuffer"===i.constructor.name))throw new Error("Invalid input for MessagePack hub protocol. Expected an ArrayBuffer.");var i;null===t&&(t=Fy.instance);const r=eb.parse(e),n=[];for(const e of r){const i=this._parseMessage(e,t);i&&n.push(i)}return n}writeMessage(e){switch(e.type){case rv.Invocation:return this._writeInvocation(e);case rv.StreamInvocation:return this._writeStreamInvocation(e);case rv.StreamItem:return this._writeStreamItem(e);case rv.Completion:return this._writeCompletion(e);case rv.Ping:return eb.write(tb);case rv.CancelInvocation:return this._writeCancelInvocation(e);case rv.Close:return this._writeClose();case rv.Ack:return this._writeAck(e);case rv.Sequence:return this._writeSequence(e);default:throw new Error("Invalid message type.")}}_parseMessage(e,t){if(0===e.length)throw new Error("Invalid payload.");const i=this._decoder.decode(e);if(0===i.length||!(i instanceof Array))throw new Error("Invalid payload.");const r=i[0];switch(r){case rv.Invocation:return this._createInvocationMessage(this._readHeaders(i),i);case rv.StreamItem:return this._createStreamItemMessage(this._readHeaders(i),i);case rv.Completion:return this._createCompletionMessage(this._readHeaders(i),i);case rv.Ping:return this._createPingMessage(i);case rv.Close:return this._createCloseMessage(i);case rv.Ack:return this._createAckMessage(i);case rv.Sequence:return this._createSequenceMessage(i);default:return t.log(_y.Information,"Unknown message type '"+r+"' ignored."),null}}_createCloseMessage(e){if(e.length<2)throw new Error("Invalid payload for Close message.");return{allowReconnect:e.length>=3?e[2]:void 0,error:e[1],type:rv.Close}}_createPingMessage(e){if(e.length<1)throw new Error("Invalid payload for Ping message.");return{type:rv.Ping}}_createInvocationMessage(e,t){if(t.length<5)throw new Error("Invalid payload for Invocation message.");const i=t[2];return i?{arguments:t[4],headers:e,invocationId:i,streamIds:[],target:t[3],type:rv.Invocation}:{arguments:t[4],headers:e,streamIds:[],target:t[3],type:rv.Invocation}}_createStreamItemMessage(e,t){if(t.length<4)throw new Error("Invalid payload for StreamItem message.");return{headers:e,invocationId:t[2],item:t[3],type:rv.StreamItem}}_createCompletionMessage(e,t){if(t.length<4)throw new Error("Invalid payload for Completion message.");const i=t[3];if(i!==this._voidResult&&t.length<5)throw new Error("Invalid payload for Completion message.");let r,n;switch(i){case this._errorResult:r=t[4];break;case this._nonVoidResult:n=t[4]}return{error:r,headers:e,invocationId:t[2],result:n,type:rv.Completion}}_createAckMessage(e){if(e.length<1)throw new Error("Invalid payload for Ack message.");return{sequenceId:e[1],type:rv.Ack}}_createSequenceMessage(e){if(e.length<1)throw new Error("Invalid payload for Sequence message.");return{sequenceId:e[1],type:rv.Sequence}}_writeInvocation(e){let t;return t=e.streamIds?this._encoder.encode([rv.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments,e.streamIds]):this._encoder.encode([rv.Invocation,e.headers||{},e.invocationId||null,e.target,e.arguments]),eb.write(t.slice())}_writeStreamInvocation(e){let t;return t=e.streamIds?this._encoder.encode([rv.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments,e.streamIds]):this._encoder.encode([rv.StreamInvocation,e.headers||{},e.invocationId,e.target,e.arguments]),eb.write(t.slice())}_writeStreamItem(e){const t=this._encoder.encode([rv.StreamItem,e.headers||{},e.invocationId,e.item]);return eb.write(t.slice())}_writeCompletion(e){const t=e.error?this._errorResult:void 0!==e.result?this._nonVoidResult:this._voidResult;let i;switch(t){case this._errorResult:i=this._encoder.encode([rv.Completion,e.headers||{},e.invocationId,t,e.error]);break;case this._voidResult:i=this._encoder.encode([rv.Completion,e.headers||{},e.invocationId,t]);break;case this._nonVoidResult:i=this._encoder.encode([rv.Completion,e.headers||{},e.invocationId,t,e.result])}return eb.write(i.slice())}_writeCancelInvocation(e){const t=this._encoder.encode([rv.CancelInvocation,e.headers||{},e.invocationId]);return eb.write(t.slice())}_writeClose(){const e=this._encoder.encode([rv.Close,null]);return eb.write(e.slice())}_writeAck(e){const t=this._encoder.encode([rv.Ack,e.sequenceId]);return eb.write(t.slice())}_writeSequence(e){const t=this._encoder.encode([rv.Sequence,e.sequenceId]);return eb.write(t.slice())}_readHeaders(e){const t=e[1];if("object"!=typeof t)throw new Error("Invalid headers.");return t}}class rb extends Error{constructor(e){super(void 0===e?"Insecure URL not allowed. All URLs must use HTTPS.":`Insecure URL not allowed: ${e}. All URLs must use HTTPS.`)}}class nb{constructor(e){this.logService=e}redactMessage(e){const t=e.indexOf("access_token=");return-1!==t?e.substring(0,t+13)+"[REDACTED]":e}log(e,t){const i=`[SignalR] ${this.redactMessage(t)}`;switch(e){case _y.Critical:case _y.Error:this.logService.error(i);break;case _y.Warning:this.logService.warning(i);break;case _y.Information:this.logService.info(i);break;case _y.Debug:this.logService.debug(i)}}}class ab{constructor(e,t,i,r=()=>new wv,n=globalThis){this.apiService=e,this.logService=t,this.platformUtilsService=i,this.hubConnectionBuilderFactory=r,this.timeoutManager=n}connect$(e,t){if(!t.startsWith("https://")&&!this.platformUtilsService.isDev())throw new rb;return new $(i=>{const r=this.hubConnectionBuilderFactory().withUrl(t+"/hub",{accessTokenFactory:()=>this.apiService.getActiveBearerToken(e),skipNegotiation:!0,transport:tv.WebSockets}).withHubProtocol(new ib).configureLogging(new nb(this.logService)).build();r.on("ReceiveMessage",e=>{i.next({type:"ReceiveMessage",message:new sy(e)})}),r.on("Heartbeat",()=>{i.next({type:"Heartbeat"})});let n=null;const a=()=>{if(null==r||r.state!==nv.Disconnected||null!=n&&!n.closed)return;if(i.closed)return;const e=this.randomReconnectTime(),t=this.timeoutManager.setTimeout(()=>{r.start().then(()=>{n=null}).catch(()=>{a()})},e);n=new f(()=>this.timeoutManager.clearTimeout(t))};return r.onclose(e=>{a()}),r.start().catch(()=>{a()}),()=>{null==n||n.unsubscribe(),null==r||r.stop().catch(e=>{this.logService.error("Error while stopping SignalR connection",e)})}})}randomReconnectTime(){return Math.floor(180001*Math.random())+12e4}}var sb=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ob=new Set([dh.AuthRequest,dh.AutoConfirmMember]);class lb{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p){var m;this.logService=e,this.syncService=t,this.appIdService=i,this.environmentService=r,this.logoutCallback=n,this.messagingService=a,this.accountService=s,this.signalRConnectionService=o,this.authService=l,this.webPushConnectionService=c,this.authRequestAnsweringService=u,this.configService=d,this.policyService=h,this.autoConfirmService=p,this.activitySubject=new $c("active"),this.notifications$=this.accountService.accounts$.pipe(X(e=>{const t=Object.entries(e).filter(([e,t])=>""!==t.email||t.emailVerified).map(([e,t])=>e);return new Set(t)}),(m=e=>this.userNotifications$(e).pipe(X(t=>[t,e])),e=>{const t=new Map,i=()=>{for(const[,e]of t.entries())e.unsubscribe();t.clear()};return new $(r=>{const n=e.subscribe({next:e=>{var i;for(const r of t.keys())e.has(r)?e.delete(r):(null===(i=t.get(r))||void 0===i||i.unsubscribe(),t.delete(r));for(const i of e.keys())t.set(i,m(i).subscribe({next:e=>{r.next(e)},error:e=>{r.error(e)},complete:()=>{t.delete(i)}}))},error:e=>{r.error(e)},complete:()=>{i(),r.complete()}});return()=>{i(),n.unsubscribe()}})}),Gt())}userNotifications$(e){return this.environmentService.getEnvironment$(e).pipe(X(e=>e.getNotificationsUrl()),Zl(),Le(t=>"http://-"===t?pe:this.userNotificationsHelper$(e,t)))}userNotificationsHelper$(e,t){return this.hasAccessToken$(e).pipe(Le(e=>e?this.activitySubject:pe),Le(t=>"inactive"===t?pe:this.webPushConnectionService.supportStatus$(e)),(i={supported:i=>(this.logService.info("Using WebPush for server notifications"),i.notifications$.pipe(Hu(i=>(this.logService.warning("Issue with web push, falling back to SignalR",i),this.connectSignalR$(e,t))))),notSupported:()=>(this.logService.info("Using SignalR for server notifications"),this.connectSignalR$(e,t))},Le((e,t)=>"supported"===e.type?i.supported(e.service,t):i.notSupported(e.reason,t))));var i}connectSignalR$(e,t){return this.signalRConnectionService.connect$(e,t).pipe(Ie(e=>"ReceiveMessage"===e.type),X(e=>e.message))}hasAccessToken$(e){return this.authService.authStatusFor$(e).pipe(X(e=>e===cu.Locked||e===cu.Unlocked),Zl())}processNotification(e,t){return sb(this,void 0,void 0,function*(){var i,r;const n=yield this.appIdService.getAppId();if(null==e||e.contextId===n)return;const a=(null===(i=e.payload)||void 0===i?void 0:i.userId)||(null===(r=e.payload)||void 0===r?void 0:r.UserId);if((null==a||a===t)&&((yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id))))===t||ob.has(e.type)))switch(e.type){case dh.SyncCipherCreate:case dh.SyncCipherUpdate:yield this.syncService.syncUpsertCipher(e.payload,e.type===dh.SyncCipherUpdate,t);break;case dh.SyncCipherDelete:case dh.SyncLoginDelete:yield this.syncService.syncDeleteCipher(e.payload,t);break;case dh.SyncFolderCreate:case dh.SyncFolderUpdate:yield this.syncService.syncUpsertFolder(e.payload,e.type===dh.SyncFolderUpdate,t);break;case dh.SyncFolderDelete:yield this.syncService.syncDeleteFolder(e.payload,t);break;case dh.SyncVault:case dh.SyncCiphers:case dh.SyncSettings:yield this.syncService.fullSync(!1);break;case dh.SyncOrganizations:yield this.syncService.fullSync(!0);break;case dh.SyncOrgKeys:yield this.syncService.fullSync(!0),this.activitySubject.next("inactive"),this.activitySubject.next("active");break;case dh.LogOut:{this.logService.info("[Notifications Service] Received logout notification");const i=e.payload;(yield Ce(this.configService.getFeatureFlag$(Ne.NoLogoutOnKdfChange)))&&i.reason===hh.KdfChange?this.logService.info("[Notifications Service] Skipping logout due to no logout KDF change"):yield this.logoutCallback("logoutNotification",t);break}case dh.SyncSendCreate:case dh.SyncSendUpdate:yield this.syncService.syncUpsertSend(e.payload,e.type===dh.SyncSendUpdate);break;case dh.SyncSendDelete:yield this.syncService.syncDeleteSend(e.payload);break;case dh.AuthRequest:if(this.authRequestAnsweringService.receivedPendingAuthRequest)try{yield this.authRequestAnsweringService.receivedPendingAuthRequest(e.payload.userId,e.payload.id)}catch(e){this.logService.error(`Failed to process auth request notification: ${e}`)}else this.messagingService.send("openLoginApproval",{notificationId:e.payload.id});break;case dh.SyncOrganizationStatusChanged:case dh.SyncOrganizationCollectionSettingChanged:yield this.syncService.fullSync(!0);break;case dh.OrganizationBankAccountVerified:this.messagingService.send("organizationBankAccountVerified",{organizationId:e.payload.organizationId});break;case dh.ProviderBankAccountVerified:this.messagingService.send("providerBankAccountVerified",{providerId:e.payload.providerId,adminId:e.payload.adminId});break;case dh.SyncPolicy:yield this.policyService.syncPolicy(ed.fromPolicy(e.payload.policy));break;case dh.AutoConfirmMember:yield this.autoConfirmService.autoConfirmUser(e.payload.userId,e.payload.targetUserId,e.payload.organizationId)}})}startListening(){return this.notifications$.pipe(de(e=>sb(this,[e],void 0,function*([e,t]){try{yield this.processNotification(e,t)}catch(t){this.logService.error(`Problem processing notification of type ${e.type}`,t)}}))).subscribe({error:e=>this.logService.error("Fatal error in server notifications$ observable, notifications won't be recieved anymore.",e)})}reconnectFromActivity(){this.activitySubject.next("active")}disconnectFromInactivity(){this.activitySubject.next("inactive")}}class cb{supportStatus$(e){return bt({type:"not-supported",reason:"client-not-supported"})}}class ub{static from(e){var t,i;const r=new ub;return r.endpoint=e.endpoint,r.p256dh=null===(t=e.keys)||void 0===t?void 0:t.p256dh,r.auth=null===(i=e.keys)||void 0===i?void 0:i.auth,r}}class db{constructor(e,t){this.apiService=e,this.appIdService=t}putSubscription(e,t){return i=this,r=void 0,a=function*(){const i=ub.from(e);yield this.apiService.send("POST",`/devices/identifier/${yield this.appIdService.getAppId()}/web-push-auth`,i,t,!1)},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}}var hb=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class pb{constructor(e,t){this.storageService=e,this.logService=t}getAppId(){return hb(this,void 0,void 0,function*(){return this.logService.info("Retrieving application id"),yield this.getEnsuredValue("global_applicationId_appId")})}getAnonymousAppId(){return hb(this,void 0,void 0,function*(){return yield this.getEnsuredValue("global_applicationId_appId")})}getEnsuredValue(e){return hb(this,void 0,void 0,function*(){let t=yield this.storageService.get(e);return null==t&&(t=Tt.newGuid(),yield this.storageService.save(e,t)),t})}}class mb extends Lt{constructor(e){super(e),this.featureStates={},null!=e&&(this.version=this.getResponseProperty("Version"),this.gitHash=this.getResponseProperty("GitHash"),this.server=new yb(this.getResponseProperty("Server")),this.environment=new fb(this.getResponseProperty("Environment")),this.featureStates=this.getResponseProperty("FeatureStates"),this.push=new gb(this.getResponseProperty("Push")),this.settings=new lf(this.getResponseProperty("Settings")))}}class gb extends Lt{constructor(e=null){super(e),null!=e&&(this.pushTechnology=this.getResponseProperty("PushTechnology"),this.vapidPublicKey=this.getResponseProperty("VapidPublicKey"))}}class fb extends Lt{constructor(e=null){super(e),null!=e&&(this.cloudRegion=this.getResponseProperty("CloudRegion"),this.vault=this.getResponseProperty("Vault"),this.api=this.getResponseProperty("Api"),this.identity=this.getResponseProperty("Identity"),this.notifications=this.getResponseProperty("Notifications"),this.sso=this.getResponseProperty("Sso"))}}class yb extends Lt{constructor(e=null){super(e),null!=e&&(this.name=this.getResponseProperty("Name"),this.url=this.getResponseProperty("Url"))}}class vb{constructor(e){this.apiService=e}get(e){return t=this,i=void 0,n=function*(){let t;return t=null==e?yield this.apiService.send("GET","/config",null,!1,!0):yield this.apiService.send("GET","/config",null,e,!0),new mb(t)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class bb{constructor(e,t){this.keyService=e,this.encryptService=t}attachToGlobal(e){e.bitwardenContainerService||(e.bitwardenContainerService=this)}getKeyService(){if(null==this.keyService)throw new Error("ContainerService.keyService not initialized.");return this.keyService}getEncryptService(){if(null==this.encryptService)throw new Error("ContainerService.encryptService not initialized.");return this.encryptService}}function wb(){for(var e=[],t=0;tt[e]),Zl(),Jt({bufferSize:1,refCount:!0}),wb(void 0))}getActiveRequest(e){return this.activeRequests$.value[e]}newActiveRequest(e,t,i){return r=this,n=void 0,s=function*(){const r={credentials:t,subject:new H};this.updateRequests(t=>Object.assign(Object.assign({},t),{[e]:r}));const n=()=>this.abortActiveRequest(e);i.signal.addEventListener("abort",n);const a=Ce(r.subject);return i.signal.removeEventListener("abort",n),a},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}removeActiveRequest(e){this.abortActiveRequest(e),this.updateRequests(t=>{const i=Object.assign({},t);return delete i[e],i})}removeAllActiveRequests(){Object.keys(this.activeRequests$.value).forEach(e=>{this.abortActiveRequest(Number(e))}),this.updateRequests(()=>({}))}abortActiveRequest(e){var t,i;null===(t=this.activeRequests$.value[e])||void 0===t||t.subject.next({type:Sb}),null===(i=this.activeRequests$.value[e])||void 0===i||i.subject.error(new DOMException("The operation either timed out or was not allowed.","AbortError"))}updateRequests(e){this.activeRequests$.next(e(this.activeRequests$.value))}}!function(e){e[e.Cipher=0]="Cipher",e[e.CipherView=1]="CipherView"}(_b||(_b={}));const Cb=e=>null!=e?new Nt(e):void 0,Ib=e=>null!=e?Nt.fromJSON(e):void 0;class Eb extends Lt{constructor(e=null){super(e),this.delete=!1,this.restore=!1,null!=e&&(this.delete=this.getResponseProperty("Delete"),this.restore=this.getResponseProperty("Restore"))}static fromJSON(e){return Object.assign(new Eb,e)}static fromSdkCipherPermissions(e){if(!e)return;const t=new Eb;return t.delete=e.delete,t.restore=e.restore,t}toSdkCipherPermissions(){return this}}class zb{constructor(e){null!=e&&(this.id=e.id,this.url=e.url,this.fileName=e.fileName,this.key=e.key,this.size=e.size,this.sizeName=e.sizeName)}}class Pb{constructor(e){null!=e&&(this.cardholderName=e.cardholderName,this.brand=e.brand,this.number=e.number,this.expMonth=e.expMonth,this.expYear=e.expYear,this.code=e.code)}}class Ab{constructor(e){this.type=am.Text,null!=e&&(this.type=e.type,this.name=e.name,this.value=e.value,this.linkedId=e.linkedId)}}class jb{constructor(e){null!=e&&(this.title=e.title,this.firstName=e.firstName,this.middleName=e.middleName,this.lastName=e.lastName,this.address1=e.address1,this.address2=e.address2,this.address3=e.address3,this.city=e.city,this.state=e.state,this.postalCode=e.postalCode,this.country=e.country,this.company=e.company,this.email=e.email,this.phone=e.phone,this.ssn=e.ssn,this.username=e.username,this.passportNumber=e.passportNumber,this.licenseNumber=e.licenseNumber)}}class Tb{constructor(e){null!=e&&(this.credentialId=e.credentialId,this.keyType=e.keyType,this.keyAlgorithm=e.keyAlgorithm,this.keyCurve=e.keyCurve,this.keyValue=e.keyValue,this.rpId=e.rpId,this.userHandle=e.userHandle,this.userName=e.userName,this.counter=e.counter,this.rpName=e.rpName,this.userDisplayName=e.userDisplayName,this.discoverable=e.discoverable,this.creationDate=e.creationDate)}}class Db{constructor(e){null!=e&&(this.uri=e.uri,this.uriChecksum=e.uriChecksum,this.match=e.match)}}class Ob{constructor(e){var t;null!=e&&(this.username=e.username,this.password=e.password,this.passwordRevisionDate=e.passwordRevisionDate,this.totp=e.totp,this.autofillOnPageLoad=e.autofillOnPageLoad,e.uris&&(this.uris=e.uris.map(e=>new Db(e))),e.fido2Credentials&&(this.fido2Credentials=null===(t=e.fido2Credentials)||void 0===t?void 0:t.map(e=>new Tb(e))))}}class Nb{constructor(e){null!=e&&(this.password=e.password,this.lastUsedDate=e.lastUsedDate)}}class Rb{constructor(e){this.type=0,null!=e&&(this.type=e.type)}}class Ub{constructor(e){null!=e&&(this.privateKey=e.privateKey,this.publicKey=e.publicKey,this.keyFingerprint=e.keyFingerprint)}}class Fb{constructor(e,t){if(this.id="",this.edit=!1,this.viewPassword=!0,this.organizationUseTotp=!1,this.favorite=!1,this.type=rm.Login,this.name="",this.reprompt=tm.None,null!=e){switch(this.id=e.id,this.organizationId=e.organizationId,this.folderId=e.folderId,this.edit=e.edit,this.viewPassword=e.viewPassword,this.permissions=e.permissions,this.organizationUseTotp=e.organizationUseTotp,this.favorite=e.favorite,this.revisionDate=e.revisionDate,this.type=e.type,this.name=e.name,this.notes=e.notes,this.collectionIds=null!=t?t:e.collectionIds,this.creationDate=e.creationDate,this.deletedDate=e.deletedDate,this.archivedDate=e.archivedDate,this.reprompt=e.reprompt,this.key=e.key,this.type){case rm.Login:this.login=new Ob(e.login);break;case rm.SecureNote:this.secureNote=new Rb(e.secureNote);break;case rm.Card:this.card=new Pb(e.card);break;case rm.Identity:this.identity=new jb(e.identity);break;case rm.SshKey:this.sshKey=new Ub(e.sshKey)}null!=e.fields&&(this.fields=e.fields.map(e=>new Ab(e))),null!=e.attachments&&(this.attachments=e.attachments.map(e=>new zb(e))),null!=e.passwordHistory&&(this.passwordHistory=e.passwordHistory.map(e=>new Nb(e)))}else this.creationDate=this.revisionDate=(new Date).toISOString()}static fromJSON(e){const t=Object.assign(new Fb,e);return null!=e.permissions&&(t.permissions=Eb.fromJSON(e.permissions)),t}}function qb(e){if(null!=e)return{lastUsedDate:e.lastUsedDate?new Date(e.lastUsedDate).getTime():void 0,lastLaunched:e.lastLaunched?new Date(e.lastLaunched).getTime():void 0}}function Lb(e){if(null!=e)return{lastUsedDate:e.lastUsedDate?new Date(e.lastUsedDate).toISOString():void 0,lastLaunched:e.lastLaunched?new Date(e.lastLaunched).toISOString():void 0}}class Bb{constructor(e){e&&(this.id=e.id,this.url=e.url,this.size=e.size,this.sizeName=e.sizeName)}get fileSize(){try{if(null!=this.size)return parseInt(this.size)}catch(e){}return 0}get hasDecryptionError(){return this._hasDecryptionError||this.fileName===Ot}set hasDecryptionError(e){this._hasDecryptionError=e}static fromJSON(e){const t=null==e.key?null:gu.fromJSON(e.key);let i;return null!=e.encryptedKey&&("string"==typeof e.encryptedKey?i=Nt.fromJSON(e.encryptedKey):e.encryptedKey instanceof Nt&&(i=e.encryptedKey)),Object.assign(new Bb,e,{key:t,encryptedKey:i})}toSdkAttachmentView(){var e;return{id:this.id,url:this.url,size:this.size,sizeName:this.sizeName,fileName:this.fileName,key:null===(e=this.encryptedKey)||void 0===e?void 0:e.toSdk(),decryptedKey:this.key?this.key.toBase64():void 0}}static fromSdkAttachmentView(e,t=!1){if(!e)return;const i=new Bb;return i.id=e.id,i.url=e.url,i.size=e.size,i.sizeName=e.sizeName,i.fileName=e.fileName,i.key=e.decryptedKey?gu.fromString(e.decryptedKey):void 0,i.encryptedKey=e.key?new Nt(e.key):void 0,i._hasDecryptionError=t,i}}class Mb{constructor(e,t){this.propertyKey=e,this._i18nKey=null==t?void 0:t.i18nKey,this.sortPosition=t.sortPosition}get i18nKey(){var e;return null!==(e=this._i18nKey)&&void 0!==e?e:this.propertyKey}}function Vb(e,t){return(i,r)=>{null==i.linkedFieldOptions&&(i.linkedFieldOptions=new Map),i.linkedFieldOptions.set(e,new Mb(r,t))}}class $b{}var Kb=function(e,t,i,r){var n,a=arguments.length,s=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var o=e.length-1;o>=0;o--)(n=e[o])&&(s=(a<3?n(s):a>3?n(t,i,s):n(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},Wb=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Hb extends $b{get maskedCode(){return null!=this.code?"•".repeat(this.code.length):void 0}get maskedNumber(){return null!=this.number?"•".repeat(this.number.length):void 0}get brand(){return this._brand}set brand(e){this._brand=e,this._subTitle=void 0}get number(){return this._number}set number(e){this._number=e,this._subTitle=void 0}get subTitle(){if(null==this._subTitle&&(this._subTitle=this.brand,null!=this.number&&this.number.length>=4)){null!=this._subTitle&&""!==this._subTitle?this._subTitle+=", ":this._subTitle="";const e=this.number.length>=5&&null!=this.number.match(new RegExp("^3[47]"))?5:4;this._subTitle+="*"+this.number.substr(this.number.length-e)}return this._subTitle}get expiration(){const e=this.expYear?dg(this.expYear):void 0;if(!this.expMonth&&!e)return;let t=null!=this.expMonth?("0"+this.expMonth).slice(-2):"__";return t+=" / "+(e||"____"),t}static fromJSON(e){return Object.assign(new Hb,e)}static getCardBrandByPatterns(e){if(null==e||"string"!=typeof e||""===e.trim())return;let t=new RegExp("^4");return null!=e.match(t)?"Visa":/^(5[1-5][0-9]{14}|2(22[1-9][0-9]{12}|2[3-9][0-9]{13}|[3-6][0-9]{14}|7[0-1][0-9]{13}|720[0-9]{12}))$/.test(e)?"Mastercard":(t=new RegExp("^3[47]"),null!=e.match(t)?"Amex":(t=new RegExp("^(6011|622(12[6-9]|1[3-9][0-9]|[2-8][0-9]{2}|9[0-1][0-9]|92[0-5]|64[4-9])|65)"),null!=e.match(t)?"Discover":(t=new RegExp("^36"),null!=e.match(t)?"Diners Club":(t=new RegExp("^30[0-5]"),null!=e.match(t)?"Diners Club":(t=new RegExp("^35(2[89]|[3-8][0-9])"),null!=e.match(t)?"JCB":(t=new RegExp("^(4026|417500|4508|4844|491(3|7))"),null!=e.match(t)?"Visa":void 0))))))}static fromSdkCardView(e){const t=new Hb;return t.cardholderName=e.cardholderName,t.brand=e.brand,t.number=e.number,t.expMonth=e.expMonth,t.expYear=e.expYear,t.code=e.code,t}toSdkCardView(){return this}}Kb([Vb(lm.CardholderName,{sortPosition:0}),Wb("design:type",String)],Hb.prototype,"cardholderName",void 0),Kb([Vb(lm.ExpMonth,{sortPosition:3,i18nKey:"expirationMonth"}),Wb("design:type",String)],Hb.prototype,"expMonth",void 0),Kb([Vb(lm.ExpYear,{sortPosition:4,i18nKey:"expirationYear"}),Wb("design:type",String)],Hb.prototype,"expYear",void 0),Kb([Vb(lm.Code,{sortPosition:5,i18nKey:"securityCode"}),Wb("design:type",String)],Hb.prototype,"code",void 0),Kb([Vb(lm.Brand,{sortPosition:2}),Wb("design:type",String),Wb("design:paramtypes",[String])],Hb.prototype,"brand",null),Kb([Vb(lm.Number,{sortPosition:1}),Wb("design:type",String),Wb("design:paramtypes",[String])],Hb.prototype,"number",null);class Gb{constructor(e){this.type=am.Text,this.newField=!1,this.showValue=!1,this.showCount=!1,e&&(this.type=e.type,this.linkedId=e.linkedId)}get maskedValue(){return null!=this.value?"••••••••":void 0}static fromJSON(e){return Object.assign(new Gb,e)}static fromSdkFieldView(e){if(!e)return;const t=new Gb;return t.name=e.name,t.value=e.value,t.type=e.type,t.linkedId=e.linkedId,t}toSdkFieldView(){var e,t,i,r;return{name:null!==(e=this.name)&&void 0!==e?e:void 0,value:null!==(t=this.value)&&void 0!==t?t:void 0,type:null!==(i=this.type)&&void 0!==i?i:Sg.PUO.Text,linkedId:null!==(r=this.linkedId)&&void 0!==r?r:void 0}}}var Qb=function(e,t,i,r){var n,a=arguments.length,s=a<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,i):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)s=Reflect.decorate(e,t,i,r);else for(var o=e.length-1;o>=0;o--)(n=e[o])&&(s=(a<3?n(s):a>3?n(t,i,s):n(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},Jb=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class Yb extends $b{constructor(){super()}get firstName(){return this._firstName}set firstName(e){this._firstName=e,this._subTitle=void 0}get lastName(){return this._lastName}set lastName(e){this._lastName=e,this._subTitle=void 0}get subTitle(){return null!=this._subTitle||null==this.firstName&&null==this.lastName||(this._subTitle="",null!=this.firstName&&(this._subTitle=this.firstName),null!=this.lastName&&(""!==this._subTitle&&(this._subTitle+=" "),this._subTitle+=this.lastName)),this._subTitle}get fullName(){if(null!=this.title||null!=this.firstName||null!=this.middleName||null!=this.lastName){let e="";return Tt.isNullOrWhitespace(this.title)||(e+=this.title+" "),Tt.isNullOrWhitespace(this.firstName)||(e+=this.firstName+" "),Tt.isNullOrWhitespace(this.middleName)||(e+=this.middleName+" "),Tt.isNullOrWhitespace(this.lastName)||(e+=this.lastName),e.trim()}}get fullAddress(){var e;let t=null!==(e=this.address1)&&void 0!==e?e:"";return Tt.isNullOrWhitespace(this.address2)||(Tt.isNullOrWhitespace(t)||(t+=", "),t+=this.address2),Tt.isNullOrWhitespace(this.address3)||(Tt.isNullOrWhitespace(t)||(t+=", "),t+=this.address3),t}get fullAddressPart2(){const e=!Tt.isNullOrWhitespace(this.city),t=!Tt.isNullOrWhitespace(this.state),i=!Tt.isNullOrWhitespace(this.postalCode);if(!e&&!t&&!i)return;const r=e?this.city:"-",n=this.state;let a=r;return t&&(a+=", "+n),a+=", "+(i?this.postalCode:"-"),a}get fullAddressForCopy(){let e=this.fullAddress;return null==this.city&&null==this.state&&null==this.postalCode||(e+="\n"+this.fullAddressPart2),null!=this.country&&(e+="\n"+this.country),e}static fromJSON(e){return Object.assign(new Yb,e)}static fromSdkIdentityView(e){const t=new Yb;return t.title=e.title,t.firstName=e.firstName,t.middleName=e.middleName,t.lastName=e.lastName,t.address1=e.address1,t.address2=e.address2,t.address3=e.address3,t.city=e.city,t.state=e.state,t.postalCode=e.postalCode,t.country=e.country,t.company=e.company,t.email=e.email,t.phone=e.phone,t.ssn=e.ssn,t.username=e.username,t.passportNumber=e.passportNumber,t.licenseNumber=e.licenseNumber,t}toSdkIdentityView(){return this}}Qb([Vb(cm.Title,{sortPosition:0}),Jb("design:type",String)],Yb.prototype,"title",void 0),Qb([Vb(cm.MiddleName,{sortPosition:2}),Jb("design:type",String)],Yb.prototype,"middleName",void 0),Qb([Vb(cm.Address1,{sortPosition:12}),Jb("design:type",String)],Yb.prototype,"address1",void 0),Qb([Vb(cm.Address2,{sortPosition:13}),Jb("design:type",String)],Yb.prototype,"address2",void 0),Qb([Vb(cm.Address3,{sortPosition:14}),Jb("design:type",String)],Yb.prototype,"address3",void 0),Qb([Vb(cm.City,{sortPosition:15,i18nKey:"cityTown"}),Jb("design:type",String)],Yb.prototype,"city",void 0),Qb([Vb(cm.State,{sortPosition:16,i18nKey:"stateProvince"}),Jb("design:type",String)],Yb.prototype,"state",void 0),Qb([Vb(cm.PostalCode,{sortPosition:17,i18nKey:"zipPostalCodeLabel"}),Jb("design:type",String)],Yb.prototype,"postalCode",void 0),Qb([Vb(cm.Country,{sortPosition:18}),Jb("design:type",String)],Yb.prototype,"country",void 0),Qb([Vb(cm.Company,{sortPosition:6}),Jb("design:type",String)],Yb.prototype,"company",void 0),Qb([Vb(cm.Email,{sortPosition:10}),Jb("design:type",String)],Yb.prototype,"email",void 0),Qb([Vb(cm.Phone,{sortPosition:11}),Jb("design:type",String)],Yb.prototype,"phone",void 0),Qb([Vb(cm.Ssn,{sortPosition:7}),Jb("design:type",String)],Yb.prototype,"ssn",void 0),Qb([Vb(cm.Username,{sortPosition:5}),Jb("design:type",String)],Yb.prototype,"username",void 0),Qb([Vb(cm.PassportNumber,{sortPosition:8}),Jb("design:type",String)],Yb.prototype,"passportNumber",void 0),Qb([Vb(cm.LicenseNumber,{sortPosition:9}),Jb("design:type",String)],Yb.prototype,"licenseNumber",void 0),Qb([Vb(cm.FirstName,{sortPosition:1}),Jb("design:type",String),Jb("design:paramtypes",[String])],Yb.prototype,"firstName",null),Qb([Vb(cm.LastName,{sortPosition:4}),Jb("design:type",String),Jb("design:paramtypes",[String])],Yb.prototype,"lastName",null),Qb([Vb(cm.FullName,{sortPosition:3}),Jb("design:type",String),Jb("design:paramtypes",[])],Yb.prototype,"fullName",null);class Xb extends $b{constructor(e){var t;super(),this.discoverable=!1,null!=e&&(this.credentialId=e.credentialId,this.keyType=e.keyType,this.keyAlgorithm=e.keyAlgorithm,this.keyCurve=e.keyCurve,this.keyValue=e.keyValue,this.rpId=e.rpId,this.userHandle=e.userHandle,this.userName=e.userName,this.counter=e.counter,this.rpName=e.rpName,this.userDisplayName=e.userDisplayName,this.discoverable=null!==(t=e.discoverable)&&void 0!==t&&t,this.creationDate=e.creationDate)}get subTitle(){return this.userDisplayName}static fromJSON(e){const t=null!=e.creationDate?new Date(e.creationDate):null;return Object.assign(new Xb,e,{creationDate:t})}static fromSdkFido2CredentialView(e){var t;if(e)return new Xb({credentialId:e.credentialId,keyType:e.keyType,keyAlgorithm:e.keyAlgorithm,keyCurve:e.keyCurve,keyValue:e.keyValue,rpId:e.rpId,userHandle:e.userHandle,userName:e.userName,counter:parseInt(e.counter),rpName:e.rpName,userDisplayName:e.userDisplayName,discoverable:"true"===(null===(t=e.discoverable)||void 0===t?void 0:t.toLowerCase()),creationDate:new Date(e.creationDate)})}toSdkFido2CredentialFullView(){var e;return{credentialId:this.credentialId,keyType:this.keyType,keyAlgorithm:this.keyAlgorithm,keyCurve:this.keyCurve,keyValue:this.keyValue,rpId:this.rpId,userHandle:this.userHandle,userName:this.userName,counter:this.counter.toString(),rpName:this.rpName,userDisplayName:this.userDisplayName,discoverable:this.discoverable?"true":"false",creationDate:null===(e=this.creationDate)||void 0===e?void 0:e.toISOString()}}}const Zb=["https://","http://","ssh://","ftp://","sftp://","irc://","vnc://","rdp://","ms-rd:","chrome://","iosapp://","androidapp://"];class ew{static canLaunch(e){if(Tt.isNullOrWhitespace(e))return!1;for(let t=0;t=0;o--)(n=e[o])&&(s=(a<3?n(s):a>3?n(t,i,s):n(t,i))||s);return a>3&&s&&Object.defineProperty(t,i,s),s},rw=function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};class nw extends $b{constructor(e){super(),this.uris=[],this.fido2Credentials=[],e&&(this.passwordRevisionDate=e.passwordRevisionDate,this.autofillOnPageLoad=e.autofillOnPageLoad)}get uri(){return this.hasUris?this.uris[0].uri:void 0}get maskedPassword(){return null!=this.password?"••••••••":void 0}get subTitle(){var e;return Tt.isNullOrEmpty(this.username)&&(null===(e=this.fido2Credentials)||void 0===e?void 0:e.length)>0?this.fido2Credentials[0].userName:this.username}get canLaunch(){return this.hasUris&&this.uris.some(e=>e.canLaunch)}get hasTotp(){return!Tt.isNullOrWhitespace(this.totp)}get launchUri(){if(this.hasUris){const e=this.uris.find(e=>e.canLaunch);if(null!=e)return e.launchUri}}get hasUris(){return null!=this.uris&&this.uris.length>0}get hasFido2Credentials(){return null!=this.fido2Credentials&&this.fido2Credentials.length>0}matchesUri(e,t,i,r){return null!=this.uris&&this.uris.some(n=>n.matchesUri(e,t,i,r))}static fromJSON(e){var t,i,r,n;if(null==e)return new nw;const a=Object.assign(new nw,e);return a.passwordRevisionDate=null==e.passwordRevisionDate?void 0:new Date(e.passwordRevisionDate),a.uris=null!==(i=null===(t=e.uris)||void 0===t?void 0:t.map(e=>tw.fromJSON(e)))&&void 0!==i?i:[],a.fido2Credentials=null!==(n=null===(r=e.fido2Credentials)||void 0===r?void 0:r.map(e=>Xb.fromJSON(e)))&&void 0!==n?n:[],a}static fromSdkLoginView(e){var t;const i=new nw;return i.username=e.username,i.password=e.password,i.passwordRevisionDate=null==e.passwordRevisionDate?void 0:new Date(e.passwordRevisionDate),i.totp=e.totp,i.autofillOnPageLoad=e.autofillOnPageLoad,i.uris=(null===(t=e.uris)||void 0===t?void 0:t.filter(e=>null!=e.uri&&""!==e.uri).map(e=>tw.fromSdkLoginUriView(e)))||[],i.fido2Credentials=[],i}toSdkLoginView(){var e,t,i;return{username:this.username,password:this.password,passwordRevisionDate:null===(e=this.passwordRevisionDate)||void 0===e?void 0:e.toISOString(),totp:this.totp,autofillOnPageLoad:null!==(t=this.autofillOnPageLoad)&&void 0!==t?t:void 0,uris:null===(i=this.uris)||void 0===i?void 0:i.map(e=>e.toSdkLoginUriView()),fido2Credentials:void 0}}}iw([Vb(om.Username,{sortPosition:0}),rw("design:type",String)],nw.prototype,"username",void 0),iw([Vb(om.Password,{sortPosition:1}),rw("design:type",String)],nw.prototype,"password",void 0);class aw{constructor(e){this.password=null,this.lastUsedDate=null,e&&(this.lastUsedDate=e.lastUsedDate)}static fromJSON(e){const t=null==e.lastUsedDate?null:new Date(e.lastUsedDate);return Object.assign(new aw,e,{lastUsedDate:t})}static fromSdkPasswordHistoryView(e){if(!e)return;const t=new aw;return t.password=e.password,t.lastUsedDate=null==e.lastUsedDate?null:new Date(e.lastUsedDate),t}toSdkPasswordHistoryView(){var e;return{password:null!==(e=this.password)&&void 0!==e?e:"",lastUsedDate:this.lastUsedDate.toISOString()}}}class sw extends $b{constructor(e){super(),this.type=0,e&&(this.type=e.type)}get subTitle(){}static fromJSON(e){return Object.assign(new sw,e)}static fromSdkSecureNoteView(e){const t=new sw;return t.type=e.type,t}toSdkSecureNoteView(){return this}}class ow extends $b{get maskedPrivateKey(){if(!this.privateKey||0===this.privateKey.length)return"";let e=this.privateKey.split("\n").filter(e=>""!==e.trim());return e=e.map((t,i)=>0===i||i===e.length-1?t:this.maskLine(t)),e.join("\n")}maskLine(e){return"•".repeat(32)}get subTitle(){return this.keyFingerprint}static fromJSON(e){return Object.assign(new ow,e)}static fromSdkSshKeyView(e){const t=new ow;return t.privateKey=e.privateKey,t.publicKey=e.publicKey,t.keyFingerprint=e.fingerprint,t}toSdkSshKeyView(){return{privateKey:this.privateKey,publicKey:this.publicKey,fingerprint:this.keyFingerprint}}}class lw{constructor(e){var t;this.initializerKey=_b.CipherView,this.id="",this.name="",this.type=rm.Login,this.favorite=!1,this.organizationUseTotp=!1,this.permissions=new Eb,this.edit=!1,this.viewPassword=!0,this.login=new nw,this.identity=new Yb,this.card=new Hb,this.secureNote=new sw,this.sshKey=new ow,this.attachments=[],this.fields=[],this.passwordHistory=[],this.collectionIds=[],this.reprompt=tm.None,this.decryptionFailure=!1,e?(this.id=e.id,this.organizationId=e.organizationId,this.folderId=e.folderId,this.favorite=e.favorite,this.organizationUseTotp=e.organizationUseTotp,this.edit=e.edit,this.viewPassword=e.viewPassword,this.permissions=e.permissions,this.type=e.type,this.localData=e.localData,this.collectionIds=e.collectionIds,this.revisionDate=e.revisionDate,this.creationDate=e.creationDate,this.deletedDate=e.deletedDate,this.archivedDate=e.archivedDate,this.reprompt=null!==(t=e.reprompt)&&void 0!==t?t:tm.None,this.key=e.key):this.creationDate=this.revisionDate=new Date}get item(){switch(this.type){case rm.Login:return this.login;case rm.SecureNote:return this.secureNote;case rm.Card:return this.card;case rm.Identity:return this.identity;case rm.SshKey:return this.sshKey}}get subTitle(){var e;return null===(e=this.item)||void 0===e?void 0:e.subTitle}get canBeArchived(){return!this.isDeleted&&!this.isArchived}get hasPasswordHistory(){return this.passwordHistory&&this.passwordHistory.length>0}get hasLoginPassword(){var e;return this.type===rm.Login&&null!=(null===(e=this.login)||void 0===e?void 0:e.password)&&""!==this.login.password}get hasAttachments(){return!!this.attachments&&this.attachments.length>0}get hasOldAttachments(){if(this.hasAttachments)for(let e=0;e0}get passwordRevisionDisplayDate(){if(this.type===rm.Login&&null!=this.login&&null!=this.login.password&&""!==this.login.password)return this.login.passwordRevisionDate}get isDeleted(){return null!=this.deletedDate}get isArchived(){return null!=this.archivedDate}get linkedFieldOptions(){var e;return null===(e=this.item)||void 0===e?void 0:e.linkedFieldOptions}get isUnassigned(){return null!=this.organizationId&&(null==this.collectionIds||0===this.collectionIds.length)}get canAssignToCollections(){return null==this.organizationId||this.edit&&this.viewPassword}get canLaunch(){return this.type===rm.Login&&this.login.canLaunch}linkedFieldValue(e){var t;const i=null===(t=this.linkedFieldOptions)||void 0===t?void 0:t.get(e),r=this.item;if(null!=i&&null!=r)return r[i.propertyKey]}toJSON(){return this}static fromJSON(e){var t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,f,y,v;if(null==e)return null;const b=new lw;if(b.type=null!==(t=e.type)&&void 0!==t?t:rm.Login,b.id=null!==(i=e.id)&&void 0!==i?i:"",b.organizationId=null!==(r=e.organizationId)&&void 0!==r?r:void 0,b.folderId=null!==(n=e.folderId)&&void 0!==n?n:void 0,b.collectionIds=null!==(a=e.collectionIds)&&void 0!==a?a:[],b.name=null!==(s=e.name)&&void 0!==s?s:"",b.notes=e.notes,b.edit=null!==(o=e.edit)&&void 0!==o&&o,b.viewPassword=null===(l=e.viewPassword)||void 0===l||l,b.favorite=null!==(c=e.favorite)&&void 0!==c&&c,b.organizationUseTotp=null!==(u=e.organizationUseTotp)&&void 0!==u&&u,b.localData=e.localData?e.localData:void 0,b.permissions=e.permissions?Eb.fromJSON(e.permissions):void 0,b.reprompt=null!==(d=e.reprompt)&&void 0!==d?d:tm.None,b.decryptionFailure=null!==(h=e.decryptionFailure)&&void 0!==h&&h,e.creationDate&&(b.creationDate=new Date(e.creationDate)),e.revisionDate&&(b.revisionDate=new Date(e.revisionDate)),b.deletedDate=null==e.deletedDate?void 0:new Date(e.deletedDate),b.archivedDate=null==e.archivedDate?void 0:new Date(e.archivedDate),b.attachments=null!==(m=null===(p=e.attachments)||void 0===p?void 0:p.map(e=>Bb.fromJSON(e)))&&void 0!==m?m:[],b.fields=null!==(f=null===(g=e.fields)||void 0===g?void 0:g.map(e=>Gb.fromJSON(e)))&&void 0!==f?f:[],b.passwordHistory=null!==(v=null===(y=e.passwordHistory)||void 0===y?void 0:y.map(e=>aw.fromJSON(e)))&&void 0!==v?v:[],null!=e.key){let t;"string"==typeof e.key?t=Nt.fromJSON(e.key):e.key instanceof Nt&&(t=e.key),b.key=t}switch(e.type){case rm.Card:b.card=Hb.fromJSON(e.card);break;case rm.Identity:b.identity=Yb.fromJSON(e.identity);break;case rm.Login:b.login=nw.fromJSON(e.login);break;case rm.SecureNote:b.secureNote=sw.fromJSON(e.secureNote);break;case rm.SshKey:b.sshKey=ow.fromJSON(e.sshKey)}return b}static fromSdkCipherView(e){var t,i,r,n,a,s,o,l,c,u;if(null==e)return;const d=null!==(i=null===(t=e.attachments)||void 0===t?void 0:t.map(e=>Bb.fromSdkAttachmentView(e)))&&void 0!==i?i:[];(null===(r=e.attachmentDecryptionFailures)||void 0===r?void 0:r.length)&&e.attachmentDecryptionFailures.forEach(e=>{const t=Bb.fromSdkAttachmentView(e,!0);t&&d.push(t)});const h=new lw;switch(h.id=e.id,h.organizationId=e.organizationId,h.folderId=e.folderId,h.name=e.name,h.notes=e.notes,h.type=e.type,h.favorite=e.favorite,h.organizationUseTotp=e.organizationUseTotp,h.permissions=e.permissions?Eb.fromSdkCipherPermissions(e.permissions):void 0,h.edit=e.edit,h.viewPassword=e.viewPassword,h.localData=qb(e.localData),h.attachments=d,h.fields=null!==(a=null===(n=e.fields)||void 0===n?void 0:n.map(e=>Gb.fromSdkFieldView(e)))&&void 0!==a?a:[],h.passwordHistory=null!==(o=null===(s=e.passwordHistory)||void 0===s?void 0:s.map(e=>aw.fromSdkPasswordHistoryView(e)))&&void 0!==o?o:[],h.collectionIds=null!==(c=null===(l=e.collectionIds)||void 0===l?void 0:l.map(e=>e))&&void 0!==c?c:[],h.revisionDate=new Date(e.revisionDate),h.creationDate=new Date(e.creationDate),h.deletedDate=null==e.deletedDate?void 0:new Date(e.deletedDate),h.archivedDate=null==e.archivedDate?void 0:new Date(e.archivedDate),h.reprompt=null!==(u=e.reprompt)&&void 0!==u?u:tm.None,h.key=e.key?Nt.fromJSON(e.key):void 0,e.type){case rm.Card:h.card=e.card?Hb.fromSdkCardView(e.card):new Hb;break;case rm.Identity:h.identity=e.identity?Yb.fromSdkIdentityView(e.identity):new Yb;break;case rm.Login:h.login=e.login?nw.fromSdkLoginView(e.login):new nw;break;case rm.SecureNote:h.secureNote=e.secureNote?sw.fromSdkSecureNoteView(e.secureNote):new sw;break;case rm.SshKey:h.sshKey=e.sshKey?ow.fromSdkSshKeyView(e.sshKey):new ow}return h}toSdkCreateCipherRequest(){var e,t,i,r;return{organizationId:this.organizationId?$g(this.organizationId):void 0,collectionIds:this.collectionIds?this.collectionIds.map(e=>$g(e)):[],folderId:this.folderId?$g(this.folderId):void 0,name:null!==(e=this.name)&&void 0!==e?e:"",notes:this.notes,favorite:null!==(t=this.favorite)&&void 0!==t&&t,reprompt:null!==(i=this.reprompt)&&void 0!==i?i:tm.None,fields:null===(r=this.fields)||void 0===r?void 0:r.map(e=>e.toSdkFieldView()),type:this.getSdkCipherViewType()}}toSdkUpdateCipherRequest(){var e,t,i,r,n,a,s,o;return{id:$g(this.id),organizationId:this.organizationId?$g(this.organizationId):void 0,folderId:this.folderId?$g(this.folderId):void 0,name:null!==(e=this.name)&&void 0!==e?e:"",notes:this.notes,favorite:null!==(t=this.favorite)&&void 0!==t&&t,reprompt:null!==(i=this.reprompt)&&void 0!==i?i:tm.None,fields:null===(r=this.fields)||void 0===r?void 0:r.map(e=>e.toSdkFieldView()),type:this.getSdkCipherViewType(),revisionDate:null===(n=this.revisionDate)||void 0===n?void 0:n.toISOString(),archivedDate:null===(a=this.archivedDate)||void 0===a?void 0:a.toISOString(),attachments:null===(s=this.attachments)||void 0===s?void 0:s.map(e=>e.toSdkAttachmentView()),key:null===(o=this.key)||void 0===o?void 0:o.toSdk()}}getSdkCipherViewType(){var e,t,i,r,n;let a;switch(this.type){case rm.Card:a={card:null===(e=this.card)||void 0===e?void 0:e.toSdkCardView()};break;case rm.Identity:a={identity:null===(t=this.identity)||void 0===t?void 0:t.toSdkIdentityView()};break;case rm.Login:a={login:null===(i=this.login)||void 0===i?void 0:i.toSdkLoginView()};break;case rm.SecureNote:a={secureNote:null===(r=this.secureNote)||void 0===r?void 0:r.toSdkSecureNoteView()};break;case rm.SshKey:a={sshKey:null===(n=this.sshKey)||void 0===n?void 0:n.toSdkSshKeyView()};break;default:a={login:(new nw).toSdkLoginView()}}return a}toSdkCipherView(){var e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,f,y,v,b,w,k,S;const _={id:this.id?$g(this.id):void 0,organizationId:this.organizationId?$g(this.organizationId):void 0,folderId:this.folderId?$g(this.folderId):void 0,name:null!==(e=this.name)&&void 0!==e?e:"",notes:this.notes,type:null!==(t=this.type)&&void 0!==t?t:rm.Login,favorite:null!==(i=this.favorite)&&void 0!==i&&i,organizationUseTotp:null!==(r=this.organizationUseTotp)&&void 0!==r&&r,permissions:null===(n=this.permissions)||void 0===n?void 0:n.toSdkCipherPermissions(),edit:null===(a=this.edit)||void 0===a||a,viewPassword:null===(s=this.viewPassword)||void 0===s||s,localData:Lb(this.localData),attachments:null===(o=this.attachments)||void 0===o?void 0:o.map(e=>e.toSdkAttachmentView()),fields:null===(l=this.fields)||void 0===l?void 0:l.map(e=>e.toSdkFieldView()),passwordHistory:null===(c=this.passwordHistory)||void 0===c?void 0:c.map(e=>e.toSdkPasswordHistoryView()),collectionIds:null!==(d=null===(u=this.collectionIds)||void 0===u?void 0:u.map(e=>$g(e)))&&void 0!==d?d:[],revisionDate:(null!==(h=this.revisionDate)&&void 0!==h?h:new Date).toISOString(),creationDate:(null!==(p=this.creationDate)&&void 0!==p?p:new Date).toISOString(),deletedDate:null===(m=this.deletedDate)||void 0===m?void 0:m.toISOString(),archivedDate:null===(g=this.archivedDate)||void 0===g?void 0:g.toISOString(),reprompt:null!==(f=this.reprompt)&&void 0!==f?f:tm.None,key:null===(y=this.key)||void 0===y?void 0:y.toSdk(),login:void 0,card:void 0,identity:void 0,secureNote:void 0,sshKey:void 0};switch(this.type){case rm.Card:_.card=null===(v=this.card)||void 0===v?void 0:v.toSdkCardView();break;case rm.Identity:_.identity=null===(b=this.identity)||void 0===b?void 0:b.toSdkIdentityView();break;case rm.Login:_.login=null===(w=this.login)||void 0===w?void 0:w.toSdkLoginView();break;case rm.SecureNote:_.secureNote=null===(k=this.secureNote)||void 0===k?void 0:k.toSdkSecureNoteView();break;case rm.SshKey:_.sshKey=null===(S=this.sshKey)||void 0===S?void 0:S.toSdkSshKeyView()}return _}}var cw=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class uw extends Rt{constructor(e){super(),null!=e&&(this.id=e.id,this.url=e.url,this.size=e.size,this.sizeName=e.sizeName,this.fileName=Cb(e.fileName),this.key=Cb(e.key))}decrypt(e){return cw(this,arguments,void 0,function*(e,t="No Cipher Context"){const i=yield this.decryptObj(this,new Bb(this),["fileName"],e,"DomainType: Attachment; "+t);return null!=this.key&&(i.key=yield this.decryptAttachmentKey(e),i.encryptedKey=this.key,i.key||(i.hasDecryptionError=!0)),i})}decryptAttachmentKey(e){return cw(this,void 0,void 0,function*(){try{if(null==this.key)return;const t=Tt.getContainerService().getEncryptService();return yield t.unwrapSymmetricKey(this.key,e)}catch(e){return void console.error("[Attachment] Error decrypting attachment",e)}})}toAttachmentData(){const e=new zb;return null!=this.size&&(e.size=this.size),this.buildDataModel(this,e,{id:null,url:null,sizeName:null,fileName:null,key:null},["id","url","sizeName"]),e}static fromJSON(e){if(null==e)return;const t=new uw;return t.id=e.id,t.url=e.url,t.size=e.size,t.sizeName=e.sizeName,t.key=Ib(e.key),t.fileName=Ib(e.fileName),t}toSdkAttachment(){var e,t;return{id:this.id,url:this.url,size:this.size,sizeName:this.sizeName,fileName:null===(e=this.fileName)||void 0===e?void 0:e.toSdk(),key:null===(t=this.key)||void 0===t?void 0:t.toSdk()}}static fromSdkAttachment(e){if(!e)return;const t=new uw;return t.id=e.id,t.url=e.url,t.size=e.size,t.sizeName=e.sizeName,t.fileName=Ib(e.fileName),t.key=Ib(e.key),t}}class dw extends Rt{constructor(e){super(),null!=e&&(this.cardholderName=Cb(e.cardholderName),this.brand=Cb(e.brand),this.number=Cb(e.number),this.expMonth=Cb(e.expMonth),this.expYear=Cb(e.expYear),this.code=Cb(e.code))}decrypt(e){return t=this,i=arguments,n=function*(e,t="No Cipher Context"){return this.decryptObj(this,new Hb,["cardholderName","brand","number","expMonth","expYear","code"],e,"DomainType: Card; "+t)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}toCardData(){const e=new Pb;return this.buildDataModel(this,e,{cardholderName:null,brand:null,number:null,expMonth:null,expYear:null,code:null}),e}static fromJSON(e){if(null==e)return;const t=new dw;return t.cardholderName=Ib(e.cardholderName),t.brand=Ib(e.brand),t.number=Ib(e.number),t.expMonth=Ib(e.expMonth),t.expYear=Ib(e.expYear),t.code=Ib(e.code),t}toSdkCard(){var e,t,i,r,n,a;return{cardholderName:null===(e=this.cardholderName)||void 0===e?void 0:e.toSdk(),brand:null===(t=this.brand)||void 0===t?void 0:t.toSdk(),number:null===(i=this.number)||void 0===i?void 0:i.toSdk(),expMonth:null===(r=this.expMonth)||void 0===r?void 0:r.toSdk(),expYear:null===(n=this.expYear)||void 0===n?void 0:n.toSdk(),code:null===(a=this.code)||void 0===a?void 0:a.toSdk()}}static fromSdkCard(e){if(!e)return;const t=new dw;return t.cardholderName=Ib(e.cardholderName),t.brand=Ib(e.brand),t.number=Ib(e.number),t.expMonth=Ib(e.expMonth),t.expYear=Ib(e.expYear),t.code=Ib(e.code),t}}class hw extends Rt{constructor(e){var t;super(),this.type=am.Text,null!=e&&(this.type=e.type,this.linkedId=null!==(t=e.linkedId)&&void 0!==t?t:void 0,this.name=Cb(e.name),this.value=Cb(e.value))}decrypt(e){return this.decryptObj(this,new Gb(this),["name","value"],e)}toFieldData(){const e=new Ab;return this.buildDataModel(this,e,{name:null,value:null,type:null,linkedId:null},["type","linkedId"]),e}static fromJSON(e){var t,i;if(null==e)return;const r=new hw;return r.type=null!==(t=e.type)&&void 0!==t?t:am.Text,r.linkedId=null!==(i=e.linkedId)&&void 0!==i?i:void 0,r.name=Ib(e.name),r.value=Ib(e.value),r}toSdkField(){var e,t;return{name:null===(e=this.name)||void 0===e?void 0:e.toSdk(),value:null===(t=this.value)||void 0===t?void 0:t.toSdk(),type:sm(this.type),linkedId:um(this.linkedId)}}static fromSdkField(e){if(null==e)return;const t=new hw;return t.name=Ib(e.name),t.value=Ib(e.value),t.type=e.type,t.linkedId=e.linkedId,t}}class pw extends Rt{constructor(e){super(),null!=e&&(this.title=Cb(e.title),this.firstName=Cb(e.firstName),this.middleName=Cb(e.middleName),this.lastName=Cb(e.lastName),this.address1=Cb(e.address1),this.address2=Cb(e.address2),this.address3=Cb(e.address3),this.city=Cb(e.city),this.state=Cb(e.state),this.postalCode=Cb(e.postalCode),this.country=Cb(e.country),this.company=Cb(e.company),this.email=Cb(e.email),this.phone=Cb(e.phone),this.ssn=Cb(e.ssn),this.username=Cb(e.username),this.passportNumber=Cb(e.passportNumber),this.licenseNumber=Cb(e.licenseNumber))}decrypt(e,t="No Cipher Context"){return this.decryptObj(this,new Yb,["title","firstName","middleName","lastName","address1","address2","address3","city","state","postalCode","country","company","email","phone","ssn","username","passportNumber","licenseNumber"],e,"DomainType: Identity; "+t)}toIdentityData(){const e=new jb;return this.buildDataModel(this,e,{title:null,firstName:null,middleName:null,lastName:null,address1:null,address2:null,address3:null,city:null,state:null,postalCode:null,country:null,company:null,email:null,phone:null,ssn:null,username:null,passportNumber:null,licenseNumber:null}),e}static fromJSON(e){if(null==e)return;const t=new pw;return t.title=Ib(e.title),t.firstName=Ib(e.firstName),t.middleName=Ib(e.middleName),t.lastName=Ib(e.lastName),t.address1=Ib(e.address1),t.address2=Ib(e.address2),t.address3=Ib(e.address3),t.city=Ib(e.city),t.state=Ib(e.state),t.postalCode=Ib(e.postalCode),t.country=Ib(e.country),t.company=Ib(e.company),t.email=Ib(e.email),t.phone=Ib(e.phone),t.ssn=Ib(e.ssn),t.username=Ib(e.username),t.passportNumber=Ib(e.passportNumber),t.licenseNumber=Ib(e.licenseNumber),t}toSdkIdentity(){var e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,f,y;return{title:null===(e=this.title)||void 0===e?void 0:e.toSdk(),firstName:null===(t=this.firstName)||void 0===t?void 0:t.toSdk(),middleName:null===(i=this.middleName)||void 0===i?void 0:i.toSdk(),lastName:null===(r=this.lastName)||void 0===r?void 0:r.toSdk(),address1:null===(n=this.address1)||void 0===n?void 0:n.toSdk(),address2:null===(a=this.address2)||void 0===a?void 0:a.toSdk(),address3:null===(s=this.address3)||void 0===s?void 0:s.toSdk(),city:null===(o=this.city)||void 0===o?void 0:o.toSdk(),state:null===(l=this.state)||void 0===l?void 0:l.toSdk(),postalCode:null===(c=this.postalCode)||void 0===c?void 0:c.toSdk(),country:null===(u=this.country)||void 0===u?void 0:u.toSdk(),company:null===(d=this.company)||void 0===d?void 0:d.toSdk(),email:null===(h=this.email)||void 0===h?void 0:h.toSdk(),phone:null===(p=this.phone)||void 0===p?void 0:p.toSdk(),ssn:null===(m=this.ssn)||void 0===m?void 0:m.toSdk(),username:null===(g=this.username)||void 0===g?void 0:g.toSdk(),passportNumber:null===(f=this.passportNumber)||void 0===f?void 0:f.toSdk(),licenseNumber:null===(y=this.licenseNumber)||void 0===y?void 0:y.toSdk()}}static fromSdkIdentity(e){if(null==e)return;const t=new pw;return t.title=Ib(e.title),t.firstName=Ib(e.firstName),t.middleName=Ib(e.middleName),t.lastName=Ib(e.lastName),t.address1=Ib(e.address1),t.address2=Ib(e.address2),t.address3=Ib(e.address3),t.city=Ib(e.city),t.state=Ib(e.state),t.postalCode=Ib(e.postalCode),t.country=Ib(e.country),t.company=Ib(e.company),t.email=Ib(e.email),t.phone=Ib(e.phone),t.ssn=Ib(e.ssn),t.username=Ib(e.username),t.passportNumber=Ib(e.passportNumber),t.licenseNumber=Ib(e.licenseNumber),t}}class mw extends Rt{constructor(e){super(),null!=e?(this.credentialId=new Nt(e.credentialId),this.keyType=new Nt(e.keyType),this.keyAlgorithm=new Nt(e.keyAlgorithm),this.keyCurve=new Nt(e.keyCurve),this.keyValue=new Nt(e.keyValue),this.rpId=new Nt(e.rpId),this.counter=new Nt(e.counter),this.discoverable=new Nt(e.discoverable),this.userHandle=Cb(e.userHandle),this.userName=Cb(e.userName),this.rpName=Cb(e.rpName),this.userDisplayName=Cb(e.userDisplayName),this.creationDate=new Date(e.creationDate)):this.creationDate=new Date}decrypt(e){return t=this,i=void 0,n=function*(){const t=yield this.decryptObj(this,new Xb,["credentialId","keyType","keyAlgorithm","keyCurve","keyValue","rpId","userHandle","userName","rpName","userDisplayName"],e),{counter:i}=yield this.decryptObj(this,{counter:""},["counter"],e);t.counter=parseInt(i);const{discoverable:r}=yield this.decryptObj(this,{discoverable:""},["discoverable"],e);return t.discoverable="true"===r,t.creationDate=this.creationDate,t},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}toFido2CredentialData(){const e=new Tb;return e.creationDate=this.creationDate.toISOString(),this.buildDataModel(this,e,{credentialId:null,keyType:null,keyAlgorithm:null,keyCurve:null,keyValue:null,rpId:null,userHandle:null,userName:null,counter:null,rpName:null,userDisplayName:null,discoverable:null}),e}static fromJSON(e){if(null==e)return;const t=new mw;return t.credentialId=Nt.fromJSON(e.credentialId),t.keyType=Nt.fromJSON(e.keyType),t.keyAlgorithm=Nt.fromJSON(e.keyAlgorithm),t.keyCurve=Nt.fromJSON(e.keyCurve),t.keyValue=Nt.fromJSON(e.keyValue),t.rpId=Nt.fromJSON(e.rpId),t.userHandle=Ib(e.userHandle),t.userName=Ib(e.userName),t.counter=Nt.fromJSON(e.counter),t.rpName=Ib(e.rpName),t.userDisplayName=Ib(e.userDisplayName),t.discoverable=Nt.fromJSON(e.discoverable),t.creationDate=new Date(e.creationDate),t}toSdkFido2Credential(){var e,t,i,r,n,a;return{credentialId:null===(e=this.credentialId)||void 0===e?void 0:e.toSdk(),keyType:this.keyType.toSdk(),keyAlgorithm:this.keyAlgorithm.toSdk(),keyCurve:this.keyCurve.toSdk(),keyValue:this.keyValue.toSdk(),rpId:this.rpId.toSdk(),userHandle:null===(t=this.userHandle)||void 0===t?void 0:t.toSdk(),userName:null===(i=this.userName)||void 0===i?void 0:i.toSdk(),counter:this.counter.toSdk(),rpName:null===(r=this.rpName)||void 0===r?void 0:r.toSdk(),userDisplayName:null===(n=this.userDisplayName)||void 0===n?void 0:n.toSdk(),discoverable:null===(a=this.discoverable)||void 0===a?void 0:a.toSdk(),creationDate:this.creationDate.toISOString()}}static fromSdkFido2Credential(e){if(null==e)return;const t=new mw;return t.credentialId=Nt.fromJSON(e.credentialId),t.keyType=Nt.fromJSON(e.keyType),t.keyAlgorithm=Nt.fromJSON(e.keyAlgorithm),t.keyCurve=Nt.fromJSON(e.keyCurve),t.keyValue=Nt.fromJSON(e.keyValue),t.rpId=Nt.fromJSON(e.rpId),t.counter=Nt.fromJSON(e.counter),t.userHandle=Ib(e.userHandle),t.userName=Ib(e.userName),t.rpName=Ib(e.rpName),t.userDisplayName=Ib(e.userDisplayName),t.discoverable=Nt.fromJSON(e.discoverable),t.creationDate=new Date(e.creationDate),t}}class gw extends Rt{constructor(e){var t;super(),null!=e&&(this.uri=Cb(e.uri),this.uriChecksum=Cb(e.uriChecksum),this.match=null!==(t=e.match)&&void 0!==t?t:void 0)}decrypt(e,t="No Cipher Context"){return this.decryptObj(this,new tw(this),["uri"],e,t)}validateChecksum(e,t){return i=this,r=void 0,a=function*(){if(null==this.uriChecksum)return!1;const i=Tt.getContainerService().getEncryptService(),r=yield i.hash(e,"sha256");return(yield i.decryptString(this.uriChecksum,t))===r},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}toLoginUriData(){const e=new Db;return this.buildDataModel(this,e,{uri:null,uriChecksum:null,match:null},["match"]),e}static fromJSON(e){var t;if(null==e)return;const i=new gw;return i.uri=Ib(e.uri),i.match=null!==(t=e.match)&&void 0!==t?t:void 0,i.uriChecksum=Ib(e.uriChecksum),i}toSdkLoginUri(){var e,t;return{uri:null===(e=this.uri)||void 0===e?void 0:e.toSdk(),uriChecksum:null===(t=this.uriChecksum)||void 0===t?void 0:t.toSdk(),match:Zm(this.match)}}static fromSdkLoginUri(e){if(null==e)return;const t=new gw;return t.uri=Ib(e.uri),t.uriChecksum=Ib(e.uriChecksum),t.match=e.match,t}}class fw extends Rt{constructor(e){super(),null!=e&&(this.passwordRevisionDate=null!=e.passwordRevisionDate?new Date(e.passwordRevisionDate):void 0,this.autofillOnPageLoad=e.autofillOnPageLoad,this.username=Cb(e.username),this.password=Cb(e.password),this.totp=Cb(e.totp),e.uris&&(this.uris=e.uris.map(e=>new gw(e))),e.fido2Credentials&&(this.fido2Credentials=e.fido2Credentials.map(e=>new mw(e))))}decrypt(e,t){return i=this,r=arguments,a=function*(e,t,i="No Cipher Context"){const r=yield this.decryptObj(this,new nw(this),["username","password","totp"],t,`DomainType: Login; ${i}`);if(null!=this.uris){r.uris=[];for(let n=0;ne.decrypt(t)))),r},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}toLoginData(){const e=new Ob;return null!=this.passwordRevisionDate&&(e.passwordRevisionDate=this.passwordRevisionDate.toISOString()),null!=this.autofillOnPageLoad&&(e.autofillOnPageLoad=this.autofillOnPageLoad),this.buildDataModel(this,e,{username:null,password:null,totp:null}),null!=this.uris&&this.uris.length>0&&(e.uris=this.uris.map(e=>e.toLoginUriData())),null!=this.fido2Credentials&&this.fido2Credentials.length>0&&(e.fido2Credentials=this.fido2Credentials.map(e=>e.toFido2CredentialData())),e}static fromJSON(e){var t,i,r;if(null==e)return;const n=new fw;return n.passwordRevisionDate=null!=e.passwordRevisionDate?new Date(e.passwordRevisionDate):void 0,n.autofillOnPageLoad=e.autofillOnPageLoad,n.username=Ib(e.username),n.password=Ib(e.password),n.totp=Ib(e.totp),n.uris=null===(t=e.uris)||void 0===t?void 0:t.map(e=>gw.fromJSON(e)).filter(e=>null!=e),n.fido2Credentials=null!==(r=null===(i=e.fido2Credentials)||void 0===i?void 0:i.map(e=>mw.fromJSON(e)).filter(e=>null!=e))&&void 0!==r?r:void 0,n}toSdkLogin(){var e,t,i,r,n,a,s;return{uris:null===(e=this.uris)||void 0===e?void 0:e.map(e=>e.toSdkLoginUri()),username:null===(t=this.username)||void 0===t?void 0:t.toSdk(),password:null===(i=this.password)||void 0===i?void 0:i.toSdk(),passwordRevisionDate:null===(r=this.passwordRevisionDate)||void 0===r?void 0:r.toISOString(),totp:null===(n=this.totp)||void 0===n?void 0:n.toSdk(),autofillOnPageLoad:null!==(a=this.autofillOnPageLoad)&&void 0!==a?a:void 0,fido2Credentials:null===(s=this.fido2Credentials)||void 0===s?void 0:s.map(e=>e.toSdkFido2Credential())}}static fromSdkLogin(e){var t,i,r,n;if(!e)return;const a=new fw;return a.passwordRevisionDate=null!=e.passwordRevisionDate?new Date(e.passwordRevisionDate):void 0,a.autofillOnPageLoad=e.autofillOnPageLoad,a.username=Ib(e.username),a.password=Ib(e.password),a.totp=Ib(e.totp),a.uris=null!==(i=null===(t=e.uris)||void 0===t?void 0:t.filter(e=>null!=e.uri).map(e=>gw.fromSdkLoginUri(e)).filter(e=>null!=e))&&void 0!==i?i:void 0,a.fido2Credentials=null!==(n=null===(r=e.fido2Credentials)||void 0===r?void 0:r.map(e=>mw.fromSdkFido2Credential(e)).filter(e=>null!=e))&&void 0!==n?n:void 0,a}}class yw extends Rt{constructor(e){super(),null!=e&&(this.password=new Nt(e.password),this.lastUsedDate=new Date(e.lastUsedDate))}decrypt(e){return this.decryptObj(this,new aw(this),["password"],e,"DomainType: PasswordHistory")}toPasswordHistoryData(){const e=new Nb;return e.lastUsedDate=this.lastUsedDate.toISOString(),this.buildDataModel(this,e,{password:null}),e}static fromJSON(e){if(null==e)return;const t=new yw;return t.password=Nt.fromJSON(e.password),t.lastUsedDate=new Date(e.lastUsedDate),t}toSdkPasswordHistory(){return{password:this.password.toSdk(),lastUsedDate:this.lastUsedDate.toISOString()}}static fromSdkPasswordHistory(e){if(!e)return;const t=new yw;return t.password=Nt.fromJSON(e.password),t.lastUsedDate=new Date(e.lastUsedDate),t}}class vw extends Rt{constructor(e){super(),this.type=0,null!=e&&(this.type=e.type)}decrypt(){return e=this,t=void 0,r=function*(){return new sw(this)},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r}toSecureNoteData(){const e=new Rb;return e.type=this.type,e}static fromJSON(e){if(null==e)return;const t=new vw;return t.type=e.type,t}toSdkSecureNote(){return{type:(this.type,0)}}static fromSdkSecureNote(e){if(null==e)return;const t=new vw;return t.type=e.type,t}}class bw extends Rt{constructor(e){super(),null!=e&&(this.privateKey=new Nt(e.privateKey),this.publicKey=new Nt(e.publicKey),this.keyFingerprint=new Nt(e.keyFingerprint))}decrypt(e,t="No Cipher Context"){return this.decryptObj(this,new ow,["privateKey","publicKey","keyFingerprint"],e,"DomainType: SshKey; "+t)}toSshKeyData(){const e=new Ub;return this.buildDataModel(this,e,{privateKey:null,publicKey:null,keyFingerprint:null}),e}static fromJSON(e){if(null==e)return;const t=new bw;return t.privateKey=Nt.fromJSON(e.privateKey),t.publicKey=Nt.fromJSON(e.publicKey),t.keyFingerprint=Nt.fromJSON(e.keyFingerprint),t}toSdkSshKey(){return{privateKey:this.privateKey.toSdk(),publicKey:this.publicKey.toSdk(),fingerprint:this.keyFingerprint.toSdk()}}static fromSdkSshKey(e){if(null==e)return;const t=new bw;return t.privateKey=Nt.fromJSON(e.privateKey),t.publicKey=Nt.fromJSON(e.publicKey),t.keyFingerprint=Nt.fromJSON(e.fingerprint),t}}var ww,kw;class Sw extends Rt{constructor(e,t){var i;if(super(),this.initializerKey=_b.Cipher,this.id="",this.name=new Nt(""),this.type=rm.Login,this.favorite=!1,this.organizationUseTotp=!1,this.edit=!1,this.viewPassword=!0,this.collectionIds=[],this.reprompt=tm.None,null!=e){switch(this.id=e.id,this.organizationId=e.organizationId,this.folderId=e.folderId,this.name=new Nt(e.name),this.notes=Cb(e.notes),this.type=e.type,this.favorite=e.favorite,this.organizationUseTotp=e.organizationUseTotp,this.edit=e.edit,this.viewPassword=e.viewPassword,this.permissions=e.permissions,this.revisionDate=new Date(e.revisionDate),this.localData=t,this.collectionIds=null!==(i=e.collectionIds)&&void 0!==i?i:[],this.creationDate=new Date(e.creationDate),this.deletedDate=null!=e.deletedDate?new Date(e.deletedDate):void 0,this.archivedDate=null!=e.archivedDate?new Date(e.archivedDate):void 0,this.reprompt=e.reprompt,this.key=Cb(e.key),this.type){case rm.Login:this.login=new fw(e.login);break;case rm.SecureNote:this.secureNote=new vw(e.secureNote);break;case rm.Card:this.card=new dw(e.card);break;case rm.Identity:this.identity=new pw(e.identity);break;case rm.SshKey:this.sshKey=new bw(e.sshKey)}null!=e.attachments&&(this.attachments=e.attachments.map(e=>new uw(e))),null!=e.fields&&(this.fields=e.fields.map(e=>new hw(e))),null!=e.passwordHistory&&(this.passwordHistory=e.passwordHistory.map(e=>new yw(e)))}else this.creationDate=this.revisionDate=new Date}decrypt(e){return t=this,i=void 0,n=function*(){zh(e,"userKeyOrOrgKey","Cipher decryption");const t=new lw(this);let i=!0,r=e;if(null!=this.key){const n=Tt.getContainerService().getEncryptService();try{r=yield n.unwrapSymmetricKey(this.key,e),i=!1}catch(e){return t.name="[error: cannot decrypt]",t.decryptionFailure=!0,t}}switch(yield this.decryptObj(this,t,["name","notes"],r),this.type){case rm.Login:null!=this.login&&(t.login=yield this.login.decrypt(i,r,`Cipher Id: ${this.id}`));break;case rm.SecureNote:null!=this.secureNote&&(t.secureNote=yield this.secureNote.decrypt());break;case rm.Card:null!=this.card&&(t.card=yield this.card.decrypt(r,`Cipher Id: ${this.id}`));break;case rm.Identity:null!=this.identity&&(t.identity=yield this.identity.decrypt(r,`Cipher Id: ${this.id}`));break;case rm.SshKey:null!=this.sshKey&&(t.sshKey=yield this.sshKey.decrypt(r,`Cipher Id: ${this.id}`))}if(null!=this.attachments&&this.attachments.length>0){const e=[];for(const t of this.attachments){const i=yield t.decrypt(r,`Cipher Id: ${this.id}`);e.push(i)}t.attachments=e}if(null!=this.fields&&this.fields.length>0){const e=[];for(const t of this.fields){const i=yield t.decrypt(r);e.push(i)}t.fields=e}if(null!=this.passwordHistory&&this.passwordHistory.length>0){const e=[];for(const t of this.passwordHistory){const i=yield t.decrypt(r);e.push(i)}t.passwordHistory=e}return t},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}toCipherData(){const e=new Fb;switch(e.id=this.id,null!=this.organizationId&&(e.organizationId=this.organizationId),null!=this.folderId&&(e.folderId=this.folderId),e.edit=this.edit,e.viewPassword=this.viewPassword,e.organizationUseTotp=this.organizationUseTotp,e.favorite=this.favorite,e.revisionDate=this.revisionDate.toISOString(),e.type=this.type,e.collectionIds=this.collectionIds,e.creationDate=this.creationDate.toISOString(),e.deletedDate=null!=this.deletedDate?this.deletedDate.toISOString():void 0,e.reprompt=this.reprompt,null!=this.key&&null!=this.key.encryptedString&&(e.key=this.key.encryptedString),null!=this.permissions&&(e.permissions=this.permissions),e.archivedDate=null!=this.archivedDate?this.archivedDate.toISOString():void 0,this.buildDataModel(this,e,{name:null,notes:null}),e.type){case rm.Login:null!=this.login&&(e.login=this.login.toLoginData());break;case rm.SecureNote:null!=this.secureNote&&(e.secureNote=this.secureNote.toSecureNoteData());break;case rm.Card:null!=this.card&&(e.card=this.card.toCardData());break;case rm.Identity:null!=this.identity&&(e.identity=this.identity.toIdentityData());break;case rm.SshKey:null!=this.sshKey&&(e.sshKey=this.sshKey.toSshKeyData())}return null!=this.fields&&(e.fields=this.fields.map(e=>e.toFieldData())),null!=this.attachments&&(e.attachments=this.attachments.map(e=>e.toAttachmentData())),null!=this.passwordHistory&&(e.passwordHistory=this.passwordHistory.map(e=>e.toPasswordHistoryData())),e}static fromJSON(e){var t,i,r;if(null==e)return;const n=new Sw;switch(n.id=e.id,n.organizationId=e.organizationId,n.folderId=e.folderId,n.type=e.type,n.favorite=e.favorite,n.organizationUseTotp=e.organizationUseTotp,n.edit=e.edit,n.viewPassword=e.viewPassword,null!=e.permissions&&(n.permissions=new Eb(e.permissions)),n.collectionIds=e.collectionIds,n.localData=e.localData,n.reprompt=e.reprompt,n.creationDate=new Date(e.creationDate),n.revisionDate=new Date(e.revisionDate),n.deletedDate=null!=e.deletedDate?new Date(e.deletedDate):void 0,n.archivedDate=null!=e.archivedDate?new Date(e.archivedDate):void 0,n.name=Nt.fromJSON(e.name),n.notes=Ib(e.notes),n.key=Ib(e.key),n.attachments=null===(t=e.attachments)||void 0===t?void 0:t.map(e=>uw.fromJSON(e)).filter(e=>null!=e),n.fields=null===(i=e.fields)||void 0===i?void 0:i.map(e=>hw.fromJSON(e)).filter(e=>null!=e),n.passwordHistory=null===(r=e.passwordHistory)||void 0===r?void 0:r.map(e=>yw.fromJSON(e)).filter(e=>null!=e),e.type){case rm.Card:null!=e.card&&(n.card=dw.fromJSON(e.card));break;case rm.Identity:null!=e.identity&&(n.identity=pw.fromJSON(e.identity));break;case rm.Login:null!=e.login&&(n.login=fw.fromJSON(e.login));break;case rm.SecureNote:null!=e.secureNote&&(n.secureNote=vw.fromJSON(e.secureNote));break;case rm.SshKey:null!=e.sshKey&&(n.sshKey=bw.fromJSON(e.sshKey))}return n}toSdkCipher(){var e,t,i,r,n,a,s;const o={id:this.id?$g(this.id):void 0,organizationId:this.organizationId?$g(this.organizationId):void 0,folderId:this.folderId?$g(this.folderId):void 0,collectionIds:this.collectionIds?this.collectionIds.map($g):[],key:null===(e=this.key)||void 0===e?void 0:e.toSdk(),name:this.name.toSdk(),notes:null===(t=this.notes)||void 0===t?void 0:t.toSdk(),type:this.type,favorite:this.favorite,organizationUseTotp:this.organizationUseTotp,edit:this.edit,permissions:this.permissions?{delete:this.permissions.delete,restore:this.permissions.restore}:void 0,viewPassword:this.viewPassword,localData:Lb(this.localData),attachments:null===(i=this.attachments)||void 0===i?void 0:i.map(e=>e.toSdkAttachment()),fields:null===(r=this.fields)||void 0===r?void 0:r.map(e=>e.toSdkField()),passwordHistory:null===(n=this.passwordHistory)||void 0===n?void 0:n.map(e=>e.toSdkPasswordHistory()),revisionDate:this.revisionDate.toISOString(),creationDate:this.creationDate.toISOString(),deletedDate:null===(a=this.deletedDate)||void 0===a?void 0:a.toISOString(),archivedDate:null===(s=this.archivedDate)||void 0===s?void 0:s.toISOString(),reprompt:im(this.reprompt),login:void 0,identity:void 0,card:void 0,secureNote:void 0,sshKey:void 0,data:void 0};switch(this.type){case rm.Login:null!=this.login&&(o.login=this.login.toSdkLogin());break;case rm.SecureNote:null!=this.secureNote&&(o.secureNote=this.secureNote.toSdkSecureNote());break;case rm.Card:null!=this.card&&(o.card=this.card.toSdkCard());break;case rm.Identity:null!=this.identity&&(o.identity=this.identity.toSdkIdentity());break;case rm.SshKey:null!=this.sshKey&&(o.sshKey=this.sshKey.toSdkSshKey())}return o}static fromSdkCipher(e){var t,i,r;if(null==e)return;const n=new Sw;return n.id=e.id?e.id:"",n.organizationId=e.organizationId?e.organizationId:void 0,n.folderId=e.folderId?e.folderId:void 0,n.collectionIds=e.collectionIds?e.collectionIds.map(Kg):[],n.key=Ib(e.key),n.name=Nt.fromJSON(e.name),n.notes=Ib(e.notes),n.type=e.type,n.favorite=e.favorite,n.organizationUseTotp=e.organizationUseTotp,n.edit=e.edit,n.permissions=Eb.fromSdkCipherPermissions(e.permissions),n.viewPassword=e.viewPassword,n.localData=qb(e.localData),n.attachments=null===(t=e.attachments)||void 0===t?void 0:t.map(e=>uw.fromSdkAttachment(e)).filter(e=>null!=e),n.fields=null===(i=e.fields)||void 0===i?void 0:i.map(e=>hw.fromSdkField(e)).filter(e=>null!=e),n.passwordHistory=null===(r=e.passwordHistory)||void 0===r?void 0:r.map(e=>yw.fromSdkPasswordHistory(e)).filter(e=>null!=e),n.creationDate=new Date(e.creationDate),n.revisionDate=new Date(e.revisionDate),n.deletedDate=e.deletedDate?new Date(e.deletedDate):void 0,n.archivedDate=e.archivedDate?new Date(e.archivedDate):void 0,n.reprompt=e.reprompt,n.login=fw.fromSdkLogin(e.login),n.secureNote=vw.fromSdkSecureNote(e.secureNote),n.card=dw.fromSdkCard(e.card),n.identity=pw.fromSdkIdentity(e.identity),n.sshKey=bw.fromSdkSshKey(e.sshKey),n}}!function(e){e[e.ES256=-7]="ES256",e[e.RS256=-257]="RS256"}(ww||(ww={})),function(e){e.Unknown="UnknownError",e.NotSupported="NotSupportedError",e.InvalidState="InvalidStateError",e.NotAllowed="NotAllowedError",e.Constraint="ConstraintError"}(kw||(kw={}));class _w extends Error{constructor(e){super(e),this.errorCode=e}}const xw=4294967296,Cw=9007199254740992;class Iw{constructor(e,t){this.value=e,this.tag=t}}const Ew=function(e){let t,i=new ArrayBuffer(256),r=new DataView(i),n=new Uint8Array(i),a=0;function s(e){let s=i.byteLength,o=a+e;for(;s>2;for(let i=0;i>6),r.push(128|63&e)):e<55296||e>=57344?(r.push(224|e>>12),r.push(128|e>>6&63),r.push(128|63&e)):(e=(1023&e)<<10,e|=1023&t.charCodeAt(++i),e+=65536,r.push(240|e>>18),r.push(128|e>>12&63),r.push(128|e>>6&63),r.push(128|63&e))}return p(3,r.length),c(r);default:let n,m;if(Array.isArray(t))for(n=t.length,p(4,n),i=0;ie.userHandle===t)}}const Pw=Array.from({length:256},(e,t)=>(t+256).toString(16).substring(1));function Aw(e){if(!Tt.isGuid(e))throw TypeError("GUID parameter is invalid");let t;const i=new Uint8Array(16);return i[0]=(t=parseInt(e.slice(0,8),16))>>>24,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i[4]=(t=parseInt(e.slice(9,13),16))>>>8,i[5]=255&t,i[6]=(t=parseInt(e.slice(14,18),16))>>>8,i[7]=255&t,i[8]=(t=parseInt(e.slice(19,23),16))>>>8,i[9]=255&t,i[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,i[11]=t/4294967296&255,i[12]=t>>>24&255,i[13]=t>>>16&255,i[14]=t>>>8&255,i[15]=255&t,i}function jw(e){if(16!==e.byteLength)throw TypeError("BufferSource length is invalid");const t=e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer),i=(Pw[t[0]]+Pw[t[1]]+Pw[t[2]]+Pw[t[3]]+"-"+Pw[t[4]]+Pw[t[5]]+"-"+Pw[t[6]]+Pw[t[7]]+"-"+Pw[t[8]]+Pw[t[9]]+"-"+Pw[t[10]]+Pw[t[11]]+Pw[t[12]]+Pw[t[13]]+Pw[t[14]]+Pw[t[15]]).toLowerCase();if(!Tt.isGuid(i))throw TypeError("Converted GUID is invalid");return i}function Tw(e){try{return e.startsWith("b64.")?zw.stringToBuffer(e.slice(4)):Aw(e).buffer}catch(e){return}}function Dw(e){return(e/8|0)+(e%8==0?0:1)}const Ow={ES256:Dw(256),ES384:Dw(384),ES512:Dw(521)};function Nw(e,t,i){let r=0;for(;t+re.alg!==ww.ES256)){const t=e.credTypesAndPubKeyAlgs.map(e=>e.alg).join(", ");throw null===(r=this.logService)||void 0===r||r.warning(`[Fido2Authenticator] No compatible algorithms found, RP requested: ${t}`),new _w(kw.NotSupported)}if(null!=e.requireResidentKey&&"boolean"!=typeof e.requireResidentKey)throw null===(n=this.logService)||void 0===n||n.error(`[Fido2Authenticator] Invalid 'requireResidentKey' value: ${String(e.requireResidentKey)}`),new _w(kw.Unknown);if(null!=e.requireUserVerification&&"boolean"!=typeof e.requireUserVerification)throw null===(a=this.logService)||void 0===a||a.error(`[Fido2Authenticator] Invalid 'requireUserVerification' value: ${String(e.requireUserVerification)}`),new _w(kw.Unknown);yield u.ensureUnlockedVault();const t=yield Ce(this.syncService.activeUserLastSync$()),i=(new Date).getTime()-18e5;(!t||t.getTime()0)throw null===(s=this.logService)||void 0===s||s.info("[Fido2Authenticator] Aborting due to excluded credential found in vault."),yield u.informExcludedCredential(d),new _w(kw.NotAllowed);let h,p,m,g,f,y=!1;const v=yield u.confirmNewCredential({credentialName:e.rpEntity.name,userName:e.userEntity.name,userHandle:zw.bufferToString(e.userEntity.id),userVerification:e.requireUserVerification,rpId:e.rpEntity.id}),b=v.cipherId;if(y=v.userVerified,void 0===b)throw null===(o=this.logService)||void 0===o||o.warning("[Fido2Authenticator] Aborting because user confirmation was not recieved."),new _w(kw.NotAllowed);try{m=yield function(){return Rw(this,void 0,void 0,function*(){return yield crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},!0,Fw)})}(),f=yield crypto.subtle.exportKey("spki",m.publicKey);const t=yield Ce(this.accountService.activeAccount$.pipe(tu)),i=yield Ce(this.cipherService.ciphers$(t).pipe(X(e=>e[b]),Ie(e=>void 0!==e),Fe({first:5e3,with:()=>{var e;throw null===(e=this.logService)||void 0===e||e.error(`[Fido2Authenticator] Aborting because cipher with ID ${b} could not be found within timeout.`),new _w(kw.Unknown)}}),X(e=>new Sw(e,null))));if(h=yield this.cipherService.decrypt(i,t),!y&&(e.requireUserVerification||h.reprompt!==tm.None))throw null===(l=this.logService)||void 0===l||l.warning("[Fido2Authenticator] Aborting because user verification was unsuccessful."),new _w(kw.NotAllowed);p=yield function(e,t){return Rw(this,void 0,void 0,function*(){if("ECDSA"!==t.algorithm.name&&"P-256"!==t.algorithm.namedCurve)throw new _w(kw.Unknown);const i=yield crypto.subtle.exportKey("pkcs8",t),r=new Xb;return r.credentialId=Tt.newGuid(),r.keyType="public-key",r.keyAlgorithm="ECDSA",r.keyCurve="P-256",r.keyValue=zw.bufferToString(i),r.rpId=e.rpEntity.id,r.userHandle=zw.bufferToString(e.userEntity.id),r.userName=e.userEntity.name,r.counter=0,r.rpName=e.rpEntity.name,r.userDisplayName=e.userEntity.displayName,r.discoverable=e.requireResidentKey,r.creationDate=new Date,r})}(e,m.privateKey),h.login.fido2Credentials=[p],Tt.isNullOrEmpty(h.login.username)&&(h.login.username=p.userName),yield this.cipherService.updateWithServer(h,t),yield this.cipherService.clearCache(t),g=p.credentialId}catch(e){throw null===(c=this.logService)||void 0===c||c.error(`[Fido2Authenticator] Aborting because of unknown error when creating credential: ${e}`),new _w(kw.Unknown)}const w=yield Bw({rpId:e.rpEntity.id,credentialId:Tw(g),counter:p.counter,userPresence:!0,userVerification:y,keyPair:m}),k=new Uint8Array(Ew({fmt:"none",attStmt:{},authData:w}));return{credentialId:Tw(g),attestationObject:k,authData:w,publicKey:f,publicKeyAlgorithm:-7}}finally{u.close()}})}getAssertion(e,t,i){return Rw(this,void 0,void 0,function*(){var r,n,a,s,o;const l=yield this.userInterface.newSession(e.fallbackSupported,t,i);try{if(null!=e.requireUserVerification&&"boolean"!=typeof e.requireUserVerification)throw null===(r=this.logService)||void 0===r||r.error(`[Fido2Authenticator] Invalid 'requireUserVerification' value: ${String(e.requireUserVerification)}`),new _w(kw.Unknown);let t;if(yield l.ensureUnlockedVault(),t=yield this.findCredential(e,t),(0===t.length||t.some(e=>e.login.fido2Credentials.some(e=>e.counter>0)))&&(yield this.syncService.fullSync(!1),t=yield this.findCredential(e,t)),0===t.length)throw null===(n=this.logService)||void 0===n||n.info("[Fido2Authenticator] Aborting because no matching credentials were found in the vault."),yield l.informCredentialNotFound(),new _w(kw.NotAllowed);let i={cipherId:t[0].id,userVerified:!1};const c=t.some(e=>e.reprompt!==tm.None);this.requiresUserVerificationPrompt(e,t,c)&&(i=yield l.pickCredential({cipherIds:t.map(e=>e.id),userVerification:e.requireUserVerification,assumeUserPresence:e.assumeUserPresence,masterPasswordRepromptRequired:c}));const u=i.cipherId,d=i.userVerified,h=t.find(e=>e.id===u);if(void 0===h)throw null===(a=this.logService)||void 0===a||a.error("[Fido2Authenticator] Aborting because the selected credential could not be found."),new _w(kw.NotAllowed);if(!d&&(e.requireUserVerification||h.reprompt!==tm.None))throw null===(s=this.logService)||void 0===s||s.warning("[Fido2Authenticator] Aborting because user verification was unsuccessful."),new _w(kw.NotAllowed);try{const t=h.login.fido2Credentials[0],i=t.credentialId;if(t.counter>0&&++t.counter,h.localData=Object.assign(Object.assign({},h.localData),{lastUsedDate:(new Date).getTime()}),t.counter>0){const e=yield Ce(this.accountService.activeAccount$.pipe(tu));yield this.cipherService.updateWithServer(h,e),yield this.cipherService.clearCache(e)}const r=yield Bw({rpId:t.rpId,credentialId:Tw(i),counter:t.counter,userPresence:!0,userVerification:d}),n=yield function(e){return Rw(this,void 0,void 0,function*(){const t=new Uint8Array([...e.authData,...zw.bufferSourceToUint8Array(e.clientDataHash)]);return function(e){const t=function(){const e=Ow["ES256"];if(e)return e;throw new Error('Unknown algorithm "ES256"')}(),i=e.length;if(i!==2*t)throw new TypeError('"ES256" signatures must be "'+2*t+'" bytes, saw "'+i+'"');const{padding:r,needs0x00:n}=Nw(e,0,t),{padding:a,needs0x00:s}=Nw(e,t,e.length),o=t-r,l=t-a,c=o+(n?1:0),u=l+(s?1:0),d=2+c+2+u,h=d<128,p=new Uint8Array((h?2:3)+d);let m=0;return p[m++]=48,h?p[m++]=d:(p[m++]=129,p[m++]=255&d),p[m++]=2,p[m++]=c,n&&(p[m++]=0),p.set(e.subarray(r,r+o),m),m+=o,p[m++]=2,p[m++]=u,s&&(p[m++]=0),p.set(e.subarray(t+a,t+a+l),m),p}(new Uint8Array(yield crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},e.privateKey,t)))})}({authData:r,clientDataHash:e.hash,privateKey:yield Lw(t)});return{authenticatorData:r,selectedCredential:{id:Tw(i),userHandle:zw.stringToBuffer(t.userHandle)},signature:n}}catch(e){throw null===(o=this.logService)||void 0===o||o.error(`[Fido2Authenticator] Aborting because of unknown error when asserting credential: ${e}`),new _w(kw.Unknown)}}finally{l.close()}})}findCredential(e,t){return Rw(this,void 0,void 0,function*(){var t;return(null===(t=e.allowCredentialDescriptorList)||void 0===t?void 0:t.length)>0?yield this.findCredentialsById(e.allowCredentialDescriptorList,e.rpId):yield this.findCredentialsByRp(e.rpId)})}requiresUserVerificationPrompt(e,t,i){return e.requireUserVerification||!e.assumeUserPresence||t.length>1||0===t.length||i}silentCredentialDiscovery(e){return Rw(this,void 0,void 0,function*(){return(yield this.findCredentialsByRp(e)).map(e=>e.login.fido2Credentials[0])})}findExcludedCredentials(e){return Rw(this,void 0,void 0,function*(){const t=[];for(const i of e)try{t.push(jw(i.id))}catch(e){}if(0===t.length)return[];const i=yield Ce(this.accountService.activeAccount$.pipe(tu));return(yield this.cipherService.getAllDecrypted(i)).filter(e=>!e.isDeleted&&null==e.organizationId&&e.type===rm.Login&&e.login.hasFido2Credentials&&t.includes(e.login.fido2Credentials[0].credentialId)).map(e=>e.id)})}findCredentialsById(e,t){return Rw(this,void 0,void 0,function*(){if(0===e.length)return[];const i=yield Ce(this.accountService.activeAccount$.pipe(tu));return(yield this.cipherService.getAllDecrypted(i)).filter(i=>!i.isDeleted&&i.type===rm.Login&&i.login.hasFido2Credentials&&i.login.fido2Credentials[0].rpId===t&&e.some(e=>function(e,t){if(e.byteLength!==t.byteLength)return!1;const i=new Uint8Array(e),r=new Uint8Array(t);for(let e=0;e!t.isDeleted&&t.type===rm.Login&&t.login.hasFido2Credentials&&t.login.fido2Credentials[0].rpId===e&&t.login.fido2Credentials[0].discoverable)})}}function Lw(e){return Rw(this,void 0,void 0,function*(){const t=zw.stringToBuffer(e.keyValue);return yield crypto.subtle.importKey("pkcs8",new Uint8Array(t),{name:e.keyAlgorithm,namedCurve:e.keyCurve},!0,Fw)})}function Bw(e){return Rw(this,void 0,void 0,function*(){const t=[],i=new Uint8Array(yield crypto.subtle.digest({name:"SHA-256"},Tt.fromByteStringToArray(e.rpId)));t.push(...i);const r=function(e){let t=0;return e.extensionData&&(t|=64),e.attestationData&&(t|=64),e.backupEligibility&&(t|=8),e.backupState&&(t|=16),e.userVerification&&(t|=4),e.userPresence&&(t|=1),t}({extensionData:!1,attestationData:null!=e.keyPair,backupEligibility:!0,backupState:!0,userVerification:e.userVerification,userPresence:e.userPresence});t.push(r);const n=e.counter;if(t.push((4278190080&n)>>24&255,(16711680&n)>>16&255,(65280&n)>>8&255,255&n),e.keyPair){const i=[];i.push(...Uw);const r=zw.bufferSourceToUint8Array(e.credentialId),n=[(r.length-(255&r.length))/256,255&r.length];i.push(...n),i.push(...r);const a=yield crypto.subtle.exportKey("jwk",e.keyPair.publicKey),s=Tt.fromUrlB64ToArray(a.x),o=Tt.fromUrlB64ToArray(a.y),l=new Uint8Array(77);l.set([165,1,2,3,38,32,1,33,88,32],0),l.set(s,10),l.set([34,88,32],42),l.set(o,45),i.push(...l),t.push(...i)}return new Uint8Array(t)})}const Mw="UserRequestedFallback";class Vw extends Error{constructor(){super("FallbackRequested"),this.fallbackRequested=!0}}var $w=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};function Kw(e,t,i,r){return $w(this,void 0,void 0,function*(){const n=function(e,t){if(!e||!t)return!1;const i=At(t,{allowPrivateDomains:!0}),r=At(e,{allowPrivateDomains:!0});return!(!r||!i)&&("localhost"===r.hostname&&"localhost"===i.hostname||!!t.startsWith("https://")&&!r.isIp&&!i.isIp&&!("localhost"!==e&&!e.includes("."))&&!(null!=i.hostname&&"localhost"!==i.hostname&&!i.hostname.includes("."))&&r.domain===i.domain&&(i.hostname===e||!(null==i.hostname||!i.hostname.endsWith("."+e))||void 0))}(e,t);return!!n||!!i&&(yield function(e,t,i){return $w(this,void 0,void 0,function*(){try{const r=null!=i?i:globalThis.fetch;let n;if("function"==typeof AbortSignal.timeout)n=AbortSignal.timeout(5e3);else{const e=new AbortController;setTimeout(()=>e.abort(),5e3),n=e.signal}const a=yield r(`https://${e}/.well-known/webauthn`,{credentials:"omit",referrerPolicy:"no-referrer",signal:n});if(!a.ok)return!1;const s=a.headers.get("content-type");if(!s||!s.includes("application/json"))return!1;const o=yield a.json();if(!o||!Array.isArray(o.origins)||!o.origins.every(e=>"string"==typeof e)||0===o.origins.length)return!1;const l=new Set;for(const e of o.origins)try{const i=new URL(e).hostname;if(!i)continue;const r=At(i,{allowPrivateDomains:!0});if(!r.domain||!r.publicSuffix)continue;const n=r.domain.slice(0,r.domain.length-r.publicSuffix.length-1);if(!n)continue;if(l.size>=5&&!l.has(n))continue;if(t===e)return!0;l.size<5&&l.add(n)}catch(e){continue}return!1}catch(e){return!1}})}(e,t,r))})}var Ww=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Hw{constructor(e,t,i,r,n,a,s,o){this.authenticator=e,this.configService=t,this.authService=i,this.vaultSettingsService=r,this.domainSettingsService=n,this.taskSchedulerService=a,this.requestManager=s,this.logService=o,this.TIMEOUTS={NO_VERIFICATION:{DEFAULT:12e4,MIN:3e4,MAX:18e4},WITH_VERIFICATION:{DEFAULT:3e5,MIN:3e4,MAX:6e5}},this.relatedOriginChecksEnabled$=this.configService.getFeatureFlag$(Ne.WebAuthnRelatedOrigins),this.setAbortTimeout=(e,t,i)=>{let r;const{WITH_VERIFICATION:n,NO_VERIFICATION:a}=this.TIMEOUTS;return t?(i=null!=i?i:n.DEFAULT,r=Math.max(n.MIN,Math.min(i,n.MAX))):(i=null!=i?i:a.DEFAULT,r=Math.max(a.MIN,Math.min(i,a.MAX))),this.timeoutAbortController=e,this.taskSchedulerService.setTimeout(Eu,r)},this.taskSchedulerService.registerTaskHandler(Eu,()=>{var e;return null===(e=this.timeoutAbortController)||void 0===e?void 0:e.abort()})}isFido2FeatureEnabled(e,t){return Ww(this,void 0,void 0,function*(){var i;if((yield this.authService.getAuthStatus())===cu.LoggedOut)return!1;const r=yield Ce(this.domainSettingsService.neverDomains$);if(null!=r&&e in r)return!1;const n=yield Ce(this.configService.serverConfig$);return!(t===(null===(i=n.environment)||void 0===i?void 0:i.vault))&&(yield Ce(this.vaultSettingsService.enablePasskeys$))})}createCredential(e,t){return Ww(this,arguments,void 0,function*(e,t,i=new AbortController){var r,n,a,s,o,l,c,u,d,h,p,m,g,f;const y=At(e.origin,{allowPrivateDomains:!0});if(!(yield this.isFido2FeatureEnabled(y.hostname,e.origin)))throw null===(r=this.logService)||void 0===r||r.warning("[Fido2Client] Fido2VaultCredential is not enabled"),new Vw;if(!e.sameOriginWithAncestors)throw null===(n=this.logService)||void 0===n||n.warning(`[Fido2Client] Invalid 'sameOriginWithAncestors' value: ${e.sameOriginWithAncestors}`),new DOMException("Invalid 'sameOriginWithAncestors' value","NotAllowedError");const v=zw.stringToBuffer(e.user.id);if(v.byteLength<1||v.byteLength>64)throw null===(a=this.logService)||void 0===a||a.warning(`[Fido2Client] Invalid 'user.id' length: ${e.user.id} (${v.byteLength})`),new TypeError("Invalid 'user.id' length");if(e.rp.id=null!==(s=e.rp.id)&&void 0!==s?s:y.hostname,null==y.hostname||!e.origin.startsWith("https://")&&"localhost"!==y.hostname)throw null===(o=this.logService)||void 0===o||o.warning(`[Fido2Client] Invalid https origin: ${e.origin}`),new DOMException("'origin' is not a valid https origin","SecurityError");if(!(yield Kw(e.rp.id,e.origin,yield Ce(this.relatedOriginChecksEnabled$))))throw null===(l=this.logService)||void 0===l||l.warning(`[Fido2Client] 'rp.id' cannot be used with the current origin: rp.id = ${e.rp.id}; origin = ${e.origin}`),new DOMException("'rp.id' cannot be used with the current origin","SecurityError");let b;if(b=(null===(c=e.pubKeyCredParams)||void 0===c?void 0:c.length)>0?e.pubKeyCredParams.filter(e=>-7===e.alg&&"public-key"===e.type):[{alg:-7,type:"public-key"},{alg:-257,type:"public-key"}],0===b.length){const e=b.map(e=>e.alg).join(", ");throw null===(u=this.logService)||void 0===u||u.warning(`[Fido2Client] No compatible algorithms found, RP requested: ${e}`),new DOMException("No supported key algorithms were found","NotSupportedError")}const w={type:"webauthn.create",challenge:e.challenge,origin:e.origin,crossOrigin:!e.sameOriginWithAncestors},k=JSON.stringify(w),S=Tt.fromByteStringToArray(k),_=function({params:e,credTypesAndPubKeyAlgs:t,clientDataHash:i}){var r,n,a,s,o,l,c,u,d,h;const p=null!==(n=null===(r=e.excludeCredentials)||void 0===r?void 0:r.map(e=>({id:zw.stringToBuffer(e.id),transports:e.transports,type:e.type})))&&void 0!==n?n:[];return{requireResidentKey:"required"===(null===(a=e.authenticatorSelection)||void 0===a?void 0:a.residentKey)||"preferred"===(null===(s=e.authenticatorSelection)||void 0===s?void 0:s.residentKey)||void 0===(null===(o=e.authenticatorSelection)||void 0===o?void 0:o.residentKey)&&(!0===(null===(l=e.authenticatorSelection)||void 0===l?void 0:l.requireResidentKey)||"true"===(null===(c=e.authenticatorSelection)||void 0===c?void 0:c.requireResidentKey)),requireUserVerification:"required"===(null===(u=e.authenticatorSelection)||void 0===u?void 0:u.userVerification)||"preferred"===(null===(d=e.authenticatorSelection)||void 0===d?void 0:d.userVerification)||void 0===(null===(h=e.authenticatorSelection)||void 0===h?void 0:h.userVerification),enterpriseAttestationPossible:"enterprise"===e.attestation,excludeCredentialDescriptorList:p,credTypesAndPubKeyAlgs:t,hash:i,rpEntity:{id:e.rp.id,name:e.rp.name},userEntity:{id:zw.stringToBuffer(e.user.id),displayName:e.user.displayName,name:e.user.name},fallbackSupported:e.fallbackSupported}}({params:e,credTypesAndPubKeyAlgs:b,clientDataHash:yield crypto.subtle.digest({name:"SHA-256"},S)});if(i.signal.aborted)throw null===(d=this.logService)||void 0===d||d.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");const x=this.setAbortTimeout(i,_.requireUserVerification,e.timeout);let C,I;try{C=yield this.authenticator.makeCredential(_,t,i)}catch(e){if(i.signal.aborted&&i.signal.reason===Mw)throw null===(h=this.logService)||void 0===h||h.info("[Fido2Client] Aborting because user requested fallback"),new Vw;if(e instanceof _w&&e.errorCode===kw.InvalidState)throw null===(p=this.logService)||void 0===p||p.warning(`[Fido2Client] Unknown error: ${e}`),new DOMException("Unknown error occured.","InvalidStateError");throw null===(m=this.logService)||void 0===m||m.info(`[Fido2Client] Aborted by user: ${e}`),new DOMException("The operation either timed out or was not allowed.","NotAllowedError")}if(i.signal.aborted)throw null===(g=this.logService)||void 0===g||g.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");return(null===(f=e.extensions)||void 0===f?void 0:f.credProps)&&(I={rk:_.requireResidentKey}),null==x||x.unsubscribe(),{credentialId:zw.bufferToString(C.credentialId),attestationObject:zw.bufferToString(C.attestationObject),authData:zw.bufferToString(C.authData),clientDataJSON:zw.bufferToString(S),publicKey:zw.bufferToString(C.publicKey),publicKeyAlgorithm:C.publicKeyAlgorithm,transports:["internal","hybrid"],extensions:{credProps:I}}})}assertCredential(e,t){return Ww(this,arguments,void 0,function*(e,t,i=new AbortController){var r,n,a,s,o,l,c,u,d;const h=At(e.origin,{allowPrivateDomains:!0});if(!(yield this.isFido2FeatureEnabled(h.hostname,e.origin)))throw null===(r=this.logService)||void 0===r||r.warning("[Fido2Client] Fido2VaultCredential is not enabled"),new Vw;if(e.rpId=null!==(n=e.rpId)&&void 0!==n?n:h.hostname,null==h.hostname||!e.origin.startsWith("https://")&&"localhost"!==h.hostname)throw null===(a=this.logService)||void 0===a||a.warning(`[Fido2Client] Invalid https origin: ${e.origin}`),new DOMException("'origin' is not a valid https origin","SecurityError");if(!(yield Kw(e.rpId,e.origin,yield Ce(this.relatedOriginChecksEnabled$))))throw null===(s=this.logService)||void 0===s||s.warning(`[Fido2Client] 'rp.id' cannot be used with the current origin: rp.id = ${e.rpId}; origin = ${e.origin}`),new DOMException("'rp.id' cannot be used with the current origin","SecurityError");const p={type:"webauthn.get",challenge:e.challenge,origin:e.origin,crossOrigin:!e.sameOriginWithAncestors},m=JSON.stringify(p),g=Tt.fromByteStringToArray(m);if("conditional"===e.mediation)return this.handleMediatedConditionalRequest(e,t,i,g);const f=Gw({params:e,clientDataHash:yield crypto.subtle.digest({name:"SHA-256"},g)});if(i.signal.aborted)throw null===(o=this.logService)||void 0===o||o.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");const y=this.setAbortTimeout(i,f.requireUserVerification,e.timeout);let v;try{v=yield this.authenticator.getAssertion(f,t,i)}catch(e){if(i.signal.aborted&&i.signal.reason===Mw)throw null===(l=this.logService)||void 0===l||l.info("[Fido2Client] Aborting because user requested fallback"),new Vw;if(e instanceof _w&&e.errorCode===kw.InvalidState)throw null===(c=this.logService)||void 0===c||c.warning(`[Fido2Client] Unknown error: ${e}`),new DOMException("Unknown error occured.","InvalidStateError");throw null===(u=this.logService)||void 0===u||u.info(`[Fido2Client] Aborted by user: ${e}`),new DOMException("The operation either timed out or was not allowed.","NotAllowedError")}if(i.signal.aborted)throw null===(d=this.logService)||void 0===d||d.info("[Fido2Client] Aborted with AbortController"),new DOMException("The operation either timed out or was not allowed.","AbortError");return null==y||y.unsubscribe(),this.generateAssertCredentialResult(v,g)})}handleMediatedConditionalRequest(e,t,i,r){return Ww(this,void 0,void 0,function*(){var n,a,s;let o,l=!1;for(;!o;){const c=(yield Ce(this.authService.activeAccountStatus$))===cu.Unlocked?yield this.authenticator.silentCredentialDiscovery(e.rpId):[];null===(n=this.logService)||void 0===n||n.info(`[Fido2Client] started mediated request, available credentials: ${c.length}`);const u=yield this.requestManager.newActiveRequest(t.id,c,i);if(u.type===kb)continue;if(u.type===Sb)break;e.allowedCredentialIds=[zw.bufferToString(Aw(u.credentialId))],l=!0;const d=yield crypto.subtle.digest({name:"SHA-256"},r),h=Gw({params:e,clientDataHash:d,assumeUserPresence:l});try{o=yield this.authenticator.getAssertion(h,t)}catch(e){null===(a=this.logService)||void 0===a||a.info(`[Fido2Client] Aborted by user: ${e}`)}i.signal.aborted&&(null===(s=this.logService)||void 0===s||s.info("[Fido2Client] Aborted with AbortController"))}return this.generateAssertCredentialResult(o,r)})}generateAssertCredentialResult(e,t){return{authenticatorData:zw.bufferToString(e.authenticatorData),clientDataJSON:zw.bufferToString(t),credentialId:zw.bufferToString(e.selectedCredential.id),userHandle:void 0!==e.selectedCredential.userHandle?zw.bufferToString(e.selectedCredential.userHandle):void 0,signature:zw.bufferToString(e.signature)}}}function Gw({params:e,clientDataHash:t,assumeUserPresence:i}){const r=e.allowedCredentialIds.map(e=>({id:zw.stringToBuffer(e),type:"public-key"})),n="required"===e.userVerification||"preferred"===e.userVerification||void 0===e.userVerification;return{rpId:e.rpId,requireUserVerification:n,hash:t,allowCredentialDescriptorList:r,extensions:{},fallbackSupported:e.fallbackSupported,assumeUserPresence:i}}var Qw=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Jw{constructor(e,t){this.logService=e,this.apiService=t}upload(e,t,i){return Qw(this,void 0,void 0,function*(){return t.buffer.byteLength<=268435456?yield this.azureUploadBlob(e,t):yield this.azureUploadBlocks(e,t,i)})}azureUploadBlob(e,t){return Qw(this,void 0,void 0,function*(){const i=Tt.getUrl(e),r=new Headers({"x-ms-date":(new Date).toUTCString(),"x-ms-version":i.searchParams.get("sv"),"Content-Length":t.buffer.byteLength.toString(),"x-ms-blob-type":"BlockBlob"}),n=new Request(e,{body:t.buffer,cache:"no-store",method:"PUT",headers:r}),a=yield this.apiService.nativeFetch(n);if(201!==a.status)throw new Error(`Failed to create Azure blob: ${a.status}`)})}azureUploadBlocks(e,t,i){return Qw(this,void 0,void 0,function*(){const r=Tt.getUrl(e),n=this.getMaxBlockSize(r.searchParams.get("sv"));let a=0;const s=Math.ceil(t.buffer.byteLength/n),o=[];if(s>5e4)throw new Error("Cannot upload file, exceeds maximum size of "+5e4*n);try{for(;a{t+=`${e}`}),t+="",t}getMaxBlockSize(e){return Yw.compare(e,"2019-12-12")>=0?4194304e3:Yw.compare(e,"2016-05-31")>=0?104857600:4194304}}class Yw{static compare(e,t){return"string"==typeof e&&(e=new Yw(e)),"string"==typeof t&&(t=new Yw(t)),e.year!==t.year?e.year-t.year:e.month!==t.month?e.month-t.month:e.day!==t.day?e.day-t.day:0}constructor(e){this.year=0,this.month=0,this.day=0;try{const t=e.split("-").map(e=>Number.parseInt(e,10));this.year=t[0],this.month=t[1],this.day=t[2]}catch(e){}}compare(e){return Yw.compare(this,e)}}class Xw{upload(e,t,i){return r=this,n=void 0,s=function*(){const r=new FormData;if(Tt.isBrowser){const i=new Blob([t.buffer],{type:"application/octet-stream"});r.append("data",i,e)}else{if(!Tt.isNode)throw new Error("Unsupported environment");r.append("data",Buffer.from(t.buffer),{filename:e,contentType:"application/octet-stream"})}yield i(r)},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}}class Zw{constructor(e,t){this.logService=e,this.azureFileUploadService=new Jw(e,t),this.bitwardenFileUploadService=new Xw}upload(e,t,i,r){return n=this,a=void 0,o=function*(){try{switch(e.fileUploadType){case ot.Direct:yield this.bitwardenFileUploadService.upload(t.encryptedString,i,e=>r.postDirect(e));break;case ot.Azure:yield this.azureFileUploadService.upload(e.url,i,r.renewFileUploadUrl);break;default:throw new Error("Unknown file upload type")}}catch(e){throw yield r.rollback(),e}},new((s=void 0)||(s=Promise))(function(e,t){function i(e){try{l(o.next(e))}catch(e){t(e)}}function r(e){try{l(o.throw(e))}catch(e){t(e)}}function l(t){var n;t.done?e(t.value):(n=t.value,n instanceof s?n:new s(function(e){e(n)})).then(i,r)}l((o=o.apply(n,a||[])).next())});var n,a,s,o}}class ek{build(){var e;return null!==(e=this.migrationBuilderCache)&&void 0!==e?e:this.migrationBuilderCache=Dr.create().with(Wl).with(Da,3,4).with(Is,4,5).with(ho,5,6).with(gl,6,7).with(Ml,7,8).with($l,8,9).with(Fr,9,10).with(Br,10,11).with(Wr,11,12).with(Qr,12,13).with(Xr,13,14).with(tn,14,15).with(an,15,16).with(ln,16,17).with(dn,17,18).with(mn,18,19).with(yn,19,20).with(wn,20,21).with(_n,21,22).with(En,22,23).with(An,23,24).with(Dn,24,25).with(Rn,25,26).with(qn,26,27).with(Mn,27,28).with($n,28,29).with(Gn,29,30).with(Yn,30,31).with(ea,31,32).with(sa,32,33).with(da,33,34).with(ma,34,35).with(ya,35,36).with(wa,36,37).with(za,37,38).with(ja,38,39).with(La,39,40).with(Va,40,41).with(Wa,41,42).with(Qa,42,43).with(Xa,43,44).with(ns,44,45).with(os,45,46).with(vs,46,47).with(ks,47,48).with(xs,48,49).with(As,49,50).with(Ds,50,51).with(Os,51,52).with(Fs,52,53).with(Ms,53,54).with(Hs,54,55).with(Ys,55,56).with(to,56,57).with(no,57,58).with(co,58,59).with(yo,59,60).with(_o,60,61).with(jo,61,62).with(Ro,62,63).with(qo,63,64).with(Yo,64,65).with(rl,65,66).with(sl,66,67).with(cl,67,68).with(pl,68,69).with(vl,69,70).with(kl,70,71).with(xl,71,72).with(Al,72,73).with(Dl,73,74).with(Ll,74,75)}}var tk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class ik{constructor(e,t,i,r){this.diskStorage=e,this.logService=t,this.migrationBuilderService=i,this.clientType=r}run(){return tk(this,void 0,void 0,function*(){const e=new Yl(yield Ql(this.diskStorage,this.logService),this.diskStorage,this.logService,"general",this.clientType);if(e.currentVersion<0)return void(yield this.diskStorage.save("stateVersion",75));const t=this.migrationBuilderService.build();yield t.migrate(e)})}waitForCompletion(){return tk(this,void 0,void 0,function*(){yield function(e,t){return Hl(this,void 0,void 0,function*(){const i=()=>Hl(this,void 0,void 0,function*(){return(yield Ql(e,t))>=75}),r=e=>Hl(this,void 0,void 0,function*(){const n=2*e;if(!(n>8192))return new Promise(a=>{setTimeout(()=>Hl(this,void 0,void 0,function*(){(yield i())||(t.info(`Waiting for migrations to finish, waiting for ${n}ms`),yield r(n)),a()}),e)})});(yield i())||(yield r(2))})}(this.diskStorage,this.logService)})}}class rk{createSdkClient(...e){return t=this,i=void 0,n=function*(){return Promise.resolve(new Sg.cPU(...e))},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}function nk(e,t){return void 0===t&&(t=!1),Q(function(i,r){var n=0;i.subscribe(J(r,function(i){var a=e(i,n++);(a||t)&&r.next(i),!a&&r.complete()}))})}function ak(e){return void 0===e&&(e=sk),Q(function(t,i){var r=!1;t.subscribe(J(i,function(e){r=!0,i.next(e)},function(){return r?i.complete():i.error(e())}))})}function sk(){return new xe}function ok(e,t){return null==e&&null==t||(!e||null!=t)&&(null!=e||!t)&&("object"!=typeof e||"object"!=typeof t?e===t:JSON.stringify(e)===JSON.stringify(t))}class lk{constructor(e){this.markedForDisposal=!1,this.refCount=0,this.value=e}take(){if(this.markedForDisposal)throw new Error("Cannot take a reference to a value marked for disposal");return this.refCount++,new ck(()=>this.release(),this.value)}markForDisposal(){this.markedForDisposal=!0,this.freeIfPossible()}release(){this.refCount--,this.freeIfPossible()}freeIfPossible(){0===this.refCount&&this.markedForDisposal&&this.value.free()}}class ck{constructor(e,t){this.release=e,this.value=t}[Symbol.dispose](){this.release()}}const uk=wi.record(wr,"ciphers",{deserializer:e=>Fb.fromJSON(e),clearOn:["logout"]}),dk=wi.record(Sr,"decryptedCiphers",{deserializer:e=>lw.fromJSON(e),clearOn:["logout","lock"]}),hk=wi.array(Sr,"failedDecryptedCiphers",{deserializer:e=>lw.fromJSON(e),clearOn:["logout","lock"]}),pk=new wi(kr,"localData",{deserializer:e=>e,clearOn:["logout"]}),mk=new wi(Sr,"addEditCipherInfo",{deserializer:e=>null==e?null:{cipher:null!=(null==e?void 0:e.cipher.toJSON)?e.cipher:lw.fromJSON(null==e?void 0:e.cipher),collectionIds:e.collectionIds},clearOn:["logout","lock"]});class gk{userKeyDefinition(){return uk}toSdk(e){return new Sw(e).toSdkCipher()}fromSdk(e){return Sw.fromSdkCipher(e).toCipherData()}}var fk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};function yk(e,t,i){return fk(this,void 0,void 0,function*(){yield t.register_cipher_repository(new vk(e,i,new gk))})}class vk{constructor(e,t,i){this.userId=e,this.stateProvider=t,this.mapper=i}get(e){return fk(this,void 0,void 0,function*(){const t=this.stateProvider.getUser(this.userId,this.mapper.userKeyDefinition()),i=(yield Ce(t.state$.pipe(X(e=>null!=e?e:{}))))[e];return i?this.mapper.toSdk(i):null})}list(){return fk(this,void 0,void 0,function*(){const e=this.stateProvider.getUser(this.userId,this.mapper.userKeyDefinition()),t=yield Ce(e.state$.pipe(X(e=>null!=e?e:{})));return Object.values(t).map(e=>this.mapper.toSdk(e))})}set(e,t){return fk(this,void 0,void 0,function*(){const i=this.stateProvider.getUser(this.userId,this.mapper.userKeyDefinition()),r=yield Ce(i.state$.pipe(X(e=>null!=e?e:{})));r[e]=this.mapper.fromSdk(t),yield i.update(()=>r)})}remove(e){return fk(this,void 0,void 0,function*(){const t=this.stateProvider.getUser(this.userId,this.mapper.userKeyDefinition()),i=yield Ce(t.state$.pipe(X(e=>null!=e?e:{})));i[e]&&(delete i[e],yield t.update(()=>i))})}}var bk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const wk=Symbol("UnsetClient");class kk{constructor(e,t){this.apiService=e,this.userId=t}get_access_token(){return bk(this,void 0,void 0,function*(){if(null!=this.userId)return yield this.apiService.getActiveBearerToken(this.userId)})}}class Sk{constructor(e,t,i,r,n,a,s,o,l,c,u=null){this.sdkClientFactory=e,this.environmentService=t,this.platformUtilsService=i,this.accountService=r,this.kdfConfigService=n,this.keyService=a,this.securityStateService=s,this.apiService=o,this.stateProvider=l,this.configService=c,this.userAgent=u,this.sdkClientOverrides=new $c({}),this.sdkClientCache=new Map,this.client$=this.environmentService.environment$.pipe(gc(e=>bk(this,void 0,void 0,function*(){yield xg.Ready;const t=yield this.toSettings(e),i=yield this.sdkClientFactory.createSdkClient(new kk(this.apiService),t);return yield this.loadFeatureFlags(i),i})),Jt({refCount:!0,bufferSize:1})),this.version$=this.client$.pipe(X(e=>e.version()),Hu(()=>"Unsupported"))}userClient$(e){return this.sdkClientOverrides.pipe(nk(t=>t[e]!==wk,!1),X(t=>{if(t[e]===wk)throw new Error("Encountered UnsetClient even though it should have been filtered out");return t[e]}),Zl(),Le(t=>t?bt(t):this.internalClient$(e)),nk(e=>void 0!==e,!1),ak(()=>new Bg(e)))}setClient(e,t){const i=this.sdkClientOverrides.value[e];this.sdkClientOverrides.next(Object.assign(Object.assign({},this.sdkClientOverrides.value),{[e]:t?new lk(t):wk})),i!==wk&&void 0!==i&&i.markForDisposal()}internalClient$(e){const t=this.sdkClientCache.get(e);if(void 0!==t)return t;const i=this.accountService.accounts$.pipe(X(t=>t[e]),Zl()),r=this.kdfConfigService.getKdfConfig$(e).pipe(Zl()),n=this.keyService.userEncryptedPrivateKey$(e).pipe(Zl()),a=this.keyService.userSigningKey$(e).pipe(Zl()),s=this.keyService.userKey$(e).pipe(Zl()),o=this.keyService.encryptedOrgKeys$(e).pipe(Zl(ok)),l=this.securityStateService.accountSecurityState$(e).pipe(Zl(ok)),c=this.keyService.userSignedPublicKey$(e).pipe(Zl(ok)),u=ai([this.environmentService.getEnvironment$(e),i,r,n,s,a,o,l,c,xg.Ready]).pipe(Le(([t,i,r,n,a,s,o,l,c])=>new $(u=>{let d;return(()=>bk(this,void 0,void 0,function*(){if(null==t||null==r||null==n||null==a)return;const u=yield this.toSettings(t),d=yield this.sdkClientFactory.createSdkClient(new kk(this.apiService,e),u);let h;return h=null!=s&&null!=l&&null!=c?{V2:{private_key:n,signing_key:s,security_state:l,signed_public_key:c}}:{V1:{private_key:n}},yield this.initializeClient(e,d,i,r,a,h,o),d}))().then(e=>{d=void 0===e?void 0:new lk(e),u.next(d)}).catch(e=>{u.error(e)}),()=>null==d?void 0:d.markForDisposal()})),ac({finalize:()=>this.sdkClientCache.delete(e)}),Gt({connector:()=>new Ht(1),resetOnRefCountZero:()=>sc(1e3)}));return this.sdkClientCache.set(e,u),u}initializeClient(e,t,i,r,n,a,s){return bk(this,void 0,void 0,function*(){yield t.crypto().initialize_user_crypto({userId:$g(e),email:i.email,method:{decryptedKey:{decrypted_user_key:n.keyB64}},kdfParams:r.kdfType===Cd.PBKDF2_SHA256?{pBKDF2:{iterations:r.iterations}}:{argon2id:{iterations:r.iterations,memory:r.memory,parallelism:r.parallelism}},accountCryptographicState:a}),yield t.crypto().initialize_org_crypto({organizationKeys:new Map(Object.entries(s).map(([e,t])=>[$g(e),t.toJSON()]))}),yield yk(e,t.platform().state(),this.stateProvider),yield this.loadFeatureFlags(t)})}loadFeatureFlags(e){return bk(this,void 0,void 0,function*(){var t;const i=yield Ce(this.configService.serverConfig$),r=new Map(Object.entries(null!==(t=null==i?void 0:i.featureStates)&&void 0!==t?t:{}).filter(([,e])=>"boolean"==typeof e).map(([e,t])=>[e,t]));e.platform().load_flags(r)})}toSettings(e){return bk(this,void 0,void 0,function*(){var t;return{apiUrl:e.getApiUrl(),identityUrl:e.getIdentityUrl(),deviceType:Vg(this.platformUtilsService.getDevice()),bitwardenClientVersion:yield this.platformUtilsService.getApplicationVersionNumber(),userAgent:null!==(t=this.userAgent)&&void 0!==t?t:navigator.userAgent}})}}class _k{createSdkClient(...e){return Promise.reject(new Error("SDK not available"))}}var xk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Ck=Symbol("UnsetClient");class Ik{constructor(e,t){this.apiService=e,this.userId=t}get_access_token(){return xk(this,void 0,void 0,function*(){if(null!=this.userId)return yield this.apiService.getActiveBearerToken(this.userId)})}}class Ek{constructor(e,t,i,r,n,a,s,o=null){this.sdkClientFactory=e,this.environmentService=t,this.platformUtilsService=i,this.accountService=r,this.apiService=n,this.stateProvider=a,this.configService=s,this.userAgent=o,this.sdkClientOverrides=new $c({}),this.sdkClientCache=new Map,this.client$=this.environmentService.environment$.pipe(gc(e=>xk(this,void 0,void 0,function*(){yield xg.Ready;const t=yield this.toSettings(e),i=yield this.sdkClientFactory.createSdkClient(new Ik(this.apiService),t);return yield this.loadFeatureFlags(i),i})),Jt({refCount:!0,bufferSize:1}))}registerClient$(e){return this.sdkClientOverrides.pipe(nk(t=>t[e]!==Ck,!1),X(t=>{if(t[e]===Ck)throw new Error("Encountered UnsetClient even though it should have been filtered out");return t[e]}),Zl(),Le(t=>t?bt(t):this.internalClient$(e)),nk(e=>void 0!==e,!1),ak(()=>new Bg(e)))}internalClient$(e){const t=this.sdkClientCache.get(e);if(void 0!==t)return t;const i=this.accountService.accounts$.pipe(X(t=>t[e]),Zl()),r=ai([this.environmentService.getEnvironment$(e),i,xg.Ready]).pipe(Le(([t,i])=>new $(r=>{let n;return(()=>xk(this,void 0,void 0,function*(){if(null==t||null==i)return;const r=yield this.toSettings(t),n=yield this.sdkClientFactory.createSdkClient(new Ik(this.apiService,e),r);return yield yk(e,n.platform().state(),this.stateProvider),yield this.loadFeatureFlags(n),n}))().then(e=>{n=void 0===e?void 0:new lk(e),r.next(n)}).catch(e=>{r.error(e)}),()=>null==n?void 0:n.markForDisposal()})),ac({finalize:()=>this.sdkClientCache.delete(e)}),Jt({refCount:!0,bufferSize:1}));return this.sdkClientCache.set(e,r),r}loadFeatureFlags(e){return xk(this,void 0,void 0,function*(){var t;const i=yield Ce(this.configService.serverConfig$),r=new Map(Object.entries(null!==(t=null==i?void 0:i.featureStates)&&void 0!==t?t:{}).filter(([,e])=>"boolean"==typeof e).map(([e,t])=>[e,t]));e.platform().load_flags(r)})}toSettings(e){return xk(this,void 0,void 0,function*(){var t;return{apiUrl:e.getApiUrl(),identityUrl:e.getIdentityUrl(),deviceType:Vg(this.platformUtilsService.getDevice()),userAgent:null!==(t=this.userAgent)&&void 0!==t?t:navigator.userAgent,bitwardenClientVersion:yield this.platformUtilsService.getApplicationVersionNumber()}})}}var zk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Pk{constructor(e,t,i){this.platformUtilsService=e,this.autofillSettingsService=t,this.taskSchedulerService=i,this.clearClipboardTimeoutFunction=null,this.taskSchedulerService.registerTaskHandler(Iu,()=>this.clearPendingClipboard())}clearClipboard(e){return zk(this,arguments,void 0,function*(e,t=null){var i;if(null===(i=this.clearClipboardTimeoutSubscription)||void 0===i||i.unsubscribe(),Tt.isNullOrWhitespace(e))return;let r=t;if(!r){const e=yield Ce(this.autofillSettingsService.clearClipboardDelay$);r=e?1e3*e:null}r&&(this.clearClipboardTimeoutFunction=()=>zk(this,void 0,void 0,function*(){const t=yield this.platformUtilsService.readFromClipboard();e===t&&this.platformUtilsService.copyToClipboard("",{clearing:!0})}),this.clearClipboardTimeoutSubscription=this.taskSchedulerService.setTimeout(Iu,r))})}clearPendingClipboard(){return zk(this,void 0,void 0,function*(){null!=this.clearClipboardTimeoutFunction&&(yield this.clearClipboardTimeoutFunction(),this.clearClipboardTimeoutFunction=null)})}}class Ak{constructor(e){this.keyService=e}setUserKeyInMemoryIfAutoUserKeySet(e){return t=this,i=void 0,n=function*(){if(null==e)return!1;const t=yield this.keyService.getUserKeyFromStorage(ht.Auto,e);return null!=t&&(yield this.keyService.setUserKey(t,e),!0)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}var jk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Tk{constructor(e,t){if(this.primaryStorageService=e,this.secondaryStorageService=t,this.updates$=this.primaryStorageService.updates$,e.valuesRequireDeserialization!==t.valuesRequireDeserialization)throw new Error("Differing values for valuesRequireDeserialization between storage services is not supported.")}get valuesRequireDeserialization(){return this.primaryStorageService.valuesRequireDeserialization}get(e,t){return jk(this,void 0,void 0,function*(){const i=yield this.primaryStorageService.get(e,t);return null==i?yield this.secondaryStorageService.get(e,t):i})}has(e,t){return jk(this,void 0,void 0,function*(){return(yield this.primaryStorageService.has(e,t))||(yield this.secondaryStorageService.has(e,t))})}save(e,t,i){return jk(this,void 0,void 0,function*(){yield Promise.allSettled([this.primaryStorageService.save(e,t,i),this.secondaryStorageService.save(e,t,i)])})}remove(e,t){return jk(this,void 0,void 0,function*(){yield Promise.allSettled([this.primaryStorageService.remove(e,t),this.secondaryStorageService.remove(e,t)])})}}class Dk{constructor(e){this.storage=e,this.updatesSubject=new H,this.updates$=this.updatesSubject.asObservable()}get valuesRequireDeserialization(){return!0}get(e,t){const i=this.storage.getItem(e);return null!=i?Promise.resolve(JSON.parse(i)):Promise.resolve(null)}has(e,t){return i=this,r=void 0,a=function*(){return null!=(yield this.get(e,t))},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}save(e,t,i){if(null==t)return this.remove(e,i);t instanceof Set&&(t=Array.from(t)),this.storage.setItem(e,JSON.stringify(t)),this.updatesSubject.next({key:e,updateType:"save"})}remove(e,t){return this.storage.removeItem(e),this.updatesSubject.next({key:e,updateType:"remove"}),Promise.resolve()}getKeys(){return Object.keys(this.storage)}}class Ok{constructor(e){this.id=e.id,this.name=e.name,this.status=e.status,this.type=e.type,this.enabled=e.enabled,this.userId=e.userId,this.useEvents=e.useEvents,this.providerStatus=e.providerStatus,this.providerType=e.providerType}}const Nk=Object.freeze({Text:0,File:1});class Rk{constructor(e){null!=e&&(this.id=e.id,this.fileName=e.fileName,this.size=e.size,this.sizeName=e.sizeName)}}class Uk{constructor(e){null!=e&&(this.text=e.text,this.hidden=e.hidden)}}class Fk{constructor(e){if(null!=e)switch(this.id=e.id,this.accessId=e.accessId,this.type=e.type,this.authType=e.authType,this.name=e.name,this.notes=e.notes,this.key=e.key,this.maxAccessCount=e.maxAccessCount,this.accessCount=e.accessCount,this.revisionDate=e.revisionDate,this.expirationDate=e.expirationDate,this.deletionDate=e.deletionDate,this.password=e.password,this.emails=e.emails,this.disabled=e.disable,this.hideEmail=e.hideEmail,this.authType=e.authType,this.type){case Nk.Text:this.text=new Uk(e.text);break;case Nk.File:this.file=new Rk(e.file)}}}class qk{constructor(e){var t,i,r;this.name=null!==(t=e.name)&&void 0!==t?t:"",this.id=null!==(i=e.id)&&void 0!==i?i:"",this.revisionDate=null!==(r=e.revisionDate)&&void 0!==r?r:(new Date).toISOString()}static fromJSON(e){return null==e?null:new qk({id:e.id,name:e.name,revisionDate:e.revisionDate})}}var Lk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Bk=new wi(ir,"lastSync",{deserializer:e=>null!=e?new Date(e):null,clearOn:["logout"]});class Mk{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h){this.tokenService=e,this.folderService=t,this.folderApiService=i,this.messageSender=r,this.logService=n,this.cipherService=a,this.collectionService=s,this.apiService=o,this.accountService=l,this.authService=c,this.sendService=u,this.sendApiService=d,this.stateProvider=h,this.syncInProgress=!1}getLastSync(){return Lk(this,void 0,void 0,function*(){const e=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id)));return null==e?null:yield Ce(this.lastSync$(e))})}lastSync$(e){return this.stateProvider.getUser(e,Bk).state$}activeUserLastSync$(){return this.accountService.activeAccount$.pipe(Le(e=>null==e?bt(null):this.lastSync$(e.id)))}setLastSync(e,t){return Lk(this,void 0,void 0,function*(){yield this.stateProvider.getUser(t,Bk).update(()=>e)})}syncUpsertFolder(e,t,i){return Lk(this,void 0,void 0,function*(){if(this.syncStarted(),(yield Ce(this.authService.authStatusFor$(i)))>=cu.Locked)try{const r=yield this.folderService.get(e.id,i);if(!t&&null==r||t&&null!=r&&r.revisionDate=cu.Locked?(yield this.folderService.delete(e.id,t),this.messageSender.send("syncedDeletedFolder",{folderId:e.id}),this.syncCompleted(!0,t),!0):this.syncCompleted(!1,t)})}syncUpsertCipher(e,t,i){return Lk(this,void 0,void 0,function*(){if(this.syncStarted(),(yield Ce(this.authService.authStatusFor$(i)))>=cu.Locked)try{let r=!0;const n=yield this.cipherService.get(e.id,i);null!=n&&n.revisionDate>=e.revisionDate&&(r=!1);let a=!1;if(r&&(t?(r=null!=n,a=!0):null==e.collectionIds||null==e.organizationId?r=null==n:(r=!1,a=!0)),!r&&a&&null!=e.organizationId&&null!=e.collectionIds&&e.collectionIds.length>0){const t=yield Ce(this.collectionService.encryptedCollections$(i).pipe(X(e=>null!=e?e:[])));if(null!=t)for(let i=0;i-1){r=!0;break}}if(r){const t=yield this.apiService.getFullCipherDetails(e.id);if(null!=t)return yield this.cipherService.upsert(new Fb(t)),this.messageSender.send("syncedUpsertedCipher",{cipherId:e.id}),this.syncCompleted(!0,i)}}catch(r){if(null!=r&&404===r.statusCode&&t)return yield this.cipherService.delete(e.id,i),this.messageSender.send("syncedDeletedCipher",{cipherId:e.id}),this.syncCompleted(!0,i)}return this.syncCompleted(!1,i)})}syncDeleteCipher(e,t){return Lk(this,void 0,void 0,function*(){return this.syncStarted(),(yield Ce(this.authService.authStatusFor$(t)))>=cu.Locked?(yield this.cipherService.delete(e.id,t),this.messageSender.send("syncedDeletedCipher",{cipherId:e.id}),this.syncCompleted(!0,t)):this.syncCompleted(!1,t)})}syncUpsertSend(e,t){return Lk(this,void 0,void 0,function*(){this.syncStarted();const[i,r]=yield Ce(this.accountService.activeAccount$.pipe(Le(e=>(null==e&&bt([null,cu.LoggedOut]),this.authService.authStatusFor$(e.id).pipe(X(t=>[e.id,t]))))));if(i===e.userId&&r!==cu.LoggedOut)try{const r=yield Ce(this.sendService.get$(e.id));if(!t&&null==r||t&&null!=r&&r.revisionDatenull==e?void 0:e.id)));return null!=t&&(yield Ce(this.tokenService.hasAccessToken$(t)))?(yield this.sendService.delete(e.id),this.messageSender.send("syncedDeletedSend",{sendId:e.id}),this.syncCompleted(!0,void 0),!0):this.syncCompleted(!1,void 0)})}syncStarted(){this.syncInProgress=!0,this.messageSender.send("syncStarted")}syncCompleted(e,t){return this.syncInProgress=!1,this.messageSender.send("syncCompleted",{successfully:e,userId:t}),e}}var Vk=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class $k extends Mk{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,f,y,v,b,w,k,S,_,x,C,I){super(k,n,m,l,d,a,o,i,t,S,u,f,_),this.masterPasswordService=e,this.domainSettingsService=r,this.keyService=s,this.policyService=c,this.keyConnectorService=h,this.providerService=p,this.organizationService=g,this.userDecryptionOptionsService=y,this.avatarService=v,this.logoutCallback=b,this.billingAccountProfileStateService=w,this.securityStateService=x,this.kdfConfigService=C,this.accountCryptographicStateService=I,this.syncInProgress=!1,this.inFlightApiCalls={refreshToken:null,sync:null}}fullSync(e,t){return Vk(this,void 0,void 0,function*(){const{allowThrowOnError:i=!1,skipTokenRefresh:r=!1}="boolean"==typeof t?{allowThrowOnError:t}:null!=t?t:{},n=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id)));if(this.syncStarted(),(yield Ce(this.authService.authStatusFor$(n)))===cu.LoggedOut)return this.syncCompleted(!1,n);const a=new Date;let s=!1,o=!0;try{s=yield this.needsSyncing(e)}catch(e){if(o=!1,i)throw this.syncCompleted(!1,n),e}if(!s)return o&&(yield this.setLastSync(a,n)),this.syncCompleted(!1,n);try{r||(null===this.inFlightApiCalls.refreshToken&&(this.inFlightApiCalls.refreshToken=this.apiService.refreshIdentityToken()),yield this.inFlightApiCalls.refreshToken),null===this.inFlightApiCalls.sync?this.inFlightApiCalls.sync=this.apiService.getSync():this.logService.debug("Sync: Sync network call already in progress, returning existing promise");const e=yield this.inFlightApiCalls.sync;return yield this.cipherService.clear(e.profile.id),yield this.syncUserDecryption(e.profile.id,e.userDecryption),yield this.syncProfile(e.profile),yield this.syncFolders(e.folders,e.profile.id),yield this.syncCollections(e.collections,e.profile.id),yield this.syncCiphers(e.ciphers,e.profile.id),yield this.syncSends(e.sends,e.profile.id),yield this.syncSettings(e.domains,e.profile.id),yield this.syncPolicies(e.policies,e.profile.id),yield this.setLastSync(a,n),this.syncCompleted(!0,n)}catch(e){if(i)throw this.syncCompleted(!1,n),e;return this.syncCompleted(!1,n)}finally{this.inFlightApiCalls.refreshToken=null,this.inFlightApiCalls.sync=null}})}needsSyncing(e){return Vk(this,void 0,void 0,function*(){if(e)return!0;const t=yield this.getLastSync();if(null==t||0===t.getTime())return!0;const i=yield this.apiService.getAccountRevisionDate();return i<0&&this.logoutCallback&&(yield this.logoutCallback("accountDeleted")),!(new Date(i)<=t)})}syncProfile(e){return Vk(this,void 0,void 0,function*(){const t=yield this.tokenService.getSecurityStamp(e.id);if(null!=t&&t!==e.securityStamp)throw null!=this.logoutCallback&&(yield this.logoutCallback("invalidSecurityStamp")),new Error("Stamp has changed");(null==e?void 0:e.key)&&(yield this.masterPasswordService.setMasterKeyEncryptedUserKey(e.key,e.id)),null!=e.accountKeys?yield this.accountCryptographicStateService.setAccountCryptographicState(e.accountKeys.toWrappedAccountCryptographicState(),e.id):yield this.accountCryptographicStateService.setAccountCryptographicState({V1:{private_key:e.privateKey}},e.id),yield this.keyService.setProviderKeys(e.providers,e.id),yield this.keyService.setOrgKeys(e.organizations,e.providerOrganizations,e.id),yield this.avatarService.setSyncAvatarColor(e.id,e.avatarColor),yield this.tokenService.setSecurityStamp(e.securityStamp,e.id),yield this.accountService.setAccountEmailVerified(e.id,e.emailVerified),yield this.accountService.setAccountCreationDate(e.id,new Date(e.creationDate)),yield this.accountService.setAccountVerifyNewDeviceLogin(e.id,e.verifyDevices),yield this.billingAccountProfileStateService.setHasPremium(e.premiumPersonally,e.premiumFromOrganization,e.id),yield this.keyConnectorService.setUsesKeyConnector(e.usesKeyConnector,e.id),yield this.setForceSetPasswordReasonIfNeeded(e);const i={};e.providers.forEach(e=>{i[e.id]=new Ok(e)}),yield this.providerService.save(i,e.id),yield this.syncProfileOrganizations(e,e.id),(yield Ce(this.keyConnectorService.convertAccountRequired$))&&this.messageSender.send("convertAccountToKeyConnector")})}setForceSetPasswordReasonIfNeeded(e){return Vk(this,void 0,void 0,function*(){var t;e.forcePasswordReset&&(yield this.masterPasswordService.setForceSetPasswordReason(Nd.AdminForcePasswordReset,e.id));const i=yield Ce(this.userDecryptionOptionsService.userDecryptionOptionsById$(e.id));null==i&&this.logService.error("Sync: Account decryption options are null or undefined.");let r=!1;for(const t of e.organizations){const e=t.type===Je.Admin,i=t.type===Je.Owner;if(e||i||t.permissions&&t.permissions.manageResetPassword){r=!0;break}}if(void 0!==i.trustedDeviceOption&&!i.hasMasterPassword&&r){const e=null===(t=yield Ce(this.accountService.activeAccount$))||void 0===t?void 0:t.id;yield this.masterPasswordService.setForceSetPasswordReason(Nd.TdeUserWithoutPasswordHasPasswordResetPermission,e)}})}syncProfileOrganizations(e,t){return Vk(this,void 0,void 0,function*(){const i={};e.organizations.forEach(e=>{i[e.id]=new Yh(e,{isMember:!0,isProviderUser:!1})}),e.providerOrganizations.forEach(e=>{null==i[e.id]?i[e.id]=new Yh(e,{isMember:!1,isProviderUser:!0}):i[e.id].isProviderUser=!0}),yield this.organizationService.replace(i,t)})}syncFolders(e,t){return Vk(this,void 0,void 0,function*(){const i={};return e.forEach(e=>{i[e.id]=new qk(e)}),yield this.folderService.replace(i,t)})}syncCollections(e,t){return Vk(this,void 0,void 0,function*(){const i={};return e.forEach(e=>{i[e.id]=new Kt(e)}),yield this.collectionService.replace(i,t)})}syncCiphers(e,t){return Vk(this,void 0,void 0,function*(){const i={};return e.forEach(e=>{i[e.id]=new Fb(e)}),yield this.cipherService.replace(i,t)})}syncSends(e,t){return Vk(this,void 0,void 0,function*(){const i={};return e.forEach(e=>{i[e.id]=new Fk(e)}),yield this.sendService.replace(i,t)})}syncSettings(e,t){return Vk(this,void 0,void 0,function*(){let i=[];return null!=e&&null!=e.equivalentDomains&&(i=i.concat(e.equivalentDomains)),null!=e&&null!=e.globalEquivalentDomains&&e.globalEquivalentDomains.forEach(e=>{e.domains.length>0&&i.push(e.domains)}),this.domainSettingsService.setEquivalentDomains(i,t)})}syncPolicies(e,t){return Vk(this,void 0,void 0,function*(){const i={};return null!=e&&e.forEach(e=>{i[e.id]=new ed(e)}),yield this.policyService.replace(i,t)})}syncUserDecryption(e,t){return Vk(this,void 0,void 0,function*(){if(null!=t){if(null!=t.masterPasswordUnlock){const i=t.masterPasswordUnlock.toMasterPasswordUnlockData();yield this.masterPasswordService.setMasterPasswordUnlockData(i,e),yield this.kdfConfigService.setKdfConfig(e,i.kdf)}if(null!=t.webAuthnPrfOptions&&t.webAuthnPrfOptions.length>0)try{const i=yield Ce(this.accountService.activeAccount$);if((null==i?void 0:i.id)!==e)return;const r=yield Ce(this.userDecryptionOptionsService.userDecryptionOptionsById$(e)).catch(()=>null);if(null!=r){const e=Object.assign(new ku,r);e.webAuthnPrfOptions=t.webAuthnPrfOptions.map(e=>bu.fromResponse(e)).filter(e=>void 0!==e),yield this.userDecryptionOptionsService.setUserDecryptionOptionsById(i.id,e)}}catch(e){this.logService.error("[Sync] Failed to update WebAuthn PRF options:",e)}}})}}class Kk{constructor(){this.notificationClicked$=tc(()=>new Error("Notification clicked is not supported."))}create(e){return t=this,i=void 0,n=function*(){throw new Error("Create OS Notification unsupported.")},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}clear(e){throw new Error("Clear OS Notification unsupported.")}isSupported(){return!1}}const Wk=new fi(rr,"selection",{deserializer:e=>e});class Hk{constructor(e,t=ft.System){this.globalStateProvider=e,this.defaultTheme=t,this.selectedThemeState=this.globalStateProvider.get(Wk),this.selectedTheme$=this.selectedThemeState.state$.pipe(X(e=>null==e||Object.values(ft).includes(e)?e:null),X(e=>null!=e?e:this.defaultTheme))}setSelectedTheme(e){return t=this,i=void 0,n=function*(){yield this.selectedThemeState.update(()=>e,{shouldUpdate:t=>t!==e})},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class Gk{constructor(e){this.ids=null==e?[]:e}}class Qk extends Lt{constructor(e,t){super(e),this.id=this.getResponseProperty("Id"),this.type=this.getResponseProperty("Type"),this.organizationId=this.getResponseProperty("OrganizationId"),this.enabled=this.getResponseProperty("Enabled");const i=this.getResponseProperty("Config");this.config=null==i?null:new t(i)}}class Jk extends Lt{constructor(e){super(e);const t=this.getResponseProperty("LastSyncDate");t&&(this.lastSyncDate=new Date(t))}}class Yk extends Lt{constructor(e){super(e),this.isTokenValid=this.getResponseProperty("IsTokenValid"),this.isFreeFamilyPolicyEnabled=this.getResponseProperty("IsFreeFamilyPolicyEnabled")}}class Xk extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.providerId=this.getResponseProperty("ProviderId"),this.organizationId=this.getResponseProperty("OrganizationId"),this.key=this.getResponseProperty("Key"),this.settings=this.getResponseProperty("Settings"),this.creationDate=this.getResponseProperty("CreationDate"),this.revisionDate=this.getResponseProperty("RevisionDate"),this.userCount=this.getResponseProperty("UserCount"),this.seats=this.getResponseProperty("Seats"),this.occupiedSeats=this.getResponseProperty("OccupiedSeats"),this.remainingSeats=this.getResponseProperty("RemainingSeats"),this.plan=this.getResponseProperty("Plan")}}class Zk extends Xk{constructor(e){super(e),this.organizationName=this.getResponseProperty("OrganizationName")}}class eS extends Lc{}class tS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.error=this.getResponseProperty("Error")}}class iS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.userId=this.getResponseProperty("UserId"),this.type=this.getResponseProperty("Type"),this.status=this.getResponseProperty("Status"),this.permissions=new Oc(this.getResponseProperty("Permissions"))}}class rS extends iS{constructor(e){super(e),this.name=this.getResponseProperty("Name"),this.email=this.getResponseProperty("Email")}}class nS extends Lt{constructor(e){super(e),this.apiKey=this.getResponseProperty("ApiKey"),this.revisionDate=new Date(this.getResponseProperty("RevisionDate"))}}class aS extends Lt{constructor(e){super(e),this.key=this.getResponseProperty("Key")}}class sS extends Lt{constructor(e){super(e),this.kdf=this.getResponseProperty("Kdf"),this.kdfIterations=this.getResponseProperty("KdfIterations"),this.kdfMemory=this.getResponseProperty("KdfMemory"),this.kdfParallelism=this.getResponseProperty("KdfParallelism")}}class oS extends Lt{constructor(e){super(e),this.token=this.getResponseProperty("Token")}}class lS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.url=this.getResponseProperty("Url"),this.pdfUrl=this.getResponseProperty("PdfUrl"),this.number=this.getResponseProperty("Number"),this.paid=this.getResponseProperty("Paid"),this.date=this.getResponseProperty("Date"),this.amount=this.getResponseProperty("Amount")}}class cS extends Lt{constructor(e){super(e),this.createdDate=this.getResponseProperty("CreatedDate"),this.amount=this.getResponseProperty("Amount"),this.refunded=this.getResponseProperty("Refunded"),this.partiallyRefunded=this.getResponseProperty("PartiallyRefunded"),this.refundedAmount=this.getResponseProperty("RefundedAmount"),this.type=this.getResponseProperty("Type"),this.paymentMethodType=this.getResponseProperty("PaymentMethodType"),this.details=this.getResponseProperty("Details")}}class uS extends Lt{constructor(e){super(e),this.invoices=[],this.transactions=[];const t=this.getResponseProperty("Transactions"),i=this.getResponseProperty("Invoices");null!=t&&(this.transactions=t.map(e=>new cS(e))),null!=i&&(this.invoices=i.map(e=>new lS(e)))}get hasNoHistory(){return 0==this.invoices.length&&0==this.transactions.length}}class dS extends Lt{constructor(e){var t,i,r,n,a,s,o;super(e),this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.usePolicies=this.getResponseProperty("UsePolicies"),this.useGroups=this.getResponseProperty("UseGroups"),this.useDirectory=this.getResponseProperty("UseDirectory"),this.useEvents=this.getResponseProperty("UseEvents"),this.useTotp=this.getResponseProperty("UseTotp"),this.use2fa=this.getResponseProperty("Use2fa"),this.useApi=this.getResponseProperty("UseApi"),this.useSso=this.getResponseProperty("UseSso"),this.useOrganizationDomains=this.getResponseProperty("UseOrganizationDomains"),this.useKeyConnector=null!==(t=this.getResponseProperty("UseKeyConnector"))&&void 0!==t&&t,this.useScim=null!==(i=this.getResponseProperty("UseScim"))&&void 0!==i&&i,this.useCustomPermissions=null!==(r=this.getResponseProperty("UseCustomPermissions"))&&void 0!==r&&r,this.useResetPassword=this.getResponseProperty("UseResetPassword"),this.useSecretsManager=this.getResponseProperty("UseSecretsManager"),this.usePasswordManager=this.getResponseProperty("UsePasswordManager"),this.useActivateAutofillPolicy=this.getResponseProperty("UseActivateAutofillPolicy"),this.useAutomaticUserConfirmation=this.getResponseProperty("UseAutomaticUserConfirmation"),this.selfHost=this.getResponseProperty("SelfHost"),this.usersGetPremium=this.getResponseProperty("UsersGetPremium"),this.seats=this.getResponseProperty("Seats"),this.maxCollections=this.getResponseProperty("MaxCollections"),this.maxStorageGb=this.getResponseProperty("MaxStorageGb"),this.key=this.getResponseProperty("Key"),this.hasPublicAndPrivateKeys=this.getResponseProperty("HasPublicAndPrivateKeys"),this.status=this.getResponseProperty("Status"),this.type=this.getResponseProperty("Type"),this.enabled=this.getResponseProperty("Enabled"),this.ssoBound=this.getResponseProperty("SsoBound"),this.identifier=this.getResponseProperty("Identifier"),this.permissions=new Oc(this.getResponseProperty("permissions")),this.resetPasswordEnrolled=this.getResponseProperty("ResetPasswordEnrolled"),this.userId=this.getResponseProperty("UserId"),this.organizationUserId=this.getResponseProperty("OrganizationUserId"),this.providerId=this.getResponseProperty("ProviderId"),this.providerName=this.getResponseProperty("ProviderName"),this.providerType=this.getResponseProperty("ProviderType"),this.familySponsorshipFriendlyName=this.getResponseProperty("FamilySponsorshipFriendlyName"),this.familySponsorshipAvailable=this.getResponseProperty("FamilySponsorshipAvailable"),this.productTierType=this.getResponseProperty("ProductTierType"),this.keyConnectorEnabled=null!==(n=this.getResponseProperty("KeyConnectorEnabled"))&&void 0!==n&&n,this.keyConnectorUrl=this.getResponseProperty("KeyConnectorUrl");const l=this.getResponseProperty("FamilySponsorshipLastSyncDate");l&&(this.familySponsorshipLastSyncDate=new Date(l));const c=this.getResponseProperty("FamilySponsorshipValidUntil");c&&(this.familySponsorshipValidUntil=new Date(c)),this.familySponsorshipToDelete=this.getResponseProperty("FamilySponsorshipToDelete"),this.accessSecretsManager=this.getResponseProperty("AccessSecretsManager"),this.limitCollectionCreation=this.getResponseProperty("LimitCollectionCreation"),this.limitCollectionDeletion=this.getResponseProperty("LimitCollectionDeletion"),this.limitItemDeletion=this.getResponseProperty("LimitItemDeletion"),this.allowAdminAccessToAllCollectionItems=this.getResponseProperty("AllowAdminAccessToAllCollectionItems"),this.userIsManagedByOrganization=this.getResponseProperty("UserIsManagedByOrganization"),this.useAccessIntelligence=this.getResponseProperty("UseRiskInsights"),this.useAdminSponsoredFamilies=this.getResponseProperty("UseAdminSponsoredFamilies"),this.useDisableSMAdsForUsers=null!==(a=this.getResponseProperty("UseDisableSMAdsForUsers"))&&void 0!==a&&a,this.isAdminInitiated=this.getResponseProperty("IsAdminInitiated"),this.ssoEnabled=null!==(s=this.getResponseProperty("SsoEnabled"))&&void 0!==s&&s,this.ssoMemberDecryptionType=this.getResponseProperty("SsoMemberDecryptionType"),this.usePhishingBlocker=null!==(o=this.getResponseProperty("UsePhishingBlocker"))&&void 0!==o&&o}}class hS extends dS{constructor(e){super(e),this.keyConnectorEnabled=!1}}class pS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.key=this.getResponseProperty("Key"),this.status=this.getResponseProperty("Status"),this.type=this.getResponseProperty("Type"),this.enabled=this.getResponseProperty("Enabled"),this.permissions=new Oc(this.getResponseProperty("permissions")),this.userId=this.getResponseProperty("UserId"),this.useEvents=this.getResponseProperty("UseEvents"),this.providerStatus=this.getResponseProperty("ProviderStatus"),this.providerType=this.getResponseProperty("ProviderType")}}class mS extends Lt{constructor(e){var t,i,r;super(e),this.accountKeys=null,this.organizations=[],this.providers=[],this.providerOrganizations=[],this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.email=this.getResponseProperty("Email"),this.emailVerified=this.getResponseProperty("EmailVerified"),this.premiumPersonally=this.getResponseProperty("Premium"),this.premiumFromOrganization=this.getResponseProperty("PremiumFromOrganization"),this.culture=this.getResponseProperty("Culture"),this.twoFactorEnabled=this.getResponseProperty("TwoFactorEnabled");const n=this.getResponseProperty("Key");n&&(this.key=new Nt(n)),null!=this.getResponseProperty("AccountKeys")&&(this.accountKeys=new Kd(this.getResponseProperty("AccountKeys"))),this.avatarColor=this.getResponseProperty("AvatarColor"),this.creationDate=this.getResponseProperty("CreationDate"),this.privateKey=this.getResponseProperty("PrivateKey"),this.securityStamp=this.getResponseProperty("SecurityStamp"),this.forcePasswordReset=null!==(t=this.getResponseProperty("ForcePasswordReset"))&&void 0!==t&&t,this.usesKeyConnector=null!==(i=this.getResponseProperty("UsesKeyConnector"))&&void 0!==i&&i,this.verifyDevices=null===(r=this.getResponseProperty("VerifyDevices"))||void 0===r||r;const a=this.getResponseProperty("Organizations");null!=a&&(this.organizations=a.map(e=>new dS(e)));const s=this.getResponseProperty("Providers");null!=s&&(this.providers=s.map(e=>new pS(e)));const o=this.getResponseProperty("ProviderOrganizations");null!=o&&(this.providerOrganizations=o.map(e=>new hS(e)))}}class gS extends Lt{constructor(e){super(e);const t=this.getResponseProperty("UserProfile");null!=t&&(this.userProfile=new mS(t)),this.paymentIntentClientSecret=this.getResponseProperty("PaymentIntentClientSecret"),this.success=this.getResponseProperty("Success")}}class fS extends Lt{constructor(e){super(e),this.type=this.getResponseProperty("Type"),this.productTier=this.getResponseProperty("ProductTier"),this.name=this.getResponseProperty("Name"),this.isAnnual=this.getResponseProperty("IsAnnual"),this.nameLocalizationKey=this.getResponseProperty("NameLocalizationKey"),this.descriptionLocalizationKey=this.getResponseProperty("DescriptionLocalizationKey"),this.canBeUsedByBusiness=this.getResponseProperty("CanBeUsedByBusiness"),this.trialPeriodDays=this.getResponseProperty("TrialPeriodDays"),this.hasSelfHost=this.getResponseProperty("HasSelfHost"),this.hasPolicies=this.getResponseProperty("HasPolicies"),this.hasGroups=this.getResponseProperty("HasGroups"),this.hasDirectory=this.getResponseProperty("HasDirectory"),this.hasEvents=this.getResponseProperty("HasEvents"),this.hasTotp=this.getResponseProperty("HasTotp"),this.has2fa=this.getResponseProperty("Has2fa"),this.hasApi=this.getResponseProperty("HasApi"),this.hasSso=this.getResponseProperty("HasSso"),this.hasResetPassword=this.getResponseProperty("HasResetPassword"),this.usersGetPremium=this.getResponseProperty("UsersGetPremium"),this.upgradeSortOrder=this.getResponseProperty("UpgradeSortOrder"),this.displaySortOrder=this.getResponseProperty("DisplaySortOrder"),this.legacyYear=this.getResponseProperty("LegacyYear"),this.disabled=this.getResponseProperty("Disabled");const t=this.getResponseProperty("PasswordManager"),i=this.getResponseProperty("SecretsManager");this.PasswordManager=null==t?null:new vS(t),this.SecretsManager=null==i?null:new yS(i)}}class yS extends Lt{constructor(e){super(e),this.stripeSeatPlanId=this.getResponseProperty("StripeSeatPlanId"),this.baseSeats=this.getResponseProperty("BaseSeats"),this.basePrice=this.getResponseProperty("BasePrice"),this.seatPrice=this.getResponseProperty("SeatPrice"),this.hasAdditionalSeatsOption=this.getResponseProperty("HasAdditionalSeatsOption"),this.maxAdditionalSeats=this.getResponseProperty("MaxAdditionalSeats"),this.maxSeats=this.getResponseProperty("MaxSeats"),this.stripeServiceAccountPlanId=this.getResponseProperty("StripeServiceAccountPlanId"),this.additionalPricePerServiceAccount=this.getResponseProperty("AdditionalPricePerServiceAccount"),this.baseServiceAccount=this.getResponseProperty("BaseServiceAccount"),this.maxServiceAccount=this.getResponseProperty("MaxServiceAccount"),this.hasAdditionalServiceAccountOption=this.getResponseProperty("HasAdditionalServiceAccountOption"),this.maxAdditionalServiceAccounts=this.getResponseProperty("MaxAdditionalServiceAccounts"),this.maxProjects=this.getResponseProperty("MaxProjects")}}class vS extends Lt{constructor(e){super(e),this.stripePlanId=this.getResponseProperty("StripePlanId"),this.stripeSeatPlanId=this.getResponseProperty("StripeSeatPlanId"),this.stripeProviderPortalSeatPlanId=this.getResponseProperty("StripeProviderPortalSeatPlanId"),this.stripeStoragePlanId=this.getResponseProperty("StripeStoragePlanId"),this.stripePremiumAccessPlanId=this.getResponseProperty("StripePremiumAccessPlanId"),this.basePrice=this.getResponseProperty("BasePrice"),this.seatPrice=this.getResponseProperty("SeatPrice"),this.providerPortalSeatPrice=this.getResponseProperty("ProviderPortalSeatPrice"),this.baseSeats=this.getResponseProperty("BaseSeats"),this.maxAdditionalSeats=this.getResponseProperty("MaxAdditionalSeats"),this.premiumAccessOptionPrice=this.getResponseProperty("PremiumAccessOptionPrice"),this.maxSeats=this.getResponseProperty("MaxSeats"),this.additionalStoragePricePerGb=this.getResponseProperty("AdditionalStoragePricePerGb"),this.hasAdditionalSeatsOption=this.getResponseProperty("HasAdditionalSeatsOption"),this.baseStorageGb=this.getResponseProperty("BaseStorageGb"),this.maxCollections=this.getResponseProperty("MaxCollections"),this.hasAdditionalStorageOption=this.getResponseProperty("HasAdditionalStorageOption"),this.maxAdditionalStorage=this.getResponseProperty("MaxAdditionalStorage"),this.hasPremiumAccessOption=this.getResponseProperty("HasPremiumAccessOption")}}class bS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.active=this.getResponseProperty("Active"),this.percentOff=this.getResponseProperty("PercentOff"),this.amountOff=this.getResponseProperty("AmountOff"),this.appliesTo=this.getResponseProperty("AppliesTo")||[]}}class wS extends Lt{constructor(e){super(e),this.storageName=this.getResponseProperty("StorageName"),this.storageGb=this.getResponseProperty("StorageGb"),this.maxStorageGb=this.getResponseProperty("MaxStorageGb"),this.license=this.getResponseProperty("License"),this.expiration=this.getResponseProperty("Expiration");const t=this.getResponseProperty("Subscription"),i=this.getResponseProperty("UpcomingInvoice"),r=this.getResponseProperty("CustomerDiscount");this.subscription=null==t?null:new kS(t),this.upcomingInvoice=null==i?null:new _S(i),this.customerDiscount=null==r?null:new bS(r)}}class kS extends Lt{constructor(e){super(e),this.items=[],this.trialStartDate=this.getResponseProperty("TrialStartDate"),this.trialEndDate=this.getResponseProperty("TrialEndDate"),this.periodStartDate=this.getResponseProperty("PeriodStartDate"),this.periodEndDate=this.getResponseProperty("PeriodEndDate"),this.cancelledDate=this.getResponseProperty("CancelledDate"),this.cancelAtEndDate=this.getResponseProperty("CancelAtEndDate"),this.status=this.getResponseProperty("Status"),this.cancelled=this.getResponseProperty("Cancelled");const t=this.getResponseProperty("Items");null!=t&&(this.items=t.map(e=>new SS(e))),this.collectionMethod=this.getResponseProperty("CollectionMethod"),this.suspensionDate=this.getResponseProperty("SuspensionDate"),this.unpaidPeriodEndDate=this.getResponseProperty("unpaidPeriodEndDate"),this.gracePeriod=this.getResponseProperty("GracePeriod")}}class SS extends Lt{constructor(e){super(e),this.productId=this.getResponseProperty("ProductId"),this.name=this.getResponseProperty("Name"),this.amount=this.getResponseProperty("Amount"),this.quantity=this.getResponseProperty("Quantity"),this.interval=this.getResponseProperty("Interval"),this.sponsoredSubscriptionItem=this.getResponseProperty("SponsoredSubscriptionItem"),this.addonSubscriptionItem=this.getResponseProperty("AddonSubscriptionItem")}}class _S extends Lt{constructor(e){super(e),this.date=this.getResponseProperty("Date"),this.amount=this.getResponseProperty("Amount")}}class xS extends Lt{constructor(e){super(e),this.type=this.getResponseProperty("Type"),this.domains=this.getResponseProperty("Domains"),this.excluded=this.getResponseProperty("Excluded")}}class CS extends Lt{constructor(e){super(e),this.globalEquivalentDomains=[],this.equivalentDomains=this.getResponseProperty("EquivalentDomains");const t=this.getResponseProperty("GlobalEquivalentDomains");this.globalEquivalentDomains=null!=t?t.map(e=>new xS(e)):[]}}class IS extends Lt{constructor(e){super(e),this.type=this.getResponseProperty("Type"),this.userId=this.getResponseProperty("UserId"),this.organizationId=this.getResponseProperty("OrganizationId"),this.providerId=this.getResponseProperty("ProviderId"),this.cipherId=this.getResponseProperty("CipherId"),this.collectionId=this.getResponseProperty("CollectionId"),this.groupId=this.getResponseProperty("GroupId"),this.policyId=this.getResponseProperty("PolicyId"),this.organizationUserId=this.getResponseProperty("OrganizationUserId"),this.providerUserId=this.getResponseProperty("ProviderUserId"),this.providerOrganizationId=this.getResponseProperty("ProviderOrganizationId"),this.actingUserId=this.getResponseProperty("ActingUserId"),this.date=this.getResponseProperty("Date"),this.deviceType=this.getResponseProperty("DeviceType"),this.ipAddress=this.getResponseProperty("IpAddress"),this.installationId=this.getResponseProperty("InstallationId"),this.systemUser=this.getResponseProperty("SystemUser"),this.domainName=this.getResponseProperty("DomainName"),this.secretId=this.getResponseProperty("SecretId"),this.projectId=this.getResponseProperty("ProjectId"),this.serviceAccountId=this.getResponseProperty("ServiceAccountId"),this.grantedServiceAccountId=this.getResponseProperty("GrantedServiceAccountId")}}class ES extends Lt{constructor(e){super(e),this.userId=this.getResponseProperty("UserId"),this.publicKey=this.getResponseProperty("PublicKey")}}class zS extends Lt{constructor(e){super(e);const t=this.getResponseProperty("MasterPasswordUnlock");null!=t&&"object"==typeof t&&(this.masterPasswordUnlock=new Qd(t));const i=this.getResponseProperty("WebAuthnPrfOptions");null!=i&&Array.isArray(i)&&(this.webAuthnPrfOptions=i.map(e=>new Xd(e)))}}class PS extends Lt{constructor(e=null){super(e),null!=e&&(this.id=this.getResponseProperty("Id"),this.fileName=this.getResponseProperty("FileName"),this.size=this.getResponseProperty("Size"),this.sizeName=this.getResponseProperty("SizeName"))}}class AS extends Lt{constructor(e=null){super(e),null!=e&&(this.text=this.getResponseProperty("Text"),this.hidden=this.getResponseProperty("Hidden")||!1)}}class jS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.accessId=this.getResponseProperty("AccessId"),this.type=this.getResponseProperty("Type"),this.authType=this.getResponseProperty("AuthType"),this.name=this.getResponseProperty("Name"),this.notes=this.getResponseProperty("Notes"),this.key=this.getResponseProperty("Key"),this.maxAccessCount=this.getResponseProperty("MaxAccessCount"),this.accessCount=this.getResponseProperty("AccessCount"),this.revisionDate=this.getResponseProperty("RevisionDate"),this.expirationDate=this.getResponseProperty("ExpirationDate"),this.deletionDate=this.getResponseProperty("DeletionDate"),this.password=this.getResponseProperty("Password"),this.emails=this.getResponseProperty("Emails"),this.disable=this.getResponseProperty("Disabled")||!1,this.hideEmail=this.getResponseProperty("HideEmail")||!1,this.authType=this.getResponseProperty("AuthType");const t=this.getResponseProperty("Text");null!=t&&(this.text=new AS(t));const i=this.getResponseProperty("File");null!=i&&(this.file=new PS(i))}}class TS extends Lt{constructor(e=null){super(e),null!=e&&(this.cardholderName=this.getResponseProperty("CardholderName"),this.brand=this.getResponseProperty("Brand"),this.number=this.getResponseProperty("Number"),this.expMonth=this.getResponseProperty("ExpMonth"),this.expYear=this.getResponseProperty("ExpYear"),this.code=this.getResponseProperty("Code"))}}class DS extends Lt{constructor(e=null){super(e),null!=e&&(this.type=this.getResponseProperty("Type"),this.name=this.getResponseProperty("Name"),this.value=this.getResponseProperty("Value"),this.linkedId=this.getResponseProperty("linkedId"))}}class OS extends Lt{constructor(e=null){super(e),null!=e&&(this.title=this.getResponseProperty("Title"),this.firstName=this.getResponseProperty("FirstName"),this.middleName=this.getResponseProperty("MiddleName"),this.lastName=this.getResponseProperty("LastName"),this.address1=this.getResponseProperty("Address1"),this.address2=this.getResponseProperty("Address2"),this.address3=this.getResponseProperty("Address3"),this.city=this.getResponseProperty("City"),this.state=this.getResponseProperty("State"),this.postalCode=this.getResponseProperty("PostalCode"),this.country=this.getResponseProperty("Country"),this.company=this.getResponseProperty("Company"),this.email=this.getResponseProperty("Email"),this.phone=this.getResponseProperty("Phone"),this.ssn=this.getResponseProperty("SSN"),this.username=this.getResponseProperty("Username"),this.passportNumber=this.getResponseProperty("PassportNumber"),this.licenseNumber=this.getResponseProperty("LicenseNumber"))}}class NS extends Lt{constructor(e=null){super(e),null!=e&&(this.credentialId=this.getResponseProperty("CredentialId"),this.keyType=this.getResponseProperty("KeyType"),this.keyAlgorithm=this.getResponseProperty("KeyAlgorithm"),this.keyCurve=this.getResponseProperty("KeyCurve"),this.keyValue=this.getResponseProperty("keyValue"),this.rpId=this.getResponseProperty("RpId"),this.userHandle=this.getResponseProperty("UserHandle"),this.userName=this.getResponseProperty("UserName"),this.counter=this.getResponseProperty("Counter"),this.rpName=this.getResponseProperty("RpName"),this.userDisplayName=this.getResponseProperty("UserDisplayName"),this.discoverable=this.getResponseProperty("Discoverable"),this.creationDate=this.getResponseProperty("CreationDate"))}}class RS extends Lt{constructor(e=null){if(super(e),this.match=null,null==e)return;this.uri=this.getResponseProperty("Uri"),this.uriChecksum=this.getResponseProperty("UriChecksum");const t=this.getResponseProperty("Match");this.match=null!=t?t:null}}class US extends Lt{constructor(e=null){if(super(e),null==e)return;this.username=this.getResponseProperty("Username"),this.password=this.getResponseProperty("Password"),this.passwordRevisionDate=this.getResponseProperty("PasswordRevisionDate"),this.totp=this.getResponseProperty("Totp"),this.autofillOnPageLoad=this.getResponseProperty("AutofillOnPageLoad");const t=this.getResponseProperty("Uris");null!=t&&(this.uris=t.map(e=>new RS(e)));const i=this.getResponseProperty("Fido2Credentials");null!=i&&(this.fido2Credentials=i.map(e=>new NS(e)))}}class FS extends Lt{constructor(e=null){super(e),null!=e&&(this.type=this.getResponseProperty("Type"))}}class qS extends Lt{constructor(e=null){super(e),null!=e&&(this.privateKey=this.getResponseProperty("PrivateKey"),this.publicKey=this.getResponseProperty("PublicKey"),this.keyFingerprint=this.getResponseProperty("KeyFingerprint"))}}class LS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.url=this.getResponseProperty("Url"),this.fileName=this.getResponseProperty("FileName"),this.key=this.getResponseProperty("Key"),this.size=this.getResponseProperty("Size"),this.sizeName=this.getResponseProperty("SizeName")}}class BS extends Lt{constructor(e){super(e),this.password=this.getResponseProperty("Password"),this.lastUsedDate=this.getResponseProperty("LastUsedDate")}}class MS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.organizationId=this.getResponseProperty("OrganizationId"),this.folderId=this.getResponseProperty("FolderId")||null,this.type=this.getResponseProperty("Type"),this.name=this.getResponseProperty("Name"),this.notes=this.getResponseProperty("Notes"),this.favorite=this.getResponseProperty("Favorite")||!1,this.edit=!!this.getResponseProperty("Edit"),null==this.getResponseProperty("ViewPassword")?this.viewPassword=!0:this.viewPassword=this.getResponseProperty("ViewPassword"),this.permissions=new Eb(this.getResponseProperty("Permissions")),this.organizationUseTotp=this.getResponseProperty("OrganizationUseTotp"),this.revisionDate=this.getResponseProperty("RevisionDate"),this.collectionIds=this.getResponseProperty("CollectionIds"),this.creationDate=this.getResponseProperty("CreationDate"),this.deletedDate=this.getResponseProperty("DeletedDate"),this.archivedDate=this.getResponseProperty("ArchivedDate");const t=this.getResponseProperty("Login");null!=t&&(this.login=new US(t));const i=this.getResponseProperty("Card");null!=i&&(this.card=new TS(i));const r=this.getResponseProperty("Identity");null!=r&&(this.identity=new OS(r));const n=this.getResponseProperty("SecureNote");null!=n&&(this.secureNote=new FS(n));const a=this.getResponseProperty("sshKey");null!=a&&(this.sshKey=new qS(a));const s=this.getResponseProperty("Fields");null!=s&&(this.fields=s.map(e=>new DS(e)));const o=this.getResponseProperty("Attachments");null!=o&&(this.attachments=o.map(e=>new LS(e)));const l=this.getResponseProperty("PasswordHistory");null!=l&&(this.passwordHistory=l.map(e=>new BS(e))),this.reprompt=this.getResponseProperty("Reprompt")||tm.None,this.key=this.getResponseProperty("Key")||null}}class VS extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.name=this.getResponseProperty("Name"),this.revisionDate=this.getResponseProperty("RevisionDate")}}class $S extends Lt{constructor(e){super(e),this.folders=[],this.collections=[],this.ciphers=[],this.policies=[],this.sends=[];const t=this.getResponseProperty("Profile");null!=t&&(this.profile=new mS(t));const i=this.getResponseProperty("Folders");null!=i&&(this.folders=i.map(e=>new VS(e)));const r=this.getResponseProperty("Collections");null!=r&&(this.collections=r.map(e=>new Vt(e)));const n=this.getResponseProperty("Ciphers");null!=n&&(this.ciphers=n.map(e=>new MS(e)));const a=this.getResponseProperty("Domains");null!=a&&(this.domains=new CS(a));const s=this.getResponseProperty("Policies");null!=s&&(this.policies=s.map(e=>new ip(e)));const o=this.getResponseProperty("Sends");null!=o&&(this.sends=o.map(e=>new jS(e)));const l=this.getResponseProperty("UserDecryption");null!=l&&"object"==typeof l&&(this.userDecryption=new zS(l))}}class KS extends Lt{constructor(e){super(e),this.url=null,this.attachmentId=this.getResponseProperty("AttachmentId"),this.fileUploadType=this.getResponseProperty("FileUploadType");const t=this.getResponseProperty("CipherResponse"),i=this.getResponseProperty("CipherMiniResponse");this.cipherResponse=null==t?null:new MS(t),this.cipherMiniResponse=null==i?null:new MS(i),this.url=this.getResponseProperty("Url")}}class WS extends Lt{constructor(e){super(e),this.cipher=new MS(this.getResponseProperty("Cipher"))}}class HS extends Lt{constructor(e){super(e),this.unavailable=this.getResponseProperty("Unavailable"),this.cipher=new MS(this.getResponseProperty("Cipher"))}}var GS=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class QS{constructor(e,t,i,r,n,a,s,o,l,c,u=null){this.tokenService=e,this.platformUtilsService=t,this.environmentService=i,this.appIdService=r,this.refreshAccessTokenErrorCallback=n,this.logService=a,this.logoutCallback=s,this.vaultTimeoutSettingsService=o,this.accountService=l,this.httpOperations=c,this.customUserAgent=u,this.refreshTokenPromise={},this.device=t.getDevice(),this.deviceType=this.device.toString()}postIdentityToken(e){return GS(this,void 0,void 0,function*(){var t;const i=new Headers({"Content-Type":"application/x-www-form-urlencoded; charset=utf-8",Accept:"application/json","Device-Type":this.deviceType});null!=this.customUserAgent&&i.set("User-Agent",this.customUserAgent);const r=e instanceof mh?e.toIdentityToken():e.toIdentityToken(this.platformUtilsService.getClientType()),n=yield Ce(this.environmentService.environment$),a=yield this.fetch(this.httpOperations.createRequest(n.getIdentityUrl()+"/connect/token",{body:this.qsStringify(r),credentials:yield this.getCredentials(n),cache:"no-store",headers:i,method:"POST"}));let s=null;if(this.isJsonResponse(a)&&(s=yield a.json()),null!=s){if(200===a.status)return new eh(s);if(400===a.status&&s.TwoFactorProviders2&&Object.keys(s.TwoFactorProviders2).length)return new th(s);if(400===a.status&&(null===(t=null==s?void 0:s.ErrorModel)||void 0===t?void 0:t.Message)===QS.NEW_DEVICE_VERIFICATION_REQUIRED_MESSAGE)return new Ld(s);if(400===a.status&&(null==s?void 0:s.SsoOrganizationIdentifier))return new Bd(s)}return Promise.reject(new Su(s,a.status,!0))})}refreshIdentityToken(){return GS(this,arguments,void 0,function*(e=null){const t=null!=e?e:e=yield this.getActiveUser();if(null==t)throw new Error("No user provided and no active user, cannot refresh the identity token.");try{yield this.refreshToken(t)}catch(e){throw this.logService.error("Error refreshing access token: ",e),e}})}getAuthRequest(e){return GS(this,void 0,void 0,function*(){const t=`/auth-requests/${e}`,i=yield this.send("GET",t,null,!0,!0);return new Sh(i)})}putAuthRequest(e,t){return GS(this,void 0,void 0,function*(){const i=`/auth-requests/${e}`,r=yield this.send("PUT",i,t,!0,!0);return new Sh(r)})}getAuthRequests(){return GS(this,void 0,void 0,function*(){const e=yield this.send("GET","/auth-requests/",null,!0,!0);return new Tc(e,Sh)})}getLastAuthRequest(){return GS(this,void 0,void 0,function*(){const e=(yield this.getAuthRequests()).data.filter(e=>!e.isAnswered&&!e.isExpired);return e.sort((e,t)=>e.creationDate.localeCompare(t.creationDate))[e.length-1]})}getProfile(){return GS(this,void 0,void 0,function*(){const e=yield this.send("GET","/accounts/profile",null,!0,!0);return new mS(e)})}getUserSubscription(){return GS(this,void 0,void 0,function*(){const e=yield this.send("GET","/accounts/subscription",null,!0,!0);return new wS(e)})}putProfile(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/accounts/profile",e,!0,!0);return new mS(t)})}putAvatar(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/accounts/avatar",e,!0,!0);return new mS(t)})}postPrelogin(e){return GS(this,void 0,void 0,function*(){const t=yield Ce(this.environmentService.environment$),i=yield this.send("POST","/accounts/prelogin",e,!1,!0,t.getIdentityUrl());return new sS(i)})}postEmailToken(e){return this.send("POST","/accounts/email-token",e,!0,!1)}postEmail(e){return this.send("POST","/accounts/email",e,!0,!1)}postSetKeyConnectorKey(e){return this.send("POST","/accounts/set-key-connector-key",e,!0,!1)}postSecurityStamp(e){return this.send("POST","/accounts/security-stamp",e,!0,!1)}getAccountRevisionDate(){return GS(this,void 0,void 0,function*(){return yield this.send("GET","/accounts/revision-date",null,!0,!0)})}postPasswordHint(e){return this.send("POST","/accounts/password-hint",e,!1,!1)}postPremium(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("POST","/accounts/premium",e,!0,!0);return new gS(t)})}postReinstatePremium(){return this.send("POST","/accounts/reinstate-premium",null,!0,!1)}postAccountStorage(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("POST","/accounts/storage",e,!0,!0);return new gS(t)})}postAccountLicense(e){return this.send("POST","/accounts/license",e,!0,!1)}postAccountKeys(e){return this.send("POST","/accounts/keys",e,!0,!1)}postAccountVerifyEmail(){return this.send("POST","/accounts/verify-email",null,!0,!1)}postAccountVerifyEmailToken(e){return this.send("POST","/accounts/verify-email-token",e,!1,!1)}postAccountRecoverDelete(e){return this.send("POST","/accounts/delete-recover",e,!1,!1)}postAccountRecoverDeleteToken(e){return this.send("POST","/accounts/delete-recover-token",e,!1,!1)}postAccountKdf(e){return this.send("POST","/accounts/kdf",e,!0,!1)}deleteSsoUser(e){return GS(this,void 0,void 0,function*(){return this.send("DELETE","/accounts/sso/"+e,null,!0,!1)})}getSsoUserIdentifier(){return GS(this,void 0,void 0,function*(){return this.send("GET","/accounts/sso/user-identifier",null,!0,!0)})}postUserApiKey(e,t){return GS(this,void 0,void 0,function*(){const e=yield this.send("POST","/accounts/api-key",t,!0,!0);return new nS(e)})}postUserRotateApiKey(e,t){return GS(this,void 0,void 0,function*(){const e=yield this.send("POST","/accounts/rotate-api-key",t,!0,!0);return new nS(e)})}postConvertToKeyConnector(){return this.send("POST","/accounts/convert-to-key-connector",null,!0,!1)}getUserBillingHistory(){return GS(this,void 0,void 0,function*(){const e=yield this.send("GET","/accounts/billing/history",null,!0,!0);return new uS(e)})}getCipher(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/ciphers/"+e,null,!0,!0);return new MS(t)})}getFullCipherDetails(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/ciphers/"+e+"/details",null,!0,!0);return new MS(t)})}getCipherAdmin(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/ciphers/"+e+"/admin",null,!0,!0);return new MS(t)})}getCiphersOrganization(e,t){return GS(this,void 0,void 0,function*(){let i="/ciphers/organization-details?organizationId="+e;t&&(i+=`&includeMemberItems=${t}`);const r=yield this.send("GET",i,null,!0,!0);return new Tc(r,MS)})}postCipher(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("POST","/ciphers",e,!0,!0);return new MS(t)})}postCipherCreate(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("POST","/ciphers/create",e,!0,!0);return new MS(t)})}postCipherAdmin(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("POST","/ciphers/admin",e,!0,!0);return new MS(t)})}putCipher(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("PUT","/ciphers/"+e,t,!0,!0);return new MS(i)})}putPartialCipher(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("PUT","/ciphers/"+e+"/partial",t,!0,!0);return new MS(i)})}putCipherAdmin(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("PUT","/ciphers/"+e+"/admin",t,!0,!0);return new MS(i)})}deleteCipher(e){return this.send("DELETE","/ciphers/"+e,null,!0,!1)}deleteCipherAdmin(e){return this.send("DELETE","/ciphers/"+e+"/admin",null,!0,!1)}deleteManyCiphers(e){return this.send("DELETE","/ciphers",e,!0,!1)}deleteManyCiphersAdmin(e){return this.send("DELETE","/ciphers/admin",e,!0,!1)}putMoveCiphers(e){return this.send("PUT","/ciphers/move",e,!0,!1)}putShareCipher(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("PUT","/ciphers/"+e+"/share",t,!0,!0);return new MS(i)})}putShareCiphers(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/ciphers/share",e,!0,!0);return new Tc(t,MS)})}putCipherCollections(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("PUT","/ciphers/"+e+"/collections_v2",t,!0,!0);return new HS(i)})}putCipherCollectionsAdmin(e,t){return this.send("PUT","/ciphers/"+e+"/collections-admin",t,!0,!0)}postPurgeCiphers(e,t=null){let i="/ciphers/purge";return null!=t&&(i+="?organizationId="+t),this.send("POST",i,e,!0,!1)}putDeleteCipher(e){return this.send("PUT","/ciphers/"+e+"/delete",null,!0,!1)}putDeleteCipherAdmin(e){return this.send("PUT","/ciphers/"+e+"/delete-admin",null,!0,!1)}putDeleteManyCiphers(e){return this.send("PUT","/ciphers/delete",e,!0,!1)}putDeleteManyCiphersAdmin(e){return this.send("PUT","/ciphers/delete-admin",e,!0,!1)}putRestoreCipher(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/ciphers/"+e+"/restore",null,!0,!0);return new MS(t)})}putRestoreCipherAdmin(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/ciphers/"+e+"/restore-admin",null,!0,!0);return new MS(t)})}putRestoreManyCiphers(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/ciphers/restore",e,!0,!0);return new Tc(t,MS)})}putRestoreManyCiphersAdmin(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/ciphers/restore-admin",e,!0,!0);return new Tc(t,MS)})}getAttachmentData(e,t,i){return GS(this,void 0,void 0,function*(){const r=(null!=i?"/emergency-access/"+i+"/":"/ciphers/")+e+"/attachment/"+t,n=yield this.send("GET",r,null,!0,!0);return new LS(n)})}getAttachmentDataAdmin(e,t){return GS(this,void 0,void 0,function*(){const i="/ciphers/"+e+"/attachment/"+t+"/admin",r=yield this.send("GET",i,null,!0,!0);return new LS(r)})}postCipherAttachment(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("POST","/ciphers/"+e+"/attachment/v2",t,!0,!0);return new KS(i)})}deleteCipherAttachment(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("DELETE","/ciphers/"+e+"/attachment/"+t,null,!0,!0);return new WS(i)})}deleteCipherAttachmentAdmin(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("DELETE","/ciphers/"+e+"/attachment/"+t+"/admin",null,!0,!0);return new WS(i)})}postShareCipherAttachment(e,t,i,r){return this.send("POST","/ciphers/"+e+"/attachment/"+t+"/share?organizationId="+r,i,!0,!1)}renewAttachmentUploadUrl(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("GET","/ciphers/"+e+"/attachment/"+t+"/renew",null,!0,!0);return new KS(i)})}postAttachmentFile(e,t,i){return this.send("POST","/ciphers/"+e+"/attachment/"+t,i,!0,!1)}getCollectionAccessDetails(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("GET","/organizations/"+e+"/collections/"+t+"/details",null,!0,!0);return new $t(i)})}getUserCollections(){return GS(this,void 0,void 0,function*(){const e=yield this.send("GET","/collections",null,!0,!0);return new Tc(e,Mt)})}getCollections(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/organizations/"+e+"/collections",null,!0,!0);return new Tc(t,Mt)})}getManyCollectionsWithAccessDetails(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/organizations/"+e+"/collections/details",null,!0,!0);return new Tc(t,$t)})}getCollectionUsers(e,t){return GS(this,void 0,void 0,function*(){return(yield this.send("GET","/organizations/"+e+"/collections/"+t+"/users",null,!0,!0)).map(e=>new Bt(e))})}postCollection(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("POST","/organizations/"+e+"/collections",t,!0,!0);return new $t(i)})}putCollection(e,t,i){return GS(this,void 0,void 0,function*(){const r=yield this.send("PUT","/organizations/"+e+"/collections/"+t,i,!0,!0);return new $t(r)})}deleteCollection(e,t){return this.send("DELETE","/organizations/"+e+"/collections/"+t,null,!0,!1)}deleteManyCollections(e,t){return this.send("DELETE","/organizations/"+e+"/collections",new Gk(t),!0,!1)}getGroupUsers(e,t){return GS(this,void 0,void 0,function*(){return yield this.send("GET","/organizations/"+e+"/groups/"+t+"/users",null,!0,!0)})}deleteGroupUser(e,t,i){return this.send("DELETE","/organizations/"+e+"/groups/"+t+"/user/"+i,null,!0,!1)}getPlans(){return GS(this,void 0,void 0,function*(){const e=yield this.send("GET","/plans",null,!1,!0);return new Tc(e,fS)})}getSettingsDomains(){return GS(this,void 0,void 0,function*(){const e=yield this.send("GET","/settings/domains",null,!0,!0);return new CS(e)})}putSettingsDomains(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("PUT","/settings/domains",e,!0,!0);return new CS(t)})}getSync(){return GS(this,void 0,void 0,function*(){const e=this.platformUtilsService.supportsAutofill()?"/sync":"/sync?excludeDomains=true",t=yield this.send("GET",e,null,!0,!0);return new $S(t)})}getCloudCommunicationsEnabled(){return GS(this,void 0,void 0,function*(){return yield this.send("GET","/organizations/connections/enabled",null,!0,!0)})}getOrganizationConnection(e,t,i){return GS(this,void 0,void 0,function*(){const r=yield this.send("GET",`/organizations/connections/${e}/${t}`,null,!0,!0);return new Qk(r,i)})}createOrganizationConnection(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("POST","/organizations/connections/",e,!0,!0);return new Qk(i,t)})}updateOrganizationConnection(e,t,i){return GS(this,void 0,void 0,function*(){const r=yield this.send("PUT","/organizations/connections/"+i,e,!0,!0);return new Qk(r,t)})}deleteOrganizationConnection(e){return GS(this,void 0,void 0,function*(){return this.send("DELETE","/organizations/connections/"+e,null,!0,!1)})}getProviderUsers(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/providers/"+e+"/users",null,!0,!0);return new Tc(t,rS)})}getProviderUser(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("GET","/providers/"+e+"/users/"+t,null,!0,!0);return new iS(i)})}postProviderUserInvite(e,t){return this.send("POST","/providers/"+e+"/users/invite",t,!0,!1)}postProviderUserReinvite(e,t){return this.send("POST","/providers/"+e+"/users/"+t+"/reinvite",null,!0,!1)}postManyProviderUserReinvite(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("POST","/providers/"+e+"/users/reinvite",t,!0,!0);return new Tc(i,tS)})}postProviderUserBulkConfirm(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("POST","/providers/"+e+"/users/confirm",t,!0,!0);return new Tc(i,tS)})}deleteManyProviderUsers(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("DELETE","/providers/"+e+"/users",t,!0,!0);return new Tc(i,tS)})}postProviderUserAccept(e,t,i){return this.send("POST","/providers/"+e+"/users/"+t+"/accept",i,!0,!1)}postProviderUserConfirm(e,t,i){return this.send("POST","/providers/"+e+"/users/"+t+"/confirm",i,!0,!1)}postProviderUsersPublicKey(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("POST","/providers/"+e+"/users/public-keys",t,!0,!0);return new Tc(i,eS)})}putProviderUser(e,t,i){return this.send("PUT","/providers/"+e+"/users/"+t,i,!0,!1)}deleteProviderUser(e,t){return this.send("DELETE","/providers/"+e+"/users/"+t,null,!0,!1)}getProviderClients(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/providers/"+e+"/organizations",null,!0,!0);return new Tc(t,Zk)})}postProviderAddOrganization(e,t){return this.send("POST","/providers/"+e+"/organizations/add",t,!0,!1)}postProviderCreateOrganization(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.send("POST","/providers/"+e+"/organizations",t,!0,!0);return new Xk(i)})}deleteProviderOrganization(e,t){return this.send("DELETE","/providers/"+e+"/organizations/"+t,null,!0,!1)}getEvents(e,t,i){return GS(this,void 0,void 0,function*(){const r=yield this.send("GET",this.addEventParameters("/events",e,t,i),null,!0,!0);return new Tc(r,IS)})}getEventsCipher(e,t,i,r){return GS(this,void 0,void 0,function*(){const n=yield this.send("GET",this.addEventParameters("/ciphers/"+e+"/events",t,i,r),null,!0,!0);return new Tc(n,IS)})}getEventsSecret(e,t,i,r,n){return GS(this,void 0,void 0,function*(){const a=yield this.send("GET",this.addEventParameters("/organization/"+e+"/secrets/"+t+"/events",i,r,n),null,!0,!0);return new Tc(a,IS)})}getEventsServiceAccount(e,t,i,r,n){return GS(this,void 0,void 0,function*(){const a=yield this.send("GET",this.addEventParameters("/organization/"+e+"/service-account/"+t+"/events",i,r,n),null,!0,!0);return new Tc(a,IS)})}getEventsProject(e,t,i,r,n){return GS(this,void 0,void 0,function*(){const a=yield this.send("GET",this.addEventParameters("/organization/"+e+"/projects/"+t+"/events",i,r,n),null,!0,!0);return new Tc(a,IS)})}getEventsOrganization(e,t,i,r){return GS(this,void 0,void 0,function*(){const n=yield this.send("GET",this.addEventParameters("/organizations/"+e+"/events",t,i,r),null,!0,!0);return new Tc(n,IS)})}getEventsOrganizationUser(e,t,i,r,n){return GS(this,void 0,void 0,function*(){const a=yield this.send("GET",this.addEventParameters("/organizations/"+e+"/users/"+t+"/events",i,r,n),null,!0,!0);return new Tc(a,IS)})}getEventsProvider(e,t,i,r){return GS(this,void 0,void 0,function*(){const n=yield this.send("GET",this.addEventParameters("/providers/"+e+"/events",t,i,r),null,!0,!0);return new Tc(n,IS)})}getEventsProviderUser(e,t,i,r,n){return GS(this,void 0,void 0,function*(){const a=yield this.send("GET",this.addEventParameters("/providers/"+e+"/users/"+t+"/events",i,r,n),null,!0,!0);return new Tc(a,IS)})}postEventsCollect(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.tokenService.getAccessToken(t),r=new Headers({"Device-Type":this.deviceType,Authorization:"Bearer "+i,"Content-Type":"application/json; charset=utf-8"});null!=this.customUserAgent&&r.set("User-Agent",this.customUserAgent);const n=yield Ce(null==t?this.environmentService.environment$:this.environmentService.getEnvironment$(t));if(200!==(yield this.fetch(this.httpOperations.createRequest(n.getEventsUrl()+"/collect",{cache:"no-store",credentials:yield this.getCredentials(n),method:"POST",body:JSON.stringify(e),headers:r}))).status)return Promise.reject("Event post failed.")})}getUserPublicKey(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/users/"+e+"/public-key",null,!0,!0);return new ES(t)})}postBitPayInvoice(e){return GS(this,void 0,void 0,function*(){return yield this.send("POST","/bitpay-invoice",e,!0,!0)})}postSetupPayment(){return GS(this,void 0,void 0,function*(){return yield this.send("POST","/setup-payment",null,!0,!0)})}getMasterKeyFromKeyConnector(e){return GS(this,void 0,void 0,function*(){const t=yield this.getActiveUser();if(null==t)throw new Error("No active user, cannot get master key from key connector.");const i=yield this.getActiveBearerToken(t),r=yield this.fetch(this.httpOperations.createRequest(e+"/user-keys",{cache:"no-store",method:"GET",headers:new Headers({Accept:"application/json",Authorization:"Bearer "+i})}));if(r.status!==lh.Ok){const e=yield this.handleApiRequestError(r,!0);return Promise.reject(e)}return new aS(yield r.json())})}postUserKeyToKeyConnector(e,t){return GS(this,void 0,void 0,function*(){const i=yield this.getActiveUser();if(null==i)throw new Error("No active user, cannot post key to key connector.");const r=yield this.getActiveBearerToken(i),n=yield this.fetch(this.httpOperations.createRequest(e+"/user-keys",{cache:"no-store",method:"POST",headers:new Headers({Accept:"application/json",Authorization:"Bearer "+r,"Content-Type":"application/json; charset=utf-8"}),body:JSON.stringify(t)}));if(n.status!==lh.Ok){const e=yield this.handleApiRequestError(n,!0);return Promise.reject(e)}})}getKeyConnectorAlive(e){return GS(this,void 0,void 0,function*(){const t=yield this.fetch(this.httpOperations.createRequest(e+"/alive",{cache:"no-store",method:"GET",headers:new Headers({Accept:"application/json","Content-Type":"application/json; charset=utf-8"})}));if(t.status!==lh.Ok){const e=yield this.handleApiRequestError(t,!0);return Promise.reject(e)}})}getActiveBearerToken(e){return GS(this,void 0,void 0,function*(){let t=yield this.tokenService.getAccessToken(e);return(yield this.tokenService.tokenNeedsRefresh(e))&&(t=yield this.refreshToken(e)),t})}fetch(e){return GS(this,void 0,void 0,function*(){if(!e.url.startsWith("https://")&&!this.platformUtilsService.isDev())throw new rb;"GET"===e.method&&(e.headers.set("Cache-Control","no-store"),e.headers.set("Pragma","no-cache")),e.headers.set("Bitwarden-Client-Name",this.platformUtilsService.getClientType()),e.headers.set("Bitwarden-Client-Version",yield this.platformUtilsService.getApplicationVersionNumber());const t=yield this.platformUtilsService.packageType();return null!=t&&e.headers.set("Bitwarden-Package-Type",t),this.nativeFetch(e)})}nativeFetch(e){return fetch(e)}preValidateSso(e){return GS(this,void 0,void 0,function*(){if(null==e||""===e)throw new Error("Organization Identifier was not provided.");const t=new Headers({Accept:"application/json","Device-Type":this.deviceType});null!=this.customUserAgent&&t.set("User-Agent",this.customUserAgent);const i=yield Ce(this.environmentService.environment$),r=`/sso/prevalidate?domainHint=${encodeURIComponent(e)}`,n=yield this.fetch(this.httpOperations.createRequest(i.getIdentityUrl()+r,{cache:"no-store",credentials:yield this.getCredentials(i),headers:t,method:"GET"}));if(200===n.status){const e=yield n.json();return new oS(e)}{const e=yield this.handleApiRequestError(n,!1);return Promise.reject(e)}})}postCreateSponsorship(e,t){return GS(this,void 0,void 0,function*(){return yield this.send("POST","/organization/sponsorship/"+(this.platformUtilsService.isSelfHost()?"self-hosted/":"")+e+"/families-for-enterprise",t,!0,!1)})}getSponsorshipSyncStatus(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("GET","/organization/sponsorship/"+e+"/sync-status",null,!0,!0);return new Jk(t)})}deleteRemoveSponsorship(e){return GS(this,void 0,void 0,function*(){return yield this.send("DELETE","/organization/sponsorship/sponsored/"+e,null,!0,!1)})}postPreValidateSponsorshipToken(e){return GS(this,void 0,void 0,function*(){const t=yield this.send("POST","/organization/sponsorship/validate-token?sponsorshipToken="+encodeURIComponent(e),null,!0,!0);return new Yk(t)})}postRedeemSponsorship(e,t){return GS(this,void 0,void 0,function*(){return yield this.send("POST","/organization/sponsorship/redeem?sponsorshipToken="+encodeURIComponent(e),t,!0,!1)})}refreshToken(e){return void 0===this.refreshTokenPromise[e]&&(this.refreshTokenPromise[e]=this.internalRefreshToken(e),this.refreshTokenPromise[e].finally(()=>{delete this.refreshTokenPromise[e]})),this.refreshTokenPromise[e]}internalRefreshToken(e){return GS(this,void 0,void 0,function*(){const t=yield this.tokenService.getRefreshToken(e);if(null!=t&&""!==t)return yield this.refreshAccessToken(e);const i=yield this.tokenService.getClientId(e),r=yield this.tokenService.getClientSecret(e);if(!Tt.isNullOrWhitespace(i)&&!Tt.isNullOrWhitespace(r))return yield this.refreshApiToken(e);throw this.refreshAccessTokenErrorCallback(),new Error("Cannot refresh access token, no refresh token or api keys are stored.")})}refreshAccessToken(e){return GS(this,void 0,void 0,function*(){const t=yield this.tokenService.getRefreshToken(e);if(null==t||""===t)throw new Error;const i=new Headers({"Content-Type":"application/x-www-form-urlencoded; charset=utf-8",Accept:"application/json","Device-Type":this.deviceType});null!=this.customUserAgent&&i.set("User-Agent",this.customUserAgent);const r=yield Ce(this.environmentService.getEnvironment$(e)),n=yield this.tokenService.decodeAccessToken(e),a=yield this.fetch(this.httpOperations.createRequest(r.getIdentityUrl()+"/connect/token",{body:this.qsStringify({grant_type:"refresh_token",client_id:n.client_id,refresh_token:t}),cache:"no-store",credentials:yield this.getCredentials(r),headers:i,method:"POST"}));if(200===a.status){const e=yield a.json(),t=new eh(e),i=(yield this.tokenService.decodeAccessToken(t.accessToken)).sub,r=yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutActionByUserId$(i)),n=yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutByUserId$(i));return(yield this.tokenService.setTokens(t.accessToken,r,n,t.refreshToken)).accessToken}{const e=yield this.handleTokenRefreshRequestError(a);return Promise.reject(e)}})}refreshApiToken(e){return GS(this,void 0,void 0,function*(){const t=yield this.tokenService.getClientId(e),i=yield this.tokenService.getClientSecret(e),r=yield this.appIdService.getAppId(),n=new Ud(r,this.platformUtilsService),a=new mh(t,i,new hu,n),s=yield this.postIdentityToken(a);if(!(s instanceof eh))throw new Error("Invalid response received when refreshing api token");const o=yield this.tokenService.decodeAccessToken(s.accessToken);if(o.sub!==e)throw new Error(`Token was supposed to be refreshed for ${e} but the token we got back was for ${o.sub}`);const l=yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutActionByUserId$(e)),c=yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutByUserId$(e));return yield this.tokenService.setAccessToken(s.accessToken,l,c)})}send(e,t,i,r,n,a,s){return GS(this,void 0,void 0,function*(){const o=yield this.getUserIdMakingRequest(r),l=yield Ce(null==o?this.environmentService.environment$:this.environmentService.getEnvironment$(o));a=Tt.isNullOrWhitespace(a)?l.getApiUrl():a;const c=yield this.buildSafeApiRequestUrl(a,t);let u=yield this.buildRequest(e,o,l,n,i,s),d=yield this.fetch(this.httpOperations.createRequest(c,u));n&&null!=o&&d.status===lh.Unauthorized&&(this.logService.warning("Unauthorized response received for request to "+t+". Attempting request again."),u=yield this.buildRequest(e,o,l,n,i,s),d=yield this.fetch(this.httpOperations.createRequest(c,u)));const h=d.headers.get("content-type"),p=null!=h&&-1!==h.indexOf("application/json"),m=null!=h&&-1!==h.indexOf("text/csv");if(n&&d.status===lh.Ok&&p)return yield d.json();if(n&&d.status===lh.Ok&&m)return yield d.text();if(d.status!==lh.Ok&&d.status!==lh.NoContent){const e=yield this.handleApiRequestError(d,null!=o);return Promise.reject(e)}})}buildSafeApiRequestUrl(e,t){const i=t.split("?"),r=e+i[0]+(i.length>1?`?${i[1]}`:"");if(Tt.invalidUrlPatterns(r))throw new Error("The request URL contains dangerous patterns.");return e+Tt.normalizePath(i[0])+(i.length>1?`?${i[1]}`:"")}getUserIdMakingRequest(e){return GS(this,void 0,void 0,function*(){if(null==e)throw new Error("A user id was given but it was null, cannot complete API request.");let t=null;return"boolean"==typeof e&&e?t=yield this.getActiveUser():"string"==typeof e&&(t=e),t})}buildRequest(e,t,i,r,n,a){return GS(this,void 0,void 0,function*(){const[s,o]=yield this.buildHeadersAndBody(t,r,n,a),l={cache:"no-store",credentials:yield this.getCredentials(i),method:e};return l.headers=s,l.body=o,l})}buildHeadersAndBody(e,t,i,r){return GS(this,void 0,void 0,function*(){let n=null;const a=new Headers({"Device-Type":this.deviceType});if(of("prereleaseBuild")&&a.set("Is-Prerelease","1"),null!=this.customUserAgent&&a.set("User-Agent",this.customUserAgent),t&&a.set("Accept","application/json"),null!=r&&r(a),null!=e){const t=yield this.getActiveBearerToken(e);a.set("Authorization","Bearer "+t)}else{const e=yield this.appIdService.getAppId();a.set("Device-Identifier",e)}return null!=i&&("string"==typeof i?(n=i,a.set("Content-Type","application/x-www-form-urlencoded; charset=utf-8")):"object"==typeof i&&(i instanceof FormData?n=i:(a.set("Content-Type","application/json; charset=utf-8"),n=JSON.stringify(i)))),[a,n]})}handleApiRequestError(e,t){return GS(this,void 0,void 0,function*(){!t||e.status!==lh.Unauthorized&&e.status!==lh.Forbidden||(yield this.logoutCallback("invalidAccessToken"));const i=yield this.getJsonResponse(e);return new Su(i,e.status)})}handleTokenRefreshRequestError(e){return GS(this,void 0,void 0,function*(){const t=yield this.getJsonResponse(e);return e.status===lh.BadRequest&&"invalid_grant"===(null==t?void 0:t.error)&&(yield this.logoutCallback("sessionExpired")),new Su(t,e.status,!0)})}getJsonResponse(e){return GS(this,void 0,void 0,function*(){let t=null;return this.isJsonResponse(e)?t=yield e.json():this.isTextPlainResponse(e)&&(t={Message:yield e.text()}),t})}qsStringify(e){return Object.keys(e).map(t=>encodeURIComponent(t)+"="+encodeURIComponent(e[t])).join("&")}getActiveUser(){return GS(this,void 0,void 0,function*(){return yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id)))})}getCredentials(e){return GS(this,void 0,void 0,function*(){if(this.platformUtilsService.getClientType()!==Ku.Web||e.hasBaseUrl())return"include"})}addEventParameters(e,t,i,r){return null!=t&&(e+="?start="+t),null!=i&&(e+=e.indexOf("?")>-1?"&":"?",e+="end="+i),null!=r&&(e+=e.indexOf("?")>-1?"&":"?",e+="continuationToken="+r),e}isJsonResponse(e){const t=e.headers.get("content-type");return null!=t&&t.indexOf("application/json")>-1}isTextPlainResponse(e){const t=e.headers.get("content-type");return null!=t&&t.indexOf("text/plain")>-1}}QS.NEW_DEVICE_VERIFICATION_REQUIRED_MESSAGE="new device verification required";var JS=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class YS{constructor(e,t,i,r=100){this.cryptoFunctionService=e,this.apiService=t,this.hibpApiService=i,this.maxConcurrent=r,this.passwordLeakedSubject=new H,this.maxConcurrent=r,this.passwordLeakedSubject.pipe(de(e=>JS(this,void 0,void 0,function*(){try{const t=yield this.fetchLeakedPasswordCount(e.password);e.resolve(t)}catch(t){e.reject(t)}}),this.maxConcurrent)).subscribe()}passwordLeaked(e){return JS(this,void 0,void 0,function*(){return new Promise((t,i)=>{this.passwordLeakedSubject.next({password:e,resolve:t,reject:i})})})}fetchLeakedPasswordCount(e){return JS(this,void 0,void 0,function*(){const t=yield this.cryptoFunctionService.hash(e,"sha1"),i=Tt.fromBufferToHex(t).toUpperCase(),r=i.substr(0,5),n=i.substr(5),a=yield this.apiService.nativeFetch(new Request("https://api.pwnedpasswords.com/range/"+r)),s=(yield a.text()).split(/\r?\n/).find(e=>e.split(":")[0]===n);return null!=s?parseInt(s.split(":")[1],10):0})}breachedAccounts(e){return JS(this,void 0,void 0,function*(){return this.hibpApiService.getHibpBreach(e)})}}function XS(){for(var e=[],t=0;tZS.fromJSON(e),clearOn:["logout"]});var t_=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class i_{constructor(e,t,i,r,n,a){this.cipherService=e,this.stateProvider=t,this.organizationService=i,this.eventUploadService=r,this.authService=n,this.accountService=a,this.getOrgIds=e=>{var t,i;return null!==(i=null===(t=null==e?void 0:e.filter(e=>e.useEvents))||void 0===t?void 0:t.map(e=>e.id))&&void 0!==i?i:[]}}collectMany(e,t){return t_(this,arguments,void 0,function*(e,t,i=!1){const r=yield Ce(tu(this.accountService.activeAccount$)),n=this.stateProvider.getUser(r,e_);if(!(yield this.shouldUpdate(r,null,e,t)))return;const a=this.organizationService.organizations$(r).pipe(X(e=>this.getOrgIds(e)),X(i=>t.filter(e=>i.includes(e.organizationId)).map(t=>({type:e,cipherId:t.id,date:(new Date).toISOString(),organizationId:t.organizationId}))));yield n.update((e,t)=>[...null!=e?e:[],...t],{combineLatestWith:a}),i&&(yield this.eventUploadService.uploadEvents())})}collect(e){return t_(this,arguments,void 0,function*(e,t=null,i=!1,r=null){const n=yield Ce(tu(this.accountService.activeAccount$)),a=this.stateProvider.getUser(n,e_);if(!(yield this.shouldUpdate(n,r,e,void 0,t)))return;const s=new ZS;s.type=e,s.cipherId=t,s.date=(new Date).toISOString(),s.organizationId=r,yield a.update(e=>((e=null!=e?e:[]).push(s),e)),i&&(yield this.eventUploadService.uploadEvents())})}shouldUpdate(e){return t_(this,arguments,void 0,function*(e,t=null,i=null,r=[],n){const a=Se(this.cipherService.get(n,e)),s=this.organizationService.organizations$(e).pipe(X(e=>this.getOrgIds(e))),[o,l,c]=yield Ce(XS(this.authService.activeAccountStatus$,s,a));return o==cu.Unlocked&&(null!=l&&0!=l.length&&(i==oh.User_ClientExportedVault||(null!=c&&r.push(new lw(c)),(null!=r&&0!=r.length||null!=t)&&(null!=r&&r.length>0?r.filter(e=>l.includes(e.organizationId)).length>0:!(null!=t&&!l.includes(t))))))})}}class r_{}var n_=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class a_{constructor(e,t,i,r,n){this.apiService=e,this.stateProvider=t,this.logService=i,this.authService=r,this.taskSchedulerService=n,this.inited=!1,this.taskSchedulerService.registerTaskHandler(Pu,()=>this.uploadEvents())}init(e){this.inited||(this.inited=!0,e&&(this.uploadEvents(),this.taskSchedulerService.setInterval(Pu,6e4)))}uploadEvents(e){return n_(this,void 0,void 0,function*(){if(e||(e=yield Ce(this.stateProvider.activeUserId$)),!e)return;if(!(yield Ce(this.authService.authStatusFor$(e).pipe(X(e=>e===cu.Unlocked)))))return;const t=yield this.takeEvents(e);if(null==t||0===t.length)return;const i=t.map(e=>{const t=new r_;return t.type=e.type,t.cipherId=e.cipherId,t.date=e.date,t.organizationId=e.organizationId,t});try{yield this.apiService.postEventsCollect(i,e)}catch(i){this.logService.error(i),yield this.stateProvider.setUserState(e_,t,e)}})}takeEvents(e){return n_(this,void 0,void 0,function*(){let t=null;return yield this.stateProvider.getUser(e,e_).update(e=>(t=null!=e?e:[],[])),t})}}var s_,o_={connector:function(){return new H}};function l_(e,t){void 0===t&&(t=o_);var i=t.connector;return Q(function(t,r){var n,a=i();le(e((n=a,new $(function(e){return n.subscribe(e)})))).subscribe(r),r.add(t.subscribe(a))})}function c_(e){return Q(function(t,i){var r=!1,n=0;t.subscribe(J(i,function(t){return(r||(r=!e(t,n++)))&&i.next(t)}))})}!function(e){e.NEXT="N",e.ERROR="E",e.COMPLETE="C"}(s_||(s_={}));var u_=function(){function e(e,t,i){this.kind=e,this.value=t,this.error=i,this.hasValue="N"===e}return e.prototype.observe=function(e){return d_(this,e)},e.prototype.do=function(e,t,i){var r=this,n=r.kind,a=r.value,s=r.error;return"N"===n?null==e?void 0:e(a):"E"===n?null==t?void 0:t(s):null==i?void 0:i()},e.prototype.accept=function(e,t,i){var r;return h(null===(r=e)||void 0===r?void 0:r.next)?this.observe(e):this.do(e,t,i)},e.prototype.toObservable=function(){var e=this,t=e.kind,i=e.value,r=e.error,n="N"===t?bt(i):"E"===t?tc(function(){return r}):"C"===t?pe:0;if(!n)throw new TypeError("Unexpected notification kind "+t);return n},e.createNext=function(t){return new e("N",t)},e.createError=function(t){return new e("E",void 0,t)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e("C"),e}();function d_(e,t){var i,r,n,a=e,s=a.kind,o=a.value,l=a.error;if("string"!=typeof s)throw new TypeError('Invalid notification, missing "kind"');"N"===s?null===(i=t.next)||void 0===i||i.call(t,o):"E"===s?null===(r=t.error)||void 0===r||r.call(t,l):null===(n=t.complete)||void 0===n||n.call(t)}function h_(){return Q(function(e,t){e.subscribe(J(t,function(e){t.next(u_.createNext(e))},function(){t.next(u_.createComplete()),t.complete()},function(e){t.next(u_.createError(e)),t.complete()}))})}function p_(){return Q(function(e,t){e.subscribe(J(t,function(e){return d_(e,t)}))})}function m_(e){return Q(function(t,i){le(e).subscribe(J(i,function(){return i.complete()},E)),!i.closed&&t.subscribe(i)})}function g_(){return Q(function(e,t){var i,r=!1;e.subscribe(J(t,function(e){var n=i;i=e,r&&t.next([n,e]),r=!0}))})}function f_(){for(var e=[],t=0;t=2;return function(r){return r.pipe(e?Ie(function(t,i){return e(t,i,r)}):B,ci(1),i?y_(t):ak(function(){return new xe}))}}function b_(e){return e}function w_(e,t){return{expectedValue:e,actualValue:t}}function k_(e=b_,t=w_){return M(wb(null),g_(),X(([i,r],n)=>{if(0===n)return r;const a=e(i),s=e(r);if(a===s)return r;throw t(a,s)}))}function S_(e,t){return X(i=>(null!=i?i:[]).reduce(e,structuredClone(t)))}function __(){return Zl((e,t)=>{let i=!0;for(const r in t)i&&(i=e[r]===t[r]);return i})}function x_(e){return Array.isArray(e)?function(){for(var e=[],t=0;t!!e).map(e=>e.pipe(ui(),f_(!0)))):e.pipe(ui(),f_(!0))}function C_(...e){return l_(t=>{const i=new Ht(1);t.subscribe(i);const r=e.map(e=>{const t=new Ht(1);return e.subscribe(t),t});return li(XS(r).pipe(v_(),ui()),i).pipe(iy(...r),m_(x_(i)))})}class I_{}const E_=Object.freeze({padding:"0",divider:"|",hasInvalidPadding:/[^0]/});class z_ extends I_{constructor(e){super(),this.frameSize=e}pack(e){const t=JSON.stringify(e),i=Tt.fromUtf8ToB64(t),r=JSON.stringify(this.frameSize),n=2*E_.divider.length,a=i.length+r.length+n,s=this.frameSize-a%this.frameSize;return`${r}|${i}|${E_.padding.repeat(s)}`}unpack(e){const t=e.indexOf(E_.divider);if(t<1)throw new Error("missing frame size");const i=parseInt(e.slice(0,t),10),r=t+1;if(e.length%i>0)throw new Error("invalid length");const n=e.lastIndexOf(E_.divider);if(n==t)throw new Error("missing json object");const a=n+1;if(e.slice(a).match(E_.hasInvalidPadding))throw new Error("invalid padding");const s=e.slice(r,n),o=Tt.fromB64ToUtf8(s);return JSON.parse(o)}}class P_{}var A_=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class j_ extends P_{constructor(e,t,i,r){super(),this.organizationId=e,this.encryptService=t,this.key=i,this.dataPacker=r,this.assertHasValue("organizationId",e),this.assertHasValue("key",i),this.assertHasValue("dataPacker",r),this.assertHasValue("encryptService",t)}encrypt(e){return A_(this,void 0,void 0,function*(){this.assertHasValue("secret",e);let t=this.dataPacker.pack(e);const i=yield this.encryptService.encryptString(t,this.key);return t=null,i})}decrypt(e){return A_(this,void 0,void 0,function*(){this.assertHasValue("secret",e);let t=yield this.encryptService.decryptString(e,this.key);const i=this.dataPacker.unpack(t);return t=null,i})}assertHasValue(e,t){if(null==t)throw new Error(`${e} cannot be null or undefined`)}}class T_{}var D_=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class O_ extends T_{constructor(e,t,i,r){super(),this.userId=e,this.encryptService=t,this.key=i,this.dataPacker=r,this.assertHasValue("userId",e),this.assertHasValue("key",i),this.assertHasValue("dataPacker",r),this.assertHasValue("encryptService",t)}encrypt(e){return D_(this,void 0,void 0,function*(){this.assertHasValue("secret",e);let t=this.dataPacker.pack(e);const i=yield this.encryptService.encryptString(t,this.key);return t=null,i})}decrypt(e){return D_(this,void 0,void 0,function*(){this.assertHasValue("secret",e);let t=yield this.encryptService.decryptString(e,this.key);const i=this.dataPacker.unpack(t);return t=null,i})}assertHasValue(e,t){if(null==t)throw new Error(`${e} cannot be null or undefined`)}}class N_{constructor(e,t){this.encryptService=e,this.keyService=t}userEncryptor$(e,t){const i=new z_(e);return t.singleUserId$.pipe(k_(e=>e,(e,t)=>({expectedUserId:e,actualUserId:t})),l_(e=>{const t=new Ht(1);return e.subscribe(t),t.pipe(Le(e=>this.keyService.userKey$(e).pipe(c_(e=>!e),nk(e=>!!e),X(t=>{const r=new O_(e,this.encryptService,t,i);return{userId:e,encryptor:r}}),h_())),p_(),m_(x_(t)))}))}organizationEncryptor$(e,t){const i=new z_(e);return t.singleOrganizationId$.pipe(k_(e=>e.userId,(e,t)=>({expectedUserId:e,actualUserId:t})),k_(e=>e.organizationId,(e,t)=>({expectedOrganizationId:e,actualOrganizationId:t})),l_(e=>{const t=new Ht(1);return e.subscribe(t),t.pipe(Le(e=>this.keyService.orgKeys$(e.userId).pipe(c_(e=>!e),nk(e=>!!e),X(t=>{const r=e.organizationId,n=t[r];return{organizationId:r,encryptor:new j_(r,this.encryptService,n,i)}}),h_())),p_(),m_(x_(t)))}))}}const R_=Object.freeze({forwarder:"forwarder"}),U_=Object.freeze({token:"token",baseUrl:"baseUrl",domain:"domain",prefix:"prefix"}),F_=Object.freeze({default:"default",none:"none",allow:"allow",deny:"deny"}),q_=Object.freeze(Object.keys(R_)),L_=Object.freeze(Object.keys(U_)),B_={[R_.forwarder]:{id:R_.forwarder,availableFields:[U_.baseUrl,U_.domain,U_.prefix,U_.token]}},M_=Object.freeze(Object.values(F_));function V_(e){const t=Reflect.ownKeys(e);for(const i of t){const t=e[i];t&&"object"==typeof t&&V_(t)}return Object.freeze(e)}class $_{constructor(e,t){this.site=e,this.extensions=t,V_(this)}}class K_{constructor(e,t){this.allowedSites=e,this.allowedFields=t,this.allPermission="default",this.siteRegistrations=new Map,this.sitePermissions=new Map,this.vendorRegistrations=new Map,this.vendorPermissions=new Map,this.extensionRegistrations=new Array,this.extensionsBySiteByVendor=new Map,Object.freeze(this.allowedFields),Object.freeze(this.allowedSites)}registerSite(e){if(!this.allowedSites.includes(e.id))return this;const t=e.availableFields.filter(e=>this.allowedFields.includes(e)),i=V_({id:e.id,availableFields:t});return this.siteRegistrations.has(e.id)||this.siteRegistrations.set(e.id,i),this}site(e){return this.siteRegistrations.get(e)}sites(){const e=[];for(const[t,i]of this.siteRegistrations.entries()){const r={site:i},n=this.sitePermissions.get(t);n&&(r.permission=n),e.push(r)}return e}registerVendor(e){if(!this.vendorRegistrations.has(e.id)){const t=V_(e);this.vendorRegistrations.set(e.id,t)}return this}vendor(e){return this.vendorRegistrations.get(e)}vendors(){const e=[];for(const[t,i]of this.vendorRegistrations.entries()){const r={vendor:i},n=this.vendorPermissions.get(t);n&&(r.permission=n),e.push(r)}return e}setPermission(e,t){if(!M_.includes(t))throw new Error(`invalid extension permission: ${t}`);if("all"in e&&e.all)this.allPermission=t;else if("vendor"in e)this.vendorPermissions.set(e.vendor,t);else{if(!("site"in e))throw new Error(`Unrecognized extension set received: ${JSON.stringify(e)}.`);this.allowedSites.includes(e.site)&&this.sitePermissions.set(e.site,t)}return this}permission(e){return"all"in e&&e.all?this.allPermission:"vendor"in e?this.vendorPermissions.get(e.vendor):"site"in e?this.sitePermissions.get(e.site):void 0}permissions(){const e=[];e.push({set:{all:!0},permission:this.allPermission});for(const[t,i]of this.sitePermissions.entries())e.push({set:{site:t},permission:i});for(const[t,i]of this.vendorPermissions.entries())e.push({set:{vendor:t},permission:i});return e}registerExtension(e){var t;const i=this.siteRegistrations.get(e.site.id),r=this.vendorRegistrations.get(e.product.vendor.id);if(!i||!r)return this;const n=null!==(t=this.extensionsBySiteByVendor.get(e.site.id))&&void 0!==t?t:new Map;if(n.has(e.product.vendor.id))return this;const a={vendor:r};e.product.name&&(a.name=e.product.name);const s=Object.freeze({site:i,product:Object.freeze(a),host:Object.freeze(Object.assign({},e.host)),requestedFields:Object.freeze([...e.requestedFields])}),o=this.extensionRegistrations.push(s)-1;return n.set(r.id,o),this.extensionsBySiteByVendor.set(i.id,n),this}extension(e,t){var i,r;const n=null!==(r=null===(i=this.extensionsBySiteByVendor.get(e))||void 0===i?void 0:i.get(t))&&void 0!==r?r:-1;return n<0?void 0:this.extensionRegistrations[n]}getPermissions(e,t){return[this.sitePermissions.get(e),this.vendorPermissions.get(t),this.allPermission].filter(e=>!!e)}extensions(){const e=[];for(const t of this.extensionRegistrations){const i=this.getPermissions(t.site.id,t.product.vendor.id);e.push({extension:t,permissions:i})}return e}build(e){var t,i;const r=this.siteRegistrations.get(e);if(!r)return;if("deny"===this.allPermission)return new $_(r,new Map);const n=new Map,a=null!==(i=null===(t=this.extensionsBySiteByVendor.get(e))||void 0===t?void 0:t.entries())&&void 0!==i?i:[];for(const[t,i]of a){const r=W_(this.getPermissions(e,t),this.extensionRegistrations[i]);r&&n.set(t,r)}return new $_(r,n)}}function W_(e,t){if(!e.includes("deny")){if(e.includes("allow"))return t;if(!e.includes("none")){if(e.includes("default"))return t;throw new Error("failed to recognize any permissions")}}}const H_=Object.freeze({addyio:"addyio",bitwarden:"bitwarden",duckduckgo:"duckduckgo",fastmail:"fastmail",forwardemail:"forwardemail",mozilla:"mozilla",simplelogin:"simplelogin"}),G_={id:H_.addyio,name:"Addy.io"},Q_=[{site:B_.forwarder,product:{vendor:G_},host:{authorization:"bearer",selfHost:"maybe",baseUrl:"https://app.addy.io"},requestedFields:[U_.token,U_.baseUrl,U_.domain]}],J_=Object.freeze({id:H_.bitwarden,name:"Bitwarden"}),Y_={id:H_.duckduckgo,name:"DuckDuckGo"},X_=[{site:B_.forwarder,product:{vendor:Y_},host:{authorization:"bearer",selfHost:"never",baseUrl:"https://quack.duckduckgo.com/api"},requestedFields:[U_.token]}],Z_={id:H_.fastmail,name:"Fastmail"},ex=[{site:B_.forwarder,product:{vendor:Z_},host:{authorization:"bearer",selfHost:"maybe",baseUrl:"https://api.fastmail.com"},requestedFields:[U_.token]}],tx={id:H_.forwardemail,name:"Forward Email"},ix=[{site:B_.forwarder,product:{vendor:tx},host:{authorization:"basic-username",selfHost:"never",baseUrl:"https://api.forwardemail.net"},requestedFields:[U_.domain,U_.token]}],rx={id:H_.mozilla,name:"Mozilla"},nx=[{site:B_.forwarder,product:{vendor:rx,name:"Firefox Relay"},host:{authorization:"token",selfHost:"never",baseUrl:"https://relay.firefox.com/api"},requestedFields:[U_.token]}],ax={id:H_.simplelogin,name:"SimpleLogin"},sx=[{site:B_.forwarder,product:{vendor:ax},host:{authentication:!0,selfHost:"maybe",baseUrl:"https://app.simplelogin.io"},requestedFields:[U_.baseUrl,U_.token,U_.domain]}],ox=V_([G_,J_,Y_,Z_,tx,rx,ax]),lx=V_([Q_,X_,ex,ix,nx,sx].flat());var cx=o(6404),ux=o.n(cx);class dx{getPasswordStrength(e,t=null,i=null){if(null==e||0===e.length)return null;const r=["bitwarden","bit","warden",...null!=i?i:[],...this.emailToUserInputs(t)],n=Array.from(new Set(r));return ux()(e,n)}emailToUserInputs(e){if(null==e||0===e.length)return[];const t=e.indexOf("@");return t<0?[]:e.substring(0,t).trim().toLowerCase().split(/[^A-Za-z0-9]/)}}function hx(e,t){return Q(function(e,t,i){return function(r,n){var a=i,s=t,o=0;r.subscribe(J(n,function(t){var i=o++;s=a?e(s,t,i):(a=!0,t),n.next(s)},undefined))}}(e,t,arguments.length>=2))}function px(e){return!!e&&"id"in e&&"secret"in e&&"disclosed"in e&&"string"==typeof e.secret&&"object"==typeof e.disclosed}const mx=new Proxy(Object.freeze({}),{get:()=>({})});class gx{constructor(){this.constraints=mx}calibrate(){return this}adjust(e){return e}fix(e){return e}}function fx(e){return e&&"calibrate"in e}var yx=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const vx="$^$ALWAYS_UPDATE_KLUDGE_PROPERTY$^$";class bx extends ${constructor(e,t,i){var r,n,a;super(),this.key=e,this.providers=t,this.context=i,this.input=new Ht(1),this.output=new Ht(1),this.counter=0,function(e){return"object"===e.target&&"format"in e&&"classifier"in e}(this.key)?(this.objectKey=this.key,this.stateKey=function(e){if("plain"===e.format)return new wi(e.state,e.key,e.options);if("classified"===e.format)return new wi(e.state,e.key,{cleanupDelayMs:e.options.cleanupDelayMs,deserializer:e=>e,clearOn:e.options.clearOn});if("secret-state"===e.format)return new wi(e.state,e.key,{cleanupDelayMs:e.options.cleanupDelayMs,deserializer:e=>e,clearOn:e.options.clearOn});throw new Error(`unknown format: ${e.format}`)}(this.key)):(this.objectKey=null,this.stateKey=this.key),this.log=this.providers.log({contextId:this.contextId,type:"UserStateSubject",storage:{state:this.stateKey.stateDefinition.name,key:this.stateKey.key}});const s=(null!==(r=this.context.when$)&&void 0!==r?r:new $c(!0)).pipe(Zl()),o=i.account$.pipe(M((null==(c={name:()=>`${this.contextId} { account$ }`,distinct:(e,t)=>e.id===t.id})?void 0:c.distinct)?Zl(c.distinct):e=>e,X((e,t)=>{var i,r;if(t>0)throw new Error(`${null!==(r=null===(i=null==c?void 0:c.name)||void 0===i?void 0:i.call(c))&&void 0!==r?r:"unknown"} observable should only emit one value.`);return e})),Jt({refCount:!0,bufferSize:1}));var c;const u=this.encryptor(o),d=(null!==(n=this.context.constraints$)&&void 0!==n?n:function(){const e=new gx;return new $c(e)}()).pipe(Hu(e=>(this.log.error(e,"constraints$ dependency failed; using last-known constraints"),pe)),Jt({refCount:!0,bufferSize:1})),h=(null!==(a=this.context.dependencies$)&&void 0!==a?a:new $c(null)).pipe(Jt({refCount:!0,bufferSize:1})),p=o.pipe(ac(e=>this.log.debug({accountId:e.id},"loading user state")),X(e=>this.providers.state.getUser(e.id,this.stateKey)),Jt({refCount:!0,bufferSize:1}));this.outputSubscription=p.pipe(Le(e=>e.state$),X(e=>(e&&"object"==typeof e&&vx in e&&delete e[vx],e)),this.declassify(u),this.adjust(Gc(d)),m_(x_(o))).subscribe(this.output);const m=new Ht(1);this.output.pipe(function(e,t){var i=arguments.length>=2;return function(r){return r.pipe(e?Ie(function(t,i){return e(t,i,r)}):B,Q(function(e,t){var i=[];e.subscribe(J(t,function(e){i.push(e),1e.state)).subscribe(m);const g=li(this.input.pipe(this.when(s),this.adjust(C_(d)),this.prepareUpdate(this,h)),m.pipe(this.fix(d),this.prepareUpdate(m,h)));this.inputSubscription=g.pipe(this.classify(u),iy(p),m_(x_([s,this.input,u]))).subscribe({next:([e,t])=>this.onNext(e,t),error:e=>this.onError(e),complete:()=>this.onComplete()})}get contextId(){return`UserStateSubject(${this.stateKey.stateDefinition.name}, ${this.stateKey.key})`}encryptor(e){var t,i;const r=e.pipe(X(e=>e.id)),n=null!==(i=null===(t=this.objectKey)||void 0===t?void 0:t.frame)&&void 0!==i?i:32;return this.providers.encryptor.userEncryptor$(n,{singleUserId$:r}).pipe(ac(()=>this.log.debug("encryptor constructed")),X(({encryptor:e})=>e),Jt({refCount:!0,bufferSize:1}))}when(e){return M(Gc(e.pipe(Zl())),ac(([e,t])=>this.log.debug({when:t},"when status")),Ie(([e,t])=>!!t),X(([e])=>e))}prepareUpdate(e,t){return i=>li(e.pipe(v_(),X(e=>[e,null])),i.pipe(X(e=>e.state),iy(t))).pipe(hx(([e],[t,i])=>{var r,n,a,s,o,l;return null===(a=null===(n=(r=this.context).shouldUpdate)||void 0===n?void 0:n.call(r,e,t,i))||void 0===a||a?[null!==(l=null===(o=(s=this.context).nextValue)||void 0===o?void 0:o.call(s,e,t,i))&&void 0!==l?l:t,i]:(this.log.debug("shouldUpdate prevented write"),[e,null])}),Ie(function(e,t){return 1<=t}),X(([e])=>e),Zl())}adjust(e){return M(e,X(([e,t])=>{var i;if(!e&&!(null===(i=this.objectKey)||void 0===i?void 0:i.initial))return this.log.debug("no value; bypassing adjustment"),{constraints:{},state:null};this.log.debug("adjusting");const r=null!=e?e:structuredClone(this.objectKey.initial),n=fx(t)?t.calibrate(r):t,a=n.adjust(r);return this.log.debug("adjusted"),{constraints:n.constraints,state:a}}))}fix(e){return M(Gc(e),X(([e,t])=>{this.log.debug("fixing");const i=fx(t)?t.calibrate(e):t,r=i.fix(e);return this.log.debug("fixed"),{constraints:i.constraints,state:r}}))}declassify(e){return this.objectKey&&"plain"!==this.objectKey.format?M(this.mapToClassifiedFormat(),Gc(e),gc(e=>yx(this,[e],void 0,function*([e,t]){if(null==e)return this.log.debug("no value; bypassing declassification"),null;this.log.debug("declassifying");const{secret:i,disclosed:r}=e,n=Nt.fromJSON(i),a=yield t.decrypt(n),s=this.objectKey.classifier.declassify(r,a),o=this.objectKey.options.deserializer(s);return this.log.debug("declassified"),o}))):(this.log.debug("key uses plain format; bypassing declassification"),e=>e)}mapToClassifiedFormat(){return this.objectKey&&"classified"===this.objectKey.format?X(e=>px(e)?e:(this.log.warn("classified data must be in classified format; dropping"),null)):this.objectKey&&"secret-state"===this.objectKey.format?X(e=>{if(!Array.isArray(e))return this.log.warn("secret-state requires array formatting; dropping"),null;const[t]=e;return px(t)?t:(this.log.warn("unwrapped secret-state must be in classified format; dropping"),null)}):void this.log.panic({format:this.objectKey.format},"unsupported serialization format")}classify(e){return this.objectKey&&"plain"!==this.objectKey.format?M(C_(e),gc(e=>yx(this,[e],void 0,function*([e,t]){if(null==e)return this.log.debug("no value; bypassing classification"),null;this.log.debug("classifying");const i=JSON.parse(JSON.stringify(e)),r=this.objectKey.classifier.classify(i),n=yield t.encrypt(r.secret),a={id:null,secret:JSON.parse(JSON.stringify(n)),disclosed:r.disclosed};return this.log.debug("classified"),a})),this.mapToStorageFormat()):(this.log.debug("key uses plain format; bypassing classification"),M(function(e){const t=Array.isArray(e)?e:[e];return M(l_(e=>{const i=new Ht(1);return e.subscribe(i),li(XS(t).pipe(v_(),ui()),i).pipe(m_(x_(i)))}))}(e),X(e=>e)))}mapToStorageFormat(){return this.objectKey&&"classified"===this.objectKey.format?X(e=>e):this.objectKey&&"secret-state"===this.objectKey.format?X(e=>[e]):void this.log.panic({format:this.objectKey.format},"unsupported serialization format")}next(e){var t;null===(t=this.input)||void 0===t||t.next(e)}error(e){var t;null===(t=this.input)||void 0===t||t.error(e)}complete(){var e;null===(e=this.input)||void 0===e||e.complete()}subscribe(e){return this.output.pipe(X(e=>e.state),Zl()).subscribe(e)}get withConstraints$(){return this.output.asObservable()}onNext(e,t){t.update(()=>{if(this.log.debug("updating"),"object"==typeof e){const t=this.counter++;t>Number.MAX_SAFE_INTEGER&&(this.counter=0),Object.assign({},e)[vx]=t}return this.log.debug("updated"),e}).catch(e=>{this.log.error(e,"updating failed"),this.onError(e)})}onError(e){this.isDisposed||(this.log.debug(e,"forwarding error to subscribers"),this.output.error(e)),this.dispose()}onComplete(){this.isDisposed||this.output.complete(),this.dispose()}get isDisposed(){return null===this.input}dispose(){var e,t;this.isDisposed||(this.log.debug("disposing"),null===(e=this.inputSubscription)||void 0===e||e.unsubscribe(),null===(t=this.outputSubscription)||void 0===t||t.unsubscribe(),this.inputSubscription=null,this.outputSubscription=null,this.input=null,this.log.debug("disposed"))}}class wx{constructor(e=void 0){this.keys=e}classify(e){var t;const i=JSON.parse(JSON.stringify(e)),r=null!==(t=this.keys)&&void 0!==t?t:Object.keys(i),n={};for(const e of r)n[e]=i[e];return{disclosed:null,secret:n}}declassify(e,t){var i;const r={},n=null!==(i=this.keys)&&void 0!==i?i:Object.keys(t);for(const e of n)r[e]=t[e];return r}}class kx{constructor(e,t){this.registry=e,this.providers=t,this.log=t.log({type:"ExtensionService"})}settings(e,t,i){const r=this.registry.extension(e.site,t);r||this.log.panic({site:e.site,vendor:t},"extension not defined");const n=function(e,t){const i=new wx;return Object.assign(Object.assign({},e.storage),{target:"object",key:`${t.site.id}.${t.product.vendor.id}.${e.storage.key}`,state:lr,classifier:i,format:"classified"})}(e,r),a=i.account$.pipe(Jt({bufferSize:1,refCount:!0}));return new bx(n,this.providers,{account$:a})}site(e){return this.registry.build(e)}}class Sx{constructor(e,t,i=()=>Date.now()){this.logger=e,this.now=i,this.context=t&&"object"==typeof t?t:{}}debug(e,i){this.log(e,t.Debug,i)}info(e,i){this.log(e,t.Info,i)}warn(e,i){this.log(e,t.Warning,i)}error(e,i){this.log(e,t.Error,i)}panic(e,i){throw this.log(e,t.Error,i),new Error(null!=i?i:"string"==typeof e?e:"a fatal error occurred")}log(e,t,i){const r=Object.assign(Object.assign({},this.context),{message:i,content:null!=e?e:void 0,level:_x(t),"@timestamp":this.now()});"string"!=typeof e||i||(r.message=e,delete r.content),this.logger.write(t,r)}}function _x(e){switch(e){case t.Debug:return"debug";case t.Info:return"information";case t.Warning:return"warning";case t.Error:return"error";default:return`${e}`}}const xx=V_({debug(e,t){},info(e,t){},warn(e,t){},error(e,t){},panic(e,t){throw"string"!=typeof e||t?new Error(t):new Error(e)}});function Cx(e,t,i){e.warning({method:t,context:i,provider:"tools/log",message:"Semantic logging enabled. 🦟 Please report this bug if you see it 🦟"})}function Ix(e){return xx}class Ex{constructor(e){this.id=null,this.size=null,this.sizeName=null,this.fileName=null,e&&(this.id=e.id,this.size=e.size,this.sizeName=e.sizeName)}get fileSize(){try{if(null!=this.size)return parseInt(this.size,null)}catch(e){}return 0}static fromJSON(e){return null==e?null:Object.assign(new Ex,e)}}class zx{constructor(e){this.text=null,e&&(this.hidden=e.hidden)}get maskedText(){return null!=this.text?"••••••••":null}static fromJSON(e){return null==e?null:Object.assign(new zx,e)}}class Px{constructor(e){this.id=null,this.accessId=null,this.name=null,this.notes=null,this.type=null,this.text=new zx,this.file=new Ex,this.maxAccessCount=null,this.accessCount=0,this.revisionDate=null,this.deletionDate=null,this.expirationDate=null,this.password=null,this.emails=[],this.disabled=!1,this.hideEmail=!1,this.authType=null,e&&(this.id=e.id,this.accessId=e.accessId,this.type=e.type,this.authType=e.authType,this.maxAccessCount=e.maxAccessCount,this.accessCount=e.accessCount,this.revisionDate=e.revisionDate,this.deletionDate=e.deletionDate,this.expirationDate=e.expirationDate,this.disabled=e.disabled,this.password=e.password,this.hideEmail=e.hideEmail,this.authType=e.authType)}get urlB64Key(){return Tt.fromBufferToUrlB64(this.key)}get maxAccessCountReached(){return null!=this.maxAccessCount&&this.accessCount>=this.maxAccessCount}get expired(){return null!=this.expirationDate&&this.expirationDate<=new Date}get pendingDelete(){return this.deletionDate<=new Date}toJSON(){return Tt.merge(Object.assign({},this),{key:Tt.fromBufferToB64(this.key)})}static fromJSON(e){return null==e?null:Object.assign(new Px,e,{key:Tt.fromB64ToArray(e.key),cryptoKey:gu.fromJSON(e.cryptoKey),text:zx.fromJSON(e.text),file:Ex.fromJSON(e.file),revisionDate:null==e.revisionDate?null:new Date(e.revisionDate),deletionDate:null==e.deletionDate?null:new Date(e.deletionDate),expirationDate:null==e.expirationDate?null:new Date(e.expirationDate)})}}class Ax extends Rt{constructor(e){super(),null!=e&&(this.size=e.size,this.buildDomainModel(this,e,{id:null,sizeName:null,fileName:null},["id","sizeName"]))}decrypt(e){return t=this,i=void 0,n=function*(){return yield this.decryptObj(this,new Ex(this),["fileName"],e)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}static fromJSON(e){return null==e?null:Object.assign(new Ax,e,{fileName:Nt.fromJSON(e.fileName)})}}class jx extends Rt{constructor(e){super(),null!=e&&(this.hidden=e.hidden,this.buildDomainModel(this,e,{text:null},[]))}decrypt(e){return this.decryptObj(this,new zx(this),["text"],e)}static fromJSON(e){return null==e?null:Object.assign(new jx,e,{text:Nt.fromJSON(e.text)})}}class Tx extends Rt{constructor(e){if(super(),null!=e)switch(this.buildDomainModel(this,e,{id:null,accessId:null,name:null,notes:null,key:null},["id","accessId"]),this.type=e.type,this.authType=e.authType,this.maxAccessCount=e.maxAccessCount,this.accessCount=e.accessCount,this.password=e.password,this.disabled=e.disabled,this.revisionDate=null!=e.revisionDate?new Date(e.revisionDate):null,this.deletionDate=null!=e.deletionDate?new Date(e.deletionDate):null,this.expirationDate=null!=e.expirationDate?new Date(e.expirationDate):null,this.hideEmail=e.hideEmail,this.authType=e.authType,this.emails=e.emails,this.type){case Nk.Text:this.text=new jx(e.text);break;case Nk.File:this.file=new Ax(e.file)}}decrypt(e){return t=this,i=void 0,n=function*(){if(!e)throw new Error("User ID must not be null or undefined");const t=new Px(this),i=Tt.getContainerService().getKeyService(),r=Tt.getContainerService().getEncryptService(),n=yield Ce(i.userKey$(e));switch(t.key=yield r.decryptBytes(this.key,n),t.cryptoKey=yield i.makeSendKey(t.key),t.name=null!=this.name?yield r.decryptString(this.name,t.cryptoKey):null,t.notes=null!=this.notes?yield r.decryptString(this.notes,t.cryptoKey):null,null!=this.emails?t.emails=this.emails?this.emails.split(",").map(e=>e.trim()):[]:t.emails=[],this.type){case Nk.File:t.file=yield this.file.decrypt(t.cryptoKey);break;case Nk.Text:t.text=yield this.text.decrypt(t.cryptoKey)}return t},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}static fromJSON(e){if(null==e)return null;const t=null==e.revisionDate?null:new Date(e.revisionDate),i=null==e.expirationDate?null:new Date(e.expirationDate),r=null==e.deletionDate?null:new Date(e.deletionDate);return Object.assign(new Tx,e,{key:Nt.fromJSON(e.key),name:Nt.fromJSON(e.name),notes:Nt.fromJSON(e.notes),emails:e.emails,text:jx.fromJSON(e.text),file:Ax.fromJSON(e.file),revisionDate:t,expirationDate:i,deletionDate:r})}}class Dx{constructor(e,t){switch(this.type=e.type,this.fileLength=t,this.name=e.name?e.name.encryptedString:null,this.notes=e.notes?e.notes.encryptedString:null,this.maxAccessCount=e.maxAccessCount,this.expirationDate=null!=e.expirationDate?e.expirationDate.toISOString():null,this.deletionDate=null!=e.deletionDate?e.deletionDate.toISOString():null,this.key=null!=e.key?e.key.encryptedString:null,this.password=e.password,this.emails=e.emails,this.disabled=e.disabled,this.hideEmail=e.hideEmail,this.type){case Nk.Text:this.text=new AS,this.text.text=null!=e.text.text?e.text.text.encryptedString:null,this.text.hidden=e.text.hidden;break;case Nk.File:this.file=new PS,this.file.fileName=null!=e.file.fileName?e.file.fileName.encryptedString:null}}}class Ox extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.type=this.getResponseProperty("Type"),this.name=this.getResponseProperty("Name");const t=this.getResponseProperty("Text");null!=t&&(this.text=new AS(t));const i=this.getResponseProperty("File");null!=i&&(this.file=new PS(i)),this.expirationDate=this.getResponseProperty("ExpirationDate"),this.creatorIdentifier=this.getResponseProperty("CreatorIdentifier")}}class Nx extends Lt{constructor(e){super(e),this.id=null,this.url=null,this.id=this.getResponseProperty("Id"),this.url=this.getResponseProperty("Url")}}class Rx extends Lt{constructor(e){super(e),this.url=null,this.fileUploadType=this.getResponseProperty("FileUploadType");const t=this.getResponseProperty("SendResponse");this.sendResponse=null==t?null:new jS(t),this.url=this.getResponseProperty("Url")}}var Ux=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Fx{constructor(e,t,i){this.apiService=e,this.fileUploadService=t,this.sendService=i}getSend(e){return Ux(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET","/sends/"+e,null,!0,!0);return new jS(t)})}postSendAccess(e,t,i){return Ux(this,void 0,void 0,function*(){const r=yield this.apiService.send("POST","/sends/access/"+e,t,!1,!0,i,t=>{t.set("Send-Id",e)});return new Ox(r)})}postSendAccessV2(e,t){return Ux(this,void 0,void 0,function*(){const i=yield this.apiService.send("POST","/sends/access",null,!1,!0,t,t=>{t.set("Authorization","Bearer "+e.token)});return new Ox(i)})}getSendFileDownloadData(e,t,i){return Ux(this,void 0,void 0,function*(){const r=yield this.apiService.send("POST","/sends/"+e.id+"/access/file/"+e.file.id,t,!1,!0,i,t=>{t.set("Send-Id",e.id)});return new Nx(r)})}getSendFileDownloadDataV2(e,t,i){return Ux(this,void 0,void 0,function*(){const r=yield this.apiService.send("POST","/sends/access/file/"+e.file.id,null,!1,!0,i,e=>{e.set("Authorization","Bearer "+t.token)});return new Nx(r)})}getSends(){return Ux(this,void 0,void 0,function*(){const e=yield this.apiService.send("GET","/sends",null,!0,!0);return new Tc(e,jS)})}postSend(e){return Ux(this,void 0,void 0,function*(){const t=yield this.apiService.send("POST","/sends",e,!0,!0);return new jS(t)})}postFileTypeSend(e){return Ux(this,void 0,void 0,function*(){const t=yield this.apiService.send("POST","/sends/file/v2",e,!0,!0);return new Rx(t)})}renewSendFileUploadUrl(e,t){return Ux(this,void 0,void 0,function*(){const i=yield this.apiService.send("GET","/sends/"+e+"/file/"+t,null,!0,!0);return new Rx(i)})}postSendFile(e,t,i){return this.apiService.send("POST","/sends/"+e+"/file/"+t,i,!0,!1)}putSend(e,t){return Ux(this,void 0,void 0,function*(){const i=yield this.apiService.send("PUT","/sends/"+e,t,!0,!0);return new jS(i)})}putSendRemovePassword(e){return Ux(this,void 0,void 0,function*(){const t=yield this.apiService.send("PUT","/sends/"+e+"/remove-password",null,!0,!0);return new jS(t)})}deleteSend(e){return this.apiService.send("DELETE","/sends/"+e,null,!0,!1)}save(e){return Ux(this,void 0,void 0,function*(){const t=yield this.upload(e),i=new Fk(t);return yield this.sendService.upsert(i),new Tx(i)})}delete(e){return Ux(this,void 0,void 0,function*(){yield this.deleteSend(e),yield this.sendService.delete(e)})}removePassword(e){return Ux(this,void 0,void 0,function*(){const t=yield this.putSendRemovePassword(e),i=new Fk(t);yield this.sendService.upsert(i)})}upload(e){return Ux(this,void 0,void 0,function*(){var t;const i=new Dx(e[0],null===(t=e[1])||void 0===t?void 0:t.buffer.byteLength);let r;if(null==e[0].id){if(e[0].type===Nk.Text)r=yield this.postSend(i);else try{const t=yield this.postFileTypeSend(i);r=t.sendResponse,yield this.fileUploadService.upload(t,e[0].file.fileName,e[1],this.generateMethods(t,r))}catch(e){throw e instanceof Su?new Error(e.getSingleMessage()):e}e[0].id=r.id,e[0].accessId=r.accessId}else r=yield this.putSend(e[0].id,i);return r})}generateMethods(e,t){return{postDirect:this.generatePostDirectCallback(t),renewFileUploadUrl:this.generateRenewFileUploadUrlCallback(t.id,t.file.id),rollback:this.generateRollbackCallback(t.id)}}generatePostDirectCallback(e){return t=>this.postSendFile(e.id,e.file.id,t)}generateRenewFileUploadUrlCallback(e,t){return()=>Ux(this,void 0,void 0,function*(){const i=yield this.renewSendFileUploadUrl(e,t);return null==i?void 0:i.url})}generateRollbackCallback(e){return()=>this.deleteSend(e)}}const qx=wi.record(hr,"sendUserEncrypted",{deserializer:e=>e,clearOn:["logout"]}),Lx=new wi(pr,"sendUserDecrypted",{deserializer:e=>e,clearOn:["lock"]});var Bx=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Mx{constructor(e){this.stateProvider=e,this.activeUserEncryptedState=this.stateProvider.getActive(qx),this.encryptedState$=this.activeUserEncryptedState.combinedState$,this.activeUserDecryptedState=this.stateProvider.getActive(Lx),this.decryptedState$=this.activeUserDecryptedState.state$}getEncryptedSends(){return Bx(this,void 0,void 0,function*(){return yield Ce(this.encryptedState$)})}setEncryptedSends(e,t){return Bx(this,void 0,void 0,function*(){yield this.stateProvider.getUser(t,qx).update(()=>e)})}getDecryptedSends(){return Bx(this,void 0,void 0,function*(){return yield Ce(this.decryptedState$)})}setDecryptedSends(e){return Bx(this,void 0,void 0,function*(){yield this.activeUserDecryptedState.update(()=>e)})}}class Vx extends Dx{constructor(e){super(e),this.id=e.id}}var $x=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Kx{constructor(e,t,i,r,n,a,s){this.accountService=e,this.keyService=t,this.i18nService=i,this.keyGenerationService=r,this.stateProvider=n,this.encryptService=a,this.configService=s,this.sendKeySalt="bitwarden-send",this.sendKeyPurpose="send",this.sends$=this.stateProvider.encryptedState$.pipe(X(([,e])=>Object.values(e||{}).map(e=>new Tx(e)))),this.sendViews$=this.stateProvider.encryptedState$.pipe(gc(([e,t])=>this.decryptSends(Object.values(t||{}).map(e=>new Tx(e)),e)))}encrypt(e,t,i,r){return $x(this,void 0,void 0,function*(){var n,a;let s=null;const o=new Tx;if(o.id=e.id,o.type=e.type,o.disabled=e.disabled,o.hideEmail=e.hideEmail,o.maxAccessCount=e.maxAccessCount,o.deletionDate=e.deletionDate,o.expirationDate=e.expirationDate,null==e.key){const t=yield this.keyGenerationService.createKeyWithPurpose(128,this.sendKeyPurpose,this.sendKeySalt);e.key=t.material,e.cryptoKey=t.derivedKey}const l=yield this.configService.getFeatureFlag(Ne.SendEmailOTP),c=(null!==(a=null===(n=e.emails)||void 0===n?void 0:n.length)&&void 0!==a?a:0)>0;if(l&&c)o.emails=e.emails.map(e=>e.trim()).join(",").toLocaleLowerCase(),o.password=null;else if(o.emails=null,null!=i){const t=yield this.keyGenerationService.deriveKeyFromPassword(i,e.key,new Pd(1e5));o.password=t.keyB64}const u=(yield Ce(this.accountService.activeAccount$)).id;if(null==r&&(r=yield Ce(this.keyService.userKey$(u))),o.key=yield this.encryptService.encryptBytes(e.key,r),o.name=null!=e.name?yield this.encryptService.encryptString(e.name,e.cryptoKey):null,o.notes=null!=e.notes?yield this.encryptService.encryptString(e.notes,e.cryptoKey):null,o.type===Nk.Text)o.text=new jx,o.text.text=yield this.encryptService.encryptString(e.text.text,e.cryptoKey),o.text.hidden=e.text.hidden;else if(o.type===Nk.File&&(o.file=new Ax,null!=t))if(t instanceof ArrayBuffer){const[i,r]=yield this.encryptFileData(e.file.fileName,t,e.cryptoKey,u);o.file.fileName=i,s=r}else s=yield this.parseFile(o,t,e.cryptoKey,u);return o.authType=e.authType,[o,s]})}get$(e){return this.sends$.pipe(Zl((t,i)=>{const r=t.find(t=>t.id===e),n=i.find(t=>t.id===e);return!(!r||!n)&&Object.keys(n).every(e=>{if(null!=r[e]&&null===n[e]||null===r[e]&&null!=n[e])return!1;switch(e){case"name":case"notes":case"key":return null===r[e]&&null===n[e]||r[e].encryptedString===n[e].encryptedString;case"text":return null==r[e].text&&null==n[e].text||!(null!=r[e].text&&null==n[e].text||null==r[e].text&&null!=n[e].text)&&r[e].text.encryptedString===n[e].text.encryptedString;case"file":return!0;case"revisionDate":case"expirationDate":case"deletionDate":return null===r[e]&&null===n[e]||r[e].getTime()===n[e].getTime();default:return r[e]===n[e]}})}),X(t=>t.find(t=>t.id===e)))}getFromState(e){return $x(this,void 0,void 0,function*(){const[,t]=yield this.stateProvider.getEncryptedSends();return null!=t&&t.hasOwnProperty(e)?new Tx(t[e]):null})}getAll(){return $x(this,void 0,void 0,function*(){const[,e]=yield this.stateProvider.getEncryptedSends(),t=[];for(const i in e)e.hasOwnProperty(i)&&t.push(new Tx(e[i]));return t})}getAllDecryptedFromState(e){return $x(this,void 0,void 0,function*(){if(!e)throw new Error("User ID must not be null or undefined");let t=yield this.stateProvider.getDecryptedSends();if(null!=t)return t;if(t=[],!(yield this.keyService.hasUserKey(e)))throw new Error("No user key found.");const i=[];return(yield this.getAll()).forEach(r=>{i.push(r.decrypt(e).then(e=>t.push(e)))}),yield Promise.all(i),t.sort(Tt.getSortFunction(this.i18nService,"name")),yield this.stateProvider.setDecryptedSends(t),t})}upsert(e){return $x(this,void 0,void 0,function*(){const[t,i]=yield this.stateProvider.getEncryptedSends();let r=i;if(null==r&&(r={}),e instanceof Fk){const t=e;r[t.id]=t}else e.forEach(e=>{r[e.id]=e});yield this.replace(r,t)})}delete(e){return $x(this,void 0,void 0,function*(){const[t,i]=yield this.stateProvider.getEncryptedSends();if(null!=i){if("string"==typeof e){if(null==i[e])return;delete i[e]}else e.forEach(e=>{delete i[e]});yield this.replace(i,t)}})}replace(e,t){return $x(this,void 0,void 0,function*(){yield this.stateProvider.setEncryptedSends(e,t)})}getRotatedData(e,t,i){return $x(this,void 0,void 0,function*(){if(null==t)throw new Error("New user key is required for rotation.");if(null==e)throw new Error("Original user key is required for rotation.");return yield Ce(this.sends$.pipe(gc(i=>$x(this,void 0,void 0,function*(){return this.toRotatedKeyRequestMap(i,e,t)}))))})}toRotatedKeyRequestMap(e,t,i){return $x(this,void 0,void 0,function*(){return yield Promise.all(e.map(e=>$x(this,void 0,void 0,function*(){const r=yield this.encryptService.decryptBytes(e.key,t);return e.key=yield this.encryptService.encryptBytes(r,i),new Vx(e)})))})}parseFile(e,t,i,r){return new Promise((n,a)=>{const s=new FileReader;s.readAsArrayBuffer(t),s.onload=s=>$x(this,void 0,void 0,function*(){try{const[a,o]=yield this.encryptFileData(t.name,s.target.result,i,r);e.file.fileName=a,n(o)}catch(e){a(e)}}),s.onerror=()=>{a("Error reading file.")}})}encryptFileData(e,t,i,r){return $x(this,void 0,void 0,function*(){return null==i&&(i=yield Ce(this.keyService.userKey$(r))),[yield this.encryptService.encryptString(e,i),yield this.encryptService.encryptFileData(new Uint8Array(t),i)]})}decryptSends(e,t){return $x(this,void 0,void 0,function*(){const i=e.map(e=>e.decrypt(t)),r=yield Promise.all(i);return r.sort(Tt.getSortFunction(this.i18nService,"name")),r})}}function Wx(e,t=void 0){const i=new Map;return r=>{let n=i.get(r);return n||(null!=t||(t=pe),n=_e(e(r),t.pipe(Ie(e=>e===r||null===e),X(()=>null))).pipe(Jt({bufferSize:1,refCount:!1})),i.set(r,n)),n}}function Hx(){return Ie(e=>null!=e)}const Gx=wi.array(xr,"notifications",{deserializer:e=>ny.fromJSON(e),clearOn:["logout","lock"]});var Qx=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const Jx=X(e=>Object.entries(null!=e?e:{}).filter(([,e])=>e>=cu.Locked).map(([e])=>e));class Yx{constructor(e,t,i,r,n){this.stateProvider=e,this.apiService=t,this.notificationService=i,this.authService=r,this.logService=n,this.notifications$=Wx(e=>this.notificationState(e).state$.pipe(Le(t=>Qx(this,void 0,void 0,function*(){return null==t?(yield this.fetchNotificationsFromApi(e),null):t})),Hx(),X(e=>e.map(e=>new ry(e))))),this.unreadNotifications$=Wx(e=>this.notifications$(e).pipe(X(e=>e.filter(e=>null==e.readDate))))}markAsRead(e,t){return Qx(this,void 0,void 0,function*(){yield this.apiService.send("PATCH",`/notifications/${e}/read`,null,!0,!1),yield this.notificationState(t).update(t=>{const i=null==t?void 0:t.find(t=>t.id===e);return i&&(i.readDate=new Date),t})})}markAsDeleted(e,t){return Qx(this,void 0,void 0,function*(){yield this.apiService.send("DELETE",`/notifications/${e}/delete`,null,!0,!1),yield this.notificationState(t).update(t=>{const i=null==t?void 0:t.find(t=>t.id===e);return i&&(i.deletedDate=new Date),t})})}clearState(e){return Qx(this,void 0,void 0,function*(){yield this.replaceNotificationState(e,[])})}refreshNotifications(e){return Qx(this,void 0,void 0,function*(){yield this.fetchNotificationsFromApi(e)})}filteredEndUserNotifications$(e){return 0==e.length?pe:this.notificationService.notifications$.pipe(Ie(([{type:t},i])=>(t===dh.Notification||t===dh.NotificationStatus)&&e.includes(i)))}listenForEndUserNotifications(){return this.authService.authStatuses$.pipe(Jx,Le(e=>this.filteredEndUserNotifications$(e)),gc(([e,t])=>this.upsertNotification(t,new ny(e.payload)))).subscribe()}fetchNotificationsFromApi(e){return Qx(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET","/notifications?pageSize=50",null,!0,!0),i=new Tc(t,ay);null!=i.continuationToken&&this.logService.warning("More notifications available, but not fetched. Consider increasing the page size from 50");const r=i.data.map(e=>new ny(e));yield this.replaceNotificationState(e,r)})}replaceNotificationState(e,t){return this.notificationState(e).update(()=>t)}upsertNotification(e,t){return Qx(this,void 0,void 0,function*(){return this.notificationState(e).update(e=>{null!=e||(e=[]);const i=e.findIndex(e=>e.id===t.id);return-1===i?e.push(t):e[i]=t,e})})}notificationState(e){return this.stateProvider.getUser(e,Gx)}}class Xx{constructor(e,t,i){this.collectionService=e,this.organizationService=t,this.accountService=i,this.organization$=e=>this.accountService.activeAccount$.pipe(tu,Le(e=>this.organizationService.organizations$(e)),X(t=>t.find(t=>t.id===e.organizationId)))}canDeleteCipher$(e,t){return this.organization$(e).pipe(X(i=>{var r;if(t){if(!e.collectionIds||0===e.collectionIds.length)return!0===(null==i?void 0:i.canEditUnassignedCiphers);if(null==i?void 0:i.canEditAllCiphers)return!0}return!!(null===(r=e.permissions)||void 0===r?void 0:r.delete)}))}canRestoreCipher$(e,t){return this.organization$(e).pipe(X(i=>{var r;if(t){if(!e.collectionIds||0===e.collectionIds.length)return!0===(null==i?void 0:i.canEditUnassignedCiphers);if(null==i?void 0:i.canEditAllCiphers)return!0}return!!(null===(r=e.permissions)||void 0===r?void 0:r.restore)}))}canEditCipher$(e,t=!1){return this.organization$(e).pipe(X(i=>{if(t){if(!e.collectionIds||0===e.collectionIds.length)return!0===(null==i?void 0:i.canEditUnassignedCiphers);if(null==i?void 0:i.canEditAllCiphers)return!0}return!!e.edit}))}canCloneCipher$(e,t){return null==e.organizationId?bt(!0):ai([this.organization$(e),this.accountService.activeAccount$.pipe(tu)]).pipe(Le(([i,r])=>{var n;return t&&i&&(i.isAdmin||(null===(n=i.permissions)||void 0===n?void 0:n.editAnyCollection))?bt(!0):this.collectionService.decryptedCollections$(r).pipe((e=>{const t=new Set(e);return X(e=>e.filter(e=>e.id&&t.has(e.id)))})(e.collectionIds.map(Kg)),X(e=>e.some(e=>e.manage)))}),Jt({bufferSize:1,refCount:!1}))}}var Zx,eC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})},tC=function(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},iC=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===n)return n=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(a).then(e,function(t){return i(t),e()})}else n|=1}catch(e){i(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});class rC{constructor(e,t){this.sdkService=e,this.logService=t}createWithServer(e,t,i){return eC(this,void 0,void 0,function*(){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const r={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const n=tC(r,t.take(),!1),a=e.toSdkCreateCipherRequest();let s;return s=i?yield n.value.vault().ciphers().admin().create(a):yield n.value.vault().ciphers().create(a),lw.fromSdkCipherView(s)}catch(e){r.error=e,r.hasError=!0}finally{iC(r)}})),Hu(e=>{throw this.logService.error(`Failed to create cipher: ${e}`),e})))})}updateWithServer(e,t,i,r){return eC(this,void 0,void 0,function*(){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const n={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const a=tC(n,t.take(),!1),s=e.toSdkUpdateCipherRequest();let o;return o=r?yield a.value.vault().ciphers().admin().edit(s,(null==i?void 0:i.toSdkCipherView())||(new lw).toSdkCipherView()):yield a.value.vault().ciphers().edit(s),lw.fromSdkCipherView(o)}catch(e){n.error=e,n.hasError=!0}finally{iC(n)}})),Hu(e=>{throw this.logService.error(`Failed to update cipher: ${e}`),e})))})}deleteWithServer(e,t){return eC(this,arguments,void 0,function*(e,t,i=!1){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const r={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const n=tC(r,t.take(),!1);i?yield n.value.vault().ciphers().admin().delete($g(e)):yield n.value.vault().ciphers().delete($g(e))}catch(e){r.error=e,r.hasError=!0}finally{iC(r)}})),Hu(e=>{throw this.logService.error(`Failed to delete cipher: ${e}`),e})))})}deleteManyWithServer(e,t){return eC(this,arguments,void 0,function*(e,t,i=!1,r){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const n={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const a=tC(n,t.take(),!1);if(i){if(null==r)throw new Error("Organization ID is required for admin delete.");yield a.value.vault().ciphers().admin().delete_many(e.map(e=>$g(e)),$g(r))}else yield a.value.vault().ciphers().delete_many(e.map(e=>$g(e)))}catch(e){n.error=e,n.hasError=!0}finally{iC(n)}})),Hu(e=>{throw this.logService.error(`Failed to delete multiple ciphers: ${e}`),e})))})}softDeleteWithServer(e,t){return eC(this,arguments,void 0,function*(e,t,i=!1){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const r={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const n=tC(r,t.take(),!1);i?yield n.value.vault().ciphers().admin().soft_delete($g(e)):yield n.value.vault().ciphers().soft_delete($g(e))}catch(e){r.error=e,r.hasError=!0}finally{iC(r)}})),Hu(e=>{throw this.logService.error(`Failed to soft delete cipher: ${e}`),e})))})}softDeleteManyWithServer(e,t){return eC(this,arguments,void 0,function*(e,t,i=!1,r){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const n={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const a=tC(n,t.take(),!1);if(i){if(null==r)throw new Error("Organization ID is required for admin soft delete.");yield a.value.vault().ciphers().admin().soft_delete_many(e.map(e=>$g(e)),$g(r))}else yield a.value.vault().ciphers().soft_delete_many(e.map(e=>$g(e)))}catch(e){n.error=e,n.hasError=!0}finally{iC(n)}})),Hu(e=>{throw this.logService.error(`Failed to soft delete multiple ciphers: ${e}`),e})))})}restoreWithServer(e,t){return eC(this,arguments,void 0,function*(e,t,i=!1){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const r={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const n=tC(r,t.take(),!1);i?yield n.value.vault().ciphers().admin().restore($g(e)):yield n.value.vault().ciphers().restore($g(e))}catch(e){r.error=e,r.hasError=!0}finally{iC(r)}})),Hu(e=>{throw this.logService.error(`Failed to restore cipher: ${e}`),e})))})}restoreManyWithServer(e,t,i){return eC(this,void 0,void 0,function*(){return yield Ce(this.sdkService.userClient$(t).pipe(Le(t=>eC(this,void 0,void 0,function*(){const r={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const n=tC(r,t.take(),!1);i?yield n.value.vault().ciphers().admin().restore_many(e.map(e=>$g(e)),$g(i)):yield n.value.vault().ciphers().restore_many(e.map(e=>$g(e)))}catch(e){r.error=e,r.hasError=!0}finally{iC(r)}})),Hu(e=>{throw this.logService.error(`Failed to restore multiple ciphers: ${e}`),e})))})}}class nC{constructor(e){this.comparator=e,this.sortedCiphersByUrl=new Map,this.timeouts=new Map}isCached(e){return this.sortedCiphersByUrl.has(e)}addCiphers(e,t){t.sort(this.comparator),this.sortedCiphersByUrl.set(e,new aC(t)),this.resetTimer(e)}getLastUsed(e){return this.resetTimer(e),this.isCached(e)?this.sortedCiphersByUrl.get(e).getLastUsed():null}getLastLaunched(e){return this.isCached(e)?this.sortedCiphersByUrl.get(e).getLastLaunched():null}getNext(e){return this.resetTimer(e),this.isCached(e)?this.sortedCiphersByUrl.get(e).getNext():null}updateLastUsedIndex(e){this.isCached(e)&&this.sortedCiphersByUrl.get(e).updateLastUsedIndex()}clear(){this.sortedCiphersByUrl.clear(),this.timeouts.clear()}resetTimer(e){clearTimeout(this.timeouts.get(e)),this.timeouts.set(e,setTimeout(()=>{this.sortedCiphersByUrl.delete(e),this.timeouts.delete(e)},3e3))}}class aC{constructor(e){this.ciphers=e,this.lastUsedIndex=-1}getLastUsed(){return this.lastUsedIndex=Math.max(this.lastUsedIndex,0),this.ciphers[this.lastUsedIndex]}getLastLaunched(){const e=this.ciphers.filter(e=>{var t;return null===(t=e.localData)||void 0===t?void 0:t.lastLaunched});return e.sort((e,t)=>t.localData.lastLaunched.valueOf()-e.localData.lastLaunched.valueOf())[0]}getNextIndex(){return(this.lastUsedIndex+1)%this.ciphers.length}getNext(){return this.ciphers[this.getNextIndex()]}updateLastUsedIndex(){this.lastUsedIndex=this.getNextIndex()}}class sC{constructor(e,t){this.ids=null==e?[]:e,this.organizationId=t}}class oC{constructor(e,t){this.ids=null==e?[]:e,this.folderId=t}}class lC{constructor(e,t){this.ids=null==e?[]:e,this.organizationId=t}}class cC{}class uC{constructor({cipher:e,encryptedFor:t}){var i,r,n;switch(this.type=e.type,this.encryptedFor=t,this.folderId=e.folderId,this.organizationId=e.organizationId,this.name=e.name?e.name.encryptedString:null,this.notes=e.notes?e.notes.encryptedString:null,this.favorite=e.favorite,this.lastKnownRevisionDate=e.revisionDate,this.archivedDate=e.archivedDate,this.reprompt=e.reprompt,this.key=null===(i=e.key)||void 0===i?void 0:i.encryptedString,this.type){case rm.Login:this.login=new US,this.login.uris=null!==(n=null===(r=e.login.uris)||void 0===r?void 0:r.map(e=>{const t=new RS;return t.uri=null!=e.uri?e.uri.encryptedString:null,t.match=null!=e.match?e.match:null,t.uriChecksum=null!=e.uriChecksum?e.uriChecksum.encryptedString:null,t}))&&void 0!==n?n:[],this.login.username=e.login.username?e.login.username.encryptedString:null,this.login.password=e.login.password?e.login.password.encryptedString:null,this.login.passwordRevisionDate=null!=e.login.passwordRevisionDate?e.login.passwordRevisionDate.toISOString():null,this.login.totp=e.login.totp?e.login.totp.encryptedString:null,this.login.autofillOnPageLoad=e.login.autofillOnPageLoad,null!=e.login.fido2Credentials&&(this.login.fido2Credentials=e.login.fido2Credentials.map(e=>{const t=new NS;return t.credentialId=null!=e.credentialId?e.credentialId.encryptedString:null,t.keyType=null!=e.keyType?e.keyType.encryptedString:null,t.keyAlgorithm=null!=e.keyAlgorithm?e.keyAlgorithm.encryptedString:null,t.keyCurve=null!=e.keyCurve?e.keyCurve.encryptedString:null,t.keyValue=null!=e.keyValue?e.keyValue.encryptedString:null,t.rpId=null!=e.rpId?e.rpId.encryptedString:null,t.rpName=null!=e.rpName?e.rpName.encryptedString:null,t.counter=null!=e.counter?e.counter.encryptedString:null,t.userHandle=null!=e.userHandle?e.userHandle.encryptedString:null,t.userName=null!=e.userName?e.userName.encryptedString:null,t.userDisplayName=null!=e.userDisplayName?e.userDisplayName.encryptedString:null,t.discoverable=null!=e.discoverable?e.discoverable.encryptedString:null,t.creationDate=null!=e.creationDate?e.creationDate.toISOString():null,t}));break;case rm.SecureNote:this.secureNote=new FS,this.secureNote.type=e.secureNote.type;break;case rm.SshKey:this.sshKey=new qS,this.sshKey.privateKey=null!=e.sshKey.privateKey?e.sshKey.privateKey.encryptedString:null,this.sshKey.publicKey=null!=e.sshKey.publicKey?e.sshKey.publicKey.encryptedString:null,this.sshKey.keyFingerprint=null!=e.sshKey.keyFingerprint?e.sshKey.keyFingerprint.encryptedString:null;break;case rm.Card:this.card=new TS,this.card.cardholderName=null!=e.card.cardholderName?e.card.cardholderName.encryptedString:null,this.card.brand=null!=e.card.brand?e.card.brand.encryptedString:null,this.card.number=null!=e.card.number?e.card.number.encryptedString:null,this.card.expMonth=null!=e.card.expMonth?e.card.expMonth.encryptedString:null,this.card.expYear=null!=e.card.expYear?e.card.expYear.encryptedString:null,this.card.code=null!=e.card.code?e.card.code.encryptedString:null;break;case rm.Identity:this.identity=new OS,this.identity.title=null!=e.identity.title?e.identity.title.encryptedString:null,this.identity.firstName=null!=e.identity.firstName?e.identity.firstName.encryptedString:null,this.identity.middleName=null!=e.identity.middleName?e.identity.middleName.encryptedString:null,this.identity.lastName=null!=e.identity.lastName?e.identity.lastName.encryptedString:null,this.identity.address1=null!=e.identity.address1?e.identity.address1.encryptedString:null,this.identity.address2=null!=e.identity.address2?e.identity.address2.encryptedString:null,this.identity.address3=null!=e.identity.address3?e.identity.address3.encryptedString:null,this.identity.city=null!=e.identity.city?e.identity.city.encryptedString:null,this.identity.state=null!=e.identity.state?e.identity.state.encryptedString:null,this.identity.postalCode=null!=e.identity.postalCode?e.identity.postalCode.encryptedString:null,this.identity.country=null!=e.identity.country?e.identity.country.encryptedString:null,this.identity.company=null!=e.identity.company?e.identity.company.encryptedString:null,this.identity.email=null!=e.identity.email?e.identity.email.encryptedString:null,this.identity.phone=null!=e.identity.phone?e.identity.phone.encryptedString:null,this.identity.ssn=null!=e.identity.ssn?e.identity.ssn.encryptedString:null,this.identity.username=null!=e.identity.username?e.identity.username.encryptedString:null,this.identity.passportNumber=null!=e.identity.passportNumber?e.identity.passportNumber.encryptedString:null,this.identity.licenseNumber=null!=e.identity.licenseNumber?e.identity.licenseNumber.encryptedString:null}null!=e.fields&&(this.fields=e.fields.map(e=>{const t=new DS;return t.type=e.type,t.name=e.name?e.name.encryptedString:null,t.value=e.value?e.value.encryptedString:null,t.linkedId=e.linkedId,t})),null!=e.passwordHistory&&(this.passwordHistory=[],e.passwordHistory.forEach(e=>{this.passwordHistory.push({lastUsedDate:e.lastUsedDate,password:e.password?e.password.encryptedString:null})})),null!=e.attachments&&(this.attachments={},this.attachments2={},e.attachments.forEach(t=>{const i=t.fileName?t.fileName.encryptedString:null;this.attachments[t.id]=i;const r=new cC;r.fileName=i,r.lastKnownRevisionDate=e.revisionDate,null!=t.key&&(r.key=t.key.encryptedString),this.attachments2[t.id]=r}))}}class dC extends uC{constructor({cipher:e,encryptedFor:t}){super({cipher:e,encryptedFor:t}),this.id=e.id}}class hC{constructor(e,t,i){this.encryptedFor=i,null!=e&&(this.ciphers=[],e.forEach(e=>{this.ciphers.push(new dC({cipher:e,encryptedFor:i}))})),this.collectionIds=t}}class pC{constructor(e,t,i,r=!1){this.organizationId=e,this.cipherIds=t,this.collectionIds=i,this.removeCollections=r}}class mC{constructor(e){this.collectionIds=null==e?[]:e}}class gC{constructor({cipher:e,encryptedFor:t}){this.cipher=new uC({cipher:e,encryptedFor:t}),this.collectionIds=e.collectionIds}}class fC{constructor(e){this.folderId=e.folderId,this.favorite=e.favorite}}class yC{constructor({cipher:e,encryptedFor:t}){this.cipher=new uC({cipher:e,encryptedFor:t}),this.collectionIds=e.collectionIds}}class vC{}Zx=vC,vC.isCipherListView=e=>"object"==typeof e.type||"string"==typeof e.type,vC.getLogin=e=>Zx.isCipherListView(e)?"object"!=typeof e.type?null:"login"in e.type?e.type.login:null:e.type===rm.Login?e.login:null,vC.uri=e=>{var t;const i=Zx.getLogin(e);return i?"uri"in i?i.uri:(null===(t=i.uris)||void 0===t?void 0:t.length)?i.uris[0].uri:null:null},vC.getCard=e=>Zx.isCipherListView(e)?"object"!=typeof e.type?null:"card"in e.type?e.type.card:null:e.type===rm.Card?e.card:null,vC.isArchived=e=>Zx.isCipherListView(e)?!!e.archivedDate:e.isArchived,vC.isDeleted=e=>Zx.isCipherListView(e)?!!e.deletedDate:e.isDeleted,vC.isUnassigned=e=>Zx.isCipherListView(e)?null!=e.organizationId&&(null==e.collectionIds||0===e.collectionIds.length):e.isUnassigned,vC.canAssignToCollections=e=>Zx.isCipherListView(e)?!e.organizationId||e.edit&&e.viewPassword:e.canAssignToCollections,vC.getType=e=>{if(!Zx.isCipherListView(e))return e.type;switch(!0){case"secureNote"===e.type:return rm.SecureNote;case"sshKey"===e.type:return rm.SshKey;case"identity"===e.type:return rm.Identity;case"object"==typeof e.type&&"card"in e.type:return rm.Card;case"object"==typeof e.type&&"login"in e.type:return rm.Login;default:throw new Error(`Unknown cipher type: ${e.type}`)}},vC.subtitle=e=>Zx.isCipherListView(e)?e.subtitle:e.subTitle,vC.hasAttachments=e=>Zx.isCipherListView(e)?"number"==typeof e.attachments&&e.attachments>0:e.hasAttachments,vC.canLaunch=e=>{var t;const i=Zx.getLogin(e);return!!i&&!!(null===(t=i.uris)||void 0===t?void 0:t.map(e=>wC(e)).some(e=>e.canLaunch))},vC.getLaunchUri=e=>{var t,i;const r=Zx.getLogin(e);if(r)return null===(i=null===(t=r.uris)||void 0===t?void 0:t.map(e=>wC(e)).find(e=>e.canLaunch))||void 0===i?void 0:i.launchUri},vC.matchesUri=(e,t,i,r=Xm.Domain,n)=>{var a;if(Zx.getType(e)!==rm.Login)return!1;if(!Zx.isCipherListView(e))return e.login.matchesUri(t,i,r,n);const s=Zx.getLogin(e);if(!(null===(a=null==s?void 0:s.uris)||void 0===a?void 0:a.length))return!1;const o=s.uris.filter(e=>!!e.uri).map(e=>{var t;const i=new tw;return i.match=null!==(t=e.match)&&void 0!==t?t:r,i.uri=e.uri,i});return o.some(e=>e.matchesUri(t,i,r,n))},vC.hasCopyableValue=(e,t)=>{var i,r,n,a,s,o,l,c,u,d,h,p;if(Zx.isCipherListView(e)){let i=t;return"username"===i&&Zx.getType(e)===rm.Login?i="usernameLogin":"username"===i&&Zx.getType(e)===rm.Identity&&(i="usernameIdentity"),e.copyableFields.includes(bC[i])}switch(t){case"username":return!!(null===(i=e.login)||void 0===i?void 0:i.username)||!!(null===(r=e.identity)||void 0===r?void 0:r.username);case"password":return!!(null===(n=e.login)||void 0===n?void 0:n.password);case"totp":return!!(null===(a=e.login)||void 0===a?void 0:a.totp);case"cardNumber":return!!(null===(s=e.card)||void 0===s?void 0:s.number);case"securityCode":return!!(null===(o=e.card)||void 0===o?void 0:o.code);case"email":return!!(null===(l=e.identity)||void 0===l?void 0:l.email);case"phone":return!!(null===(c=e.identity)||void 0===c?void 0:c.phone);case"address":return!!(null===(u=e.identity)||void 0===u?void 0:u.fullAddressForCopy);case"secureNote":return!!e.notes;case"privateKey":return!!(null===(d=e.sshKey)||void 0===d?void 0:d.privateKey);case"publicKey":return!!(null===(h=e.sshKey)||void 0===h?void 0:h.publicKey);case"keyFingerprint":return!!(null===(p=e.sshKey)||void 0===p?void 0:p.keyFingerprint);default:return!1}},vC.hasFido2Credentials=e=>{var t;const i=Zx.getLogin(e);return!!(null===(t=null==i?void 0:i.fido2Credentials)||void 0===t?void 0:t.length)},vC.decryptionFailure=e=>"decryptionFailure"in e&&e.decryptionFailure,vC.getNotes=e=>e.notes,vC.getFields=e=>(Zx.isCipherListView(e),e.fields),vC.getAttachmentNames=e=>{var t;return Zx.isCipherListView(e)?e.attachmentNames:null===(t=e.attachments)||void 0===t?void 0:t.map(e=>e.fileName).filter(e=>null!=e)},vC.getUriHostname=e=>{var t;if("hostname"in e&&void 0!==e.hostname)return null!==(t=e.hostname)&&void 0!==t?t:void 0;if(e.match!==Xm.RegularExpression&&e.uri){const t=Tt.getHostname(e.uri);return""===t?void 0:t}};const bC={usernameLogin:"LoginUsername",password:"LoginPassword",totp:"LoginTotp",cardNumber:"CardNumber",securityCode:"CardSecurityCode",usernameIdentity:"IdentityUsername",email:"IdentityEmail",phone:"IdentityPhone",address:"IdentityAddress",secureNote:"SecureNotes",privateKey:"SshKey",publicKey:"SshKey",keyFingerprint:"SshKey"},wC=e=>{if(e instanceof tw)return e;const t=new tw;return e.match&&(t.match=e.match),e.uri&&(t.uri=e.uri),t};var kC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const SC=new af.SemVer("2024.2.0");class _C{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m){this.keyService=e,this.domainSettingsService=t,this.apiService=i,this.i18nService=r,this.searchService=n,this.autofillSettingsService=a,this.encryptService=s,this.cipherFileUploadService=o,this.configService=l,this.stateProvider=c,this.accountService=u,this.logService=d,this.cipherEncryptionService=h,this.messageSender=p,this.cipherSdkService=m,this.sortedCiphersCache=new nC(this.sortCiphersByLastUsed),this.clearCipherViewsForUser$=new H,this.sdkCipherCrudEnabled$=this.configService.getFeatureFlag$(Ne.PM27632_SdkCipherCrudOperations),this.cipherListViews$=Wx(e=>{let t;return this.configService.getFeatureFlag$(Ne.PM22134SdkCipherListView).pipe(Le(i=>i?ai([this.encryptedCiphersState(e).state$,this.localData$(e),this.keyService.cipherDecryptionKeys$(e,!0)]).pipe(Ie(([e,t,i])=>null!=e&&null!=i),X(([e,t])=>Object.values(e).map(e=>new Sw(e,null==t?void 0:t[e.id]))),ac(()=>{t=performance.now()}),Le(t=>kC(this,void 0,void 0,function*(){return yield this.decryptCiphersWithSdk(t,e,!1)})),ac(([i,r])=>{Promise.all([this.setFailedDecryptedCiphers(r,e),this.searchService.indexCiphers(e,i)]),this.logService.measure(t,"Vault","CipherService","listView decrypt complete",[["Items",i.length]])}),X(([e])=>e)):this.cipherViews$(e)))},this.clearCipherViewsForUser$),this.cipherViews$=Wx(e=>ai([this.encryptedCiphersState(e).state$,this.localData$(e),this.keyService.cipherDecryptionKeys$(e)]).pipe(Ie(([e,t,i])=>null!=e&&null!=i),Le(()=>this.getAllDecrypted(e)),ac(()=>{this.messageSender.send("updateOverlayCiphers")})),this.clearCipherViewsForUser$),this.failedToDecryptCiphers$=Wx(e=>this.failedToDecryptCiphersState(e).state$.pipe(Ie(e=>null!=e)),this.clearCipherViewsForUser$)}localData$(e){return this.localDataState(e).state$.pipe(X(e=>null!=e?e:{}))}ciphers$(e){return this.encryptedCiphersState(e).state$.pipe(X(e=>null!=e?e:{}))}addEditCipherInfo$(e){return this.addEditCipherInfoState(e).state$}setDecryptedCipherCache(e,t){return kC(this,void 0,void 0,function*(){null!=e&&0===e.length||(yield this.setDecryptedCiphers(e,t)),null!=this.searchService&&(null==e?yield this.searchService.clearIndex(t):this.searchService.indexCiphers(t,e))})}setFailedDecryptedCiphers(e,t){return kC(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(hk,e,t)})}setDecryptedCiphers(e,t){return kC(this,void 0,void 0,function*(){const i={};null==e||e.forEach(e=>{i[e.id]=e}),yield this.stateProvider.setUserState(dk,i,t)})}clearCache(e){return kC(this,void 0,void 0,function*(){const t=yield Ce(this.stateProvider.activeUserId$);null!=e||(e=t),yield this.clearDecryptedCiphersState(e),this.clearCipherViewsForUser$.next(e)})}adjustCipherHistory(e,t,i){return kC(this,void 0,void 0,function*(){null!=e.id&&(null==i&&(i=yield this.get(e.id,t)),null!=i&&(yield this.updateModelfromExistingCipher(e,i,t)),this.adjustPasswordHistoryLength(e))})}encrypt(e,t,i,r){return kC(this,arguments,void 0,function*(e,t,i,r,n=null){var a;if(yield this.adjustCipherHistory(e,t,n),(yield this.configService.getFeatureFlag(Ne.PM22136_SdkCipherEncryption))&&null==i&&null==r)return yield this.cipherEncryptionService.encrypt(e,t);const s=new Sw;if(s.id=e.id,s.folderId=e.folderId,s.favorite=e.favorite,s.organizationId=e.organizationId,s.type=e.type,s.collectionIds=e.collectionIds,s.creationDate=e.creationDate,s.revisionDate=e.revisionDate,s.archivedDate=e.archivedDate,s.reprompt=e.reprompt,s.edit=e.edit,(e.viewPassword||(null==n?void 0:n.key))&&(yield this.getCipherKeyEncryptionEnabled())){s.key=null!==(a=null==n?void 0:n.key)&&void 0!==a?a:null;const o=yield this.getKeyForCipherKeyDecryption(s,t);return i||(i=o),r||(r=o),{cipher:yield this.encryptCipherWithCipherKey(e,s,i,r),encryptedFor:t}}return i||(i=yield this.getKeyForCipherKeyDecryption(s,t)),s.key=null,{cipher:yield this.encryptCipher(e,s,i),encryptedFor:t}})}encryptMany(e,t){return kC(this,void 0,void 0,function*(){if(yield this.configService.getFeatureFlag(Ne.PM22136_SdkCipherEncryption))return yield this.cipherEncryptionService.encryptMany(e,t);const i=[];for(const r of e){const e=yield this.encrypt(r,t);i.push(e)}return i})}encryptAttachments(e,t){return kC(this,void 0,void 0,function*(){if(null==e||0===e.length)return null;const i=[],r=[];return e.forEach(e=>kC(this,void 0,void 0,function*(){const n=new uw;n.id=e.id,n.size=e.size,n.sizeName=e.sizeName,n.url=e.url;const a=this.encryptObjProperty(e,n,{fileName:null},t).then(()=>kC(this,void 0,void 0,function*(){null!=e.key&&(n.key=yield this.encryptService.wrapSymmetricKey(e.key,t)),r.push(n)}));i.push(a)})),yield Promise.all(i),r})}encryptFields(e,t){return kC(this,void 0,void 0,function*(){if(!e||!e.length)return null;const i=this,r=[];return yield e.reduce((e,n)=>kC(this,void 0,void 0,function*(){yield e;const a=yield i.encryptField(n,t);r.push(a)}),Promise.resolve()),r})}encryptField(e,t){return kC(this,void 0,void 0,function*(){const i=new hw;return i.type=e.type,i.linkedId=e.linkedId,e.type===am.Boolean&&"true"!==e.value&&(e.value="false"),yield this.encryptObjProperty(e,i,{name:null,value:null},t),i})}encryptPasswordHistories(e,t){return kC(this,void 0,void 0,function*(){if(!e||!e.length)return null;const i=this,r=[];return yield e.reduce((e,n)=>kC(this,void 0,void 0,function*(){yield e;const a=yield i.encryptPasswordHistory(n,t);r.push(a)}),Promise.resolve()),r})}encryptPasswordHistory(e,t){return kC(this,void 0,void 0,function*(){const i=new yw;return i.lastUsedDate=e.lastUsedDate,yield this.encryptObjProperty(e,i,{password:null},t),i})}get(e,t){return kC(this,void 0,void 0,function*(){const i=yield Ce(this.ciphers$(t));if(null==i||!i.hasOwnProperty(e))return null;const r=yield Ce(this.localData$(t)),n=e;return new Sw(i[n],r?r[n]:null)})}getAll(e){return kC(this,void 0,void 0,function*(){const t=yield Ce(this.localData$(e)),i=yield Ce(this.ciphers$(e)),r=[];for(const e in i)if(i.hasOwnProperty(e)){const n=e;r.push(new Sw(i[n],t?t[n]:null))}return r})}getAllDecrypted(e){return kC(this,void 0,void 0,function*(){const t=yield this.getDecryptedCiphers(e);if(null!=t&&0!==t.length)return yield this.reindexCiphers(e),t;const i=yield this.decryptCiphers(yield this.getAll(e),e);if(null==i)return[];const[r,n]=i;return yield this.setDecryptedCipherCache(r,e),yield this.setFailedDecryptedCiphers(n,e),r})}getDecryptedCiphers(e){return kC(this,void 0,void 0,function*(){return Object.values(yield Ce(this.decryptedCiphersState(e).state$.pipe(X(e=>null!=e?e:{}))))})}decryptCiphers(e,t){return kC(this,void 0,void 0,function*(){if(0===e.length)return[[],[]];if(yield this.configService.getFeatureFlag(Ne.PM19941MigrateCipherDomainToSdk)){const i=performance.now(),r=yield this.decryptCiphersWithSdk(e,t,!0);return this.logService.measure(i,"Vault","CipherService","decrypt complete",[["Items",e.length]]),r}const i=yield Ce(this.keyService.cipherDecryptionKeys$(t));if(null==i||null==i.userKey&&0===Object.keys(i.orgKeys).length)return null;const r=e.reduce((e,t)=>{var i,r;return null!==(i=e[r=t.organizationId])&&void 0!==i||(e[r]=[]),e[t.organizationId].push(t),e},{}),n=performance.now(),a=(yield Promise.all(Object.entries(r).map(e=>kC(this,[e],void 0,function*([e,t]){var r;const n=null!==(r=i.orgKeys[e])&&void 0!==r?r:i.userKey;return yield Promise.all(t.map(e=>kC(this,void 0,void 0,function*(){return yield e.decrypt(n)})))})))).flat().sort(this.getLocaleSortingFunction());return this.logService.measure(n,"Vault","CipherService","decrypt complete",[["Items",e.length]]),a.reduce((e,t)=>(t.decryptionFailure?e[1].push(t):e[0].push(t),e),[[],[]])})}decrypt(e,t){return kC(this,void 0,void 0,function*(){if(yield this.configService.getFeatureFlag(Ne.PM19941MigrateCipherDomainToSdk))return yield this.cipherEncryptionService.decrypt(e,t);{const i=yield this.getKeyForCipherKeyDecryption(e,t);return yield e.decrypt(i)}})}reindexCiphers(e){return kC(this,void 0,void 0,function*(){var t;null!=this.searchService&&(null!==(t=yield Ce(this.searchService.indexedEntityId$(e)))&&void 0!==t?t:e)!==e&&(yield this.searchService.indexCiphers(e,yield this.getDecryptedCiphers(e),e))})}getAllDecryptedForGrouping(e,t){return kC(this,arguments,void 0,function*(e,t,i=!0){return(yield this.getAllDecrypted(t)).filter(t=>!t.isDeleted&&(!(!i||t.folderId!==e)||!i&&null!=t.collectionIds&&t.collectionIds.indexOf(e)>-1))})}getAllDecryptedForUrl(e,t,i){return kC(this,arguments,void 0,function*(e,t,i,r=null,n){return yield Ce(this.cipherViews$(t).pipe(Ie(e=>null!=e),Le(t=>kC(this,void 0,void 0,function*(){return yield this.filterCiphersForUrl(t,e,i,r,n)}))))})}getAllDecryptedForIds(e,t){return kC(this,void 0,void 0,function*(){return Ce(this.cipherViews$(e).pipe(Ie(e=>null!=e),X(e=>e.filter(e=>t.includes(e.id)))))})}filterCiphersForUrl(e,t,i){return kC(this,arguments,void 0,function*(e,t,i,r=null,n){if(null==t&&null==i)return[];const a=yield Ce(this.domainSettingsService.getUrlEquivalentDomains(t));null!=r||(r=yield Ce(this.domainSettingsService.resolvedDefaultUriMatchStrategy$));const s=yield this.configService.getFeatureFlag(Ne.PM19148_InnovationArchive);return e.filter(e=>{const o=vC.getType(e),l=null!==vC.getLogin(e);return!vC.isDeleted(e)&&(!s||!vC.isArchived(e))&&(!(!Array.isArray(i)||!i.includes(o)||l)||!!l&&vC.matchesUri(e,t,a,r,n))})})}getAllDecryptedCiphersOfType(e,t){return kC(this,void 0,void 0,function*(){const i=yield this.getAllDecrypted(t),r=yield this.configService.getFeatureFlag(Ne.PM19148_InnovationArchive);return i.filter(t=>null==t.deletedDate&&(!r||!t.isArchived)&&e.includes(t.type)).sort((e,t)=>this.sortCiphersByLastUsedThenName(e,t))})}getAllFromApiForOrganization(e,t){return kC(this,void 0,void 0,function*(){const i=yield this.apiService.getCiphersOrganization(e,t);return yield this.decryptOrganizationCiphersResponse(i,e)})}getManyFromApiForOrganization(e){return kC(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET","/ciphers/organization-details/assigned?organizationId="+e,null,!0,!0),i=new Tc(t,MS);return this.decryptOrganizationCiphersResponse(i,e)})}decryptOrganizationCiphersResponse(e,t){return kC(this,void 0,void 0,function*(){if(null==(null==e?void 0:e.data)||e.data.length<1)return[];const i=e.data.map(e=>new Sw(new Fb(e))),r=yield this.keyService.getOrgKey(t),n=yield Promise.all(i.map(e=>kC(this,void 0,void 0,function*(){return yield e.decrypt(r)})));return n.sort(this.getLocaleSortingFunction()),n})}getLastUsedForUrl(e,t){return kC(this,arguments,void 0,function*(e,t,i=!1){return this.getCipherForUrl(e,t,!0,!1,i)})}getLastLaunchedForUrl(e,t){return kC(this,arguments,void 0,function*(e,t,i=!1){return this.getCipherForUrl(e,t,!1,!0,i)})}getNextCipherForUrl(e,t){return kC(this,void 0,void 0,function*(){return this.getCipherForUrl(e,t,!1,!1,!1)})}getNextCardCipher(e){return kC(this,void 0,void 0,function*(){const t="cardCiphers";if(!this.sortedCiphersCache.isCached(t)){const i=yield this.getAllDecryptedCiphersOfType([rm.Card],e);if(!(null==i?void 0:i.length))return null;this.sortedCiphersCache.addCiphers(t,i)}return this.sortedCiphersCache.getNext(t)})}getNextIdentityCipher(e){return kC(this,void 0,void 0,function*(){const t="identityCiphers";if(!this.sortedCiphersCache.isCached(t)){const i=yield this.getAllDecryptedCiphersOfType([rm.Identity],e);if(!(null==i?void 0:i.length))return null;this.sortedCiphersCache.addCiphers(t,i)}return this.sortedCiphersCache.getNext(t)})}updateLastUsedIndexForUrl(e){this.sortedCiphersCache.updateLastUsedIndex(e)}updateLastUsedDate(e,t){return kC(this,void 0,void 0,function*(){let i=yield Ce(this.localData$(t));i||(i={});const r=e;i[r]?i[r].lastUsedDate=(new Date).getTime():i[r]={lastUsedDate:(new Date).getTime()},yield this.localDataState(t).update(()=>i);const n=yield this.getDecryptedCiphers(t);if(n){for(let t=0;ti);const n=yield this.getDecryptedCiphers(t);if(n){for(let t=0;t0){const i=new gC({cipher:e,encryptedFor:t});r=yield this.apiService.postCipherCreate(i)}else{const i=new uC({cipher:e,encryptedFor:t});r=yield this.apiService.postCipher(i)}e.id=r.id;const n=new Fb(r,e.collectionIds),a=yield this.upsert(n);return new Sw(a[e.id])})}updateWithServer(e,t,i,r){return kC(this,void 0,void 0,function*(){if(yield Ce(this.sdkCipherCrudEnabled$))return yield this.updateWithServerUsingSdk(e,t,i,r);const n=yield this.encrypt(e,t),a=yield this.updateWithServer_legacy(n,r);return yield this.decrypt(a,t)})}updateWithServerUsingSdk(e,t,i,r){return kC(this,void 0,void 0,function*(){return yield this.clearCache(t),yield this.cipherSdkService.updateWithServer(e,t,i,r)})}updateWithServer_legacy(e,t){return kC(this,arguments,void 0,function*({cipher:e,encryptedFor:t},i){let r;if(i){const i=new uC({cipher:e,encryptedFor:t});r=yield this.apiService.putCipherAdmin(e.id,i);const n=new Fb(r,e.collectionIds);return new Sw(n,e.localData)}if(e.edit){const i=new uC({cipher:e,encryptedFor:t});r=yield this.apiService.putCipher(e.id,i)}else{const t=new fC(e);r=yield this.apiService.putPartialCipher(e.id,t)}const n=new Fb(r,e.collectionIds),a=yield this.upsert(n);return new Sw(a[e.id],e.localData)})}shareWithServer(e,t,i,r,n){return kC(this,void 0,void 0,function*(){const a=yield this.configService.getFeatureFlag(Ne.PM22136_SdkCipherEncryption);let s;if(yield this.adjustCipherHistory(e,r,n),a){if(null!=e.organizationId)throw new Error("Cipher is already associated with an organization.");s=yield this.cipherEncryptionService.moveToOrganization(e,t,r),s.cipher.collectionIds=i}else{const n=[];null!=e.attachments&&e.attachments.forEach(i=>{null==i.key&&n.push(this.shareAttachmentWithServer(i,e.id,t,e.revisionDate))}),yield Promise.all(n),e.organizationId=t,e.collectionIds=i,s=yield this.encryptSharedCipher(e,r)}const o=new yC(s),l=yield this.apiService.putShareCipher(e.id,o),c=new Fb(l,i);return yield this.upsert(c),new Sw(c,e.localData)})}shareManyWithServer(e,t,i,r){return kC(this,void 0,void 0,function*(){const n=yield this.configService.getFeatureFlag(Ne.PM22136_SdkCipherEncryption),a=[],s=[];for(const o of e)if(n){if(null!=o.organizationId)throw new Error("Cipher is already associated with an organization.");a.push(this.cipherEncryptionService.moveToOrganization(o,t,r).then(e=>{e.cipher.collectionIds=i,s.push(e.cipher)}))}else o.organizationId=t,o.collectionIds=i,a.push(this.encryptSharedCipher(o,r).then(e=>{s.push(e.cipher)}));yield Promise.all(a);const o=new hC(s,i,r);try{const e=yield this.apiService.putShareCiphers(o),t=new Map(e.data.map(e=>[e.id,e]));s.forEach(e=>{const i=t.get(e.id);i&&(e.revisionDate=new Date(i.revisionDate))}),yield this.upsert(s.map(e=>e.toCipherData()))}catch(t){for(const t of e)t.organizationId=null,t.collectionIds=null;throw t}})}saveAttachmentWithServer(e,t,i,r=!1){return new Promise((n,a)=>{const s=new FileReader;s.readAsArrayBuffer(t),s.onload=s=>kC(this,void 0,void 0,function*(){try{const a=yield this.saveAttachmentRawWithServer(e,t.name,s.target.result,i,r);n(a)}catch(e){a(e)}}),s.onerror=()=>{a("Error reading file.")}})}saveAttachmentRawWithServer(e,t,i,r){return kC(this,arguments,void 0,function*(e,t,i,r,n=!1){const a=yield this.getKeyForCipherKeyDecryption(e,r),s=null!=e.key?yield this.encryptService.unwrapSymmetricKey(e.key,a):a,o=yield this.encryptService.encryptString(t,s),l=yield this.keyService.makeDataEncKey(s),c=yield this.encryptService.encryptFileData(new Uint8Array(i),l[0]),u=yield this.cipherFileUploadService.upload(e,o,c,n,l),d=new Fb(u,e.collectionIds);return n||(yield this.upsert(d)),new Sw(d)})}saveCollectionsWithServer(e,t){return kC(this,void 0,void 0,function*(){const i=new mC(e.collectionIds),r=yield this.apiService.putCipherCollections(e.id,i);if(r.unavailable)return void(yield this.delete(e.id,t));const n=new Fb(r.cipher),a=yield this.upsert(n);return new Sw(a[e.id],e.localData)})}saveCollectionsWithServerAdmin(e){return kC(this,void 0,void 0,function*(){const t=new mC(e.collectionIds),i=yield this.apiService.putCipherCollectionsAdmin(e.id,t),r=new MS(i);r.edit=!0,r.viewPassword=!0,r.favorite=!1;const n=new Fb(r);return new Sw(n)})}bulkUpdateCollectionsWithServer(e,t,i,r){return kC(this,arguments,void 0,function*(e,t,i,r,n=!1){var a,s;const o=new pC(e,i,r,n);yield this.apiService.send("POST","/ciphers/bulk-collections",o,!0,!1);const l=yield Ce(this.ciphers$(t));for(const e of i){const t=l[e];t&&(t.collectionIds=n?null===(a=t.collectionIds)||void 0===a?void 0:a.filter(e=>!r.includes(e)):[...new Set([...null!==(s=t.collectionIds)&&void 0!==s?s:[],...r])])}yield this.clearCache(),yield this.encryptedCiphersState(t).update(()=>l)})}upsert(e,t){return kC(this,void 0,void 0,function*(){const i=e instanceof Fb?[e]:e,r=yield this.updateEncryptedCipherState(e=>(i.forEach(t=>e[t.id]=t),e),t);return yield new Promise(e=>setTimeout(e,0)),r})}replace(e,t){return kC(this,void 0,void 0,function*(){var i;const r=null!==(i=yield Ce(this.encryptedCiphersState(t).state$))&&void 0!==i?i:{};Object.keys(r).length>0&&JSON.stringify(r)===JSON.stringify(e)||(yield this.updateEncryptedCipherState(()=>e,t))})}updateEncryptedCipherState(e){return kC(this,arguments,void 0,function*(e,t=null){t||(t=yield Ce(this.stateProvider.activeUserId$)),yield this.clearCache(t);const i=yield this.stateProvider.getUser(t,uk).update(t=>e(null!=t?t:{}));return yield new Promise(e=>setTimeout(e,0)),i})}clear(e){return kC(this,void 0,void 0,function*(){null!=e||(e=yield Ce(this.stateProvider.activeUserId$)),yield this.clearEncryptedCiphersState(e),yield this.clearCache(e)})}moveManyWithServer(e,t,i){return kC(this,void 0,void 0,function*(){yield this.apiService.putMoveCiphers(new oC(e,t));let r=yield Ce(this.ciphers$(i));null==r&&(r={}),e.forEach(e=>{r.hasOwnProperty(e)&&(r[e].folderId=t)}),yield this.clearCache(),yield this.encryptedCiphersState(i).update(()=>r)})}delete(e,t){return kC(this,void 0,void 0,function*(){const i=yield Ce(this.ciphers$(t));if(null!=i){if("string"==typeof e){const t=e;if(null==i[t])return;delete i[t]}else e.forEach(e=>{delete i[e]});yield this.clearCache(),yield this.encryptedCiphersState(t).update(()=>i)}})}deleteWithServer(e,t){return kC(this,arguments,void 0,function*(e,t,i=!1){if(yield Ce(this.sdkCipherCrudEnabled$))return yield this.cipherSdkService.deleteWithServer(e,t,i),void(yield this.clearCache(t));i?yield this.apiService.deleteCipherAdmin(e):yield this.apiService.deleteCipher(e),yield this.delete(e,t)})}deleteManyWithServer(e,t){return kC(this,arguments,void 0,function*(e,t,i=!1,r){if(yield Ce(this.sdkCipherCrudEnabled$))return yield this.cipherSdkService.deleteManyWithServer(e,t,i,r),void(yield this.clearCache(t));const n=new sC(e,r);i?yield this.apiService.deleteManyCiphersAdmin(n):yield this.apiService.deleteManyCiphers(n),yield this.delete(e,t)})}deleteAttachment(e,t,i,r){return kC(this,void 0,void 0,function*(){let n=yield Ce(this.ciphers$(r));const a=e;if(null!=n&&n.hasOwnProperty(e)&&null!=n[a].attachments){for(let e=0;e(null==n&&(n={}),n)),n[a]}})}deleteAttachmentWithServer(e,t,i){return kC(this,arguments,void 0,function*(e,t,i,r=!1){let n;try{n=r?yield this.apiService.deleteCipherAttachmentAdmin(e,t):yield this.apiService.deleteCipherAttachment(e,t)}catch(e){return Promise.reject(e.getSingleMessage())}const a=new Fb(n.cipher);return yield this.deleteAttachment(e,a.revisionDate,t,i)})}sortCiphersByLastUsed(e,t){const i=e.localData&&e.localData.lastUsedDate?e.localData.lastUsedDate:null,r=t.localData&&t.localData.lastUsedDate?t.localData.lastUsedDate:null,n=null!=i&&null!=r;return n&&ir?-1:null!=r&&null==i?1:0}sortCiphersByLastUsedThenName(e,t){const i=this.sortCiphersByLastUsed(e,t);return 0!==i?i:this.getLocaleSortingFunction()(e,t)}getLocaleSortingFunction(){return(e,t)=>{let i=e.name,r=t.name;if(null==i&&null!=r)return-1;if(null!=i&&null==r)return 1;if(null==i&&null==r)return 0;const n=this.i18nService.collator?this.i18nService.collator.compare(i,r):i.localeCompare(r),a=vC.getType(e),s=vC.getType(t);if(0!==n||a!==rm.Login||s!==rm.Login)return n;const o=vC.getLogin(e),l=vC.getLogin(t);return null!=o.username&&(i+=o.username),null!=l.username&&(r+=l.username),this.i18nService.collator?this.i18nService.collator.compare(i,r):i.localeCompare(r)}}softDelete(e,t){return kC(this,void 0,void 0,function*(){let i=yield Ce(this.ciphers$(t));if(null==i)return;const r=e=>{null!=i[e]&&(i[e].deletedDate=(new Date).toISOString())};"string"==typeof e?r(e):e.forEach(r),yield this.clearCache(),yield this.encryptedCiphersState(t).update(()=>(null==i&&(i={}),i))})}softDeleteWithServer(e,t){return kC(this,arguments,void 0,function*(e,t,i=!1){if(yield Ce(this.sdkCipherCrudEnabled$))return yield this.cipherSdkService.softDeleteWithServer(e,t,i),void(yield this.clearCache(t));i?yield this.apiService.putDeleteCipherAdmin(e):yield this.apiService.putDeleteCipher(e),yield this.softDelete(e,t)})}softDeleteManyWithServer(e,t){return kC(this,arguments,void 0,function*(e,t,i=!1,r){if(yield Ce(this.sdkCipherCrudEnabled$))return yield this.cipherSdkService.softDeleteManyWithServer(e,t,i,r),void(yield this.clearCache(t));const n=new sC(e,r);i?yield this.apiService.putDeleteManyCiphersAdmin(n):yield this.apiService.putDeleteManyCiphers(n),yield this.softDelete(e,t)})}restore(e,t){return kC(this,void 0,void 0,function*(){let i=yield Ce(this.ciphers$(t));if(null==i)return;const r=e=>{const t=e.id;null!=i[t]&&(i[t].deletedDate=null,i[t].revisionDate=e.revisionDate)};e.constructor.name===Array.name?e.forEach(r):r(e),yield this.clearCache(),yield this.encryptedCiphersState(t).update(()=>(null==i&&(i={}),i))})}restoreWithServer(e,t){return kC(this,arguments,void 0,function*(e,t,i=!1){if(yield Ce(this.sdkCipherCrudEnabled$))return yield this.cipherSdkService.restoreWithServer(e,t,i),void(yield this.clearCache(t));let r;r=i?yield this.apiService.putRestoreCipherAdmin(e):yield this.apiService.putRestoreCipher(e),yield this.restore({id:e,revisionDate:r.revisionDate},t)})}restoreManyWithServer(e,t,i){return kC(this,void 0,void 0,function*(){if(yield Ce(this.sdkCipherCrudEnabled$))return yield this.cipherSdkService.restoreManyWithServer(e,t,i),void(yield this.clearCache(t));let r;if(i){const t=new lC(e,i);r=yield this.apiService.putRestoreManyCiphersAdmin(t)}else{const t=new lC(e);r=yield this.apiService.putRestoreManyCiphers(t)}const n=[];for(const e of r.data)n.push({id:e.id,revisionDate:e.revisionDate});yield this.restore(n,t)})}getKeyForCipherKeyDecryption(e,t){return kC(this,void 0,void 0,function*(){return null==e.organizationId?yield Ce(this.keyService.userKey$(t)):yield Ce(this.keyService.orgKeys$(t).pipe(X(t=>t[e.organizationId])))})}setAddEditCipherInfo(e,t){return kC(this,void 0,void 0,function*(){yield this.addEditCipherInfoState(t).update(()=>e,{shouldUpdate:t=>!(null==t&&null==e)})})}getRotatedData(e,t,i){return kC(this,void 0,void 0,function*(){if(null==e)throw new Error("Original user key is required to rotate ciphers");if(null==t)throw new Error("New user key is required to rotate ciphers");let r=[];const n=yield Ce(this.cipherViews$(i)),a=yield Ce(this.failedToDecryptCiphers$(i));if(!n)return r;if(a.length>0)throw new Error("Cannot rotate ciphers when decryption failures are present");const s=n.filter(e=>null==e.organizationId);if(0===s.length)return r;const o=yield this.configService.getFeatureFlag(Ne.PM22136_SdkCipherEncryption);return r=yield Promise.all(s.map(r=>kC(this,void 0,void 0,function*(){const n=o?yield this.cipherEncryptionService.encryptCipherForRotation(r,i,t):yield this.encrypt(r,i,t,e);return new dC(n)}))),r})}getDecryptedAttachmentBuffer(e,t,i,r,n){return kC(this,void 0,void 0,function*(){const a=yield this.configService.getFeatureFlag(Ne.PM19941MigrateCipherDomainToSdk),s=yield Ce(this.ciphers$(r).pipe(X(t=>new Sw(t[e]))));if(a&&!n){const e=yield i.arrayBuffer();return this.cipherEncryptionService.decryptAttachmentContent(s,t,new Uint8Array(e),r)}const o=yield Eg.fromResponse(i),l=null!=t.key?t.key:s.organizationId?yield Ce(this.keyService.orgKeys$(r).pipe(Hx(),X(e=>e[s.organizationId]))):yield Ce(this.keyService.userKey$(r).pipe(Hx()));return yield this.encryptService.decryptFileData(o,l)})}localDataState(e){return this.stateProvider.getUser(e,pk)}encryptedCiphersState(e){return this.stateProvider.getUser(e,uk)}decryptedCiphersState(e){return this.stateProvider.getUser(e,dk)}addEditCipherInfoState(e){return this.stateProvider.getUser(e,mk)}failedToDecryptCiphersState(e){return this.stateProvider.getUser(e,hk)}encryptSharedCipher(e,t){return kC(this,void 0,void 0,function*(){const i=yield this.keyService.getUserKey(t);return yield this.encrypt(e,t,null,i)})}updateModelfromExistingCipher(e,t,i){return kC(this,void 0,void 0,function*(){const r=yield this.decrypt(t,i);if(e.passwordHistory=r.passwordHistory||[],e.type===rm.Login&&r.type===rm.Login)if(null!=r.login.password&&""!==r.login.password&&r.login.password!==e.login.password){const t=new aw;t.password=r.login.password,t.lastUsedDate=e.login.passwordRevisionDate=new Date,e.passwordHistory.splice(0,0,t)}else e.login.passwordRevisionDate=r.login.passwordRevisionDate;if(r.hasFields){const t=r.fields.filter(e=>e.type===am.Hidden&&null!=e.name&&""!==e.name&&null!=e.value&&""!==e.value),i=null==e.fields?[]:e.fields.filter(e=>e.type===am.Hidden&&null!=e.name&&""!==e.name);t.forEach(t=>{const r=i.find(e=>e.name===t.name);if(null==r||r.value!==t.value){const i=new aw;i.password=t.name+": "+t.value,i.lastUsedDate=new Date,e.passwordHistory.splice(0,0,i)}})}})}adjustPasswordHistoryLength(e){null!=e.passwordHistory&&0===e.passwordHistory.length?e.passwordHistory=null:null!=e.passwordHistory&&e.passwordHistory.length>5&&(e.passwordHistory=e.passwordHistory.slice(0,5))}shareAttachmentWithServer(e,t,i,r){return kC(this,void 0,void 0,function*(){const n=yield Ce(this.accountService.activeAccount$),a=yield this.apiService.nativeFetch(new Request(e.url,{cache:"no-store"}));if(200!==a.status)throw Error("Failed to download attachment: "+a.status.toString());const s=yield Eg.fromResponse(a),o=yield this.keyService.getUserKey(n.id),l=yield this.encryptService.decryptFileData(s,o);let c;c=yield this.keyService.getOrgKey(i),c||(c=yield this.keyService.getUserKey());const u=yield this.keyService.makeDataEncKey(c),d=yield this.encryptService.encryptString(e.fileName,c),h=yield this.encryptService.encryptFileData(new Uint8Array(l),u[0]),p=new FormData;try{const e=new Blob([h.buffer],{type:"application/octet-stream"});p.append("key",u[1].encryptedString),p.append("data",e,d.encryptedString),p.append("lastKnownRevisionDate",r.toISOString())}catch(e){if(!Tt.isNode||Tt.isBrowser)throw e;p.append("key",u[1].encryptedString),p.append("lastKnownRevisionDate",r.toISOString()),p.append("data",Buffer.from(h.buffer),{filepath:d.encryptedString,contentType:"application/octet-stream"})}try{yield this.apiService.postShareCipherAttachment(t,e.id,p,i)}catch(e){throw new Error(e.getSingleMessage())}})}upgradeOldCipherAttachments(e,t,i){return kC(this,void 0,void 0,function*(){if(!e.hasOldAttachments)return e;let r=yield this.get(e.id,t);for(const n of e.attachments)if(null==n.key&&(null==i||n.id===i))try{const i=yield this.getAttachmentDownloadUrl(e.id,n),a=yield this.apiService.nativeFetch(new Request(i,{cache:"no-store"}));if(200!==a.status)throw new Error(`Failed to download attachment. Status: ${a.status}`);const s=yield this.getDecryptedAttachmentBuffer(e.id,n,a,t);r=yield this.saveAttachmentRawWithServer(r,n.fileName,s,t);const o=yield this.deleteAttachmentWithServer(e.id,n.id,t);r=new Sw(o)}catch(e){throw this.logService.error(`Failed to upgrade attachment ${n.id}`,e),e}return yield this.decrypt(r,t)})}getAttachmentDownloadUrl(e,t){return kC(this,void 0,void 0,function*(){try{return(yield this.apiService.getAttachmentData(e,t.id)).url}catch(e){if(e instanceof Su&&404===e.statusCode&&t.url)return t.url;throw new Error(`Failed to get download URL for attachment ${t.id}`)}})}encryptObjProperty(e,t,i,r){return kC(this,void 0,void 0,function*(){const n=[],a=this;for(const s in i)i.hasOwnProperty(s)&&function(t,s){const o=Promise.resolve().then(()=>{const n=e[i[t]||t];return n&&""!==n?a.encryptService.encryptString(n,r):null}).then(e=>{s[t]=e});n.push(o)}(s,t);yield Promise.all(n)})}encryptCipherData(e,t,i){return kC(this,void 0,void 0,function*(){switch(e.type){case rm.Login:if(e.login=new fw,e.login.passwordRevisionDate=t.login.passwordRevisionDate,e.login.autofillOnPageLoad=t.login.autofillOnPageLoad,yield this.encryptObjProperty(t.login,e.login,{username:null,password:null,totp:null},i),null!=t.login.uris){e.login.uris=[],t.login.uris=t.login.uris.filter(e=>null!=e.uri&&""!==e.uri);for(let r=0;rkC(this,void 0,void 0,function*(){const t=new mw;return yield this.encryptObjProperty(e,t,{credentialId:null,keyType:null,keyAlgorithm:null,keyCurve:null,keyValue:null,rpId:null,rpName:null,userHandle:null,userName:null,userDisplayName:null,origin:null},i),t.counter=yield this.encryptService.encryptString(String(e.counter),i),t.discoverable=yield this.encryptService.encryptString(String(e.discoverable),i),t.creationDate=e.creationDate,t})))));case rm.SecureNote:return e.secureNote=new vw,void(e.secureNote.type=t.secureNote.type);case rm.Card:return e.card=new dw,void(yield this.encryptObjProperty(t.card,e.card,{cardholderName:null,brand:null,number:null,expMonth:null,expYear:null,code:null},i));case rm.Identity:return e.identity=new pw,void(yield this.encryptObjProperty(t.identity,e.identity,{title:null,firstName:null,middleName:null,lastName:null,address1:null,address2:null,address3:null,city:null,state:null,postalCode:null,country:null,company:null,email:null,phone:null,ssn:null,username:null,passportNumber:null,licenseNumber:null},i));case rm.SshKey:return e.sshKey=new bw,void(yield this.encryptObjProperty(t.sshKey,e.sshKey,{privateKey:null,publicKey:null,keyFingerprint:null},i));default:throw new Error("Unknown cipher type.")}})}getAutofillOnPageLoadDefault(){return kC(this,void 0,void 0,function*(){return yield Ce(this.autofillSettingsService.autofillOnPageLoadDefault$)})}getCipherForUrl(e,t,i,r,n){return kC(this,void 0,void 0,function*(){const a=n?"autofillOnPageLoad-"+e:e;if(!this.sortedCiphersCache.isCached(a)){let i=yield this.getAllDecryptedForUrl(e,t);if(!(null==i?void 0:i.length))return null;const r=yield Ce(this.localData$(t));if(r)for(const e of i){const t=r[e.id];t&&(e.localData=t)}if(n){const e=yield this.getAutofillOnPageLoadDefault();if(i=i.filter(t=>t.login.autofillOnPageLoad||null==t.login.autofillOnPageLoad&&!1!==e),0===i.length)return null}this.sortedCiphersCache.addCiphers(a,i)}return r?this.sortedCiphersCache.getLastLaunched(a):i?this.sortedCiphersCache.getLastUsed(a):this.sortedCiphersCache.getNext(a)})}clearEncryptedCiphersState(e){return kC(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(uk,{},e)})}clearDecryptedCiphersState(e){return kC(this,void 0,void 0,function*(){yield this.setDecryptedCiphers(null,e),yield this.setFailedDecryptedCiphers(null,e),this.clearSortedCiphers()})}clearSortedCiphers(){this.sortedCiphersCache.clear()}encryptCipher(e,t,i){return kC(this,void 0,void 0,function*(){if(null==i)throw new Error("Key to encrypt cipher must not be null. Use the org key, user key or cipher key.");return yield Promise.all([this.encryptObjProperty(e,t,{name:null,notes:null},i),this.encryptCipherData(t,e,i),this.encryptFields(e.fields,i).then(e=>{t.fields=e}),this.encryptPasswordHistories(e.passwordHistory,i).then(e=>{t.passwordHistory=e}),this.encryptAttachments(e.attachments,i).then(e=>{t.attachments=e})]),t})}encryptCipherWithCipherKey(e,t,i,r){return kC(this,void 0,void 0,function*(){let n;return n=null==t.key?yield this.keyService.makeCipherKey():yield this.encryptService.unwrapSymmetricKey(t.key,r),t.key=yield this.encryptService.wrapSymmetricKey(n,i),this.encryptCipher(e,t,n)})}getCipherKeyEncryptionEnabled(){return kC(this,void 0,void 0,function*(){const e=yield this.configService.getFeatureFlag(Ne.CipherKeyEncryption),t=yield Ce(this.configService.checkServerMeetsVersionRequirement$(SC));return e&&t})}decryptCiphersWithSdk(e,t){return kC(this,arguments,void 0,function*(e,t,i=!0){if(0===e.length)return[[],[]];if(i){const[i,r]=yield this.cipherEncryptionService.decryptManyLegacy(e,t);return[i.sort(this.getLocaleSortingFunction()),r]}const[r,n]=yield this.cipherEncryptionService.decryptManyWithFailures(e,t),a=n.map(e=>{const t=new lw(e);return t.name="[error: cannot decrypt]",t.decryptionFailure=!0,t});return[r.sort(this.getLocaleSortingFunction()),a]})}getFullCipherView(e){return kC(this,void 0,void 0,function*(){if(vC.isCipherListView(e)){const t=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id))),i=yield this.get(e.id,t);return this.decrypt(i,t)}return Promise.resolve(e)})}}var xC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})},CC=function(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,n;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(n=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},IC=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,n=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===n)return n=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(a).then(e,function(t){return i(t),e()})}else n|=1}catch(e){i(e)}if(1===n)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});class EC{constructor(e,t){this.sdkService=e,this.logService=t}encrypt(e,t){return xC(this,void 0,void 0,function*(){return Ce(this.sdkService.userClient$(t).pipe(X(t=>{const i={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const r=CC(i,t.take(),!1),n=this.toSdkCipherView(e,r.value),a=r.value.vault().ciphers().encrypt(n);return{cipher:Sw.fromSdkCipher(a.cipher),encryptedFor:a.encryptedFor}}catch(e){i.error=e,i.hasError=!0}finally{IC(i)}}),Hu(e=>(this.logService.error(`Failed to encrypt cipher: ${e}`),pe))))})}encryptMany(e,t){return xC(this,void 0,void 0,function*(){return e&&0!==e.length?Ce(this.sdkService.userClient$(t).pipe(X(t=>{const i={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const r=CC(i,t.take(),!1);return r.value.vault().ciphers().encrypt_list(e.map(e=>this.toSdkCipherView(e,r.value))).map(e=>({cipher:Sw.fromSdkCipher(e.cipher),encryptedFor:e.encryptedFor}))}catch(e){i.error=e,i.hasError=!0}finally{IC(i)}}),Hu(e=>(this.logService.error(`Failed to encrypt ciphers in batch: ${e}`),pe)))):[]})}moveToOrganization(e,t,i){return xC(this,void 0,void 0,function*(){return Ce(this.sdkService.userClient$(i).pipe(X(i=>{const r={stack:[],error:void 0,hasError:!1};try{if(!i)throw new Error("SDK not available");const n=CC(r,i.take(),!1),a=this.toSdkCipherView(e,n.value),s=n.value.vault().ciphers().move_to_organization(a,$g(t)),o=n.value.vault().ciphers().encrypt(s);return{cipher:Sw.fromSdkCipher(o.cipher),encryptedFor:o.encryptedFor}}catch(e){r.error=e,r.hasError=!0}finally{IC(r)}}),Hu(e=>(this.logService.error(`Failed to move cipher to organization: ${e}`),pe))))})}encryptCipherForRotation(e,t,i){return xC(this,void 0,void 0,function*(){return Ce(this.sdkService.userClient$(t).pipe(X(t=>{const r={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const n=CC(r,t.take(),!1),a=this.toSdkCipherView(e,n.value),s=n.value.vault().ciphers().encrypt_cipher_for_rotation(a,i.toBase64());return{cipher:Sw.fromSdkCipher(s.cipher),encryptedFor:s.encryptedFor}}catch(e){r.error=e,r.hasError=!0}finally{IC(r)}}),Hu(e=>(this.logService.error(`Failed to rotate cipher data: ${e}`),pe))))})}decrypt(e,t){return xC(this,void 0,void 0,function*(){return Ce(this.sdkService.userClient$(t).pipe(X(t=>{var i,r;const n={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const a=CC(n,t.take(),!1),s=a.value.vault().ciphers().decrypt(e.toSdkCipher()),o=lw.fromSdkCipherView(s);if(o.type===rm.Login&&(null===(r=null===(i=s.login)||void 0===i?void 0:i.fido2Credentials)||void 0===r?void 0:r.length)){const e=a.value.vault().ciphers().decrypt_fido2_credentials(s),t=a.value.vault().ciphers().decrypt_fido2_private_key(s);o.login.fido2Credentials=e.map(e=>{const i=Xb.fromSdkFido2CredentialView(e);return i.keyValue=t,i}).filter(e=>void 0!==e)}return o}catch(e){n.error=e,n.hasError=!0}finally{IC(n)}}),Hu(e=>(this.logService.error(`Failed to decrypt cipher ${e}`),pe))))})}decryptManyLegacy(e,t){return Ce(this.sdkService.userClient$(t).pipe(X(t=>{const i={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK not available");const r=CC(i,t.take(),!1),n=[],a=[];return e.forEach(e=>{var t,i;try{const a=r.value.vault().ciphers().decrypt(e.toSdkCipher()),s=lw.fromSdkCipherView(a);if(s.type===rm.Login&&(null===(i=null===(t=a.login)||void 0===t?void 0:t.fido2Credentials)||void 0===i?void 0:i.length)){const e=r.value.vault().ciphers().decrypt_fido2_credentials(a),t=r.value.vault().ciphers().decrypt_fido2_private_key(a);s.login.fido2Credentials=e.map(e=>{const i=Xb.fromSdkFido2CredentialView(e);return i.keyValue=t,i}).filter(e=>void 0!==e)}n.push(s)}catch(t){this.logService.error(`Failed to decrypt cipher ${e.id}: ${t}`);const i=new lw(e);i.name="[error: cannot decrypt]",i.decryptionFailure=!0,a.push(i)}}),[n,a]}catch(e){i.error=e,i.hasError=!0}finally{IC(i)}}),Hu(e=>(this.logService.error(`Failed to decrypt ciphers: ${e}`),pe))))}decryptManyWithFailures(e,t){return xC(this,void 0,void 0,function*(){return Ce(this.sdkService.userClient$(t).pipe(X(t=>{const i={stack:[],error:void 0,hasError:!1};try{if(!t)throw new Error("SDK is undefined");const r=CC(i,t.take(),!1).value.vault().ciphers().decrypt_list_with_failures(e.map(e=>e.toSdkCipher()));return[r.successes,r.failures.map(e=>Sw.fromSdkCipher(e)).filter(e=>void 0!==e)]}catch(e){i.error=e,i.hasError=!0}finally{IC(i)}})))})}decryptAttachmentContent(e,t,i,r){return xC(this,void 0,void 0,function*(){return Ce(this.sdkService.userClient$(r).pipe(X(r=>{const n={stack:[],error:void 0,hasError:!1};try{if(!r)throw new Error("SDK is undefined");return CC(n,r.take(),!1).value.vault().attachments().decrypt_buffer(e.toSdkCipher(),t.toSdkAttachmentView(),i)}catch(e){n.error=e,n.hasError=!0}finally{IC(n)}}),Hu(e=>(this.logService.error(`Failed to decrypt cipher buffer: ${e}`),pe))))})}toSdkCipherView(e,t){var i,r;let n=e.toSdkCipherView();if(e.type===rm.Login&&(null===(i=e.login)||void 0===i?void 0:i.hasFido2Credentials)){const i=null===(r=e.login.fido2Credentials)||void 0===r?void 0:r.map(e=>e.toSdkFido2CredentialFullView());n=t.vault().ciphers().set_fido2_credentials(n,i)}return n}}var zC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class PC{constructor(e,t){this.apiService=e,this.fileUploadService=t}upload(e,t,i,r,n){return zC(this,void 0,void 0,function*(){const a={key:n[1].encryptedString,fileName:t.encryptedString,fileSize:i.buffer.byteLength,adminRequest:r,lastKnownRevisionDate:e.revisionDate};let s;try{const n=yield this.apiService.postCipherAttachment(e.id,a);s=r?n.cipherMiniResponse:n.cipherResponse,yield this.fileUploadService.upload(n,t,i,this.generateMethods(n,s,a.adminRequest))}catch(e){throw e instanceof Su?new Error(e.getSingleMessage()):e}return s})}generateMethods(e,t,i){return{postDirect:this.generatePostDirectCallback(e,i),renewFileUploadUrl:this.generateRenewFileUploadUrlCallback(e,t,i),rollback:this.generateRollbackCallback(t,e,i)}}generatePostDirectCallback(e,t){return i=>{const r=t?e.cipherMiniResponse:e.cipherResponse;return this.apiService.postAttachmentFile(r.id,e.attachmentId,i)}}generateRenewFileUploadUrlCallback(e,t,i){return()=>zC(this,void 0,void 0,function*(){const i=yield this.apiService.renewAttachmentUploadUrl(t.id,e.attachmentId);return null==i?void 0:i.url})}generateRollbackCallback(e,t,i){return()=>zC(this,void 0,void 0,function*(){i?yield this.apiService.deleteCipherAttachmentAdmin(e.id,t.attachmentId):yield this.apiService.deleteCipherAttachment(e.id,t.attachmentId)})}}class AC{constructor(e){this.name=e.name?e.name.encryptedString:null}}var jC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class TC{constructor(e,t){this.folderService=e,this.apiService=t}save(e,t){return jC(this,void 0,void 0,function*(){const i=new AC(e);let r;e.id?r=yield this.putFolder(e.id,i):(r=yield this.postFolder(i),e.id=r.id);const n=new qk(r);return yield this.folderService.upsert(n,t),n})}delete(e,t){return jC(this,void 0,void 0,function*(){yield this.deleteFolder(e),yield this.folderService.delete(e,t)})}deleteAll(e){return jC(this,void 0,void 0,function*(){yield this.apiService.send("DELETE","/folders/all",null,!0,!1),yield this.folderService.clear(e)})}get(e){return jC(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET","/folders/"+e,null,!0,!0);return new VS(t)})}postFolder(e){return jC(this,void 0,void 0,function*(){const t=yield this.apiService.send("POST","/folders",e,!0,!0);return new VS(t)})}putFolder(e,t){return jC(this,void 0,void 0,function*(){const i=yield this.apiService.send("PUT","/folders/"+e,t,!0,!0);return new VS(i)})}deleteFolder(e){return this.apiService.send("DELETE","/folders/"+e,null,!0,!1)}}class DC{constructor(e){this.id="",this.name="",e?(this.id=e.id,this.revisionDate=e.revisionDate):this.revisionDate=new Date}static fromJSON(e){var t,i;const r=new DC;return r.id=null!==(t=e.id)&&void 0!==t?t:"",r.name=null!==(i=e.name)&&void 0!==i?i:"",null!=e.revisionDate&&(r.revisionDate=new Date(e.revisionDate)),r}}class OC extends Rt{constructor(e){super(),this.id="",this.name=new Nt(""),this.revisionDate=new Date,null!=e&&(this.id=e.id,this.name=new Nt(e.name),this.revisionDate=new Date(e.revisionDate))}decrypt(e){return this.decryptObj(this,new DC(this),["name"],e)}decryptWithKey(e,t){return i=this,r=void 0,a=function*(){const i=new DC;i.id=this.id,i.revisionDate=this.revisionDate;try{i.name=yield t.decryptString(this.name,e)}catch(e){throw console.error("[Folder] Error decrypting folder",e),e}return i},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}static fromJSON(e){if(null==e)return null;const t=new OC;return t.id=e.id,t.name=Nt.fromJSON(e.name),t.revisionDate=new Date(e.revisionDate),t}}class NC extends AC{constructor(e){super(e),this.id=e.id||null}}const RC=wi.record(fr,"folders",{deserializer:e=>qk.fromJSON(e),clearOn:["logout"]}),UC=new wi(yr,"decryptedFolders",{deserializer:e=>{var t;return null!==(t=null==e?void 0:e.map(e=>DC.fromJSON(e)))&&void 0!==t?t:[]},clearOn:["logout","lock"]});var FC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class qC{constructor(e,t,i,r,n){this.keyService=e,this.encryptService=t,this.i18nService=i,this.cipherService=r,this.stateProvider=n,this.folderViewCache=new Map,this.forceFolderViews={}}folders$(e){return this.encryptedFoldersState(e).state$.pipe(X(e=>null==e?[]:Object.values(e).map(e=>new OC(e))))}folderViews$(e){if(!this.folderViewCache.has(e)){this.forceFolderViews[e]||(this.forceFolderViews[e]=new H);const t=_e(this.forceFolderViews[e],ai([this.encryptedFoldersState(e).state$,this.keyService.userKey$(e)]).pipe(Ie(([e,t])=>null!=e&&null!=t),Le(([t,i])=>this.decryptFolders(e,t)))).pipe(Jt({refCount:!1,bufferSize:1}));this.folderViewCache.set(e,t)}return this.folderViewCache.get(e)}encrypt(e,t){return FC(this,void 0,void 0,function*(){const i=new OC;return i.id=e.id,i.name=yield this.encryptService.encryptString(e.name,t),i})}get(e,t){return FC(this,void 0,void 0,function*(){return(yield Ce(this.folders$(t))).find(t=>t.id===e)})}getDecrypted$(e,t){return this.folderViews$(t).pipe(X(t=>t.find(t=>t.id===e)),Jt({refCount:!0,bufferSize:1}))}getAllFromState(e){return FC(this,void 0,void 0,function*(){return yield Ce(this.folders$(e))})}getFromState(e,t){return FC(this,void 0,void 0,function*(){return(yield this.get(e,t))||null})}getAllDecryptedFromState(e){return FC(this,void 0,void 0,function*(){return yield Ce(this.folderViews$(e))})}upsert(e,t){return FC(this,void 0,void 0,function*(){yield this.clearDecryptedFolderState(t),yield this.encryptedFoldersState(t).update(t=>{if(null==t&&(t={}),e instanceof qk){const i=e;t[i.id]=i}else e.forEach(e=>{t[e.id]=e});return t})})}replace(e,t){return FC(this,void 0,void 0,function*(){e&&(yield this.clearDecryptedFolderState(t),yield this.stateProvider.getUser(t,RC).update(()=>Object.assign({},e)))})}clearDecryptedFolderState(e){return FC(this,void 0,void 0,function*(){if(null==e)throw new Error("User ID is required.");yield this.setDecryptedFolders([],e)})}clear(e){return FC(this,void 0,void 0,function*(){var t;null===(t=this.forceFolderViews[e])||void 0===t||t.next([]),yield this.encryptedFoldersState(e).update(()=>({})),yield this.clearDecryptedFolderState(e)})}delete(e,t){return FC(this,void 0,void 0,function*(){yield this.clearDecryptedFolderState(t),yield this.encryptedFoldersState(t).update(t=>{if(null!=t)return(Array.isArray(e)?e:[e]).forEach(e=>{null!=t[e]&&delete t[e]}),t});const i=yield this.cipherService.getAll(t);if(null!=i){const t=[];for(const r in i)i[r].folderId===e&&(i[r].folderId=null,t.push(i[r]));t.length>0&&(yield this.cipherService.upsert(t.map(e=>e.toCipherData())))}})}getRotatedData(e,t,i){return FC(this,void 0,void 0,function*(){if(null==t)throw new Error("New user key is required for rotation.");let e=[];const r=yield Ce(this.folderViews$(i));return r?(e=yield Promise.all(r.map(e=>FC(this,void 0,void 0,function*(){const i=yield this.encrypt(e,t);return new NC(i)}))),e):e})}decryptFolders(e,t){return FC(this,void 0,void 0,function*(){const i=yield Ce(this.stateProvider.getUser(e,UC).state$);if(null==i?void 0:i.length)return i;if(null==t)return[];const r=Object.values(t).map(e=>new OC(e)),n=yield Ce(this.keyService.userKey$(e));if(!n)return[];const a=r.map(e=>FC(this,void 0,void 0,function*(){try{return yield e.decryptWithKey(n,this.encryptService)}catch(e){return null}})),s=(yield Promise.all(a)).filter(e=>null!==e).sort(Tt.getSortFunction(this.i18nService,"name")),o=new DC;return o.name=this.i18nService.t("noneFolder"),s.push(o),yield this.setDecryptedFolders(s,e),s})}encryptedFoldersState(e){return this.stateProvider.getUser(e,RC)}setDecryptedFolders(e,t){return FC(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(UC,e,t)})}}class LC{constructor(e,t,i){this.accountService=e,this.organizationService=t,this.policyService=i,this.restricted$=this.accountService.activeAccount$.pipe(iu,Le(e=>null==e?bt([]):ai([this.organizationService.organizations$(e),this.policyService.policiesByType$(Ye.RestrictedItemTypes,e)]).pipe(X(([e,t])=>{const i=e=>{var t;return null!==(t=e.data)&&void 0!==t?t:[rm.Card]};return Array.from(new Set(t.flatMap(i))).map(r=>{const n=e.filter(e=>{const n=t.find(t=>t.organizationId===e.id);return!n||!i(n).includes(r)}).map(e=>e.id);return{cipherType:r,allowViewOrgIds:n}})}))),Zl(),Jt({bufferSize:1,refCount:!0}))}isCipherRestricted(e,t){const i=t.find(t=>t.cipherType===vC.getType(e));return!(!i||e.organizationId&&i.allowViewOrgIds.includes(e.organizationId))}isCipherRestricted$(e){return this.restricted$.pipe(X(t=>this.isCipherRestricted(e,t)))}}var BC=o(1998),MC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const VC=new wi(br,"searchIndex",{deserializer:e=>e,clearOn:["lock","logout"]}),$C=new wi(br,"searchIndexedEntityId",{deserializer:e=>e,clearOn:["lock","logout"]}),KC=new wi(br,"isIndexing",{deserializer:e=>e,clearOn:["lock","logout"]});class WC{constructor(e,t,i){this.logService=e,this.i18nService=t,this.stateProvider=i,this.immediateSearchLocales=["zh-CN","zh-TW","ja","ko","vi"],this.defaultSearchableMinLength=2,this.searchableMinLength=this.defaultSearchableMinLength,this._isCipherSearching$=new $c(!1),this.isCipherSearching$=this._isCipherSearching$.asObservable(),this._isSendSearching$=new $c(!1),this.isSendSearching$=this._isSendSearching$.asObservable(),this.index$=Wx(e=>this.searchIndexState(e).state$.pipe(X(e=>{let t=null;if(e){const i=performance.now();t=BC.Index.load(e),this.logService.measure(i,"Vault","SearchService","index load")}return t}))),this.i18nService.locale$.subscribe(e=>{-1!==this.immediateSearchLocales.indexOf(e)?this.searchableMinLength=1:this.searchableMinLength=this.defaultSearchableMinLength}),WC.registeredPipeline||(WC.registeredPipeline=!0,BC.Pipeline.registerFunction(this.normalizeAccentsPipelineFunction,"normalizeAccents"))}searchIndexState(e){return this.stateProvider.getUser(e,VC)}searchIndexEntityIdState(e){return this.stateProvider.getUser(e,$C)}indexedEntityId$(e){return this.searchIndexEntityIdState(e).state$.pipe(X(e=>e))}searchIsIndexingState(e){return this.stateProvider.getUser(e,KC)}searchIsIndexing$(e){return this.searchIsIndexingState(e).state$.pipe(X(e=>null!=e&&e))}clearIndex(e){return MC(this,void 0,void 0,function*(){yield this.searchIndexEntityIdState(e).update(()=>null),yield this.searchIndexState(e).update(()=>null),yield this.searchIsIndexingState(e).update(()=>null)})}isSearchable(e,t){return MC(this,void 0,void 0,function*(){return null!=(t=WC.normalizeSearchQuery(t))&&""!==t&&(0===t.indexOf(">")?null!=(yield this.getIndexForSearch(e)):t.length>=this.searchableMinLength)})}indexCiphers(e,t,i){return MC(this,void 0,void 0,function*(){if(yield this.getIsIndexing(e))return;const r=performance.now();yield this.setIsIndexing(e,!0),yield this.setIndexedEntityIdForSearch(e,i);const n=new BC.Builder;n.pipeline.add(this.normalizeAccentsPipelineFunction),n.ref("id"),n.field("shortid",{boost:100,extractor:e=>e.id.substr(0,8)}),n.field("name",{boost:10}),n.field("subtitle",{boost:5,extractor:e=>{const t=vC.subtitle(e);return null!=t&&vC.getType(e)===rm.Card?t.replace(/\*/g,""):t}}),n.field("notes",{extractor:e=>vC.getNotes(e)}),n.field("login.username",{extractor:e=>{var t;const i=vC.getLogin(e);return null!==(t=null==i?void 0:i.username)&&void 0!==t?t:null}}),n.field("login.uris",{boost:2,extractor:e=>this.uriExtractor(e)}),n.field("fields",{extractor:e=>this.fieldExtractor(e,!1)}),n.field("fields_joined",{extractor:e=>this.fieldExtractor(e,!0)}),n.field("attachments",{extractor:e=>this.attachmentExtractor(e,!1)}),n.field("attachments_joined",{extractor:e=>this.attachmentExtractor(e,!0)}),n.field("organizationid",{extractor:e=>e.organizationId}),(t=t||[]).forEach(e=>n.add(e));const a=n.build();yield this.setIndexForSearch(e,a.toJSON()),yield this.setIsIndexing(e,!1),this.logService.measure(r,"Vault","SearchService","index complete",[["Items",t.length]])})}searchCiphers(e,t){return MC(this,arguments,void 0,function*(e,t,i=null,r){this._isCipherSearching$.next(!0);const n=[],a=performance.now();if(null!=t&&(t=WC.normalizeSearchQuery(t.trim().toLowerCase())),""===t&&(t=null),null==r&&(r=[]),null!=i&&Array.isArray(i)&&i.length>0?r=r.filter(e=>i.every(t=>null==t||t(e))):null!=i&&(r=r.filter(i)),!(yield this.isSearchable(e,t)))return this._isCipherSearching$.next(!1),r;(yield this.getIsIndexing(e))&&(yield new Promise(e=>setTimeout(e,250)),(yield this.getIsIndexing(e))&&(yield new Promise(e=>setTimeout(e,500))));const s=yield this.getIndexForSearch(e);if(null==s){const e=this.searchCiphersBasic(r,t);return this.logService.measure(a,"Vault","SearchService","basic search complete"),this._isCipherSearching$.next(!1),e}const o=new Map;r.forEach(e=>o.set(e.id,e));let l=null;if(null!=t&&t.length>1&&0===t.indexOf(">"))try{l=s.search(t.substr(1).trim())}catch(e){this.logService.error(e)}else{const e=BC.Query.wildcard.LEADING|BC.Query.wildcard.TRAILING;l=s.query(i=>{BC.tokenizer(t).forEach(t=>{const r=t.toString();i.term(r,{fields:["name"],wildcard:e}),i.term(r,{fields:["subtitle"],wildcard:e}),i.term(r,{fields:["login.uris"],wildcard:e}),i.term(r,{})})})}return null!=l&&l.forEach(e=>{o.has(e.ref)&&n.push(o.get(e.ref))}),this.logService.measure(a,"Vault","SearchService","search complete"),this._isCipherSearching$.next(!1),n})}searchCiphersBasic(e,t,i=!1,r=!1){return t=WC.normalizeSearchQuery(t.trim().toLowerCase()),e.filter(e=>{var n,a;if(i!==vC.isDeleted(e))return!1;if(r!==vC.isArchived(e))return!1;if(null!=e.name&&e.name.toLowerCase().indexOf(t)>-1)return!0;if(t.length>=8&&e.id.startsWith(t))return!0;const s=vC.subtitle(e);if(null!=s&&s.toLowerCase().indexOf(t)>-1)return!0;const o=vC.getLogin(e);return!!(o&&(null===(n=o.uris)||void 0===n?void 0:n.length)&&(null===(a=o.uris)||void 0===a?void 0:a.some(e=>(null==e?void 0:e.uri)&&e.uri.toLowerCase().indexOf(t)>-1)))})}searchSends(e,t){if(this._isSendSearching$.next(!0),null===(t=WC.normalizeSearchQuery(t.trim().toLocaleLowerCase())))return this._isSendSearching$.next(!1),e;const i=[],r=[];return e.forEach(e=>{var n,a,s;null!=e.name&&e.name.toLowerCase().indexOf(t)>-1?i.push(e):(t.length>=8&&(e.id.startsWith(t)||e.accessId.toLocaleLowerCase().startsWith(t)||null!=(null===(n=e.file)||void 0===n?void 0:n.id)&&e.file.id.startsWith(t))||null!=e.notes&&e.notes.toLowerCase().indexOf(t)>-1||null!=(null===(a=e.text)||void 0===a?void 0:a.text)&&e.text.text.toLowerCase().indexOf(t)>-1||null!=(null===(s=e.file)||void 0===s?void 0:s.fileName)&&e.file.fileName.toLowerCase().indexOf(t)>-1)&&r.push(e)}),this._isSendSearching$.next(!1),i.concat(r)}getIndexForSearch(e){return MC(this,void 0,void 0,function*(){return yield Ce(this.index$(e))})}setIndexForSearch(e,t){return MC(this,void 0,void 0,function*(){yield this.searchIndexState(e).update(()=>t)})}setIndexedEntityIdForSearch(e,t){return MC(this,void 0,void 0,function*(){yield this.searchIndexEntityIdState(e).update(()=>t)})}setIsIndexing(e,t){return MC(this,void 0,void 0,function*(){yield this.searchIsIndexingState(e).update(()=>t)})}getIsIndexing(e){return MC(this,void 0,void 0,function*(){return yield Ce(this.searchIsIndexing$(e))})}fieldExtractor(e,t){const i=vC.getFields(e);if(!i||0===i.length)return null;let r=[];return i.forEach(e=>{if(null!=e.name&&r.push(e.name),null!=e.value){const t=e.type;void 0!==t&&t!==am.Text||r.push(e.value)}}),r=r.filter(e=>""!==e.trim()),0===r.length?null:t?r.join(" "):r}attachmentExtractor(e,t){const i=vC.getAttachmentNames(e);if(!i||0===i.length)return null;let r=[];return i.forEach(e=>{null!=e&&(t&&e.indexOf(".")>-1?r.push(e.substring(0,e.lastIndexOf("."))):r.push(e))}),r=r.filter(e=>""!==e.trim()),0===r.length?null:t?r.join(" "):r}uriExtractor(e){var t;if(vC.getType(e)!==rm.Login)return null;const i=vC.getLogin(e);if(!(null===(t=null==i?void 0:i.uris)||void 0===t?void 0:t.length))return null;const r=[];return i.uris.forEach(e=>{if(null==e.uri||""===e.uri)return;const t=e.uri.match(/:(\d+)(?:[/?#]|$)/),i=null==t?void 0:t[1],n=vC.getUriHostname(e);void 0!==n&&(r.push(n),i&&(r.push(`${n}:${i}`),r.push(i)));let a=e.uri;if(e.match!==Xm.RegularExpression){const e=a.indexOf("://");e>-1&&(a=a.substring(e+3));const t=a.search(/\?|&|#/);t>-1&&(a=a.substring(0,t))}r.push(a)}),r.length>0?r:null}normalizeAccentsPipelineFunction(e){const t=["name","login.username","subtitle","notes"];return e.metadata.fields.every(e=>t.includes(e))?WC.normalizeSearchQuery(e.toString()):e}static normalizeSearchQuery(e){return null==e?void 0:e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}}WC.registeredPipeline=!1;class HC{constructor(e){this.sdkService=e}getCode$(e){return sc(0,1e3).pipe(Le(()=>this.sdkService.client$.pipe(X(t=>t.vault().totp().generate_totp(e)))),Jt({refCount:!0,bufferSize:1}))}}const GC=new fi(vr,"enablePasskeys",{deserializer:e=>e}),QC=new wi(vr,"showCardsCurrentTab",{deserializer:e=>e,clearOn:[]}),JC=new wi(vr,"showIdentitiesCurrentTab",{deserializer:e=>e,clearOn:[]}),YC=new wi(vr,"clickItemsToAutofillOnVaultView",{deserializer:e=>e,clearOn:[]});var XC=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class ZC{constructor(e,t){this.stateProvider=e,this.restrictedItemTypesService=t,this.enablePasskeysState=this.stateProvider.getGlobal(GC),this.enablePasskeys$=this.enablePasskeysState.state$.pipe(X(e=>null==e||e)),this.showCardsCurrentTabState=this.stateProvider.getActive(QC),this.showCardsCurrentTab$=ai([this.showCardsCurrentTabState.state$.pipe(X(e=>null==e||e)),this.restrictedItemTypesService.restricted$]).pipe(X(([e,t])=>e&&!t.some(e=>e.cipherType===rm.Card))),this.showIdentitiesCurrentTabState=this.stateProvider.getActive(JC),this.showIdentitiesCurrentTab$=this.showIdentitiesCurrentTabState.state$.pipe(X(e=>null==e||e)),this.clickItemsToAutofillVaultViewState=this.stateProvider.getActive(YC),this.clickItemsToAutofillVaultView$=this.clickItemsToAutofillVaultViewState.state$.pipe(X(e=>null!=e&&e),Jt({bufferSize:1,refCount:!1}))}setShowCardsCurrentTab(e){return XC(this,void 0,void 0,function*(){yield this.showCardsCurrentTabState.update(()=>e)})}setShowIdentitiesCurrentTab(e){return XC(this,void 0,void 0,function*(){yield this.showIdentitiesCurrentTabState.update(()=>e)})}setClickItemsToAutofillVaultView(e){return XC(this,void 0,void 0,function*(){yield this.clickItemsToAutofillVaultViewState.update(()=>e)})}setEnablePasskeys(e){return XC(this,void 0,void 0,function*(){yield this.enablePasskeysState.update(()=>e)})}}class eI{constructor(e){this.id=e.id,this.organizationId=e.organizationId,this.cipherId=e.cipherId,this.type=e.type,this.status=e.status,this.creationDate=e.creationDate,this.revisionDate=e.revisionDate}}class tI{constructor(e){this.id=e.id,this.organizationId=e.organizationId,this.cipherId=e.cipherId,this.type=e.type,this.status=e.status,this.creationDate=e.creationDate,this.revisionDate=e.revisionDate}static fromJSON(e){return Object.assign(new tI({}),e,{creationDate:new Date(e.creationDate),revisionDate:new Date(e.revisionDate)})}}class iI extends Lt{constructor(e){super(e),this.id=this.getResponseProperty("Id"),this.organizationId=this.getResponseProperty("OrganizationId"),this.cipherId=this.getResponseProperty("CipherId")||void 0,this.type=this.getResponseProperty("Type"),this.status=this.getResponseProperty("Status"),this.creationDate=this.getResponseProperty("CreationDate"),this.revisionDate=this.getResponseProperty("RevisionDate")}}const rI=wi.array(_r,"securityTasks",{deserializer:e=>tI.fromJSON(e),clearOn:["logout","lock"]});var nI=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const aI=X(e=>Object.entries(null!=e?e:{}).filter(([,e])=>e>=cu.Unlocked).map(([e])=>e));class sI{constructor(e,t,i,r,n,a){this.stateProvider=e,this.apiService=t,this.organizationService=i,this.authService=r,this.notificationService=n,this.messageListener=a,this.tasksEnabled$=Wx(e=>this.organizationService.organizations$(e).pipe(X(e=>e.some(e=>e.canUseAccessIntelligence)),Zl())),this.tasks$=Wx(e=>this.tasksEnabled$(e).pipe(Le(t=>t?this.taskState(e).state$.pipe(Le(t=>nI(this,void 0,void 0,function*(){return null==t?(yield this.fetchTasksFromApi(e),null):t})),Hx(),X(e=>e.map(e=>new eI(e)))):bt([])))),this.pendingTasks$=Wx(e=>this.tasks$(e).pipe(X(e=>e.filter(e=>0===e.status)))),this.completedTasks$=Wx(e=>this.tasks$(e).pipe(X(e=>e.filter(e=>1===e.status)))),this.getOnlyTaskEnabledUsers=Le(e=>0===e.length?bt([]):ai(e.map(e=>this.tasksEnabled$(e).pipe(X(t=>t?e:null)))).pipe(X(e=>e.filter(e=>null!==e))))}refreshTasks(e){return nI(this,void 0,void 0,function*(){yield this.fetchTasksFromApi(e)})}clear(e){return nI(this,void 0,void 0,function*(){yield this.updateTaskState(e,[])})}markAsComplete(e,t){return nI(this,void 0,void 0,function*(){yield this.apiService.send("PATCH",`/tasks/${e}/complete`,null,!0,!1),yield this.refreshTasks(t)})}fetchTasksFromApi(e){return nI(this,void 0,void 0,function*(){const t=yield this.apiService.send("GET","/tasks",null,!0,!0),i=new Tc(t,iI).data.map(e=>new tI(e));yield this.updateTaskState(e,i)})}taskState(e){return this.stateProvider.getUser(e,rI)}updateTaskState(e,t){return this.taskState(e).update(()=>t)}securityTaskNotifications$(e){return this.notificationService.notifications$.pipe(Ie(([t,i])=>t.type===dh.RefreshSecurityTasks&&e.includes(i)),X(([,e])=>e))}syncCompletedMessage$(e){return this.messageListener.allMessages$.pipe(Ie(e=>"syncCompleted"===e.command&&!!e.successfully&&!!e.userId),X(e=>e.userId),Ie(t=>e.includes(t)))}listenForTaskNotifications(){return this.authService.authStatuses$.pipe(aI,this.getOnlyTaskEnabledUsers,Ie(e=>e.length>0),Le(e=>_e(this.securityTaskNotifications$(e),this.syncCompletedMessage$(e))),Le(e=>this.refreshTasks(e))).subscribe()}}const oI=Object.freeze({catchallType:"random",catchallDomain:"",website:null}),lI=function(){const e=Object.freeze({min:3,max:20});return Object.freeze({numWords:e})}(),cI=function(){const e=Object.freeze({min:5,max:128}),t=Object.freeze({min:0,max:9}),i=Object.freeze({min:0,max:9});return Object.freeze({length:e,minDigits:t,minSpecialCharacters:i})}(),uI=Object.freeze({wordCapitalize:!1,wordIncludeNumber:!1,website:null}),dI=Object.freeze({numWords:6,wordSeparator:"-",capitalize:!1,includeNumber:!1}),hI=Object.freeze({length:14,minLength:cI.length.min,ambiguous:!0,uppercase:!0,minUppercase:1,lowercase:!0,minLowercase:1,number:!0,minNumber:1,special:!1,minSpecial:0}),pI=Object.freeze({subaddressType:"random",subaddressEmail:"",website:null});class mI{constructor(e){this.keys=e}classify(e){const t=JSON.parse(JSON.stringify(e)),i={};for(const e of this.keys)i[e]=t[e];return{disclosed:i,secret:null}}declassify(e,t){const i={};for(const t of this.keys)i[t]=e[t];return i}}class gI{constructor(e,t,i){this.stateDefinition=e,this.key=t,this.options=i}toKeyDefinition(){return new wi(this.stateDefinition,this.key,this.options)}shouldOverwrite(e){var t;const i=null===(t=this.options)||void 0===t?void 0:t.shouldOverwrite;return i?i(e):!!e}map(e,t){var i;const r=null===(i=this.options)||void 0===i?void 0:i.map;return r?r(e,t):Promise.resolve(e)}isValid(e,t){var i;if(null===e)return Promise.resolve(!1);const r=null===(i=this.options)||void 0===i?void 0:i.isValid;return r?r(e,t):Promise.resolve(!!e)}}const fI=Object.freeze({token:"",domain:"",baseUrl:""}),yI=Object.freeze({url:(e,t)=>t.baseUrl()+"/api/v1/aliases",body:(e,t)=>({domain:t.emailDomain(),description:t.generatedBy(e,{extractHostname:!0,maxLength:200})}),hasJsonPayload:e=>200===e.status||201===e.status,processJson(e){var t;return[null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.email]}}),vI=Object.freeze({defaultSettings:fI,createForwardingEmail:yI,request:["token","baseUrl","domain"],settingsConstraints:{token:{required:!0},domain:{required:!0},baseUrl:{}},local:{settings:{key:"addyIoForwarder",target:"object",format:"secret-state",frame:512,classifier:new wx,state:cr,initial:fI,options:{deserializer:e=>e,clearOn:["logout"]}},import:{key:"forwarder.AddyIo.local.import",target:"object",format:"plain",classifier:new mI(["token","baseUrl","domain"]),state:ur,options:{deserializer:e=>e,clearOn:["logout","lock"]}}},settings:new wi(cr,"addyIoForwarder",{deserializer:e=>e,clearOn:[]}),importBuffer:new gI(cr,"addyIoBuffer",{deserializer:e=>e,clearOn:["logout"]})}),bI=Object.freeze({id:H_.addyio,name:"Addy.io",extends:["forwarder"],selfHost:"maybe",baseUrl:"https://app.addy.io",authenticate:(e,t)=>({Authorization:"Bearer "+t.authenticationToken()}),forwarder:vI}),wI=Object.freeze({token:""}),kI=Object.freeze({url:(e,t)=>t.baseUrl()+"/email/addresses",body(e,t){},hasJsonPayload:e=>200===e.status||201===e.status,processJson:e=>[`${e.address}@duck.com`]}),SI=Object.freeze({defaultSettings:wI,createForwardingEmail:kI,request:["token"],settingsConstraints:{token:{required:!0}},local:{settings:{key:"duckDuckGoForwarder",target:"object",format:"secret-state",frame:512,classifier:new wx,state:cr,initial:wI,options:{deserializer:e=>e,clearOn:["logout"]}},import:{key:"forwarder.DuckDuckGo.local.import",target:"object",format:"plain",classifier:new mI(["token"]),state:ur,options:{deserializer:e=>e,clearOn:["logout","lock"]}}},settings:new wi(cr,"duckDuckGoForwarder",{deserializer:e=>e,clearOn:[]}),importBuffer:new gI(cr,"duckDuckGoBuffer",{deserializer:e=>e,clearOn:["logout"]})}),_I=Object.freeze({id:H_.duckduckgo,name:"DuckDuckGo",baseUrl:"https://quack.duckduckgo.com/api",selfHost:"never",extends:["forwarder"],authenticate:(e,t)=>({Authorization:"Bearer "+t.authenticationToken()}),forwarder:SI}),xI=Object.freeze({domain:"",prefix:"",token:""}),CI=Object.freeze({url:(e,t)=>t.baseUrl()+"/jmap/session",hasJsonPayload:e=>200===e.status,processJson(e,t){var i,r;const n=null!==(r=null===(i=e.primaryAccounts)||void 0===i?void 0:i["https://www.fastmail.com/dev/maskedemail"])&&void 0!==r?r:void 0;return[n,n?void 0:t.missingAccountIdCause()]}}),II=Object.freeze({url:(e,t)=>t.baseUrl()+"/jmap/api/",body:(e,t)=>({using:["https://www.fastmail.com/dev/maskedemail","urn:ietf:params:jmap:core"],methodCalls:[["MaskedEmail/set",{accountId:e.accountId,create:{"new-masked-email":{state:"enabled",description:"",forDomain:t.website(e),emailPrefix:""}}},"0"]]}),hasJsonPayload:e=>200===e.status,processJson(e){var t,i,r,n,a,s,o,l,c,u,d;if(null!=e.methodResponses&&e.methodResponses.length>0&&e.methodResponses[0].length>0)if("MaskedEmail/set"===e.methodResponses[0][0]){if(null!=(null===(i=null===(t=e.methodResponses[0][1])||void 0===t?void 0:t.created)||void 0===i?void 0:i["new-masked-email"]))return[null===(a=null===(n=null===(r=e.methodResponses[0][1])||void 0===r?void 0:r.created)||void 0===n?void 0:n["new-masked-email"])||void 0===a?void 0:a.email];if(null!=(null===(o=null===(s=e.methodResponses[0][1])||void 0===s?void 0:s.notCreated)||void 0===o?void 0:o["new-masked-email"]))return[void 0,null===(u=null===(c=null===(l=e.methodResponses[0][1])||void 0===l?void 0:l.notCreated)||void 0===c?void 0:c["new-masked-email"])||void 0===u?void 0:u.description]}else if("error"===e.methodResponses[0][0])return[void 0,null===(d=e.methodResponses[0][1])||void 0===d?void 0:d.description]}}),EI=Object.freeze({defaultSettings:xI,createForwardingEmail:II,getAccountId:CI,request:["token"],settingsConstraints:{token:{required:!0},domain:{required:!0},prefix:{}},local:{settings:{key:"fastmailForwarder",target:"object",format:"secret-state",frame:512,classifier:new wx,state:cr,initial:xI,options:{deserializer:e=>e,clearOn:["logout"]}},import:{key:"forwarder.Fastmail.local.import",target:"object",format:"plain",classifier:new mI(["token"]),state:ur,options:{deserializer:e=>e,clearOn:["logout","lock"]}}},settings:new wi(cr,"fastmailForwarder",{deserializer:e=>e,clearOn:[]}),importBuffer:new gI(cr,"fastmailBuffer",{deserializer:e=>e,clearOn:["logout"]})}),zI=Object.freeze({id:H_.fastmail,name:"Fastmail",baseUrl:"https://api.fastmail.com",selfHost:"maybe",extends:["forwarder"],authenticate:(e,t)=>({Authorization:"Bearer "+t.authenticationToken()}),forwarder:EI}),PI=Object.freeze({token:""}),AI=Object.freeze({url:(e,t)=>t.baseUrl()+"/v1/relayaddresses/",body:(e,t)=>({enabled:!0,generated_for:t.website(e,{maxLength:255}),description:t.generatedBy(e,{extractHostname:!0,maxLength:64})}),hasJsonPayload:e=>200===e.status||201===e.status,processJson:e=>[e.full_address]}),jI=Object.freeze({defaultSettings:PI,createForwardingEmail:AI,request:["token"],settingsConstraints:{token:{required:!0}},local:{settings:{key:"firefoxRelayForwarder",target:"object",format:"secret-state",frame:512,classifier:new wx,state:cr,initial:PI,options:{deserializer:e=>e,clearOn:["logout"]}},import:{key:"forwarder.Firefox.local.import",target:"object",format:"plain",classifier:new mI(["token"]),state:ur,options:{deserializer:e=>e,clearOn:["logout","lock"]}}},settings:new wi(cr,"firefoxRelayForwarder",{deserializer:e=>e,clearOn:[]}),importBuffer:new gI(cr,"firefoxRelayBuffer",{deserializer:e=>e,clearOn:["logout"]})}),TI=Object.freeze({id:H_.mozilla,name:"Firefox Relay",baseUrl:"https://relay.firefox.com/api",selfHost:"never",extends:["forwarder"],authenticate:(e,t)=>({Authorization:"Token "+t.authenticationToken()}),forwarder:jI}),DI=Object.freeze({token:"",domain:""}),OI=Object.freeze({url(e,t){const i=t.emailDomain();return t.baseUrl()+`/v1/domains/${i}/aliases`},body:(e,t)=>({labels:t.website(e),description:t.generatedBy(e)}),hasJsonPayload:e=>200===e.status||201===e.status,processJson(e,t){var i;const{name:r,domain:n}=e;return[`${r}@${null!==(i=null==n?void 0:n.name)&&void 0!==i?i:t.emailDomain()}`]}}),NI=Object.freeze({defaultSettings:DI,request:["token","domain"],settingsConstraints:{token:{required:!0},domain:{required:!0}},local:{settings:{key:"forwardEmailForwarder",target:"object",format:"secret-state",frame:512,classifier:new wx,state:cr,initial:DI,options:{deserializer:e=>e,clearOn:["logout"]}},import:{key:"forwarder.ForwardEmail.local.import",target:"object",format:"plain",classifier:new mI(["token","domain"]),state:ur,options:{deserializer:e=>e,clearOn:["logout","lock"]}}},settings:new wi(cr,"forwardEmailForwarder",{deserializer:e=>e,clearOn:[]}),importBuffer:new gI(cr,"forwardEmailBuffer",{deserializer:e=>e,clearOn:["logout"]}),createForwardingEmail:OI}),RI=Object.freeze({id:H_.forwardemail,name:"Forward Email",extends:["forwarder"],selfHost:"never",baseUrl:"https://api.forwardemail.net",authenticate:(e,t)=>({Authorization:"Basic "+t.authenticationToken({base64:!0,suffix:":"})}),forwarder:NI}),UI=Object.freeze({token:"",domain:"",baseUrl:""}),FI=Object.freeze({url(e,t){const i=t.baseUrl()+"/api/alias/random/new",r=t.website(e);return""!==r?`${i}?hostname=${r}`:i},body:(e,t)=>({note:t.generatedBy(e)}),hasJsonPayload:e=>200===e.status||201===e.status,processJson:e=>[null==e?void 0:e.alias]}),qI=Object.freeze({defaultSettings:UI,createForwardingEmail:FI,request:["token","baseUrl"],settingsConstraints:{token:{required:!0}},local:{settings:{key:"simpleLoginForwarder",target:"object",format:"secret-state",frame:512,classifier:new wx,state:cr,initial:UI,options:{deserializer:e=>e,clearOn:["logout"]}},import:{key:"forwarder.SimpleLogin.local.import",target:"object",format:"plain",classifier:new mI(["token","baseUrl"]),state:ur,options:{deserializer:e=>e,clearOn:["logout","lock"]}}},settings:new wi(cr,"simpleLoginForwarder",{deserializer:e=>e,clearOn:[]}),importBuffer:new gI(cr,"simpleLoginBuffer",{deserializer:e=>e,clearOn:["logout"]})}),LI=Object.freeze({id:H_.simplelogin,name:"SimpleLogin",selfHost:"maybe",extends:["forwarder"],baseUrl:"https://app.simplelogin.io",authenticate:(e,t)=>({Authentication:t.authenticationToken()}),forwarder:qI}),BI=Object.freeze({AddyIo:bI,DuckDuckGo:_I,Fastmail:zI,FirefoxRelay:TI,ForwardEmail:RI,SimpleLogin:LI});new Map(Object.values(BI).map(e=>[e.id,e]));var MI=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class VI{constructor(){}pick(e){return MI(this,void 0,void 0,function*(){var t;if((null!==(t=null==e?void 0:e.length)&&void 0!==t?t:0)<=0)throw new Error("list must have at least one entry.");const i=yield this.uniform(0,e.length-1);return e[i]})}pickWord(e,t){return MI(this,void 0,void 0,function*(){var i,r;let n=yield this.pick(e);return null!==(i=null==t?void 0:t.titleCase)&&void 0!==i&&i&&(n=n.charAt(0).toUpperCase()+n.slice(1)),null!==(r=null==t?void 0:t.number)&&void 0!==r&&r&&(yield xg.Ready,n+=Sg.IEs.random_number(0,9).toString()),n})}shuffle(e,t){return MI(this,void 0,void 0,function*(){var i,r;if((null!==(i=null==e?void 0:e.length)&&void 0!==i?i:0)<=0)throw new Error("items must have at least one entry.");const n=null===(r=null==t?void 0:t.copy)||void 0===r||r?[...e]:e;for(let e=n.length-1;e>0;e--){const t=yield this.uniform(0,e);[n[e],n[t]]=[n[t],n[e]]}return n})}chars(e){return MI(this,void 0,void 0,function*(){let t="";for(let i=0;it)})}evaluator$(e){let t=this._evaluators$.get(e);return t||(t=this.createEvaluator(e),this._evaluators$.set(e,t)),t}createEvaluator(e){return this.policy.policiesByType$(this.strategy.policy,e).pipe(this.strategy.toEvaluator())}enforcePolicy(e,t){return $I(this,void 0,void 0,function*(){const i=yield Ce(this.evaluator$(e)),r=i.applyPolicy(t);return i.sanitize(r)})}generate(e){return $I(this,void 0,void 0,function*(){return yield this.strategy.generate(e)})}}const WI=Object.freeze({password:"password",passphrase:"passphrase",username:"username",catchall:"catchall",plusAddress:"subaddress"}),HI=Object.freeze({password:"password",username:"username",email:"email"}),GI=Object.freeze({account:"account"}),QI=V_({[HI.password]:[WI.password,WI.passphrase],[HI.username]:[WI.username],[HI.email]:[WI.catchall,WI.plusAddress]});class JI{constructor(e,t,i){this.metadata=e,this.settings=t,this.i18n=i}baseUrl(){var e,t;const i=null!==(e=this.settings&&"baseUrl"in this.settings?this.settings.baseUrl:void 0)&&void 0!==e?e:"";let r="";if(r="always"===this.metadata.selfHost?i:"never"===this.metadata.selfHost||i.length<=0?null!==(t=this.metadata.baseUrl)&&void 0!==t?t:"":i,""===r)throw this.i18n.t("forwarderNoUrl",this.metadata.name);return r}authenticationToken(e=null){var t,i;let r="token"in this.settings&&null!==(t=this.settings.token)&&void 0!==t?t:"";if(""===r)throw this.i18n.t("forwaderInvalidToken",this.metadata.name);return r+=null!==(i=null==e?void 0:e.suffix)&&void 0!==i?i:"",(null==e?void 0:e.base64)&&(r=Tt.fromUtf8ToB64(r)),r}website(e,t){var i,r;let n=null!==(i=e.website)&&void 0!==i?i:"";return(null==t?void 0:t.extractHostname)&&(n=null!==(r=Tt.getHost(n))&&void 0!==r?r:n),n.slice(0,null==t?void 0:t.maxLength)}generatedBy(e,t){var i;const r=this.website(e,{extractHostname:null!==(i=null==t?void 0:t.extractHostname)&&void 0!==i&&i}),n=""===r?"forwarderGeneratedBy":"forwarderGeneratedByWithWebsite";return this.i18n.t(n,r).slice(0,null==t?void 0:t.maxLength)}}class YI extends JI{constructor(e,t,i){super(e,t,i),this.configuration=e}emailDomain(){var e;const t="domain"in this.settings&&null!==(e=this.settings.domain)&&void 0!==e?e:"";if(""===t)throw this.i18n.t("forwarderNoDomain",this.configuration.name);return t}emailPrefix(){var e;const t="prefix"in this.settings&&null!==(e=this.settings.prefix)&&void 0!==e?e:"";if(""===t)throw this.i18n.t("forwarderNoPrefix",this.configuration.name);return t}missingAccountIdCause(){return this.i18n.t("forwarderNoAccountId",this.configuration.name)}}class XI{constructor(e,t,i,r,n){this.credential=e,this.category=t,this.source=r,this.website=n,this.generationDate="number"==typeof i?new Date(i):i}static fromJSON(e){return new XI(e.credential,e.category,e.generationDate)}toJSON(){return{credential:this.credential,category:this.category,generationDate:this.generationDate.valueOf()}}}function ZI(e){const t=e.split("");return Object.freeze(t)}const eE=ZI("!@#$%^&*"),tE=Object.freeze({Full:Object.freeze({Uppercase:ZI("ABCDEFGHIJKLMNOPQRSTUVWXYZ"),Lowercase:ZI("abcdefghijklmnopqrstuvwxyz"),Digit:ZI("0123456789"),Special:eE}),Unmistakable:Object.freeze({Uppercase:ZI("ABCDEFGHJKLMNPQRSTUVWXYZ"),Lowercase:ZI("abcdefghijkmnopqrstuvwxyz"),Digit:ZI("23456789"),Special:eE})}),iE=new RegExp("(?[^@+]+)(?\\+.+)?(?@.+)");var rE=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class nE{constructor(e){this.random=e}randomAsciiSubaddress(e,t){return rE(this,void 0,void 0,function*(){var i,r;let n=null!=e?e:"";const a=null!==(i=null==t?void 0:t.length)&&void 0!==i?i:8;if(a<1)return n;const s=iE.exec(n);if(!s)return n;let o=null!==(r=s.groups.subaddress)&&void 0!==r?r:"+";return o+=(yield this.random.chars(a)),n=`${s.groups.username}${o}${s.groups.domain}`,n})}randomAsciiCatchall(e,t){return rE(this,void 0,void 0,function*(){var i;if(((null==e?void 0:e.startsWith("@"))?e.substring(1,1/0):null!=e?e:"").length<1)return null;const r=null!==(i=null==t?void 0:t.length)&&void 0!==i?i:8;return r<1?null:`${yield this.random.chars(r)}@${e}`})}randomWordsCatchall(e,t){return rE(this,void 0,void 0,function*(){var i,r;if(((null==e?void 0:e.startsWith("@"))?e.substring(1,1/0):null!=e?e:"").length<1)return null;const n=null!==(i=null==t?void 0:t.numberOfWords)&&void 0!==i?i:1;if(n<1)return null;const a=null!==(r=null==t?void 0:t.words)&&void 0!==r?r:wd,s=[];for(let e=0;e{let r=t.get(i);if(void 0===r){const n=e();r=new $c(Object.assign({},n)),t.set(i,r)}return r.asObservable()}}function oE(e,t){return i=>t.getUser(i,e)}const lE=(...e)=>(null!=e?e:[]).reduce((e,t)=>e+(null!=t?t:0),0);function cE(e){var t,i;function r(e,t,i,r){return(null!=e?e:i)?null!=t?t:r:void 0}const n={uppercase:r(e.uppercase,e.minUppercase,hI.uppercase,hI.minUppercase),lowercase:r(e.lowercase,e.minLowercase,hI.lowercase,hI.minLowercase),digits:r(e.number,e.minNumber,hI.number,hI.minNumber),special:r(e.special,e.minSpecial,hI.special,hI.minSpecial),ambiguous:null!==(t=e.ambiguous)&&void 0!==t?t:hI.ambiguous,all:0},a=lE(n.uppercase,n.lowercase,n.digits,n.special),s=(null!==(i=e.length)&&void 0!==i?i:0)-a;return n.all=Math.max(s,0),n}function uE(e){var t,i,r,n;const a=null!==(t=e.numWords)&&void 0!==t?t:dI.numWords;return{numberOfWords:Math.max(a,lI.numWords.min),capitalize:null!==(i=e.capitalize)&&void 0!==i?i:dI.capitalize,number:null!==(r=e.includeNumber)&&void 0!==r?r:dI.includeNumber,separator:null!==(n=e.wordSeparator)&&void 0!==n?n:dI.wordSeparator}}var dE=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class hE{constructor(e,t){this.randomizer=e,this.currentTime=t}randomAscii(e){return dE(this,void 0,void 0,function*(){const t=function(e){function t(e,t){const i=new Array(e>0?e:0);return i.fill(t,0,e),i}const i=[],r=e.ambiguous?tE.Full:tE.Unmistakable,n=[];return void 0!==e.uppercase&&(n.push(...t(e.uppercase,r.Uppercase)),i.push(...r.Uppercase)),void 0!==e.lowercase&&(n.push(...t(e.lowercase,r.Lowercase)),i.push(...r.Lowercase)),void 0!==e.digits&&(n.push(...t(e.digits,r.Digit)),i.push(...r.Digit)),void 0!==e.special&&(n.push(...t(e.special,r.Special)),i.push(...r.Special)),n.push(...t(e.all,i)),n}(e),i=(yield this.randomizer.shuffle(t)).flatMap(e=>this.randomizer.pick(e));return(yield Promise.all(i)).join("")})}randomEffLongWords(e){return dE(this,void 0,void 0,function*(){let t=-1;e.number&&(t=yield this.randomizer.uniform(0,e.numberOfWords-1));const i=new Array(e.numberOfWords);for(let r=0;r!1;"camelCase"===(null==e?void 0:e.casing)?s=e=>0!==e:"TitleCase"===(null==e?void 0:e.casing)&&(s=e=>!0);const o=null!==(r=null==e?void 0:e.words)&&void 0!==r?r:wd,l=[];for(let e=0;e.+)");class yE{constructor(e){var t;if(this.constraints={},!e)return void(this.domain="");const i=fE.exec(e);i&&(null===(t=i.groups)||void 0===t?void 0:t.domain)&&(this.domain=i.groups.domain)}adjust(e){var t;if(""!==(null!==(t=e.catchallDomain)&&void 0!==t?t:"").trim())return e;const i=Object.assign({},e);return i.catchallDomain=this.domain,i}fix(e){return e}}const vE=V_({id:WI.catchall,type:HI.email,weight:210,i18nKeys:{name:"catchallEmail",description:"catchallEmailDesc",credentialType:"email",generateCredential:"generateEmail",credentialGenerated:"emailGenerated",copyCredential:"copyEmail",useCredential:"useThisEmail"},capabilities:{autogenerate:!0,fields:[]},engine:{create:e=>new nE(e.randomizer)},profiles:{[GI.account]:{type:"core",storage:{key:"catchallGeneratorSettings",target:"object",format:"plain",classifier:new mI(["catchallType","catchallDomain"]),state:cr,initial:{catchallType:"random",catchallDomain:""},options:{deserializer:e=>e,clearOn:["logout"]}},constraints:{default:{catchallDomain:{minLength:1}},create(e,t){var i;return new yE(null!==(i=t.email)&&void 0!==i?i:"")}}}}}),bE=vE;class wE{constructor(e){this.email=e,this.constraints={},e||(this.email="")}adjust(e){var t;if(""!==(null!==(t=e.subaddressEmail)&&void 0!==t?t:"").trim())return e;const i=Object.assign({},e);return i.subaddressEmail=this.email,i}fix(e){return e}}const kE=V_({id:WI.plusAddress,type:HI.email,weight:200,i18nKeys:{name:"plusAddressedEmail",description:"plusAddressedEmailDesc",credentialType:"email",generateCredential:"generateEmail",credentialGenerated:"emailGenerated",copyCredential:"copyEmail",useCredential:"useThisEmail"},capabilities:{autogenerate:!0,fields:[]},engine:{create:e=>new nE(e.randomizer)},profiles:{[GI.account]:{type:"core",storage:{key:"subaddressGeneratorSettings",target:"object",format:"plain",classifier:new mI(["subaddressType","subaddressEmail"]),state:cr,initial:{subaddressType:"random",subaddressEmail:""},options:{deserializer:e=>e,clearOn:["logout"]}},constraints:{default:{},create(e,t){var i;return new wE(null!==(i=t.email)&&void 0!==i?i:"")}}}}}),SE=kE;class _E{get policy(){return{}}get policyInEffect(){return!1}applyPolicy(e){return e}sanitize(e){return e}}const xE={min:0,max:0},CE={min:1},IE={requiredValue:!0};function EE(e,t){var i;const r=lE(...t.map(e=>null==e?void 0:e.min));return PE(Math.max(null!==(i=null==e?void 0:e.min)&&void 0!==i?i:0,r),e)}function zE(e,t){return e?t:void 0}function PE(e,t){var i;if(null==e)return t;const r=Object.assign({},null!=t?t:{});return r.min=Math.max(null!==(i=r.min)&&void 0!==i?i:-1/0,e),"max"in r&&(r.max=Math.max(r.max,e)),r}function AE(e,t){if(!t)return e;const{min:i,max:r}=t,n=Math.min(null!=e?e:0,null!=r?r:1/0);return Math.max(n,null!=i?i:-1/0)}function jE(e,t,i){if(!t)return e;const{minLength:r,maxLength:n}=t,{fillString:a}=null!=i?i:{fillString:" "},s=(null!=e?e:"").slice(0,null!=n?n:1/0);return s.padEnd(null!=r?r:s.length,a)}function TE(e,t){return(null==t?void 0:t.readonly)?t.requiredValue:e}function DE(e){return zE(e,function(e,t){if(!e)return t;const i=Object.assign({},null!=t?t:{});return i.readonly=!0,i}(e,IE))}class OE{constructor(e){this.constraints=e}adjust(e){const t=Object.assign(Object.assign({},null!=e?e:hI),{length:AE(e.length,this.constraints.length),lowercase:TE(e.lowercase,this.constraints.lowercase),uppercase:TE(e.uppercase,this.constraints.uppercase),number:TE(e.number,this.constraints.number),special:TE(e.special,this.constraints.special),minLowercase:AE(e.minLowercase,this.constraints.minLowercase),minUppercase:AE(e.minUppercase,this.constraints.minUppercase),minNumber:AE(e.minNumber,this.constraints.minNumber),minSpecial:AE(e.minSpecial,this.constraints.minSpecial)});return t.lowercase||(t.lowercase=e.minLowercase>0),t.uppercase||(t.uppercase=e.minUppercase>0),t.number||(t.number=e.minNumber>0),t.special||(t.special=e.minSpecial>0),[t.lowercase,t.uppercase,t.number,t.special].some(e=>e)||(t.lowercase=!0,t.uppercase=!0),t}fix(e){return e}}class NE{constructor(e,t){this.defaults=t;const i=zE(e.useLowercase,CE),r=zE(e.useUppercase,CE),n=PE(e.numberCount||e.useNumbers&&CE.min,t.minNumber),a=PE(e.specialCount||e.useSpecial&&CE.min,t.minSpecial),s=EE(PE(e.minLength,t.length),[i,r,n,a]);this.constraints=Object.freeze({policyInEffect:RE(e,t),lowercase:DE(e.useLowercase),uppercase:DE(e.useUppercase),number:DE(e.useNumbers),special:DE(e.useSpecial),length:s,minLowercase:i,minUppercase:r,minNumber:n,minSpecial:a})}calibrate(e){var t,i,r,n,a,s,o,l;const c=e.lowercase||(null===(t=this.constraints.lowercase)||void 0===t?void 0:t.requiredValue)||!1,u=e.uppercase||(null===(i=this.constraints.uppercase)||void 0===i?void 0:i.requiredValue)||!1,d=e.number||(null===(r=this.constraints.number)||void 0===r?void 0:r.requiredValue)||!1,h=e.special||(null===(n=this.constraints.special)||void 0===n?void 0:n.requiredValue)||!1,p=Object.assign(Object.assign({},this.constraints),{minLowercase:zE(c,null!==(a=this.constraints.minLowercase)&&void 0!==a?a:CE),minUppercase:zE(u,null!==(s=this.constraints.minUppercase)&&void 0!==s?s:CE),minNumber:null!==(o=zE(d,this.constraints.minNumber))&&void 0!==o?o:xE,minSpecial:null!==(l=zE(h,this.constraints.minSpecial))&&void 0!==l?l:xE});return p.length=EE(this.constraints.length,[PE(e.minNumber,p.minNumber),PE(e.minSpecial,p.minSpecial),PE(e.minLowercase,p.minLowercase),PE(e.minUppercase,p.minUppercase)]),new OE(p)}}function RE(e,t){return[e.useUppercase,e.useLowercase,e.useNumbers,e.useSpecial,e.minLength>t.length.min,e.numberCount>t.minNumber.min,e.specialCount>t.minSpecial.min].includes(!0)}class UE{constructor(e){var t,i;this.policy=structuredClone(e),this.numWords=(t=e.minNumberWords,i=lI.numWords,{min:Math.max(i.min,t),max:Math.max(i.max,t)})}get policyInEffect(){return[this.policy.capitalize,this.policy.includeNumber,this.policy.minNumberWords>lI.numWords.min].includes(!0)}applyPolicy(e){const t=this.policy.capitalize||e.capitalize||!1,i=this.policy.includeNumber||e.includeNumber||!1,r=function(e,t){const{min:i,max:r}=t,n=Math.min(null!=e?e:t.min,r);return Math.max(n,i)}(e.numWords,this.numWords);return Object.assign(Object.assign({},e),{numWords:r,capitalize:t,includeNumber:i})}sanitize(e){var t,i;const r=""===e.wordSeparator?"":null!==(i=null===(t=e.wordSeparator)||void 0===t?void 0:t[0])&&void 0!==i?i:dI.wordSeparator;return Object.assign(Object.assign({},e),{wordSeparator:r})}}class FE{constructor(e,t){this.policy=e,this.defaults=t,this.constraints={policyInEffect:qE(e,t),wordSeparator:{minLength:0,maxLength:1},capitalize:DE(e.capitalize),includeNumber:DE(e.includeNumber),numWords:PE(e.minNumberWords,t.numWords)}}adjust(e){return{wordSeparator:jE(e.wordSeparator,this.constraints.wordSeparator,{fillString:dI.wordSeparator}),capitalize:TE(e.capitalize,this.constraints.capitalize),includeNumber:TE(e.includeNumber,this.constraints.includeNumber),numWords:AE(e.numWords,this.constraints.numWords)}}fix(e){return e}}function qE(e,t){return[e.capitalize,e.includeNumber,e.minNumberWords>t.numWords.min].includes(!0)}class LE{get minNumber(){return this.minDigits}get minSpecial(){return this.minSpecialCharacters}constructor(e){function t(e,t){return{min:Math.max(t.min,e),max:Math.max(t.max,e)}}this.policy=structuredClone(e),this.minDigits=t(e.numberCount,cI.minDigits),this.minSpecialCharacters=t(e.specialCount,cI.minSpecialCharacters);const i=this.minDigits.min+this.minSpecialCharacters.min,r=e.minLength>0?e.minLength:cI.length.min,n=Math.max(r,i,cI.length.min);this.length={min:n,max:Math.max(cI.length.max,n)}}get policyInEffect(){return[this.policy.useUppercase,this.policy.useLowercase,this.policy.useNumbers,this.policy.useSpecial,this.policy.minLength>cI.length.min,this.policy.numberCount>cI.minDigits.min,this.policy.specialCount>cI.minSpecialCharacters.min].includes(!0)}applyPolicy(e){function t(e,t){const{min:i,max:r}=t,n=Math.min(e||0,r);return Math.max(n,i)}const i=this.policy.useUppercase||e.uppercase||!1,r=this.policy.useLowercase||e.lowercase||!1,n=this.policy.useNumbers||e.number||e.minNumber>0,a=this.policy.useSpecial||e.special||e.minSpecial>0,s=t(e.length,this.length),o=t(e.minNumber,this.minDigits),l=t(e.minSpecial,this.minSpecialCharacters);return Object.assign(Object.assign({},e),{length:s,uppercase:i,lowercase:r,number:n,minNumber:o,special:a,minSpecial:l})}sanitize(e){var t;function i(e,t){const i=null!=e?e:t>0;return[i,i?t||1:0]}const[r,n]=i(e.lowercase,e.minLowercase),[a,s]=i(e.uppercase,e.minUppercase),[o,l]=i(e.number,e.minNumber),[c,u]=i(e.special,e.minSpecial),d=n+s+l+u,h=Math.max(d,this.length.min),p=Math.max(null!==(t=e.length)&&void 0!==t?t:h,h);return Object.assign(Object.assign({},e),{length:p,minLength:h,lowercase:r,minLowercase:n,uppercase:a,minUppercase:s,number:o,minNumber:l,special:c,minSpecial:u})}}function BE(e,t){var i;return t.type!==Ye.PasswordGenerator?e:{minNumberWords:Math.max(e.minNumberWords,null!==(i=t.data.minNumberWords)&&void 0!==i?i:e.minNumberWords),capitalize:t.data.capitalize||e.capitalize,includeNumber:t.data.includeNumber||e.includeNumber}}function ME(e,t){var i,r,n;return t.type===Ye.PasswordGenerator&&t.enabled?{minLength:Math.max(e.minLength,null!==(i=t.data.minLength)&&void 0!==i?i:e.minLength),useUppercase:t.data.useUpper||e.useUppercase,useLowercase:t.data.useLower||e.useLowercase,useNumbers:t.data.useNumbers||e.useNumbers,numberCount:Math.max(e.numberCount,null!==(r=t.data.minNumbers)&&void 0!==r?r:e.numberCount),useSpecial:t.data.useSpecial||e.useSpecial,specialCount:Math.max(e.specialCount,null!==(n=t.data.minSpecial)&&void 0!==n?n:e.specialCount)}:e}const VE={id:WI.passphrase,type:HI.password,weight:110,i18nKeys:{name:"passphrase",credentialType:"passphrase",generateCredential:"generatePassphrase",credentialGenerated:"passphraseGenerated",copyCredential:"copyPassphrase",useCredential:"useThisPassphrase"},capabilities:{autogenerate:!0,fields:[]},engine:{create:e=>null==e.sdk?new hE(e.randomizer,e.now):new pE(e.sdk,e.now)},profiles:{[GI.account]:{type:"core",storage:{key:"passphraseGeneratorSettings",target:"object",format:"plain",classifier:new mI(["numWords","wordSeparator","capitalize","includeNumber"]),state:cr,initial:{numWords:6,wordSeparator:"-",capitalize:!1,includeNumber:!1},options:{deserializer:e=>e,clearOn:["logout"]}},constraints:{type:Ye.PasswordGenerator,default:{wordSeparator:{maxLength:1},numWords:{min:3,max:20,recommendation:6}},create(e,t){const i=e.reduce(BE,{minNumberWords:0,capitalize:!1,includeNumber:!1});return new FE(i,t.defaultConstraints)}}}}},$E=VE,KE=V_({id:WI.password,type:HI.password,weight:100,i18nKeys:{name:"password",generateCredential:"generatePassword",credentialGenerated:"passwordGenerated",credentialType:"password",copyCredential:"copyPassword",useCredential:"useThisPassword"},capabilities:{autogenerate:!0,fields:[]},engine:{create:e=>null==e.sdk?new hE(e.randomizer,e.now):new pE(e.sdk,e.now)},profiles:{[GI.account]:{type:"core",storage:{key:"passwordGeneratorSettings",target:"object",format:"plain",classifier:new mI(["length","ambiguous","uppercase","minUppercase","lowercase","minLowercase","number","minNumber","special","minSpecial"]),state:cr,initial:{length:14,ambiguous:!0,uppercase:!0,minUppercase:1,lowercase:!0,minLowercase:1,number:!0,minNumber:1,special:!1,minSpecial:0},options:{deserializer:e=>e,clearOn:["logout"]}},constraints:{type:Ye.PasswordGenerator,default:{length:{min:5,max:128,recommendation:14},minNumber:{min:0,max:9},minSpecial:{min:0,max:9}},create(e,t){const i=e.reduce(ME,{minLength:0,useUppercase:!1,useLowercase:!1,useNumbers:!1,numberCount:0,useSpecial:!1,specialCount:0});return new NE(i,t.defaultConstraints)}}}}}),WE=KE,HE=V_({id:WI.username,type:HI.username,weight:400,i18nKeys:{name:"randomWord",credentialType:"username",generateCredential:"generateUsername",credentialGenerated:"usernameGenerated",copyCredential:"copyUsername",useCredential:"useThisUsername"},capabilities:{autogenerate:!0,fields:[]},engine:{create:e=>new gE(e.randomizer)},profiles:{[GI.account]:{type:"core",storage:{key:"effUsernameGeneratorSettings",target:"object",format:"plain",classifier:new mI(["wordCapitalize","wordIncludeNumber"]),state:cr,initial:{wordCapitalize:!1,wordIncludeNumber:!1,website:null},options:{deserializer:e=>e,clearOn:["logout"]}},constraints:{default:{},create:(e,t)=>new gx}}}});Object.freeze({catchall:bE,plusAddress:SE,passphrase:$E,password:WE,effWordList:HE});const GE=QI;function QE(e){return M(S_(e.combine,e.disabledValue),__(),X(e.createEvaluator))}function JE(){return()=>M(X(e=>new _E))}Object.freeze(Object.values(WI)),Object.freeze(Object.values(HI)),new wi(cr,"credentialPreferences",{deserializer:e=>{var t;const i=null!==(t=e)&&void 0!==t?t:{};for(const e in GE){const t=e;if(i[t])i[t].updated=new Date(i[t].updated);else{const[e]=GE[t];i[t]={algorithm:e,updated:new Date}}}return i},clearOn:["logout"]});var YE=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class XE{constructor(e,t,i,r=null){this.key=t,this.output=i,this.bufferedState=e.getUser(i.userId,t.toKeyDefinition());const n=ai([li(bt(null),this.bufferedState.state$).pipe(X(e=>null!==(null!=e?e:null))),(null!=r?r:bt(!0)).pipe(X(e=>[t.shouldOverwrite(e),e]))]).pipe(gc(e=>YE(this,[e],void 0,function*([e,[t,i]]){return e&&t&&(yield this.overwriteOutput(i)),[!1,null]}))),a=this.output.state$.pipe(X(e=>[!0,e]));this.state$=_e(n,a).pipe(Ie(([e])=>e),X(([,e])=>e)),this.combinedState$=this.state$.pipe(X(e=>[this.output.userId,e])),this.bufferedState$=this.bufferedState.state$}overwriteOutput(e){return YE(this,void 0,void 0,function*(){let t;if(yield this.bufferedState.update(e=>(t=null!=e?e:null,null)),yield this.key.isValid(t,e)){const i=yield this.key.map(t,e);yield this.output.update(()=>i)}})}get userId(){return this.output.userId}buffer(e){return YE(this,void 0,void 0,function*(){const t=null!=e?e:null;null!==t&&(yield this.bufferedState.update(()=>t))})}update(e,t=null){return this.output.update(e,t)}}class ZE{constructor(e,t,i,r,n,a){this.stateDefinition=e,this.key=t,this.classifier=i,this.options=r,this.deconstruct=n,this.reconstruct=a}toEncryptedStateKey(){return new wi(this.stateDefinition,this.key,{cleanupDelayMs:this.options.cleanupDelayMs,deserializer:e=>e,clearOn:this.options.clearOn})}static value(e,t,i,r){return new ZE(e,t,i,r,e=>[[null,e]],([[,e]])=>e)}static array(e,t,i,r){return new ZE(e,t,i,r,e=>e.map((e,t)=>[t,e]),e=>e.map(([,e])=>e))}static record(e,t,i,r){return new ZE(e,t,i,r,e=>Object.entries(e),e=>Object.fromEntries(e))}}var ez=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class tz{constructor(e,t,i,r){this.key=e,this.$encryptor=t,this.encryptedState=r.getUser(i,e.toEncryptedStateKey()),this.combinedState$=ai([this.encryptedState.combinedState$,this.$encryptor]).pipe(gc(e=>ez(this,[e],void 0,function*([[e,t],i]){return[e,yield this.declassifyAll(i,t)]})),Gt({connector:()=>new Ht(1),resetOnRefCountZero:()=>{var t;return sc(null!==(t=e.options.cleanupDelayMs)&&void 0!==t?t:6e4)}})),this.state$=this.combinedState$.pipe(X(([,e])=>e))}get userId(){return this.encryptedState.userId}static from(e,t,i,r){return new tz(t,r,e,i)}declassifyItem(e,t){return ez(this,arguments,void 0,function*(e,{id:t,secret:i,disclosed:r}){const n=Nt.fromJSON(i),a=yield e.decrypt(n),s=this.key.classifier.declassify(r,a);return[t,this.key.options.deserializer(s)]})}declassifyAll(e,t){return ez(this,void 0,void 0,function*(){if(null==t)return null;const i=t.map(t=>ez(this,void 0,void 0,function*(){return this.declassifyItem(e,t)})),r=yield Promise.all(i);return this.key.reconstruct(r)})}classifyItem(e,t){return ez(this,arguments,void 0,function*(e,[t,i]){const r=this.key.classifier.classify(i),n=yield e.encrypt(r.secret);return{id:t,secret:JSON.parse(JSON.stringify(n)),disclosed:r.disclosed}})}classifyAll(e,t){return ez(this,void 0,void 0,function*(){if(null==t)return null;const i=this.key.deconstruct(t).map(t=>ez(this,void 0,void 0,function*(){return this.classifyItem(e,t)}));return yield Promise.all(i)})}update(e){return ez(this,arguments,void 0,function*(e,t=null){var i,r,n;const a=ai([null!==(i=null==t?void 0:t.combineLatestWith)&&void 0!==i?i:bt(null),this.$encryptor]);let s,o,l;yield this.encryptedState.update(e=>e,{shouldUpdate:(e,t)=>(s=e,[o,l]=t,!1),combineLatestWith:a});const c=yield this.declassifyAll(l,s);if(null!==(n=null===(r=null==t?void 0:t.shouldUpdate)||void 0===r?void 0:r.call(t,c,o))&&void 0!==n&&!n)return c;const u=e(c,o),d=yield this.classifyAll(l,u);return yield this.encryptedState.update(()=>d),u})}}class iz{}class rz{constructor(e,t){this.requestor=e,this.context=t}get createForwardingEmail(){return this.requestor.forwarder.createForwardingEmail}toRequest(e){const t=this.createForwardingEmail.url(e,this.context),i=this.requestor.authenticate(e,this.context),r=this.body(e);return new Request(t,{redirect:"manual",cache:"no-store",method:"POST",headers:new Headers(Object.assign(Object.assign({},i),{"Content-Type":"application/json",Accept:"application/json"})),body:r})}body(e){const t=this.createForwardingEmail.body;if(!t)return;const i=t(e,this.context);return i?JSON.stringify(i):void 0}hasJsonPayload(e){return this.createForwardingEmail.hasJsonPayload(e,this.context)}processJson(e){return this.createForwardingEmail.processJson(e,this.context)}}class nz{constructor(e,t){this.requestor=e,this.context=t}hasJsonPayload(e){return this.requestor.forwarder.getAccountId.hasJsonPayload(e,this.context)}processJson(e){return this.requestor.forwarder.getAccountId.processJson(e,this.context)}toRequest(e){const t=this.requestor.forwarder.getAccountId.url(e,this.context),i=this.requestor.authenticate(e,this.context);return new Request(t,{redirect:"manual",cache:"no-store",method:"GET",headers:new Headers(Object.assign(Object.assign({},i),{"Content-Type":"application/json",Accept:"application/json"}))})}}class az{classify(e){const t=JSON.parse(JSON.stringify(e));return delete t.website,{disclosed:{},secret:t}}declassify(e,t){return Object.assign(Object.assign({},t),{website:null})}}class sz extends iz{constructor(e,t,i,r,n,a){super(),this.configuration=e,this.client=t,this.i18nService=i,this.encryptService=r,this.keyService=n,this.stateProvider=a,this.policy=Ye.PasswordGenerator,this.defaults$=sE(()=>this.configuration.forwarder.defaultSettings),this.toEvaluator=JE(),this.durableState=function(e){const t=new Map;return i=>{let r=t.get(i);return void 0===r&&(r=e(i),t.set(i,r)),r}}(e=>this.getUserSecrets(e)),this.generate=e=>{return t=this,i=void 0,n=function*(){const t={website:e.website},i=yield this.getAccountId(this.configuration,e);i&&(t.accountId=yield this.client.fetchJson(i,t));const r=this.createForwardingAddress(this.configuration,e);return yield this.client.fetchJson(r,t)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}get key(){return this.configuration.forwarder.settings}get rolloverKey(){return this.configuration.forwarder.importBuffer}getUserSecrets(e){const t=new z_(512),i=this.keyService.userKey$(e).pipe(X(i=>i?new O_(e,this.encryptService,i,t):null),Ie(e=>!!e)),r=new az,n=ZE.value(this.key.stateDefinition,this.key.key,r,{deserializer:e=>this.key.deserializer(e),cleanupDelayMs:this.key.cleanupDelayMs,clearOn:this.key.clearOn}),a=tz.from(e,n,this.stateProvider,i),s=this.keyService.userKey$(e).pipe(X(e=>null!==e));return new XE(this.stateProvider,this.rolloverKey,a,s)}createContext(e,t){return new YI(e,t,this.i18nService)}createForwardingAddress(e,t){const i=this.createContext(e,t);return new rz(e,i)}getAccountId(e,t){if(!e.forwarder.getAccountId)return null;const i=this.createContext(e,t);return new nz(e,i)}}const oz=new wi(cr,"passwordGeneratorSettings",{deserializer:e=>e,clearOn:[]}),lz=new wi(cr,"passphraseGeneratorSettings",{deserializer:e=>e,clearOn:[]}),cz=new wi(cr,"effUsernameGeneratorSettings",{deserializer:e=>e,clearOn:[]}),uz=new wi(cr,"catchallGeneratorSettings",{deserializer:e=>e,clearOn:[]}),dz=new wi(cr,"subaddressGeneratorSettings",{deserializer:e=>e,clearOn:[]});class hz{constructor(e,t){this.randomizer=e,this.stateProvider=t,this.durableState=oE(lz,this.stateProvider),this.defaults$=sE(()=>dI),this.policy=Ye.PasswordGenerator}toEvaluator(){return QE({type:Ye.PasswordGenerator,disabledValue:Object.freeze({minNumberWords:0,capitalize:!1,includeNumber:!1}),combine:BE,createEvaluator:e=>new UE(e)})}generate(e){return t=this,i=void 0,n=function*(){const t=uE(e);return this.randomizer.randomEffLongWords(t)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class pz{constructor(e,t){this.randomizer=e,this.stateProvider=t,this.durableState=oE(oz,this.stateProvider),this.defaults$=sE(()=>hI),this.policy=Ye.PasswordGenerator}toEvaluator(){return QE({type:Ye.PasswordGenerator,disabledValue:{minLength:0,useUppercase:!1,useLowercase:!1,useNumbers:!1,numberCount:0,useSpecial:!1,specialCount:0},combine:ME,createEvaluator:e=>new LE(e)})}generate(e){return t=this,i=void 0,n=function*(){const t=cE(e);return yield this.randomizer.randomAscii(t)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class mz{constructor(e,t,i,r=oI){this.emailCalculator=e,this.emailRandomizer=t,this.stateProvider=i,this.defaultOptions=r,this.durableState=oE(uz,this.stateProvider),this.defaults$=sE(()=>this.defaultOptions),this.toEvaluator=JE(),this.policy=Ye.PasswordGenerator}generate(e){return t=this,i=void 0,n=function*(){return null==e.catchallType&&(e.catchallType="random"),"website-name"===e.catchallType?yield this.emailCalculator.concatenate(e.website,e.catchallDomain):this.emailRandomizer.randomAsciiCatchall(e.catchallDomain)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class gz{constructor(e,t,i,r=pI){this.emailCalculator=e,this.emailRandomizer=t,this.stateProvider=i,this.defaultOptions=r,this.durableState=oE(dz,this.stateProvider),this.defaults$=sE(()=>this.defaultOptions),this.toEvaluator=JE(),this.policy=Ye.PasswordGenerator}generate(e){return t=this,i=void 0,n=function*(){return null==e.subaddressType&&(e.subaddressType="random"),"website-name"===e.subaddressType?this.emailCalculator.appendToSubaddress(e.website,e.subaddressEmail):this.emailRandomizer.randomAsciiSubaddress(e.subaddressEmail)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}const fz=Object.freeze({enabled:4,disabled:0});class yz{constructor(e,t,i=uI){this.randomizer=e,this.stateProvider=t,this.defaultOptions=i,this.durableState=oE(cz,this.stateProvider),this.defaults$=sE(()=>this.defaultOptions),this.toEvaluator=JE(),this.policy=Ye.PasswordGenerator}generate(e){return t=this,i=void 0,n=function*(){var t,i;const r=(null!==(t=e.wordCapitalize)&&void 0!==t?t:uI.wordCapitalize)?"TitleCase":"lowercase",n=(null!==(i=e.wordIncludeNumber)&&void 0!==i?i:uI.wordIncludeNumber)?fz.enabled:fz.disabled;return yield this.randomizer.randomWords({numberOfWords:1,casing:r,digits:n})},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}class vz{constructor(e,t){this.password=e,this.date=t}}class bz{constructor(e,t,i){this.credential=e,this.category=t,this.generationDate="number"==typeof i?new Date(i):i}static fromJSON(e){return new bz(e.credential,e.category,e.generationDate)}toJSON(){return{credential:this.credential,category:this.category,generationDate:this.generationDate.valueOf()}}}class wz{}class kz{constructor(e,t){this.disclosed=e,this.excluded=t}static allSecret(){const e=Object.freeze([]),t=Object.freeze([]);return new kz(e,t)}disclose(e){const t=[...this.disclosed,e];return new kz(Object.freeze(t),this.excluded)}exclude(e){const t=[...this.excluded,e];return new kz(this.disclosed,Object.freeze(t))}classify(e){const t=JSON.parse(JSON.stringify(e));for(const e of this.excluded)delete t[e];const i={};for(const e of this.disclosed)i[e]=t[e],delete t[e];return{disclosed:i,secret:t}}declassify(e,t){const i={};for(const t of this.disclosed)i[t]=e[t];const r=Object.assign(i,t);for(const e of this.excluded)delete r[e];return r}}var Sz=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const _z=ZE.array(cr,"localGeneratorHistory",kz.allSecret(),{deserializer:bz.fromJSON,clearOn:["logout"]}),xz=new gI(cr,"localGeneratorHistoryBuffer",{deserializer:e=>null==e?void 0:e.map(e=>new vz(e.password,e.date)),isValid(e){return Sz(this,void 0,void 0,function*(){return!!e.length})},map(e,t){return Sz(this,void 0,void 0,function*(){return(yield t.decrypt(e)).map(e=>new bz(e.password,"password",e.date))})},clearOn:["logout"]});var Cz=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Iz{constructor(e,t,i){this.userId=e,this.keyService=t,this.encryptService=i}decrypt(e){return Cz(this,void 0,void 0,function*(){const t=yield Ce(this.keyService.userKey$(this.userId));if(null==t)throw new Error("No user key found for decryption");const i=(null!=e?e:[]).map(e=>Cz(this,void 0,void 0,function*(){const i=new Nt(e.password),r=yield this.encryptService.decryptString(i,t);return new vz(r,e.date)}));return yield Promise.all(i)})}}var Ez=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class zz extends wz{constructor(e,t,i,r={maxTotal:200}){super(),this.encryptService=e,this.keyService=t,this.stateProvider=i,this.options=r,this._credentialStates=new Map,this.track=(e,t,i,r)=>Ez(this,void 0,void 0,function*(){const n=this.getCredentialState(e);let a=null;return yield n.update(e=>{e=null!=e?e:[],a=new bz(t,i,null!=r?r:Date.now()),e.unshift(a);const n=Math.max(0,this.options.maxTotal);return e.splice(n,1/0),e},{shouldUpdate:e=>{var i;return!(null!==(i=null==e?void 0:e.some(e=>e.credential===t))&&void 0!==i&&i)}}),a}),this.take=(e,t)=>Ez(this,void 0,void 0,function*(){const i=this.getCredentialState(e);let r,n=null;return yield i.update(e=>(e=null!=e?e:[],[n]=e.splice(r,1),e),{shouldUpdate:e=>{var i;return r=null!==(i=null==e?void 0:e.findIndex(e=>e.credential===t))&&void 0!==i?i:-1,r>=0}}),n}),this.clear=e=>Ez(this,void 0,void 0,function*(){var t;const i=this.getCredentialState(e);return null!==(t=yield i.update(()=>null))&&void 0!==t?t:[]}),this.credentials$=e=>this.getCredentialState(e).state$.pipe(X(e=>null!=e?e:[]))}getCredentialState(e){let t=this._credentialStates.get(e);return t||(t=this.createSecretState(e),this._credentialStates.set(e,t)),t}createSecretState(e){const t=new z_(2048),i=this.keyService.userKey$(e).pipe(X(i=>i?new O_(e,this.encryptService,i,t):null),Ie(e=>!!e)),r=tz.from(e,_z,this.stateProvider,i),n=new Iz(e,this.keyService,this.encryptService),a=this.keyService.userKey$(e).pipe(X(e=>e&&n));return new XE(this.stateProvider,xz,r,a)}}const Pz=Object.freeze({type:"password",username:"word",forwarder:""});class Az{constructor(e){this.policy=e}get policyInEffect(){var e;return GE[HI.password].includes(null===(e=this.policy)||void 0===e?void 0:e.overridePasswordType)}applyPolicy(e){var t;const i=Object.assign({},e);return this.policyInEffect&&(i.type=null!==(t=this.policy.overridePasswordType)&&void 0!==t?t:i.type),i}sanitize(e){var t;return Object.assign(Object.assign({},e),{type:null!==(t=e.type)&&void 0!==t?t:Pz.type})}}function jz(e,t){return t.type===Ye.PasswordGenerator&&t.enabled&&"password"!==e.overridePasswordType&&t.data.overridePasswordType?Object.assign(Object.assign({},e),{overridePasswordType:t.data.overridePasswordType}):e}const Tz=Object.freeze({overridePasswordType:null}),Dz=new wi(cr,"generatorSettings",{deserializer:e=>e,clearOn:["logout"]});var Oz=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Nz{constructor(e,t){this.stateProvider=e,this.policy=t}options$(e){return this.stateProvider.getUserState$(Dz,e)}defaults$(e){return new $c(Object.assign({},Pz))}evaluator$(e){return this.policy.policiesByType$(Ye.PasswordGenerator,e).pipe(S_(jz,Tz),__(),X(e=>new Az(e)))}enforcePolicy(e,t){return Oz(this,void 0,void 0,function*(){const i=yield Ce(this.evaluator$(e)),r=i.applyPolicy(t);return i.sanitize(r)})}saveOptions(e,t){return Oz(this,void 0,void 0,function*(){yield this.stateProvider.setUserState(Dz,t,e)})}}class Rz extends Rt{constructor(){super(...arguments),this.overridePasswordType="",this.minLength=0,this.useUppercase=!1,this.useLowercase=!1,this.useNumbers=!1,this.numberCount=0,this.useSpecial=!1,this.specialCount=0,this.minNumberWords=0,this.capitalize=!1,this.includeNumber=!1}inEffect(){return this.overridePasswordType||this.minLength>0||this.numberCount>0||this.specialCount>0||this.useUppercase||this.useLowercase||this.useNumbers||this.useSpecial||this.minNumberWords>0||this.capitalize||this.includeNumber}clone(){const e=new Rz;return Object.assign(e,this),e}}var Uz=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Fz{constructor(e,t,i,r,n){this.accountService=e,this.navigation=t,this.passwords=i,this.passphrases=r,this.history=n}generatePassword(e){return"password"===e.type?this.passwords.generate(e):this.passphrases.generate(e)}generatePassphrase(e){return this.passphrases.generate(e)}getRawOptions$(){function e(e){return e.pipe(X((e,t)=>[e,t]))}return this.accountService.activeAccount$.pipe(gc(t=>li(bt([null,null,[null,-1],null,null,[null,-1],null,null,[null,-1]]),ai([this.passwords.options$(t.id),this.passwords.defaults$(t.id),e(this.passwords.evaluator$(t.id)),this.passphrases.options$(t.id),this.passphrases.defaults$(t.id),e(this.passphrases.evaluator$(t.id)),this.navigation.options$(t.id),this.navigation.defaults$(t.id),e(this.navigation.evaluator$(t.id))]))),g_(),X(function([e,t]){const[,,[,i],,,[,r],,,[,n]]=e,[a,s,[o,l],c,u,[d,h],p,m,[g,f]]=t;return[a,s,o,c,u,d,p,m,g,i{const u=i.applyPolicy(null!=e?e:t),d=a.applyPolicy(null!=r?r:n),h=l.applyPolicy(null!=s?s:o);return[this.toPasswordGeneratorOptions({password:i.sanitize(u),passphrase:a.sanitize(d),generator:l.sanitize(h),policyUpdated:c}),Object.assign(new Rz,i.policy,a.policy,l.policy)]}))}getOptions(){return Uz(this,void 0,void 0,function*(){return yield Ce(this.getOptions$())})}enforcePasswordGeneratorPoliciesOnOptions(e){return Uz(this,void 0,void 0,function*(){const t=this.accountService.activeAccount$.pipe(gc(e=>XS(this.passwords.evaluator$(e.id),this.passphrases.evaluator$(e.id),this.navigation.evaluator$(e.id))),X(([t,i,r])=>{const n=Object.assign(new Rz,t.policy,i.policy,r.policy),a=r.applyPolicy(e),s=Object.assign(Object.assign({},e),r.sanitize(a));if("password"===s.type){const e=t.applyPolicy(s);return[t.sanitize(e),n]}{const e=i.applyPolicy(s);return[i.sanitize(e),n]}})),[i,r]=yield Ce(t);return[Object.assign(e,i),r]})}saveOptions(e){return Uz(this,void 0,void 0,function*(){const t=this.toStoredOptions(e),i=yield Ce(this.accountService.activeAccount$),r=XS(this.navigation.options$(i.id),this.navigation.defaults$(i.id)).pipe(X(([e,t])=>null!=e?e:t));let n=yield Ce(r);n=Object.assign(n,t.generator),yield this.navigation.saveOptions(i.id,n),yield this.passwords.saveOptions(i.id,t.password),yield this.passphrases.saveOptions(i.id,t.passphrase)})}toStoredOptions(e){return{generator:{type:e.type},password:{length:e.length,minLength:e.minLength,ambiguous:e.ambiguous,uppercase:e.uppercase,minUppercase:e.minUppercase,lowercase:e.lowercase,minLowercase:e.minLowercase,number:e.number,minNumber:e.minNumber,special:e.special,minSpecial:e.minSpecial},passphrase:{numWords:e.numWords,wordSeparator:e.wordSeparator,capitalize:e.capitalize,includeNumber:e.includeNumber},policyUpdated:!1}}toPasswordGeneratorOptions(e){return{type:e.generator.type,length:e.password.length,minLength:e.password.minLength,ambiguous:e.password.ambiguous,uppercase:e.password.uppercase,minUppercase:e.password.minUppercase,lowercase:e.password.lowercase,minLowercase:e.password.minLowercase,number:e.password.number,minNumber:e.password.minNumber,special:e.password.special,minSpecial:e.password.minSpecial,numWords:e.passphrase.numWords,wordSeparator:e.passphrase.wordSeparator,capitalize:e.passphrase.capitalize,includeNumber:e.passphrase.includeNumber,policyUpdated:e.policyUpdated}}getHistory(){return Ce(this.accountService.activeAccount$.pipe(gc(e=>this.history.credentials$(e.id)),Fe({each:1e3,with:()=>[]}),X(e=>e.map(qz))))}addHistory(e){return Uz(this,void 0,void 0,function*(){const t=yield Ce(this.accountService.activeAccount$);(null==t?void 0:t.id)&&(yield this.history.track(t.id,e,"password"))})}clear(){return Ce(this.accountService.activeAccount$.pipe(Ie(e=>!!(null==e?void 0:e.id)),gc(e=>this.history.clear(e.id)),Fe({each:1e3,with:()=>[]}),X(e=>e.map(qz))))}}function qz(e){return new vz(e.credential,e.generationDate.valueOf())}const{jK:Lz,gb:Bz}=i,{f3:Mz,Zx:Vz}=e,$z=KI;var Kz=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Wz{constructor(e,t){this.api=e,this.i18n=t}fetchJson(e,t){return Kz(this,void 0,void 0,function*(){const i=e.toRequest(t),r=yield this.api.nativeFetch(i);let n,a,s;const o=yield this.detectCommonErrors(r);if(o?[a,s]=o:e.hasJsonPayload(r)&&([n,s]=e.processJson(yield r.json())),n)return n;throw null!=a||(a=s?"forwarderError":"forwarderUnknownError"),this.i18n.t(a,e.requestor.name,s)})}detectCommonErrors(e){return Kz(this,void 0,void 0,function*(){if(401===e.status){const t=yield this.tryGetErrorMessage(e);return[t?"forwaderInvalidTokenWithMessage":"forwaderInvalidToken",t]}if(403===e.status){const t=yield this.tryGetErrorMessage(e);return[t?"forwaderInvalidOperationWithMessage":"forwaderInvalidOperation",t]}if(e.status>=400){const t=yield this.tryGetErrorMessage(e);return[t?"forwarderError":"forwarderUnknownError",t]}})}tryGetErrorMessage(e){return Kz(this,void 0,void 0,function*(){var t,i,r;const n=null!==(t=yield e.text())&&void 0!==t?t:"";return(null!==(r=null!==(i=this.tryFindErrorAsJson(n))&&void 0!==i?i:this.tryFindErrorAsText(n))&&void 0!==r?r:e.statusText)||void 0})}tryFindErrorAsJson(e){var t,i,r,n,a;if(!(e.startsWith("{")||e.startsWith("'")||e.startsWith('"')))return;let s;try{s=JSON.parse(e)}catch(e){return!1}if(s&&"string"==typeof s)return s;const o=null!==(i=null===(t=s.error)||void 0===t?void 0:t.toString())&&void 0!==i?i:null,l=null!==(n=null===(r=s.message)||void 0===r?void 0:r.toString())&&void 0!==n?n:null;return o&&l?`${o}: ${l}`:null!==(a=null!=o?o:l)&&void 0!==a&&a}tryFindErrorAsText(e){if(e.length&&!e.includes("<"))return e}}const Hz=Object.freeze({AddyIo:Object.freeze({id:"anonaddy",name:"Addy.io",validForSelfHosted:!0}),DuckDuckGo:Object.freeze({id:"duckduckgo",name:"DuckDuckGo",validForSelfHosted:!1}),Fastmail:Object.freeze({id:"fastmail",name:"Fastmail",validForSelfHosted:!0}),FirefoxRelay:Object.freeze({id:"firefoxrelay",name:"Firefox Relay",validForSelfHosted:!1}),ForwardEmail:Object.freeze({id:"forwardemail",name:"Forward Email",validForSelfHosted:!0}),SimpleLogin:Object.freeze({id:"simplelogin",name:"SimpleLogin",validForSelfHosted:!0})});var Gz=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Qz{constructor(e,t,i,r,n,a,s,o,l,c,u){this.accountService=e,this.navigation=t,this.catchall=i,this.effUsername=r,this.subaddress=n,this.addyIo=a,this.duckDuckGo=s,this.fastmail=o,this.firefoxRelay=l,this.forwardEmail=c,this.simpleLogin=u}generateUsername(e){return"catchall"===e.type?this.generateCatchall(e):"subaddress"===e.type?this.generateSubaddress(e):"forwarded"===e.type?this.generateForwarded(e):this.generateWord(e)}generateWord(e){return this.effUsername.generate(e)}generateSubaddress(e){return this.subaddress.generate(e)}generateCatchall(e){return this.catchall.generate(e)}generateForwarded(e){if(!e.forwardedService)return null;const t=this.toStoredOptions(e);switch(e.forwardedService){case Hz.AddyIo.id:case H_.addyio:return this.addyIo.generate(t.forwarders.addyIo);case Hz.DuckDuckGo.id:return this.duckDuckGo.generate(t.forwarders.duckDuckGo);case Hz.Fastmail.id:return this.fastmail.generate(t.forwarders.fastmail);case Hz.FirefoxRelay.id:case H_.mozilla:return this.firefoxRelay.generate(t.forwarders.firefoxRelay);case Hz.ForwardEmail.id:return this.forwardEmail.generate(t.forwarders.forwardEmail);case Hz.SimpleLogin.id:return this.simpleLogin.generate(t.forwarders.simpleLogin)}}getOptions$(){return this.accountService.activeAccount$.pipe(gc(e=>ai([this.navigation.options$(e.id),this.navigation.defaults$(e.id),this.catchall.options$(e.id),this.catchall.defaults$(e.id),this.effUsername.options$(e.id),this.effUsername.defaults$(e.id),this.subaddress.options$(e.id),this.subaddress.defaults$(e.id),this.addyIo.options$(e.id),this.addyIo.defaults$(e.id),this.duckDuckGo.options$(e.id),this.duckDuckGo.defaults$(e.id),this.fastmail.options$(e.id),this.fastmail.defaults$(e.id),this.firefoxRelay.options$(e.id),this.firefoxRelay.defaults$(e.id),this.forwardEmail.options$(e.id),this.forwardEmail.defaults$(e.id),this.simpleLogin.options$(e.id),this.simpleLogin.defaults$(e.id)])),X(([e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,f,y,v,b])=>this.toUsernameOptions({generator:null!=e?e:t,algorithms:{catchall:null!=i?i:r,effUsername:null!=n?n:a,subaddress:null!=s?s:o},forwarders:{addyIo:null!=l?l:c,duckDuckGo:null!=u?u:d,fastmail:null!=h?h:p,firefoxRelay:null!=m?m:g,forwardEmail:null!=f?f:y,simpleLogin:null!=v?v:b}})))}getOptions(){return Ce(this.getOptions$())}saveOptions(e){return Gz(this,void 0,void 0,function*(){const t=this.toStoredOptions(e),i=yield Ce(this.accountService.activeAccount$);(yield this.saveGeneratorOptions(i.id,e.type,t))||(yield this.saveForwarderOptions(i.id,e.forwardedService,t)),yield this.saveNavigationOptions(i.id,t)})}saveNavigationOptions(e,t){return Gz(this,void 0,void 0,function*(){const i=XS(this.navigation.options$(e),this.navigation.defaults$(e)).pipe(X(([e,t])=>null!=e?e:t));let r=yield Ce(i);r=Object.assign(r,t.generator),yield this.navigation.saveOptions(e,r)})}saveGeneratorOptions(e,t,i){return Gz(this,void 0,void 0,function*(){switch(t){case"word":return yield this.effUsername.saveOptions(e,i.algorithms.effUsername),!0;case"subaddress":return yield this.subaddress.saveOptions(e,i.algorithms.subaddress),!0;case"catchall":return yield this.catchall.saveOptions(e,i.algorithms.catchall),!0;default:return!1}})}saveForwarderOptions(e,t,i){return Gz(this,void 0,void 0,function*(){switch(t){case Hz.AddyIo.id:case H_.addyio:return yield this.addyIo.saveOptions(e,i.forwarders.addyIo),!0;case Hz.DuckDuckGo.id:return yield this.duckDuckGo.saveOptions(e,i.forwarders.duckDuckGo),!0;case Hz.Fastmail.id:return yield this.fastmail.saveOptions(e,i.forwarders.fastmail),!0;case Hz.FirefoxRelay.id:case H_.mozilla:return yield this.firefoxRelay.saveOptions(e,i.forwarders.firefoxRelay),!0;case Hz.ForwardEmail.id:return yield this.forwardEmail.saveOptions(e,i.forwarders.forwardEmail),!0;case Hz.SimpleLogin.id:return yield this.simpleLogin.saveOptions(e,i.forwarders.simpleLogin),!0;default:return!1}})}toStoredOptions(e){const t={addyIo:{baseUrl:e.forwardedAnonAddyBaseUrl,token:e.forwardedAnonAddyApiToken,domain:e.forwardedAnonAddyDomain,website:e.website},duckDuckGo:{token:e.forwardedDuckDuckGoToken,website:e.website},fastmail:{token:e.forwardedFastmailApiToken,website:e.website},firefoxRelay:{token:e.forwardedFirefoxApiToken,website:e.website},forwardEmail:{token:e.forwardedForwardEmailApiToken,domain:e.forwardedForwardEmailDomain,website:e.website},simpleLogin:{token:e.forwardedSimpleLoginApiKey,baseUrl:e.forwardedSimpleLoginBaseUrl,website:e.website}};return{generator:{username:e.type,forwarder:e.forwardedService},algorithms:{effUsername:{wordCapitalize:e.wordCapitalize,wordIncludeNumber:e.wordIncludeNumber,website:e.website},subaddress:{subaddressType:e.subaddressType,subaddressEmail:e.subaddressEmail,website:e.website},catchall:{catchallType:e.catchallType,catchallDomain:e.catchallDomain,website:e.website}},forwarders:t}}toUsernameOptions(e){return{type:e.generator.username,wordCapitalize:e.algorithms.effUsername.wordCapitalize,wordIncludeNumber:e.algorithms.effUsername.wordIncludeNumber,subaddressType:e.algorithms.subaddress.subaddressType,subaddressEmail:e.algorithms.subaddress.subaddressEmail,catchallType:e.algorithms.catchall.catchallType,catchallDomain:e.algorithms.catchall.catchallDomain,forwardedService:e.generator.forwarder,forwardedAnonAddyApiToken:e.forwarders.addyIo.token,forwardedAnonAddyDomain:e.forwarders.addyIo.domain,forwardedAnonAddyBaseUrl:e.forwarders.addyIo.baseUrl,forwardedDuckDuckGoToken:e.forwarders.duckDuckGo.token,forwardedFirefoxApiToken:e.forwarders.firefoxRelay.token,forwardedFastmailApiToken:e.forwarders.fastmail.token,forwardedForwardEmailApiToken:e.forwarders.forwardEmail.token,forwardedForwardEmailDomain:e.forwarders.forwardEmail.domain,forwardedSimpleLoginApiKey:e.forwarders.simpleLogin.token,forwardedSimpleLoginBaseUrl:e.forwarders.simpleLogin.baseUrl}}}const{f3:Jz,QS:Yz,Mt:Xz,Lq:Zz}=e,eP=KI,{B:tP,Vm:iP,KQ:rP,ji:nP}=i,aP=Object.freeze({file:"file",chromium:"chromium",ipc:"ipc",download:"download"}),sP=Object.freeze({unique:"unique",chromium:"chromium"}),oP=V_({[aP.chromium]:[Ku.Desktop],[aP.download]:[Ku.Browser],[aP.file]:[Ku.Browser,Ku.Desktop,Ku.Web,Ku.Cli],[aP.ipc]:[]}),lP=[{id:"bitwardenjson",loaders:[aP.file],instructions:sP.unique},{id:"chromecsv",loaders:[aP.file],instructions:sP.chromium},{id:"operacsv",loaders:[aP.file],instructions:sP.chromium},{id:"vivaldicsv",loaders:[aP.file],instructions:sP.chromium},{id:"bravecsv",loaders:[aP.file],instructions:sP.chromium},{id:"edgecsv",loaders:[aP.file],instructions:sP.chromium}],cP=V_(Object.fromEntries(lP.map(e=>[e.id,e])));var uP=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class dP{constructor(e){this.apiService=e}postImportCiphers(e){return uP(this,void 0,void 0,function*(){return yield this.apiService.send("POST","/ciphers/import",e,!0,!1)})}postImportOrganizationCiphers(e,t){return uP(this,void 0,void 0,function*(){return yield this.apiService.send("POST","/ciphers/import-organization?organizationId="+e,t,!0,!1)})}}class hP{constructor(){this.ciphers=[],this.folders=[],this.folderRelationships=[]}}class pP{constructor(){this.ciphers=[],this.collections=[],this.collectionRelationships=[]}}class mP{constructor(e,t){this.key=e,this.value=t}}class gP{constructor(){this.success=!1,this.ciphers=[],this.folders=[],this.folderRelationships=[],this.collections=[],this.collectionRelationships=[]}}var fP=o(1880);class yP{constructor(){this.organizationId=null,this.logService=new r(!1),this.newLineRegex=/(?:\r\n|\r|\n)/,this.passwordFieldNames=["password","pass word","passphrase","pass phrase","pass","code","code word","codeword","secret","secret word","personpwd","key","keyword","key word","keyphrase","key phrase","form_pw","wppassword","pin","pwd","pw","pword","passwd","p","serial","serial#","license key","reg #","passwort"],this.usernameFieldNames=["user","name","user name","username","login name","email","e-mail","id","userid","user id","login","form_loginname","wpname","mail","loginid","login id","log","personlogin","first name","last name","card#","account #","member","member #","nom","benutzername"],this.notesFieldNames=["note","notes","comment","comments","memo","description","free form","freeform","free text","freetext","free","kommentar"],this.uriFieldNames=["url","hyper link","hyperlink","link","host","hostname","host name","server","address","hyper ref","href","web","website","web site","site","web-site","uri","ort","adresse"],this.parseCsvOptions={encoding:"UTF-8",skipEmptyLines:!1}}get organization(){return null!=this.organizationId}parseXml(e){if(!this.validateNoExternalEntities(e))return null;const t=(new DOMParser).parseFromString(e,"application/xml");return null!=t&&null==t.querySelector("parsererror")?t:null}parseCsv(e,t,i={}){const r=Object.assign({header:t},this.parseCsvOptions,i);e=this.splitNewLine(e).join("\n").trim();const n=fP.parse(e,r);return null!=n.errors&&n.errors.length>0&&n.errors.forEach(e=>{null!=e.row&&this.logService.warning("Error parsing row "+e.row+": "+e.message)}),n.data&&n.data.length>0?n.data:null}parseSingleRowCsv(e){if(this.isNullOrWhitespace(e))return null;const t=this.parseCsv(e,!1);return null!=t&&t.length>0&&t[0].length>0?t[0]:null}makeUriArray(e){if(null==e)return null;if("string"==typeof e){const t=new tw;return t.uri=this.fixUri(e),this.isNullOrWhitespace(t.uri)?null:[t]}if(e.length>0){const t=[];return e.forEach(e=>{const i=new tw;i.uri=this.fixUri(e),this.isNullOrWhitespace(i.uri)||t.push(i)}),0===t.length?null:t}return null}fixUri(e){return null==e?null:(-1===(e=e.trim()).indexOf("://")&&e.indexOf(".")>=0&&(e="http://"+e),e.length>1e3?e.substring(0,1e3):e)}nameFromUrl(e){const t=Tt.getHostname(e);return this.isNullOrWhitespace(t)?null:t.startsWith("www.")?t.replace("www.",""):t}isNullOrWhitespace(e){return Tt.isNullOrWhitespace(e)}getValueOrDefault(e,t=null){return this.isNullOrWhitespace(e)?t:e}splitNewLine(e){return e.split(this.newLineRegex)}setCardExpiration(e,t){if(this.isNullOrWhitespace(t))return!1;t=t.replace(/\s/g,"");const i=new RegExp("^0?(?[1-9]|1[0-2])/(?(?:[1-2][0-9])?[0-9]{2})$"),r=t.match(i);if(!r)return!1;e.card.expMonth=r.groups.month;const n=r.groups.year;return e.card.expYear=dg(n),!0}moveFoldersToCollections(e){e.folderRelationships.forEach(t=>e.collectionRelationships.push(t)),e.collections=e.folders.map(e=>new qt({name:e.name,organizationId:this.organizationId,id:e.id&&""!==e.id?e.id:null})),e.folderRelationships=[],e.folders=[]}querySelectorDirectChild(e,t){const i=this.querySelectorAllDirectChild(e,t);return 0===i.length?null:i[0]}querySelectorAllDirectChild(e,t){return Array.from(e.querySelectorAll(t)).filter(t=>t.parentNode===e)}initLoginCipher(){const e=new lw;return e.favorite=!1,e.notes="",e.fields=[],e.login=new nw,e.type=rm.Login,e}cleanupCipher(e){null!=e&&(e.type!==rm.Login&&(e.login=null),this.isNullOrWhitespace(e.name)&&(e.name="--"),this.isNullOrWhitespace(e.notes)&&(e.notes=null))}processKvp(e,t,i,r=am.Text){if(!this.isNullOrWhitespace(i))if(this.isNullOrWhitespace(t)&&(t=""),i.length>200||i.trim().search(this.newLineRegex)>-1)null==e.notes&&(e.notes=""),e.notes+=t+": "+this.splitNewLine(i).join("\n")+"\n";else{null==e.fields&&(e.fields=[]);const n=new Gb;n.type=r,n.name=t,n.value=i,e.fields.push(n)}}processFolder(e,t,i=!0){if(this.isNullOrWhitespace(t))return;let r=e.folders.length;t=t.replace(/\\/g,"/");let n=!0;for(let i=0;i0;t--){const i=a.slice(0,t).join("/");if(null==e.folders.find(e=>e.name===i)){const t=new DC;t.name=i,e.folders.push(t)}}}convertToNoteIfNeeded(e){e.type===rm.Login&&this.isNullOrWhitespace(e.login.username)&&this.isNullOrWhitespace(e.login.password)&&(null==e.login.uris||0===e.login.uris.length)&&(e.type=rm.SecureNote,e.secureNote=new sw,e.secureNote.type=0)}processFullName(e,t){if(this.isNullOrWhitespace(t))return;const i=t.split(" ");i.length>0&&(e.identity.firstName=this.getValueOrDefault(i[0])),2===i.length?e.identity.lastName=this.getValueOrDefault(i[1]):i.length>=3&&(e.identity.middleName=this.getValueOrDefault(i[1]),e.identity.lastName=i.slice(2,i.length).join(" "))}validateNoExternalEntities(e){return!new RegExp("{var i;const r=this.initLoginCipher(),n=this.getValueOrDefault(e.url);r.name=this.getValueOrDefault(null!==(i=this.nameFromUrl(n))&&void 0!==i?i:"","--"),r.login.username=this.getValueOrDefault(e.username),r.login.password=this.getValueOrDefault(e.password),r.login.uris=this.makeUriArray(e.url),r.notes=this.getValueOrDefault(e.note),this.cleanupCipher(r),t.ciphers.push(r)}),t.success=!0,Promise.resolve(t))}}class bP extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(e.length<2)return;const i=this.initLoginCipher();if(i.notes=this.getValueOrDefault(e[e.length-1]),i.name=this.getValueOrDefault(e[0],"--"),e.length>2&&e.length%2==0)for(let t=0;t-1?i.login.password=this.getValueOrDefault(r):null==i.login.username&&this.usernameFieldNames.indexOf(a)>-1?i.login.username=this.getValueOrDefault(r):(null==i.login.uris||0===i.login.uris.length)&&this.uriFieldNames.indexOf(a)>-1?i.login.uris=this.makeUriArray(r):this.processKvp(i,n,r)}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class wP extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.name),i.login.uris=this.makeUriArray(e.web),i.login.password=this.getValueOrDefault(e.password),i.login.username=this.getValueOrDefault(e.login),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class kP extends yP{parse(e){const t=new gP,i=JSON.parse(e);return null==i?(t.success=!1,Promise.resolve(t)):(null!=i.logins&&i.logins.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.custName),i.notes=this.getValueOrDefault(e.note),i.login.uris=this.makeUriArray(e.url),i.login.password=this.getValueOrDefault(e.pwd),i.login.username=this.getValueOrDefault(e.loginName),this.cleanupCipher(i),t.ciphers.push(i)}),null!=i.notes&&i.notes.forEach(e=>{const i=this.initLoginCipher();i.type=rm.SecureNote,i.secureNote.type=0,i.name=this.getValueOrDefault(e.label),i.notes=this.getValueOrDefault(e.text),this.cleanupCipher(i),t.ciphers.push(i)}),null!=i.cards&&i.cards.forEach(e=>{const i=this.initLoginCipher();i.type=rm.Card,i.name=this.getValueOrDefault(e.custName),i.notes=this.getValueOrDefault(e.note),i.card.cardholderName=this.getValueOrDefault(e.holderName),i.card.number=this.getValueOrDefault(e.cardNumber),i.card.code=this.getValueOrDefault(e.cvv),i.card.brand=Hb.getCardBrandByPatterns(i.card.number),null!=e.expirationDate&&(null!=e.expirationDate.month&&(i.card.expMonth=e.expirationDate.month+""),null!=e.expirationDate.year&&(i.card.expYear=e.expirationDate.year+"")),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class SP extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.name,this.getValueOrDefault(this.nameFromUrl(e.website),"--")),i.login.uris=this.makeUriArray(e.website),i.login.password=this.getValueOrDefault(e.password),this.isNullOrWhitespace(e.username)&&!this.isNullOrWhitespace(e.secondary_username)?i.login.username=e.secondary_username:(i.login.username=this.getValueOrDefault(e.username),i.notes=this.getValueOrDefault(e.secondary_username)),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class _P extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if("list"===e.grouping)return;const i=this.initLoginCipher();i.favorite="1"===e.fav,i.name=this.getValueOrDefault(e.name),i.notes=this.getValueOrDefault(e.extra),"note"!==e.grouping&&(i.login.uris=this.makeUriArray(e.url),i.login.password=this.getValueOrDefault(e.password),i.login.username=this.getValueOrDefault(e.username)),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class xP extends yP{constructor(){super(...arguments),this.androidPatternRegex=new RegExp("^android:\\/\\/.*(?<=@)(.*)(?=\\/)")}normalizeAndroidUrl(e){const t=null==e?void 0:e.match(this.androidPatternRegex);return t?`androidapp://${t[1]}`:e}parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher(),r=this.normalizeAndroidUrl(e.url);let n=e.name;!n&&this.androidPatternRegex.test(e.url)&&(n=e.url.match(this.androidPatternRegex)[1]),i.name=this.getValueOrDefault(n,"--"),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(r),i.notes=this.getValueOrDefault(e.note),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class CP extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{this.organization&&!this.isNullOrWhitespace(e.collections)?e.collections.split(",").forEach(e=>{this.processFolder(t,e)}):this.organization||this.processFolder(t,e.folder);const i=new lw;i.favorite=!this.organization&&"0"!==this.getValueOrDefault(e.favorite,"0"),i.type=rm.Login,i.notes=this.getValueOrDefault(e.notes),i.name=this.getValueOrDefault(e.name,"--");try{i.reprompt=parseInt(this.getValueOrDefault(e.reprompt,tm.None.toString()),10)}catch(e){console.error("Unable to parse reprompt value",e),i.reprompt=tm.None}if(!this.isNullOrWhitespace(e.archivedDate))try{i.archivedDate=new Date(e.archivedDate)}catch(e){console.error("Unable to parse archivedDate value",e)}if(!this.isNullOrWhitespace(e.fields)){const t=this.splitNewLine(e.fields);for(let e=0;er+2&&(n.value=t[e].substr(r+2)),i.fields.push(n)}}switch(null!=e.type?e.type.toLowerCase():null){case"note":i.type=rm.SecureNote,i.secureNote=new sw,i.secureNote.type=0;break;default:{i.type=rm.Login,i.login=new nw,i.login.totp=this.getValueOrDefault(e.login_totp||e.totp),i.login.username=this.getValueOrDefault(e.login_username||e.username),i.login.password=this.getValueOrDefault(e.login_password||e.password);const t=this.parseSingleRowCsv(e.login_uri||e.uri);i.login.uris=this.makeUriArray(t);break}}t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}function IP(e){return null==e?null:"string"==typeof e?e:null==e?void 0:e.encryptedString}class EP{static template(){const e=new EP;return e.cardholderName="John Doe",e.brand="visa",e.number="4242424242424242",e.expMonth="04",e.expYear="2023",e.code="123",e}static toView(e,t=new Hb){return t.cardholderName=e.cardholderName,t.brand=e.brand,t.number=e.number,t.expMonth=e.expMonth,t.expYear=e.expYear,t.code=e.code,t}static toDomain(e,t=new dw){return t.cardholderName=null!=e.cardholderName?new Nt(e.cardholderName):null,t.brand=null!=e.brand?new Nt(e.brand):null,t.number=null!=e.number?new Nt(e.number):null,t.expMonth=null!=e.expMonth?new Nt(e.expMonth):null,t.expYear=null!=e.expYear?new Nt(e.expYear):null,t.code=null!=e.code?new Nt(e.code):null,t}constructor(e){null!=e&&(this.cardholderName=IP(e.cardholderName),this.brand=IP(e.brand),this.number=IP(e.number),this.expMonth=IP(e.expMonth),this.expYear=IP(e.expYear),this.code=IP(e.code))}}class zP{static template(){const e=new zP;return e.name="Field name",e.value="Some value",e.type=am.Text,e}static toView(e,t=new Gb){return t.type=e.type,t.value=e.value,t.name=e.name,t.linkedId=e.linkedId,t}static toDomain(e,t=new hw){return t.type=e.type,t.value=null!=e.value?new Nt(e.value):null,t.name=null!=e.name?new Nt(e.name):null,t.linkedId=e.linkedId,t}constructor(e){null!=e&&(this.name=IP(e.name),this.value=IP(e.value),this.type=e.type,this.linkedId=e.linkedId)}}class PP{static template(){const e=new PP;return e.title="Mr",e.firstName="John",e.middleName="William",e.lastName="Doe",e.address1="123 Any St",e.address2="Apt #123",e.address3=null,e.city="New York",e.state="NY",e.postalCode="10001",e.country="US",e.company="Acme Inc.",e.email="john@company.com",e.phone="5555551234",e.ssn="000-123-4567",e.username="jdoe",e.passportNumber="US-123456789",e.licenseNumber="D123-12-123-12333",e}static toView(e,t=new Yb){return t.title=e.title,t.firstName=e.firstName,t.middleName=e.middleName,t.lastName=e.lastName,t.address1=e.address1,t.address2=e.address2,t.address3=e.address3,t.city=e.city,t.state=e.state,t.postalCode=e.postalCode,t.country=e.country,t.company=e.company,t.email=e.email,t.phone=e.phone,t.ssn=e.ssn,t.username=e.username,t.passportNumber=e.passportNumber,t.licenseNumber=e.licenseNumber,t}static toDomain(e,t=new pw){return t.title=null!=e.title?new Nt(e.title):null,t.firstName=null!=e.firstName?new Nt(e.firstName):null,t.middleName=null!=e.middleName?new Nt(e.middleName):null,t.lastName=null!=e.lastName?new Nt(e.lastName):null,t.address1=null!=e.address1?new Nt(e.address1):null,t.address2=null!=e.address2?new Nt(e.address2):null,t.address3=null!=e.address3?new Nt(e.address3):null,t.city=null!=e.city?new Nt(e.city):null,t.state=null!=e.state?new Nt(e.state):null,t.postalCode=null!=e.postalCode?new Nt(e.postalCode):null,t.country=null!=e.country?new Nt(e.country):null,t.company=null!=e.company?new Nt(e.company):null,t.email=null!=e.email?new Nt(e.email):null,t.phone=null!=e.phone?new Nt(e.phone):null,t.ssn=null!=e.ssn?new Nt(e.ssn):null,t.username=null!=e.username?new Nt(e.username):null,t.passportNumber=null!=e.passportNumber?new Nt(e.passportNumber):null,t.licenseNumber=null!=e.licenseNumber?new Nt(e.licenseNumber):null,t}constructor(e){null!=e&&(this.title=IP(e.title),this.firstName=IP(e.firstName),this.middleName=IP(e.middleName),this.lastName=IP(e.lastName),this.address1=IP(e.address1),this.address2=IP(e.address2),this.address3=IP(e.address3),this.city=IP(e.city),this.state=IP(e.state),this.postalCode=IP(e.postalCode),this.country=IP(e.country),this.company=IP(e.company),this.email=IP(e.email),this.phone=IP(e.phone),this.ssn=IP(e.ssn),this.username=IP(e.username),this.passportNumber=IP(e.passportNumber),this.licenseNumber=IP(e.licenseNumber))}}class AP{static template(){const e=new AP;return e.credentialId="keyId",e.keyType="keyType",e.keyAlgorithm="keyAlgorithm",e.keyCurve="keyCurve",e.keyValue="keyValue",e.rpId="rpId",e.userHandle="userHandle",e.userName="userName",e.counter="counter",e.rpName="rpName",e.userDisplayName="userDisplayName",e.discoverable="false",e.creationDate=null,e}static toView(e,t=new Xb){return t.credentialId=e.credentialId,t.keyType=e.keyType,t.keyAlgorithm=e.keyAlgorithm,t.keyCurve=e.keyCurve,t.keyValue=e.keyValue,t.rpId=e.rpId,t.userHandle=e.userHandle,t.userName=e.userName,t.counter=parseInt(e.counter),t.rpName=e.rpName,t.userDisplayName=e.userDisplayName,t.discoverable="true"===e.discoverable,t.creationDate=new Date(e.creationDate),t}static toDomain(e,t=new mw){return t.credentialId=null!=e.credentialId?new Nt(e.credentialId):null,t.keyType=null!=e.keyType?new Nt(e.keyType):null,t.keyAlgorithm=null!=e.keyAlgorithm?new Nt(e.keyAlgorithm):null,t.keyCurve=null!=e.keyCurve?new Nt(e.keyCurve):null,t.keyValue=null!=e.keyValue?new Nt(e.keyValue):null,t.rpId=null!=e.rpId?new Nt(e.rpId):null,t.userHandle=null!=e.userHandle?new Nt(e.userHandle):null,t.userName=null!=e.userName?new Nt(e.userName):null,t.counter=null!=e.counter?new Nt(e.counter):null,t.rpName=null!=e.rpName?new Nt(e.rpName):null,t.userDisplayName=null!=e.userDisplayName?new Nt(e.userDisplayName):null,t.discoverable=null!=e.discoverable?new Nt(e.discoverable):null,t.creationDate=null!=e.creationDate?new Date(e.creationDate):null,t}constructor(e){null!=e&&(this.credentialId=IP(e.credentialId),this.keyType=IP(e.keyType),this.keyAlgorithm=IP(e.keyAlgorithm),this.keyCurve=IP(e.keyCurve),this.keyValue=IP(e.keyValue),this.rpId=IP(e.rpId),this.userHandle=IP(e.userHandle),this.userName=IP(e.userName),this.counter=IP(e instanceof Xb?String(e.counter):e.counter),this.rpName=IP(e.rpName),this.userDisplayName=IP(e.userDisplayName),this.discoverable=IP(e instanceof Xb?String(e.discoverable):e.discoverable),this.creationDate=e.creationDate)}}class jP{static template(){const e=new jP;return e.uri="https://google.com",e.match=null,e}static toView(e,t=new tw){return t.uri=e.uri,t.match=e.match,t}static toDomain(e,t=new gw){return t.uri=null!=e.uri?new Nt(e.uri):null,t.uriChecksum=null!=e.uriChecksum?new Nt(e.uriChecksum):null,t.match=e.match,t}constructor(e){var t;this.match=null,null!=e&&(this.uri=IP(e.uri),"uriChecksum"in e&&(this.uriChecksum=null===(t=e.uriChecksum)||void 0===t?void 0:t.encryptedString),this.match=e.match)}}class TP{static template(){const e=new TP;return e.uris=[],e.username="jdoe",e.password="myp@ssword123",e.totp="JBSWY3DPEHPK3PXP",e.fido2Credentials=[],e}static toView(e,t=new nw){return null!=e.uris&&(t.uris=e.uris.map(e=>jP.toView(e))),t.username=e.username,t.password=e.password,t.totp=e.totp,null!=e.fido2Credentials&&(t.fido2Credentials=e.fido2Credentials.map(e=>AP.toView(e))),t}static toDomain(e,t=new fw){return null!=e.uris&&(t.uris=e.uris.map(e=>jP.toDomain(e))),t.username=null!=e.username?new Nt(e.username):null,t.password=null!=e.password?new Nt(e.password):null,t.totp=null!=e.totp?new Nt(e.totp):null,null!=e.fido2Credentials&&(t.fido2Credentials=e.fido2Credentials.map(e=>AP.toDomain(e))),t}constructor(e){null!=e&&(null!=e.uris&&(this.uris=e.uris.map(e=>new jP(e))),null!=e.fido2Credentials&&(this.fido2Credentials=e.fido2Credentials.map(e=>new AP(e))),this.username=IP(e.username),this.password=IP(e.password),this.totp=IP(e.totp))}}class DP{static template(){const e=new DP;return e.password=null,e.lastUsedDate=null,e}static toView(e,t=new aw){return t.password=e.password,t.lastUsedDate=e.lastUsedDate?new Date(e.lastUsedDate):null,t}static toDomain(e,t=new yw){return t.password=null!=e.password?new Nt(e.password):null,t.lastUsedDate=e.lastUsedDate?new Date(e.lastUsedDate):null,t}constructor(e){this.lastUsedDate=null,null!=e&&(this.password=IP(e.password),this.lastUsedDate=e.lastUsedDate)}}class OP{static template(){const e=new OP;return e.type=0,e}static toView(e,t=new sw){return t.type=e.type,t}static toDomain(e,t=new vw){return t.type=e.type,t}constructor(e){null!=e&&(this.type=e.type)}}class NP{static template(){const e=new NP;return e.privateKey="",e.publicKey="",e.keyFingerprint="",e}static toView(e,t=new ow){if(null!=e){if(!e.privateKey||""===e.privateKey.trim())throw new Error("SSH key private key is required.");if(!e.publicKey||""===e.publicKey.trim())throw new Error("SSH key public key is required.");if(!e.keyFingerprint||""===e.keyFingerprint.trim())throw new Error("SSH key fingerprint is required.");return t.privateKey=e.privateKey,t.publicKey=e.publicKey,t.keyFingerprint=e.keyFingerprint,t}}static toDomain(e,t=new bw){return t.privateKey=new Nt(e.privateKey),t.publicKey=new Nt(e.publicKey),t.keyFingerprint=new Nt(e.keyFingerprint),t}constructor(e){null!=e&&(this.privateKey=IP(e.privateKey),this.publicKey=IP(e.publicKey),this.keyFingerprint=IP(e.keyFingerprint))}}class RP{constructor(){this.passwordHistory=null,this.revisionDate=null,this.creationDate=null,this.deletedDate=null,this.archivedDate=null}static template(){const e=new RP;return e.organizationId=null,e.collectionIds=null,e.folderId=null,e.type=rm.Login,e.name="Item name",e.notes="Some notes about this item.",e.favorite=!1,e.fields=[],e.login=null,e.secureNote=null,e.card=null,e.identity=null,e.sshKey=null,e.reprompt=tm.None,e.passwordHistory=[],e.creationDate=null,e.revisionDate=null,e.deletedDate=null,e.archivedDate=null,e}static toView(e,t=new lw){var i,r,n;if(t.type=e.type,t.folderId=e.folderId,null==t.organizationId&&(t.organizationId=e.organizationId),t.collectionIds||e.collectionIds){const n=new Set((null!==(i=t.collectionIds)&&void 0!==i?i:[]).concat(null!==(r=e.collectionIds)&&void 0!==r?r:[]));t.collectionIds=Array.from(n.values())}switch(t.name=e.name,t.notes=e.notes,t.favorite=e.favorite,t.reprompt=null!==(n=e.reprompt)&&void 0!==n?n:tm.None,t.key=null!=e.key?new Nt(e.key):null,null!=e.fields&&(t.fields=e.fields.map(e=>zP.toView(e))),e.type){case rm.Login:t.login=TP.toView(e.login);break;case rm.SecureNote:t.secureNote=OP.toView(e.secureNote);break;case rm.Card:t.card=EP.toView(e.card);break;case rm.Identity:t.identity=PP.toView(e.identity);break;case rm.SshKey:t.sshKey=NP.toView(e.sshKey)}return null!=e.passwordHistory&&(t.passwordHistory=e.passwordHistory.map(e=>DP.toView(e))),t.creationDate=e.creationDate?new Date(e.creationDate):t.creationDate,t.revisionDate=e.revisionDate?new Date(e.revisionDate):t.revisionDate,t.deletedDate=e.deletedDate?new Date(e.deletedDate):t.deletedDate,t.archivedDate=e.archivedDate?new Date(e.archivedDate):t.archivedDate,t}static toDomain(e,t=new Sw){var i;switch(t.type=e.type,t.folderId=e.folderId,null==t.organizationId&&(t.organizationId=e.organizationId),t.name=null!=e.name?new Nt(e.name):null,t.notes=null!=e.notes?new Nt(e.notes):null,t.favorite=e.favorite,t.reprompt=null!==(i=e.reprompt)&&void 0!==i?i:tm.None,t.key=null!=e.key?new Nt(e.key):null,null!=e.fields&&(t.fields=e.fields.map(e=>zP.toDomain(e))),e.type){case rm.Login:t.login=TP.toDomain(e.login);break;case rm.SecureNote:t.secureNote=OP.toDomain(e.secureNote);break;case rm.Card:t.card=EP.toDomain(e.card);break;case rm.Identity:t.identity=PP.toDomain(e.identity);break;case rm.SshKey:t.sshKey=NP.toDomain(e.sshKey)}return null!=e.passwordHistory&&(t.passwordHistory=e.passwordHistory.map(e=>DP.toDomain(e))),t.creationDate=e.creationDate?new Date(e.creationDate):null,t.revisionDate=e.revisionDate?new Date(e.revisionDate):null,t.deletedDate=e.deletedDate?new Date(e.deletedDate):null,t.archivedDate=e.archivedDate?new Date(e.archivedDate):null,t}build(e){var t;switch(this.organizationId=e.organizationId,this.folderId=e.folderId,this.type=e.type,this.reprompt=e.reprompt,this.name=IP(e.name),this.notes=IP(e.notes),"key"in e&&(this.key=null===(t=e.key)||void 0===t?void 0:t.encryptedString),this.favorite=e.favorite,null!=e.fields&&(this.fields=e.fields.map(e=>new zP(e))),e.type){case rm.Login:this.login=new TP(e.login);break;case rm.SecureNote:this.secureNote=new OP(e.secureNote);break;case rm.Card:this.card=new EP(e.card);break;case rm.Identity:this.identity=new PP(e.identity);break;case rm.SshKey:this.sshKey=new NP(e.sshKey)}null!=e.passwordHistory&&(this.passwordHistory=e.passwordHistory.map(e=>new DP(e))),this.creationDate=e.creationDate,this.revisionDate=e.revisionDate,this.deletedDate=e.deletedDate,this.archivedDate=e.archivedDate}}class UP extends RP{build(e){this.id=e.id,super.build(e),this.collectionIds=e.collectionIds}}class FP{static template(){const e=new FP;return e.organizationId="00000000-0000-0000-0000-000000000000",e.name="Collection name",e.externalId=null,e}static toView(e,t){const i=new qt({name:e.name,organizationId:e.organizationId,id:t});return i.externalId=e.externalId,i}static toDomain(e,t){return t.name=null!=e.name?new Nt(e.name):null,t.externalId=e.externalId,null==t.organizationId&&(t.organizationId=e.organizationId),t}build(e){this.organizationId=e.organizationId,this.name=IP(e.name),this.externalId=e.externalId}}class qP extends FP{static toView(e){return super.toView(e,e.id)}static toDomain(e,t){return t.id=e.id,super.toDomain(e,t)}build(e){this.id=e.id,super.build(e)}}class LP{constructor(){this.name=""}static template(){const e=new LP;return e.name="Folder name",e}static toView(e,t=new DC){return t.name=e.name,t}static toDomain(e,t=new OC){return t.name=new Nt(e.name),t}build(e){var t,i;this.name=null!==(i=IP(null!==(t=e.name)&&void 0!==t?t:""))&&void 0!==i?i:""}}class BP extends LP{static toView(e,t=new DC){return t.id=e.id,super.toView(e,t)}static toDomain(e,t=new OC){return t.id=e.id,super.toDomain(e,t)}build(e){this.id=e.id,super.build(e)}}function MP(e){return null!=e&&!0!==e.encrypted}function VP(e){return null!=e&&!0===e.encrypted&&!0===e.passwordProtected}var $P=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class KP{constructor(e,t,i){this.individualVaultExportService=e,this.organizationVaultExportService=t,this.accountService=i}getExport(e){return $P(this,arguments,void 0,function*(e,t="csv",i=""){if(yield this.checkForImpersonation(e),!Tt.isNullOrWhitespace(i)){if("csv"==t)throw new Error("CSV does not support password protected export");return this.individualVaultExportService.getPasswordProtectedExport(e,i)}return this.individualVaultExportService.getExport(e,t)})}getOrganizationExport(e,t,i,r){return $P(this,arguments,void 0,function*(e,t,i,r,n=!1){if(yield this.checkForImpersonation(e),!Tt.isNullOrWhitespace(r)){if("csv"==i)throw new Error("CSV does not support password protected export");return this.organizationVaultExportService.getPasswordProtectedExport(e,t,r,n)}return this.organizationVaultExportService.getOrganizationExport(e,t,i,n)})}formats$(e){const t=[{name:".json",format:"json"},{name:".csv",format:"csv"},{name:".json (Encrypted)",format:"encrypted_json"}];return e.isMyVault?bt([...t,{name:".zip (with attachments)",format:"zip"}]):bt(t)}checkForImpersonation(e){return $P(this,void 0,void 0,function*(){const t=yield Ce(this.accountService.activeAccount$.pipe(tu));if(e!==t)throw new Error("UserId does not match the currently authenticated user")})}}class WP{constructor(e,t,i,r){this.keyGenerationService=e,this.encryptService=t,this.cryptoFunctionService=i,this.kdfConfigService=r}buildPasswordExport(e,t,i){return r=this,n=void 0,s=function*(){const r=yield this.kdfConfigService.getKdfConfig(e),n=Tt.fromBufferToB64(yield this.cryptoFunctionService.randomBytes(16)),a=yield this.keyGenerationService.deriveVaultExportKey(i,n,r),s=yield this.encryptService.encryptString(Tt.newGuid(),a),o=yield this.encryptService.encryptString(t,a),l={encrypted:!0,passwordProtected:!0,salt:n,kdfType:r.kdfType,kdfIterations:r.iterations,encKeyValidation_DO_NOT_EDIT:s.encryptedString,data:o.encryptedString};return r.kdfType===Cd.Argon2id&&(l.kdfMemory=r.memory,l.kdfParallelism=r.parallelism),JSON.stringify(l,null," ")},new((a=void 0)||(a=Promise))(function(e,t){function i(e){try{l(s.next(e))}catch(e){t(e)}}function o(e){try{l(s.throw(e))}catch(e){t(e)}}function l(t){var r;t.done?e(t.value):(r=t.value,r instanceof a?r:new a(function(e){e(r)})).then(i,o)}l((s=s.apply(r,n||[])).next())});var r,n,a,s}buildCommonCipher(e,t){switch(e.type=null,e.name=t.name,e.notes=t.notes,e.fields=null,e.reprompt=t.reprompt,e.archivedDate=t.archivedDate?t.archivedDate.toISOString():null,e.login_uri=null,e.login_username=null,e.login_password=null,e.login_totp=null,t.fields&&t.fields.forEach(t=>{e.fields?e.fields+="\n":e.fields="",e.fields+=(t.name||"")+": "+t.value}),t.type){case rm.Login:e.type="login",e.login_username=t.login.username,e.login_password=t.login.password,e.login_totp=t.login.totp,t.login.uris&&(e.login_uri=[],t.login.uris.forEach(t=>{e.login_uri.push(t.uri)}));break;case rm.SecureNote:e.type="note";break;default:return}return e}}class HP{static getFileName(e="",t="csv"){"encrypted_json"===t&&(e=""==e?"encrypted":"encrypted_"+e,t="json");const i=new Date;return"bitwarden"+(e?"_"+e:"")+"_export_"+i.getFullYear()+this.padNumber(i.getMonth()+1,2)+this.padNumber(i.getDate(),2)+this.padNumber(i.getHours(),2)+this.padNumber(i.getMinutes(),2)+this.padNumber(i.getSeconds(),2)+"."+t}static padNumber(e,t,i="0"){const r=e.toString();return r.length>=t?r:new Array(t-r.length+1).join(i)+r}}var GP=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class QP extends WP{constructor(e,t,i,r,n,a,s,o,l){super(i,n,a,o),this.cipherService=e,this.vaultExportApiService=t,this.keyService=r,this.collectionService=s,this.restrictedItemTypesService=l}getPasswordProtectedExport(e,t,i,r){return GP(this,void 0,void 0,function*(){const n=yield this.getOrganizationExport(e,t,"json",r);return{type:"text/plain",data:yield this.buildPasswordExport(e,n.data,i),fileName:HP.getFileName("org","encrypted_json")}})}getOrganizationExport(e,t){return GP(this,arguments,void 0,function*(e,t,i="csv",r){if(Tt.isNullOrWhitespace(t))throw new Error("OrganizationId must be set");if("zip"===i)throw new Error("Zip export not supported for organization");return"encrypted_json"===i?{type:"text/plain",data:r?yield this.getEncryptedManagedExport(e,t):yield this.getOrganizationEncryptedExport(e,t),fileName:HP.getFileName("org","encrypted_json")}:{type:"text/plain",data:r?yield this.getDecryptedManagedExport(e,t,i):yield this.getOrganizationDecryptedExport(e,t,i),fileName:HP.getFileName("org",i)}})}getOrganizationDecryptedExport(e,t,i){return GP(this,void 0,void 0,function*(){const r=[],n=[],a=[],s=yield Ce(this.keyService.orgKeys$(e).pipe(Ie(e=>null!=e))),o=yield Ce(this.restrictedItemTypesService.restricted$);return a.push(this.vaultExportApiService.getOrganizationExport(t).then(i=>{const a=[];return null!=i&&(null!=i.collections&&i.collections.length>0&&i.collections.forEach(e=>{const i=Ut.fromCollectionData(new Kt(e)),n=s[t];a.push(i.decrypt(n,this.encryptService).then(e=>{r.push(e)}))}),null!=i.ciphers&&i.ciphers.length>0&&i.ciphers.filter(e=>null===e.deletedDate).forEach(t=>GP(this,void 0,void 0,function*(){const i=new Sw(new Fb(t));a.push(this.cipherService.decrypt(i,e).then(e=>{this.restrictedItemTypesService.isCipherRestricted(e,o)||n.push(e)}))}))),Promise.all(a)})),yield Promise.all(a),"csv"===i?this.buildCsvExport(r,n):this.buildJsonExport(r,n)})}getOrganizationEncryptedExport(e,t){return GP(this,void 0,void 0,function*(){const i=[],r=[],n=yield Ce(this.restrictedItemTypesService.restricted$),a=yield this.vaultExportApiService.getOrganizationExport(t);if(null!=a)return null!=a.collections&&a.collections.length>0&&a.collections.forEach(e=>{const t=Ut.fromCollectionData(new Kt(e));i.push(t)}),null!=a.ciphers&&a.ciphers.length>0&&a.ciphers.filter(e=>null===e.deletedDate).forEach(e=>{const t=new Sw(new Fb(e));this.restrictedItemTypesService.isCipherRestricted(t,n)||r.push(t)}),this.BuildEncryptedExport(e,t,i,r)})}getDecryptedManagedExport(e,t,i){return GP(this,void 0,void 0,function*(){let r=[],n=[];const a=[];a.push(this.cipherService.getAllDecrypted(e).then(e=>{n=e})),yield Promise.all(a);const s=yield Ce(this.collectionService.decryptedCollections$(e).pipe(X(e=>e.filter(e=>e.organizationId==t&&e.manage)))),o=yield Ce(this.restrictedItemTypesService.restricted$);return r=n.filter(e=>null==e.deletedDate&&e.organizationId==t&&s.some(t=>e.collectionIds.some(e=>t.id===e))&&!this.restrictedItemTypesService.isCipherRestricted(e,o)),"csv"===i?this.buildCsvExport(s,r):this.buildJsonExport(s,r)})}getEncryptedManagedExport(e,t){return GP(this,void 0,void 0,function*(){let i=[],r=[];const n=[];n.push(this.cipherService.getAll(e).then(e=>{r=e})),yield Promise.all(n);const a=yield Ce(this.collectionService.encryptedCollections$(e).pipe(X(e=>null!=e?e:[]),X(e=>e.filter(e=>e.organizationId==t&&e.manage)))),s=yield Ce(this.restrictedItemTypesService.restricted$);return i=r.filter(e=>null==e.deletedDate&&e.organizationId==t&&a.some(t=>e.collectionIds.some(e=>t.id===e))&&!this.restrictedItemTypesService.isCipherRestricted(e,s)),this.BuildEncryptedExport(e,t,a,i)})}BuildEncryptedExport(e,t,i,r){return GP(this,void 0,void 0,function*(){const n=yield Ce(this.keyService.orgKeys$(e)),a=null==n?void 0:n[t];if(null==a)throw new Error("No encryption key found for organization");const s={encrypted:!0,encKeyValidation_DO_NOT_EDIT:(yield this.encryptService.encryptString("xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}),a)).encryptedString,collections:[],items:[]};return i.forEach(e=>{const t=new qP;t.build(e),s.collections.push(t)}),r.forEach(e=>{const t=new UP;t.build(e),s.items.push(t)}),JSON.stringify(s,null," ")})}buildCsvExport(e,t){const i=new Map;e.forEach(e=>{i.set(e.id,e)});const r=[];return t.forEach(e=>{if(e.type!==rm.Login&&e.type!==rm.SecureNote)return;const t={collections:[]};null!=e.collectionIds&&(t.collections=e.collectionIds.filter(e=>i.has(e)).map(e=>i.get(e).name)),this.buildCommonCipher(t,e),r.push(t)}),fP.unparse(r)}buildJsonExport(e,t){const i={encrypted:!1,collections:[],items:[]};return e.forEach(e=>{const t=new qP;t.build(e),i.collections.push(t)}),t.forEach(e=>{const t=new UP;t.build(e),delete t.key,i.items.push(t)}),JSON.stringify(i,null," ")}}var JP=o(2461),YP=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class XP extends WP{constructor(e,t,i,r,n,a,s,o,l){super(i,n,a,s),this.folderService=e,this.cipherService=t,this.keyService=r,this.apiService=o,this.restrictedItemTypesService=l}getExport(e){return YP(this,arguments,void 0,function*(e,t="csv"){return"encrypted_json"===t?this.getEncryptedExport(e):"zip"===t?this.getDecryptedExportZip(e):this.getDecryptedExport(e,t)})}getPasswordProtectedExport(e,t){return YP(this,void 0,void 0,function*(){const i=yield this.getExport(e,"json");if("text/plain"!==i.type)throw new Error("Unexpected export type");return{type:"text/plain",data:yield this.buildPasswordExport(e,i.data,t),fileName:HP.getFileName("","encrypted_json")}})}getDecryptedExportZip(e){return YP(this,void 0,void 0,function*(){const t=new JP,i=yield this.getDecryptedExport(e,"json");t.file("data.json",i.data);const r=t.folder("attachments");if(null==r)throw new Error("Error creating attachments folder");for(const t of yield this.cipherService.getAllDecrypted(e)){if(!t.attachments||0===t.attachments.length||null!=t.deletedDate||null!=t.organizationId)continue;const i=r.folder(t.id);for(const r of t.attachments){const n=yield this.downloadAttachment(t.id,r.id);try{const a=yield this.cipherService.getDecryptedAttachmentBuffer(t.id,r,n,e);i.file(r.fileName,a)}catch(e){throw new Error("Error decrypting attachment")}}}return{type:"application/zip",data:yield t.generateAsync({type:"blob"}),fileName:HP.getFileName("","zip")}})}downloadAttachment(e,t){return YP(this,void 0,void 0,function*(){const i=(yield this.apiService.getAttachmentData(e,t)).url,r=yield fetch(new Request(i,{cache:"no-store"}));if(200!==r.status)throw new Error("Error downloading attachment");return r})}getDecryptedExport(e,t){return YP(this,void 0,void 0,function*(){let i=[],r=[];const n=[];n.push(Ce(this.folderService.folderViews$(e)).then(e=>{i=e}));const a=yield Ce(this.restrictedItemTypesService.restricted$);return n.push(this.cipherService.getAllDecrypted(e).then(e=>{r=e.filter(e=>null==e.deletedDate&&!this.restrictedItemTypesService.isCipherRestricted(e,a))})),yield Promise.all(n),"csv"===t?{type:"text/plain",data:this.buildCsvExport(i,r),fileName:HP.getFileName("","csv")}:{type:"text/plain",data:this.buildJsonExport(i,r),fileName:HP.getFileName("","json")}})}getEncryptedExport(e){return YP(this,void 0,void 0,function*(){if(!e)throw new Error("User ID must not be null or undefined");let t=[],i=[];const r=[];r.push(Ce(this.folderService.folders$(e)).then(e=>{t=e}));const n=yield Ce(this.restrictedItemTypesService.restricted$);r.push(this.cipherService.getAll(e).then(e=>{i=e.filter(e=>null==e.deletedDate&&!this.restrictedItemTypesService.isCipherRestricted(e,n))})),yield Promise.all(r);const a=yield Ce(this.keyService.userKey$(e)),s={encrypted:!0,encKeyValidation_DO_NOT_EDIT:(yield this.encryptService.encryptString(Tt.newGuid(),a)).encryptedString,folders:[],items:[]};return t.forEach(e=>{if(!e.id)return;const t=new BP;t.build(e),s.folders.push(t)}),i.forEach(e=>{if(null!=e.organizationId)return;const t=new UP;t.build(e),t.collectionIds=null,s.items.push(t)}),{type:"text/plain",data:JSON.stringify(s,null," "),fileName:HP.getFileName("","encrypted_json")}})}buildCsvExport(e,t){const i=new Map;e.forEach(e=>{e.id&&i.set(e.id,e)});const r=[];return t.forEach(e=>{if(e.type!==rm.Login&&e.type!==rm.SecureNote)return;if(null!=e.organizationId)return;const t={};t.folder=null!=e.folderId&&i.has(e.folderId)?i.get(e.folderId).name:null,t.favorite=e.favorite?1:null,this.buildCommonCipher(t,e),r.push(t)}),fP.unparse(r)}buildJsonExport(e,t){const i={encrypted:!1,folders:[],items:[]};return e.forEach(e=>{if(!e.id)return;const t=new BP;t.build(e),i.folders.push(t)}),t.forEach(e=>{if(null!=e.organizationId)return;const t=new UP;t.build(e),t.collectionIds=null,delete t.key,i.items.push(t)}),JSON.stringify(i,null," ")}}class ZP extends Lt{constructor(e){super(e);const t=this.getResponseProperty("Collections");null!=t&&(this.collections=t.map(e=>new Mt(e)));const i=this.getResponseProperty("Ciphers");null!=i&&(this.ciphers=i.map(e=>new MS(e)))}}class eA{constructor(e){this.apiService=e}getOrganizationExport(e){return t=this,i=void 0,n=function*(){const t=yield this.apiService.send("GET","/organizations/"+e+"/export",void 0,!0,!0);return new ZP(t)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}var tA=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class iA extends yP{constructor(){super()}parse(e){return tA(this,void 0,void 0,function*(){const t=JSON.parse(e);if(null==t||null==t.items){const e=new gP;return e.success=!1,e}if(!MP(t))throw new Error("Data is encrypted. Use BitwardenEncryptedJsonImporter instead.");return yield this.parseDecrypted(t)})}parseDecrypted(e){return tA(this,void 0,void 0,function*(){const t=new gP,i=MP(r=e)&&null!=r.collections?yield this.parseCollections(e,t):yield this.parseFolders(e,t);var r;return e.items.forEach(e=>{const r=UP.toView(e);r.id=null,r.organizationId=null,r.collectionIds=null,null!=r.passwordHistory&&r.passwordHistory.length>5&&(r.passwordHistory=r.passwordHistory.slice(0,5)),!this.organization&&null!=e.folderId&&i.has(e.folderId)?t.folderRelationships.push([t.ciphers.length,i.get(e.folderId)]):this.organization&&null!=e.collectionIds&&e.collectionIds.forEach(e=>{i.has(e)&&t.collectionRelationships.push([t.ciphers.length,i.get(e)])}),this.cleanupCipher(r),t.ciphers.push(r)}),t.success=!0,t})}parseFolders(e,t){return tA(this,void 0,void 0,function*(){const i=new Map;if(null==e.folders)return i;for(const r of e.folders){const e=BP.toView(r);null!=e&&(i.set(r.id,t.folders.length),t.folders.push(e))}return i})}parseCollections(e,t){return tA(this,void 0,void 0,function*(){const i=new Map;if(null==e.collections)return i;for(const r of e.collections){const e=qP.toView(r);e.organizationId=null,null!=e&&(i.set(r.id,t.collections.length),t.collections.push(e))}return i})}}var rA=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class nA extends iA{constructor(e,t,i,r,n){super(),this.keyService=e,this.encryptService=t,this.i18nService=i,this.cipherService=r,this.accountService=n}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return rA(this,void 0,void 0,function*(){const i=JSON.parse(e);if(VP(i))throw new Error("Data is password-protected. Use BitwardenPasswordProtectedImporter instead.");if(null==i||null==i.items){const e=new gP;return e.success=!1,e}return MP(i)?t.parse.call(this,e):yield this.parseEncrypted(i)})}parseEncrypted(e){return rA(this,void 0,void 0,function*(){const t=new gP,i=yield Ce(this.accountService.activeAccount$);if(this.isNullOrWhitespace(e.encKeyValidation_DO_NOT_EDIT))return t.success=!1,t.errorMessage=this.i18nService.t("importEncKeyError"),t;const r=yield Ce(this.keyService.orgKeys$(i.id));let n=null==r?void 0:r[this.organizationId];if(n||(n=yield Ce(this.keyService.userKey$(i.id))),!n)return t.success=!1,t.errorMessage=this.i18nService.t("importEncKeyError"),t;const a=new Nt(e.encKeyValidation_DO_NOT_EDIT);try{yield this.encryptService.decryptString(a,n)}catch(e){return t.success=!1,t.errorMessage=this.i18nService.t("importEncKeyError"),t}let s=null;s=function(e){return function(e){return null!=e&&!0===e.encrypted}(e)&&null!=e.collections}(e)?yield this.parseEncryptedCollections(i.id,e,t):yield this.parseEncryptedFolders(i.id,e,t);for(const r of e.items){const e=UP.toDomain(r);e.id=null,e.organizationId=this.organizationId,e.collectionIds=null,null!=e.passwordHistory&&e.passwordHistory.length>5&&(e.passwordHistory=e.passwordHistory.slice(0,5)),!this.organization&&null!=r.folderId&&s.has(r.folderId)?t.folderRelationships.push([t.ciphers.length,s.get(r.folderId)]):this.organization&&null!=r.collectionIds&&r.collectionIds.forEach(e=>{s.has(e)&&t.collectionRelationships.push([t.ciphers.length,s.get(e)])});const n=yield this.cipherService.decrypt(e,i.id);this.cleanupCipher(n),t.ciphers.push(n)}return t.success=!0,t})}parseEncryptedFolders(e,t,i){return rA(this,void 0,void 0,function*(){const r=new Map;if(null==t.folders)return r;const n=yield Ce(this.keyService.userKey$(e));for(const e of t.folders){let t;const a=BP.toDomain(e);null!=a&&(t=yield a.decrypt(n)),null!=t&&(r.set(e.id,i.folders.length),i.folders.push(t))}return r})}parseEncryptedCollections(e,t,i){return rA(this,void 0,void 0,function*(){const r=new Map;if(null==t.collections)return r;const n=yield Ce(this.keyService.orgKeys$(e).pipe(Ie(e=>null!=e)));for(const e of t.collections){const t=qP.toDomain(e,new Ut({id:e.id,name:new Nt(e.name),organizationId:this.organizationId})),a=n[e.organizationId],s=yield t.decrypt(a,this.encryptService);null!=s&&(r.set(e.id,i.collections.length),i.collections.push(s))}return r})}}var aA=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class sA extends nA{constructor(e,t,i,r,n,a,s){super(e,t,i,r,a),this.keyGenerationService=n,this.promptForPassword_callback=s}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return aA(this,void 0,void 0,function*(){const i=new gP,r=JSON.parse(e);if(!r)return i.success=!1,i;if(!VP(r))return yield t.parse.call(this,e);if(this.cannotParseFile(r))return i.success=!1,i;const n=yield this.promptForPassword_callback();if(!(yield this.checkPassword(r,n)))return i.success=!1,i.errorMessage=this.i18nService.t("invalidFilePassword"),i;const a=new Nt(r.data),s=yield this.encryptService.decryptString(a,this.key);return yield t.parse.call(this,s)})}checkPassword(e,t){return aA(this,void 0,void 0,function*(){if(this.isNullOrWhitespace(t))return!1;const i=e.kdfType===Cd.PBKDF2_SHA256?new Pd(e.kdfIterations):new Ad(e.kdfIterations,e.kdfMemory,e.kdfParallelism);this.key=yield this.keyGenerationService.deriveVaultExportKey(t,e.salt,i);const r=new Nt(e.encKeyValidation_DO_NOT_EDIT);try{return yield this.encryptService.decryptString(r,this.key),!0}catch(e){return!1}})}cannotParseFile(e){return!(e&&e.encrypted&&e.passwordProtected&&e.salt&&e.kdfIterations&&"number"==typeof e.kdfIterations&&null!=e.kdfType&&null!=Cd[e.kdfType]&&e.encKeyValidation_DO_NOT_EDIT&&e.data)}}class oA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{"null"===e.label&&(e.label=null);const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.label,this.getValueOrDefault(this.nameFromUrl(e.domain),"--")),i.login.uris=this.makeUriArray(e.domain),i.login.password=this.getValueOrDefault(e.password),this.isNullOrWhitespace(e.email)&&!this.isNullOrWhitespace(e.username)?i.login.username=e.username:(i.login.username=this.getValueOrDefault(e.email),i.notes=this.getValueOrDefault(e.username)),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}const lA=["!group_id","!group_name","!type","title","username","password","URL","url","note","id"];class cA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{this.processFolder(t,this.getValueOrDefault(e["!group_name"]));const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.title,"--"),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password);const r=e.URL||e.url||e.Url;i.login.uris=this.makeUriArray(r);const n=e.note||e.Note||e.notes||e.Notes;n&&(i.notes=n);for(const t in e)if(e.hasOwnProperty(t)){const r=t.toLowerCase();!lA.some(e=>e.toLowerCase()===r)&&e[t]&&this.processKvp(i,t,e[t])}this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}class uA extends yP{parse(e){const t=new gP,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);const r=i.querySelector("textarea");return null==r||this.isNullOrWhitespace(r.textContent)?(t.errorMessage="Missing textarea.",t.success=!1,Promise.resolve(t)):(JSON.parse(r.textContent).forEach(e=>{const i=this.initLoginCipher();if(this.isNullOrWhitespace(e.label)||(i.name=e.label.split(" ")[0]),null==e.data||this.isNullOrWhitespace(e.data.notes)||(i.notes=e.data.notes.split("\\n").join("\n")),null!=e.currentVersion&&null!=e.currentVersion.fields)for(const t in e.currentVersion.fields){if(!e.currentVersion.fields.hasOwnProperty(t))continue;const r=e.currentVersion.fields[t];switch(null!=r.actionType?r.actionType.toLowerCase():null){case"password":i.login.password=this.getValueOrDefault(r.value);break;case"email":case"username":case"user":case"name":i.login.username=this.getValueOrDefault(r.value);break;case"url":i.login.uris=this.makeUriArray(r.value);break;default:{const e=null!=r.label?r.label.toLowerCase():null;null==i.login.password&&this.passwordFieldNames.indexOf(e)>-1?i.login.password=this.getValueOrDefault(r.value):null==i.login.username&&this.usernameFieldNames.indexOf(e)>-1?i.login.username=this.getValueOrDefault(r.value):(null==i.login.uris||0===i.login.uris.length)&&this.uriFieldNames.indexOf(e)>-1?i.login.uris=this.makeUriArray(r.value):this.processKvp(i,r.label,r.value);break}}}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class dA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{this.processFolder(t,this.getValueOrDefault(e.Category));const i=this.initLoginCipher();i.favorite="True"===this.getValueOrDefault(e.Favorite),i.name=this.getValueOrDefault(e.Entry,"--"),i.notes=this.getValueOrDefault(e.Note),i.login.username=this.getValueOrDefault(e.Username,e.Email),i.login.password=this.getValueOrDefault(e.Password),i.login.totp=this.getValueOrDefault(e.TOTP),i.login.uris=this.makeUriArray(e.Website),this.isNullOrWhitespace(e.Username)||this.processKvp(i,"Email",e.Email),this.processKvp(i,"Phone",e.Phone),this.processKvp(i,"PIN",e.PIN),this.processKvp(i,"Account",e.Account),this.processKvp(i,"Date",e.Date),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}const hA=new Set(["title","note","username","password","url","otpSecret","category"]),pA=new Set(["type","title","first_name","middle_name","last_name","login","email","phone_number","address","country","state","city","zip","item_name"]),mA=new Set(["title","note"]);class gA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);if(null==i)return t.success=!1,Promise.resolve(t);if(null!=i[0].type&&null!=i[0].title&&1===i.filter(e=>"name"===e.type).length){const e=this.initLoginCipher();return e.type=rm.Identity,e.identity=new Yb,i.forEach(t=>{this.parsePersonalInformationRecordAsIdentity(e,t)}),this.cleanupCipher(e),t.ciphers.push(e),t.success=!0,Promise.resolve(t)}return i.forEach(e=>{const i=this.initLoginCipher(),r=Object.keys(e);"username"===r[0]&&(this.processFolder(t,e.category),this.parseCredentialsRecord(i,e)),"type"===r[0]&&"account_name"===r[1]&&this.parsePaymentRecord(i,e),"type"===r[0]&&"number"===r[1]&&this.parseIdRecord(i,e),"type"===r[0]&&"title"===r[1]&&this.parsePersonalInformationRecord(i,e),"title"===r[0]&&"note"===r[1]&&this.parseSecureNoteRecords(i,e),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}parseCredentialsRecord(e,t){e.type=rm.Login,e.login=new nw,e.name=t.title,e.notes=t.note,e.login.username=t.username,e.login.password=t.password,e.login.totp=Object.keys(t).includes("otpUrl")?t.otpUrl:t.otpSecret,e.login.uris=this.makeUriArray(t.url),this.importUnmappedFields(e,t,hA)}parsePaymentRecord(e,t){e.type=rm.Card,e.card=new Hb,e.name=t.account_name;let i=[];switch(t.type){case"credit_card":e.card.cardholderName=t.account_name,e.card.number=t.cc_number,e.card.brand=Hb.getCardBrandByPatterns(e.card.number),e.card.code=t.code,this.setCardExpiration(e,`${t.expiration_month}/${t.expiration_year}`),i=["account_name","account_holder","cc_number","code","expiration_month","expiration_year"];break;case"bank":e.card.cardholderName=t.account_holder,e.card.number=t.account_number,i=["account_name","account_holder","account_number"]}this.importUnmappedFields(e,t,new Set(i))}parseIdRecord(e,t){e.type=rm.Identity,e.identity=new Yb;const i=["name","number"];switch(t.type){case"card":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.licenseNumber=t.number;break;case"passport":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.passportNumber=t.number;break;case"license":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.licenseNumber=t.number,e.identity.state=t.state,i.push("state");break;case"social_security":e.name=`${t.name} ${t.type}`,this.processFullName(e,t.name),e.identity.ssn=t.number;break;case"tax_number":e.name=t.type,e.identity.licenseNumber=t.number}this.importUnmappedFields(e,t,new Set(i))}parsePersonalInformationRecord(e,t){e.type=rm.SecureNote,e.secureNote.type=0,"name"===t.type?e.name=`${t.title} ${t.first_name} ${t.middle_name} ${t.last_name}`.replace(" "," ").trim():e.name=t.item_name;const i=t;Object.keys(t).forEach(t=>{this.processKvp(e,t,i[t])})}parsePersonalInformationRecordAsIdentity(e,t){switch(t.type){case"name":this.processFullName(e,`${t.first_name} ${t.middle_name} ${t.last_name}`),e.identity.title=t.title,e.name=e.identity.fullName,e.identity.username=t.login;break;case"email":e.identity.email=t.email;break;case"number":e.identity.phone=t.phone_number;break;case"address":e.identity.address1=t.address,e.identity.city=t.city,e.identity.postalCode=t.zip,e.identity.state=t.state,e.identity.country=t.country}this.importUnmappedFields(e,t,pA)}parseSecureNoteRecords(e,t){e.type=rm.SecureNote,e.secureNote.type=0,e.name=t.title,e.notes=t.note,this.importUnmappedFields(e,t,mA)}importUnmappedFields(e,t,i){Object.keys(t).filter(e=>!i.has(e)).forEach(i=>{const r=t;this.processKvp(e,i,r[i])})}}const fA=new Set(["ADDRESS","AUTHENTIFIANT","BANKSTATEMENT","IDCARD","IDENTITY","PAYMENTMEANS_CREDITCARD","PAYMENTMEAN_PAYPAL","EMAIL"]);class yA extends yP{parse(e){this.result=new gP;const t=JSON.parse(e);if(null==t||0===t.length)return this.result.success=!1,Promise.resolve(this.result);null!=t.ADDRESS&&this.processAddress(t.ADDRESS),null!=t.AUTHENTIFIANT&&this.processAuth(t.AUTHENTIFIANT),null!=t.BANKSTATEMENT&&this.processNote(t.BANKSTATEMENT,"BankAccountName"),null!=t.IDCARD&&this.processNote(t.IDCARD,"Fullname"),null!=t.PAYMENTMEANS_CREDITCARD&&this.processCard(t.PAYMENTMEANS_CREDITCARD),null!=t.IDENTITY&&this.processIdentity(t.IDENTITY);for(const e in t)t.hasOwnProperty(e)&&!fA.has(e)&&this.processNote(t[e],null,"Generic Note");return this.result.success=!0,Promise.resolve(this.result)}processAuth(e){e.forEach(e=>{const t=this.initLoginCipher();t.name=this.getValueOrDefault(e.title),t.login.username=this.getValueOrDefault(e.login,this.getValueOrDefault(e.secondaryLogin)),this.isNullOrWhitespace(t.login.username)?t.login.username=this.getValueOrDefault(e.email):this.isNullOrWhitespace(e.email)||(t.notes="Email: "+e.email+"\n"),t.login.password=this.getValueOrDefault(e.password),t.login.uris=this.makeUriArray(e.domain),t.notes+=this.getValueOrDefault(e.note,""),this.convertToNoteIfNeeded(t),this.cleanupCipher(t),this.result.ciphers.push(t)})}processIdentity(e){e.forEach(e=>{const t=new lw;t.identity=new Yb,t.type=rm.Identity,t.name=this.getValueOrDefault(e.fullName,"");const i=t.name.split(" ");i.length>0&&(t.identity.firstName=this.getValueOrDefault(i[0])),2===i.length?t.identity.lastName=this.getValueOrDefault(i[1]):3===i.length&&(t.identity.middleName=this.getValueOrDefault(i[1]),t.identity.lastName=this.getValueOrDefault(i[2])),t.identity.username=this.getValueOrDefault(e.pseudo),this.cleanupCipher(t),this.result.ciphers.push(t)})}processAddress(e){e.forEach(e=>{const t=new lw;t.identity=new Yb,t.type=rm.Identity,t.name=this.getValueOrDefault(e.addressName),t.identity.address1=this.getValueOrDefault(e.addressFull),t.identity.city=this.getValueOrDefault(e.city),t.identity.state=this.getValueOrDefault(e.state),t.identity.postalCode=this.getValueOrDefault(e.zipcode),t.identity.country=this.getValueOrDefault(e.country),null!=t.identity.country&&(t.identity.country=t.identity.country.toUpperCase()),this.cleanupCipher(t),this.result.ciphers.push(t)})}processCard(e){e.forEach(e=>{const t=new lw;t.card=new Hb,t.type=rm.Card,t.name=this.getValueOrDefault(e.bank),t.card.number=this.getValueOrDefault(e.cardNumber),t.card.brand=Hb.getCardBrandByPatterns(t.card.number),t.card.cardholderName=this.getValueOrDefault(e.owner),this.isNullOrWhitespace(t.card.brand)||(this.isNullOrWhitespace(t.name)?t.name=t.card.brand:t.name+=" - "+t.card.brand),this.cleanupCipher(t),this.result.ciphers.push(t)})}processNote(e,t,i=null){e.forEach(e=>{const r=new lw;r.secureNote=new sw,r.type=rm.SecureNote,r.secureNote.type=0,r.name=null!=i?i:this.getValueOrDefault(e[t]);for(const i in e)e.hasOwnProperty(i)&&i!==t&&this.processKvp(r,i,e[i].toString());this.cleanupCipher(r),this.result.ciphers.push(r)})}}class vA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.Label,"--"),i.notes=this.getValueOrDefault(e.Notes);const r=this.getValueOrDefault(e.Text);this.isNullOrWhitespace(r)||(this.isNullOrWhitespace(i.notes)?i.notes=r:i.notes+="\n\n"+r);const n=e["Entry Type"];if("Password"===n)i.login.username=this.getValueOrDefault(e.Username),i.login.password=this.getValueOrDefault(e.Password),i.login.uris=this.makeUriArray(e["Site URL"]);else if("Credit Card"===n){i.type=rm.Card,i.card=new Hb,i.card.cardholderName=this.getValueOrDefault(e["Name on card"]),i.card.number=this.getValueOrDefault(e["Card Number"]),i.card.brand=Hb.getCardBrandByPatterns(i.card.number),i.card.code=this.getValueOrDefault(e.CVV);const t=this.getValueOrDefault(e.Expiry);if(!this.isNullOrWhitespace(t)){const e=t.split("/");e.length>1&&(i.card.expMonth=parseInt(e[0],null).toString(),i.card.expYear=(2e3+parseInt(e[1],null)).toString())}}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class bA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);if(null==i)return t.success=!1,Promise.resolve(t);let r=!0;return i.forEach(e=>{if(e.length<2||r&&("Title"===e[0]||"title"===e[0]))return void(r=!1);const i=this.initLoginCipher();if(i.notes=this.getValueOrDefault(e[e.length-1]),i.name=this.getValueOrDefault(e[0],"--"),2!==e.length&&(this.containsField(e,"username")||this.containsField(e,"password")||this.containsField(e,"email")||this.containsField(e,"url"))||(i.type=rm.SecureNote,i.secureNote=new sw,i.secureNote.type=0),this.containsField(e,"cardholder")&&this.containsField(e,"number")&&this.containsField(e,"expiry date")&&(i.type=rm.Card,i.card=new Hb),e.length>2&&e.length%2==0)for(let t=0;t!this.isNullOrWhitespace(e)&&e.toLowerCase()===t.toLowerCase()).length>0}}const wA=new RegExp("androidapp://.*==@","g");class kA extends yP{parse(e){const t=new gP,i=JSON.parse(e);if(null==i||null==i.items||0===i.items.length)return t.success=!1,Promise.resolve(t);const r=new Map,n=new Map,a=this.buildFolderTree(i.folders);return this.flattenFolderTree(null,a,r),r.forEach((e,i)=>{n.set(i,t.folders.length);const r=new DC;r.name=e,t.folders.push(r)}),i.items.forEach(e=>{null!=e.folders&&e.folders.length>0&&n.has(e.folders[0])&&t.folderRelationships.push([t.ciphers.length,n.get(e.folders[0])]);const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.title),i.favorite=e.favorite>0,null!=e.template_type&&null!=e.fields&&e.fields.length>0&&(0===e.template_type.indexOf("login.")||0===e.template_type.indexOf("password.")?this.processLogin(i,e.fields):0===e.template_type.indexOf("creditcard.")?this.processCard(i,e.fields):e.template_type.indexOf("identity.")<0&&e.fields.some(e=>"password"===e.type&&!this.isNullOrWhitespace(e.value))?this.processLogin(i,e.fields):this.processNote(i,e.fields));const r=this.getValueOrDefault(e.note,"");r&&(i.notes=r.trimEnd()),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t)}processLogin(e,t){const i=[];t.forEach(t=>{if(!this.isNullOrWhitespace(t.value)&&"section"!==t.type)if("username"!==t.type&&"email"!==t.type||!this.isNullOrWhitespace(e.login.username))if("password"===t.type&&this.isNullOrWhitespace(e.login.password))e.login.password=t.value;else if("totp"===t.type&&this.isNullOrWhitespace(e.login.totp))e.login.totp=t.value;else if("url"===t.type)i.push(t.value);else if(".Android#"===t.type){let e=t.value.startsWith("androidapp://")?t.value:"androidapp://"+t.value;e=e.replace("android://",""),e=e.replace(wA,"androidapp://"),i.push(e)}else this.processKvp(e,t.label,t.value,1===t.sensitive?am.Hidden:am.Text);else e.login.username=t.value}),e.login.uris=this.makeUriArray(i)}processCard(e,t){e.card=new Hb,e.type=rm.Card,t.forEach(t=>{this.isNullOrWhitespace(t.value)||"section"===t.type||"ccType"===t.type||("ccName"===t.type&&this.isNullOrWhitespace(e.card.cardholderName)?e.card.cardholderName=t.value:"ccNumber"===t.type&&this.isNullOrWhitespace(e.card.number)?(e.card.number=t.value,e.card.brand=Hb.getCardBrandByPatterns(e.card.number)):"ccCvc"===t.type&&this.isNullOrWhitespace(e.card.code)?e.card.code=t.value:"ccExpiry"===t.type&&this.isNullOrWhitespace(e.card.expYear)&&this.setCardExpiration(e,t.value)||this.processKvp(e,t.label,t.value,1===t.sensitive?am.Hidden:am.Text))})}processNote(e,t){t.forEach(t=>{this.isNullOrWhitespace(t.value)||"section"===t.type||this.processKvp(e,t.label,t.value,1===t.sensitive?am.Hidden:am.Text)})}buildFolderTree(e){if(null==e)return[];const t=[],i=new Map([]);return e.forEach(e=>{i.set(e.uuid,e),e.children=[]}),e.forEach(e=>{null!=e.parent_uuid&&""!==e.parent_uuid&&i.has(e.parent_uuid)?i.get(e.parent_uuid).children.push(e):t.push(e)}),t}flattenFolderTree(e,t,i){null!=t&&t.forEach(t=>{if(null!=t.title&&""!==t.title.trim()){let r=t.title.trim();null!=e&&""!==e.trim()&&(r=e+"/"+r),i.set(t.uuid,r),null!=t.children&&0!==t.children.length&&this.flattenFolderTree(r,t.children,i)}})}}class SA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.filter(e=>"chrome://FirefoxAccounts"!==e.url).forEach(e=>{const i=this.initLoginCipher(),r=this.getValueOrDefault(e.url,this.getValueOrDefault(e.hostname));i.name=this.getValueOrDefault(this.nameFromUrl(r),"--"),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(r),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}const _A=Object.freeze({Login:1,CreditCard:2});class xA extends yP{parse(e){const t=new gP,i=JSON.parse(e);if(null==i||null==i.data)return t.success=!1,Promise.resolve(t);for(const[,e]of Object.entries(i.data)){const i=this.parseEntry(e);null!=i&&t.ciphers.push(i)}return t.success=!0,Promise.resolve(t)}parseEntry(e){const t=this.initLoginCipher();switch(t.name=this.getValueOrDefault(e.service),t.notes=this.getValueOrDefault(e.notes),t.favorite=e.favorite>0,e.type){case _A.Login:this.handleLoginEntry(e,t);break;case _A.CreditCard:this.handleCreditCardEntry(e,t);break;default:return}return this.convertToNoteIfNeeded(t),this.cleanupCipher(t),t}handleLoginEntry(e,t){t.login.username=this.getValueOrDefault(e.username),t.login.password=this.getValueOrDefault(e.password),t.login.uris=this.makeUriArray(e.url)}handleCreditCardEntry(e,t){t.type=rm.Card,t.card=new Hb,t.card.cardholderName=this.getValueOrDefault(e.username),t.card.number=this.getValueOrDefault(e.creditNumber),t.card.brand=Hb.getCardBrandByPatterns(t.card.number),t.card.code=this.getValueOrDefault(e.creditCvv),this.isNullOrWhitespace(e.creditExpiry)||this.setCardExpiration(t,e.creditExpiry)||this.processKvp(t,"Expiration",e.creditExpiry),this.isNullOrWhitespace(e.password)||this.processKvp(t,"PIN",e.password)}}class CA extends yP{parse(e){const t=new gP,i=JSON.parse(e);if(null==i||0===Object.keys(i).length)return t.success=!1,Promise.resolve(t);for(const e in i)i.hasOwnProperty(e)&&!this.isNullOrWhitespace(e)&&0!==i[e].length&&i[e].forEach(i=>{if(this.isNullOrWhitespace(i.display_name)||0!==i.display_name.indexOf("http"))return;this.processFolder(t,e);const r=this.initLoginCipher();if(r.name=i.display_name.replace("http://","").replace("https://",""),r.name.length>30&&(r.name=r.name.substring(0,30)),r.login.password=this.getValueOrDefault(i.secret),r.login.uris=this.makeUriArray(i.display_name),null!=i.attributes){r.login.username=null!=i.attributes?this.getValueOrDefault(i.attributes.username_value):null;for(const e in i.attributes)i.attributes.hasOwnProperty(e)&&"username_value"!==e&&"xdg:schema"!==e&&this.processKvp(r,e,i.attributes[e])}this.convertToNoteIfNeeded(r),this.cleanupCipher(r),t.ciphers.push(r)});return this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}const IA="Notes\n\n",EA="Applications\n\n",zA="Websites\n\n",PA="\n---\n";class AA extends yP{parse(e){const t=new gP;let i,r,n,a=this.splitNewLine(e).join("\n");if(-1!==a.indexOf(IA)){const e=a.split(IA);e.length>1&&(a=e[0],i=e[1])}if(-1!==a.indexOf(EA)){const e=a.split(EA);e.length>1&&(a=e[0],r=e[1])}if(0===a.indexOf(zA)){const e=a.split(zA);e.length>1&&(a=e[0],n=e[1])}const s=this.parseDataCategory(i),o=this.parseDataCategory(r),l=this.parseDataCategory(n);return s.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.get("Name")),i.notes=this.getValueOrDefault(e.get("Text")),this.cleanupCipher(i),t.ciphers.push(i)}),l.concat(o).forEach(e=>{const i=this.initLoginCipher(),r=e.has("Website name")?"Website name":"Application";i.name=this.getValueOrDefault(e.get(r),""),this.isNullOrWhitespace(e.get("Login name"))||(this.isNullOrWhitespace(i.name)||(i.name+=": "),i.name+=e.get("Login name")),i.notes=this.getValueOrDefault(e.get("Comment")),e.has("Website URL")&&(i.login.uris=this.makeUriArray(e.get("Website URL"))),i.login.username=this.getValueOrDefault(e.get("Login")),i.login.password=this.getValueOrDefault(e.get("Password")),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t)}parseDataCategory(e){if(this.isNullOrWhitespace(e)||-1===e.indexOf(PA))return[];const t=[];return e.split(PA).forEach(e=>{if(-1===e.indexOf("\n"))return;const i=new Map;let r,n;e.split("\n").forEach(e=>{if(null!=r)return void(r+="\n"+e);const t=e.indexOf(":");let a,s;-1!==t&&(a=e.substring(0,t),e.length>t+1&&(s=e.substring(t+2)),null!=a&&i.set(a,s),"Comment"!==a&&"Text"!==a||(r=s,n=a))}),null!=r&&null!=n&&i.set(n,r),0!==i.size&&t.push(i)}),t}}class jA extends yP{constructor(){super(...arguments),this.result=new gP}parse(e){const t=this.parseXml(e);if(null==t)return this.result.success=!1,Promise.resolve(this.result);const i=t.querySelector("KeePassFile");if(null==i)return this.result.errorMessage="Missing `KeePassFile` node.",this.result.success=!1,Promise.resolve(this.result);const r=i.querySelector("Root");if(null==r)return this.result.errorMessage="Missing `KeePassFile > Root` node.",this.result.success=!1,Promise.resolve(this.result);const n=r.querySelector("Group");return null==n?(this.result.errorMessage="Missing `KeePassFile > Root > Group` node.",this.result.success=!1,Promise.resolve(this.result)):(this.traverse(n,!0,""),this.organization&&this.moveFoldersToCollections(this.result),this.result.success=!0,Promise.resolve(this.result))}traverse(e,t,i){const r=this.result.folders.length;let n=i;if(!t){""!==n&&(n+="/");const t=this.querySelectorDirectChild(e,"Name");n+=null==t?"-":t.textContent;const i=new DC;i.name=n,this.result.folders.push(i)}this.querySelectorAllDirectChild(e,"Entry").forEach(e=>{const i=this.result.ciphers.length,n=this.initLoginCipher();this.querySelectorAllDirectChild(e,"String").forEach(e=>{const t=this.querySelectorDirectChild(e,"Value"),i=null!=t?t.textContent:null;if(this.isNullOrWhitespace(i))return;const r=this.querySelectorDirectChild(e,"Key"),a=null!=r?r.textContent:null;if("URL"===a)n.login.uris=this.makeUriArray(i);else if("UserName"===a)n.login.username=i;else if("Password"===a)n.login.password=i;else if("otp"===a)n.login.totp=i.replace("key=","");else if("Title"===a)n.name=i;else if("Notes"===a)n.notes+=i+"\n";else{const e=t.attributes;if(e.length>0&&null!=e.ProtectInMemory&&"True"===e.ProtectInMemory.value){null==n.fields&&(n.fields=[]);const e=new Gb;e.type=am.Hidden,e.name=a,e.value=i,n.fields.push(e)}else this.processKvp(n,a,i,am.Text)}}),this.cleanupCipher(n),this.result.ciphers.push(n),t||this.result.folderRelationships.push([i,r])}),this.querySelectorAllDirectChild(e,"Group").forEach(e=>{this.traverse(e,!1,n)})}}class TA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(this.isNullOrWhitespace(e.Title))return;e.Group=!this.isNullOrWhitespace(e.Group)&&e.Group.startsWith("Root/")?e.Group.replace("Root/",""):e.Group;const i=this.isNullOrWhitespace(e.Group)?null:e.Group;this.processFolder(t,i);const r=this.initLoginCipher();r.notes=this.getValueOrDefault(e.Notes),r.name=this.getValueOrDefault(e.Title,"--"),r.login.username=this.getValueOrDefault(e.Username),r.login.password=this.getValueOrDefault(e.Password),r.login.uris=this.makeUriArray(e.URL),r.login.totp=this.getValueOrDefault(e.TOTP),this.cleanupCipher(r),t.ciphers.push(r)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}class DA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(e.length<6)return;this.processFolder(t,e[0]);const i=this.initLoginCipher(),r=this.getValueOrDefault(e[5]);if(r&&(i.notes=r.trimEnd()),i.name=this.getValueOrDefault(e[1],"--"),i.login.username=this.getValueOrDefault(e[2]),i.login.password=this.getValueOrDefault(e[3]),i.login.uris=this.makeUriArray(e[4]),e.length>7)for(let t=7;t{const i=t.ciphers.length;let r=t.folders.length,n=e.grouping;null!=n&&(n=n.replace(/\\/g,"/").replace(/[\x00-\x1F\x7F-\x9F]/g,""));const a="(none)"!==this.getValueOrDefault(n,"(none)");let s=a;if(a)for(let e=0;e-1){const i=e.ccexp.split("-");i.length>1&&(t.expYear=i[0],t.expMonth=i[1],2===t.expMonth.length&&"0"===t.expMonth[0]&&(t.expMonth=t.expMonth[1]))}return t}parseIdentity(e){const t=new Yb;return t.title=this.getValueOrDefault(e.title),t.firstName=this.getValueOrDefault(e.firstname),t.middleName=this.getValueOrDefault(e.middlename),t.lastName=this.getValueOrDefault(e.lastname),t.username=this.getValueOrDefault(e.username),t.company=this.getValueOrDefault(e.company),t.ssn=this.getValueOrDefault(e.ssn),t.address1=this.getValueOrDefault(e.address1),t.address2=this.getValueOrDefault(e.address2),t.address3=this.getValueOrDefault(e.address3),t.city=this.getValueOrDefault(e.city),t.state=this.getValueOrDefault(e.state),t.postalCode=this.getValueOrDefault(e.zip),t.country=this.getValueOrDefault(e.country),t.email=this.getValueOrDefault(e.email),t.phone=this.getValueOrDefault(e.phone),this.isNullOrWhitespace(t.title)||(t.title=t.title.charAt(0).toUpperCase()+t.title.slice(1)),t}parseSecureNote(e,t){const i=this.splitNewLine(e.extra);let r=!1;if(i.length){const e=i[0].split(":");if(e.length>1&&"NoteType"===e[0]&&("Credit Card"===e[1]||"Address"===e[1])){if("Credit Card"===e[1]){const e=this.parseSecureNoteMapping(t,i,{Number:"number","Name on Card":"cardholderName","Security Code":"code","Expiration Date":"expMonth"});if(this.isNullOrWhitespace(e.expMonth)||","===e.expMonth)e.expMonth=void 0;else{const[t,i]=e.expMonth.split(",");if(this.isNullOrWhitespace(t))e.expMonth=void 0;else{const i=new Date(Date.parse(t.trim()+" 1, 2012")).getMonth()+1;isNaN(i)?e.expMonth=void 0:e.expMonth=i.toString()}this.isNullOrWhitespace(i)||(e.expYear=i)}t.type=rm.Card,t.card=e}else if("Address"===e[1]){const e=this.parseSecureNoteMapping(t,i,{Title:"title","First Name":"firstName","Last Name":"lastName","Middle Name":"middleName",Company:"company","Address 1":"address1","Address 2":"address2","Address 3":"address3","City / Town":"city",State:"state","Zip / Postal Code":"postalCode",Country:"country","Email Address":"email",Username:"username"});t.type=rm.Identity,t.identity=e}r=!0}}r||(t.secureNote=new sw,t.secureNote.type=0,t.notes=this.getValueOrDefault(e.extra))}parseSecureNoteMapping(e,t,i){const r={};let n=!1;return t.forEach(t=>{let a=null,s=null;if(!n){if(this.isNullOrWhitespace(t))return;const e=t.indexOf(":");if(-1===e?a=t:(a=t.substring(0,e),t.length>e&&(s=t.substring(e+1))),this.isNullOrWhitespace(a)||this.isNullOrWhitespace(s)||"NoteType"===a)return}n?e.notes+="\n"+t:"Notes"===a?(this.isNullOrWhitespace(e.notes)?e.notes=s:e.notes+="\n"+s,n=!0):i.hasOwnProperty(a)?r[i[a]]=s:this.processKvp(e,a,s)}),r}}class NA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(e.length<4)return;const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--"),i.login.username=this.getValueOrDefault(e[2]),i.login.password=this.getValueOrDefault(e[3]),i.login.uris=this.makeUriArray(e[1]),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class RA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.DisplayName,"--"),i.notes=this.getValueOrDefault(e.Notes),i.login.username=this.getValueOrDefault(e.UserName),i.login.password=this.getValueOrDefault(e.Password),i.login.uris=this.makeUriArray(e.Url),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class UA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1,{delimiter:","});return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(e.length<3)return;const i="Unassigned"!==this.getValueOrDefault(e[2],"Unassigned")?e[2]:null;this.processFolder(t,i);const r=this.initLoginCipher();if(r.name=this.getValueOrDefault(e[0].split("|")[0],"--"),"Web Logins"===e[1]||"Login"===e[1])r.login.username=this.getValueOrDefault(this.splitValueRetainingLastPart(e[5])),r.login.uris=this.makeUriArray(this.splitValueRetainingLastPart(e[4])),r.login.password=this.getValueOrDefault(this.splitValueRetainingLastPart(e[6])),r.notes=this.isNullOrWhitespace(e[3])?null:e[3].split("\\n").join("\n");else if("Credit Card"===e[1]){r.type=rm.Card,r.card.number=this.getValueOrDefault(this.splitValueRetainingLastPart(e[4]));const[t,i]=this.getValueOrDefault(this.splitValueRetainingLastPart(e[5])).split("/");r.card.expMonth=t.trim(),r.card.expYear=i.trim();const n=RegExp("^Security Code\\|\\d*\\|"),a=e.find(e=>n.test(e));r.card.code=this.getValueOrDefault(this.splitValueRetainingLastPart(a));const s=RegExp("^Name on Card\\|\\d*\\|"),o=e.find(e=>e.match(s));r.card.cardholderName=this.getValueOrDefault(this.splitValueRetainingLastPart(o)),r.card.brand=this.getValueOrDefault(this.splitValueRetainingLastPart(e[9]),"");const l=RegExp("\\|\\d*\\|"),c=e.slice(2).filter(e=>!this.isNullOrWhitespace(e)&&!l.test(e)),u=[8,10,11].filter(t=>e[t]&&l.test(e[t])).map(t=>e[t]).map(e=>`${e.split("|")[0]}: ${this.getValueOrDefault(this.splitValueRetainingLastPart(e),"")}`);r.notes=[...c,...u].join("\n")}else if(e.length>3){r.type=rm.SecureNote,r.secureNote=new sw,r.secureNote.type=0;for(let t=3;t{const i=this.initLoginCipher();if(i.name=this.getValueOrDefault(e.nickname,"--"),i.notes=this.getValueOrDefault(e.additionalInfo,"").trimEnd(),void 0!==e.url)i.login.uris=this.makeUriArray(e.url),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.totp=this.getValueOrDefault(e.twofaSecret),this.importUnmappedFields(i,e,qA);else if(void 0!==e.authToken)i.login.totp=this.getValueOrDefault(e.authToken),this.importUnmappedFields(i,e,VA);else if(void 0!==e.cardNumber)i.card=new Hb,i.type=rm.Card,i.card.cardholderName=this.getValueOrDefault(e.cardName),i.card.number=this.getValueOrDefault(e.cardNumber),i.card.brand=Hb.getCardBrandByPatterns(i.card.number),i.card.expMonth=this.getValueOrDefault(e.exp_month),i.card.expYear=this.getValueOrDefault(e.exp_year),i.card.code=this.getValueOrDefault(e.cvv),this.importUnmappedFields(i,e,LA);else if(void 0!==e.firstName)i.identity=new Yb,i.type=rm.Identity,i.identity.title=this.getValueOrDefault(e.title),i.identity.firstName=this.getValueOrDefault(e.firstName),i.identity.middleName=this.getValueOrDefault(e.middleName),i.identity.lastName=this.getValueOrDefault(e.lastName),i.identity.phone=this.getValueOrDefault(e.number),i.identity.email=this.getValueOrDefault(e.email),i.identity.address1=this.getValueOrDefault(e.firstAddressLine),i.identity.address2=this.getValueOrDefault(e.secondAddressLine),i.identity.city=this.getValueOrDefault(e.city),i.identity.country=this.getValueOrDefault(e.country),i.identity.postalCode=this.getValueOrDefault(e.zipCode),this.importUnmappedFields(i,e,BA);else if(void 0!==e.idType){switch(i.identity=new Yb,i.type=rm.Identity,this.processFullName(i,e.idName),i.identity.country=this.getValueOrDefault(e.idCountry),e.idType){case"Passport":i.identity.passportNumber=e.idNumber;break;case"Social Security":i.identity.ssn=e.idNumber;break;default:i.identity.licenseNumber=e.idNumber}this.importUnmappedFields(i,e,MA)}else{if(void 0===e.content)return;i.secureNote=new sw,i.type=rm.SecureNote,i.secureNote.type=0,i.notes=this.getValueOrDefault(e.content,"").trimEnd(),this.importUnmappedFields(i,e,$A)}this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}importUnmappedFields(e,t,i){Object.keys(t).filter(e=>!i.has(e)).forEach(i=>{const r=t;this.processKvp(e,i,r[i])})}}const WA=new Set(["Organisationseinheit","Informationen","Beschreibung","Benutzername","Passwort","Internetseite","One-Time Passwort"]);class HA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{this.processFolder(t,e.Organisationseinheit);const i=this.initLoginCipher(),r=this.getValueOrDefault(e.Informationen);r&&(i.notes=r.trimEnd()),i.name=this.getValueOrDefault(e.Beschreibung,"--"),i.login.username=this.getValueOrDefault(e.Benutzername),i.login.password=this.getValueOrDefault(e.Passwort),i.login.uris=this.makeUriArray(e.Internetseite),i.login.totp=this.getValueOrDefault(e["One-Time Passwort"]),this.importUnmappedFields(i,e,WA),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}importUnmappedFields(e,t,i){Object.keys(t).filter(e=>!i.has(e)).forEach(i=>{const r=t;this.processKvp(e,i,r[i])})}}class GA extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.evaluateType(e);if(void 0===i)return;this.processFolder(t,e.folder);const r=new lw;if(r.name=this.getValueOrDefault(e.name,"--"),r.notes=this.getValueOrDefault(e.note),e.custom_fields){const t=JSON.parse(e.custom_fields);t&&t.length>0&&t.forEach(e=>{let t=am.Text;"hidden"==e.type&&(t=am.Hidden),this.processKvp(r,e.label,e.value,t)})}switch(i){case rm.Login:if(r.type=rm.Login,r.login=new nw,r.login.username=this.getValueOrDefault(e.username),r.login.password=this.getValueOrDefault(e.password),e.additional_urls){const t=JSON.parse(e.additional_urls),i=[e.url,...t];r.login.uris=this.makeUriArray(i)}else r.login.uris=this.makeUriArray(e.url);break;case rm.Card:r.type=rm.Card,r.card.cardholderName=this.getValueOrDefault(e.cardholdername),r.card.number=this.getValueOrDefault(e.cardnumber),r.card.code=this.getValueOrDefault(e.cvc),r.card.brand=Hb.getCardBrandByPatterns(r.card.number),this.setCardExpiration(r,e.expirydate);break;case rm.Identity:r.type=rm.Identity,this.processFullName(r,this.getValueOrDefault(e.full_name)),r.identity.address1=this.getValueOrDefault(e.address1),r.identity.address2=this.getValueOrDefault(e.address2),r.identity.city=this.getValueOrDefault(e.city),r.identity.state=this.getValueOrDefault(e.state),r.identity.postalCode=this.getValueOrDefault(e.zipcode),r.identity.country=this.getValueOrDefault(e.country),null!=r.identity.country&&(r.identity.country=r.identity.country.toUpperCase()),r.identity.email=this.getValueOrDefault(e.email),r.identity.phone=this.getValueOrDefault(e.phone_number);break;case rm.SecureNote:r.type=rm.SecureNote,r.secureNote.type=0}this.cleanupCipher(r),t.ciphers.push(r)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}evaluateType(e){switch(e.type){case"password":return rm.Login;case"credit_card":return rm.Card;case"note":return rm.SecureNote;case"identity":return rm.Identity}}}class QA extends yP{constructor(){super(...arguments),this.result=new gP}parse(e){return e.split(this.newLineRegex).forEach(e=>{if(this.isNullOrWhitespace(e)||"{"!==e[0])return;const t=JSON.parse(e);if(!0===t.trashed)return;const i=this.initLoginCipher();this.isNullOrWhitespace(t.hmac)?this.processStandardItem(t,i):this.processWinOpVaultItem(t,i),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),this.result.ciphers.push(i)}),this.result.success=!0,Promise.resolve(this.result)}processWinOpVaultItem(e,t){if(null!=e.overview&&(t.name=this.getValueOrDefault(e.overview.title),null!=e.overview.URLs)){const i=[];e.overview.URLs.forEach(e=>{this.isNullOrWhitespace(e.u)||i.push(e.u)}),t.login.uris=this.makeUriArray(i)}null!=e.details&&(null!=e.details.passwordHistory&&this.parsePasswordHistory(e.details.passwordHistory,t),this.isNullOrWhitespace(e.details.ccnum)&&this.isNullOrWhitespace(e.details.cvv)?this.isNullOrWhitespace(e.details.firstname)&&this.isNullOrWhitespace(e.details.address1)||(t.type=rm.Identity,t.identity=new Yb):(t.type=rm.Card,t.card=new Hb),t.type!==rm.Login||this.isNullOrWhitespace(e.details.password)||(t.login.password=e.details.password),this.isNullOrWhitespace(e.details.notesPlain)||(t.notes=e.details.notesPlain.split(this.newLineRegex).join("\n")+"\n"),null!=e.details.fields&&this.parseFields(e.details.fields,t,"designation","value","name"),null!=e.details.sections&&e.details.sections.forEach(e=>{null!=e.fields&&this.parseFields(e.fields,t,"n","v","t")}))}processStandardItem(e,t){if(t.favorite=!(!e.openContents||!e.openContents.faveIndex),t.name=this.getValueOrDefault(e.title),"securenotes.SecureNote"===e.typeName?(t.type=rm.SecureNote,t.secureNote=new sw,t.secureNote.type=0):"wallet.financial.CreditCard"===e.typeName?(t.type=rm.Card,t.card=new Hb):"identities.Identity"===e.typeName?(t.type=rm.Identity,t.identity=new Yb):t.login.uris=this.makeUriArray(e.location),null!=e.secureContents){if(null!=e.secureContents.passwordHistory&&this.parsePasswordHistory(e.secureContents.passwordHistory,t),this.isNullOrWhitespace(e.secureContents.notesPlain)||(t.notes=e.secureContents.notesPlain.split(this.newLineRegex).join("\n")+"\n"),t.type===rm.Login&&(this.isNullOrWhitespace(e.secureContents.password)||(t.login.password=e.secureContents.password),null!=e.secureContents.URLs)){const i=[];e.secureContents.URLs.forEach(e=>{this.isNullOrWhitespace(e.url)||i.push(e.url)}),i.length>0&&(t.login.uris=this.makeUriArray(i))}null!=e.secureContents.fields&&this.parseFields(e.secureContents.fields,t,"designation","value","name"),null!=e.secureContents.sections&&e.secureContents.sections.forEach(e=>{null!=e.fields&&this.parseFields(e.fields,t,"n","v","t")})}}parsePasswordHistory(e,t){const i=e.length>5?5:e.length;t.passwordHistory=e.filter(e=>!this.isNullOrWhitespace(e.value)&&null!=e.time).sort((e,t)=>t.time-e.time).slice(0,i).map(e=>{const t=new aw;return t.password=e.value,t.lastUsedDate=new Date((""+e.time).length>=13?e.time:1e3*e.time),t})}parseFields(e,t,i,r,n){e.forEach(e=>{if(null==e[r]||""===e[r].toString().trim())return;const a="date"===e.k?new Date(1e3*e[r]).toUTCString():e[r].toString(),s=null!=e[i]?e[i].toString():null;if(t.type===rm.Login){if(this.isNullOrWhitespace(t.login.username)&&"username"===s)return void(t.login.username=a);if(this.isNullOrWhitespace(t.login.password)&&"password"===s)return void(t.login.password=a);if(this.isNullOrWhitespace(t.login.totp)&&null!=s&&s.startsWith("TOTP_"))return void(t.login.totp=a)}else if(t.type===rm.Card){if(this.isNullOrWhitespace(t.card.number)&&"ccnum"===s)return t.card.number=a,void(t.card.brand=Hb.getCardBrandByPatterns(t.card.number));if(this.isNullOrWhitespace(t.card.code)&&"cvv"===s)return void(t.card.code=a);if(this.isNullOrWhitespace(t.card.cardholderName)&&"cardholder"===s)return void(t.card.cardholderName=a);if(this.isNullOrWhitespace(t.card.expiration)&&"expiry"===s&&6===a.length)return t.card.expMonth=a.substr(4,2),"0"===t.card.expMonth[0]&&(t.card.expMonth=t.card.expMonth.substr(1,1)),void(t.card.expYear=a.substr(0,4));if("type"===s)return}else if(t.type===rm.Identity){const i=t.identity;if(this.isNullOrWhitespace(i.firstName)&&"firstname"===s)return void(i.firstName=a);if(this.isNullOrWhitespace(i.lastName)&&"lastname"===s)return void(i.lastName=a);if(this.isNullOrWhitespace(i.middleName)&&"initial"===s)return void(i.middleName=a);if(this.isNullOrWhitespace(i.phone)&&"defphone"===s)return void(i.phone=a);if(this.isNullOrWhitespace(i.company)&&"company"===s)return void(i.company=a);if(this.isNullOrWhitespace(i.email)&&"email"===s)return void(i.email=a);if(this.isNullOrWhitespace(i.username)&&"username"===s)return void(i.username=a);if("address"===s){const{street:t,city:n,country:a,zip:s}=e[r];return i.address1=this.getValueOrDefault(t),i.city=this.getValueOrDefault(n),this.isNullOrWhitespace(a)||(i.country=a.toUpperCase()),void(i.postalCode=this.getValueOrDefault(s))}}const o=this.isNullOrWhitespace(e[n])?"no_name":e[n];if("password"===o&&null!=t.passwordHistory&&t.passwordHistory.some(e=>e.password===a))return;const l="concealed"===e.k?am.Hidden:am.Text;this.processKvp(t,o,a,l)})}}const JA=Object.freeze({Login:"001",CreditCard:"002",SecureNote:"003",Identity:"004",Password:"005",Document:"006",SoftwareLicense:"100",BankAccount:"101",Database:"102",DriversLicense:"103",OutdoorLicense:"104",Membership:"105",Passport:"106",RewardsProgram:"107",SocialSecurityNumber:"108",WirelessRouter:"109",Server:"110",EmailAccount:"111",API_Credential:"112",MedicalRecord:"113",SSH_Key:"114"}),YA=Object.freeze({TextOrHtml:"T",EmailAddress:"E",URL:"U",Number:"N",Password:"P",TextArea:"A",PhoneNumber:"TEL",CheckBox:"C"});class XA extends yP{constructor(){super(...arguments),this.result=new gP}parse(e){return JSON.parse(e).accounts[0].vaults.forEach(e=>{e.items.forEach(e=>{if("archived"===e.state)return;const t=this.initLoginCipher(),i=e.categoryUuid;switch(i){case JA.Login:case JA.Database:case JA.Password:case JA.WirelessRouter:case JA.Server:case JA.API_Credential:t.type=rm.Login,t.login=new nw;break;case JA.CreditCard:case JA.BankAccount:t.type=rm.Card,t.card=new Hb;break;case JA.SecureNote:case JA.SoftwareLicense:case JA.EmailAccount:case JA.MedicalRecord:t.type=rm.SecureNote,t.secureNote=new sw,t.secureNote.type=0;break;case JA.Identity:case JA.DriversLicense:case JA.OutdoorLicense:case JA.Membership:case JA.Passport:case JA.RewardsProgram:case JA.SocialSecurityNumber:t.type=rm.Identity,t.identity=new Yb;break;case JA.SSH_Key:t.type=rm.SshKey,t.sshKey=new ow}t.favorite=1===e.favIndex,this.processOverview(e.overview,t),this.processLoginFields(e,t),this.processDetails(i,e.details,t),this.parsePasswordHistory(e.details.passwordHistory,t),this.processSections(i,e.details.sections,t),this.isNullOrWhitespace(e.details.notesPlain)||(t.notes=e.details.notesPlain.split(this.newLineRegex).join("\n").trimEnd()),this.convertToNoteIfNeeded(t),this.cleanupCipher(t),this.result.ciphers.push(t)})}),this.organization&&this.moveFoldersToCollections(this.result),this.result.success=!0,Promise.resolve(this.result)}processOverview(e,t){if(null!=e){if(t.name=this.getValueOrDefault(e.title),null!=e.urls){const i=[];e.urls.forEach(e=>{this.isNullOrWhitespace(e.url)||i.push(e.url)}),t.login.uris=this.makeUriArray(i)}if(null!=e.tags&&e.tags.length>0){const t=this.capitalize(e.tags[0]);this.processFolder(this.result,t)}}}capitalize(e){return e.trim().replace(/\w\S*/g,e=>e.replace(/^\w/,e=>e.toUpperCase()))}processLoginFields(e,t){null!=e.details&&null!=e.details.loginFields&&0!==e.details.loginFields.length&&e.details.loginFields.forEach(e=>{if("username"===e.designation&&""!==e.value)return t.type=rm.Login,void(t.login.username=e.value);if("password"===e.designation&&""!==e.value)return t.type=rm.Login,void(t.login.password=e.value);let i=e.value,r=am.Text;switch(e.fieldType){case YA.Password:r=am.Hidden;break;case YA.CheckBox:i=""!==e.value?"true":"false",r=am.Boolean}this.processKvp(t,e.name,i,r)})}processDetails(e,t,i){e===JA.Password&&null!=t&&(i.login.password=t.password)}processSections(e,t,i){null!=t&&0!==t.length&&t.forEach(t=>{null!=t.fields&&this.parseSectionFields(e,t.fields,i,t.title)})}parseSectionFields(e,t,i,r){t.forEach(t=>{const n=Object.keys(t.value)[0],a=t;if(null==a.value||null==a.value[n]||""===a.value[n])return;const s=this.getFieldName(t.title,r),o=this.extractValue(t.value,n);if(i.type===rm.Login){if(this.fillLogin(t,o,i))return;switch(e){case JA.Login:case JA.Database:case JA.EmailAccount:case JA.WirelessRouter:break;case JA.Server:if(this.isNullOrWhitespace(i.login.uri)&&"url"===t.id)return void(i.login.uris=this.makeUriArray(o));break;case JA.API_Credential:if(this.fillApiCredentials(t,o,i))return}}else if(i.type===rm.Card){if(this.fillCreditCard(t,o,i))return;if(e===JA.BankAccount&&this.fillBankAccount(t,o,i))return}else if(i.type===rm.Identity){if(this.fillIdentity(t,o,i,n))return;if("address"===n){const{street:e,city:r,country:n,zip:a,state:s}=t.value.address;return i.identity.address1=this.getValueOrDefault(e),i.identity.city=this.getValueOrDefault(r),this.isNullOrWhitespace(n)||(i.identity.country=n.toUpperCase()),i.identity.postalCode=this.getValueOrDefault(a),void(i.identity.state=this.getValueOrDefault(s))}switch(e){case JA.Identity:break;case JA.DriversLicense:if(this.fillDriversLicense(t,o,i))return;break;case JA.OutdoorLicense:if(this.fillOutdoorLicense(t,o,i))return;break;case JA.Membership:if(this.fillMembership(t,o,i))return;break;case JA.Passport:if(this.fillPassport(t,o,i))return;break;case JA.RewardsProgram:if(this.fillRewardsProgram(t,o,i))return;break;case JA.SocialSecurityNumber:if(this.fillSSN(t,o,i))return}}else if(i.type===rm.SshKey&&"sshKey"===n){const{privateKey:e}=t.value.sshKey.metadata,r=(0,Sg.bnN)(e);return i.sshKey.privateKey=r.privateKey,i.sshKey.publicKey=r.publicKey,void(i.sshKey.keyFingerprint=r.fingerprint)}if("email"===n){const{email_address:e,provider:r}=t.value.email;return this.processKvp(i,s,e,am.Text),void this.processKvp(i,"provider",r,am.Text)}if("password"===t.title&&null!=i.passwordHistory&&i.passwordHistory.some(e=>e.password===o))return;t.guarded&&i.reprompt===tm.None&&(i.reprompt=tm.Password);const l="concealed"===n?am.Hidden:am.Text;this.processKvp(i,s,o,l)})}getFieldName(e,t){return this.isNullOrWhitespace(e)?this.isNullOrWhitespace(t)?"":t:e}extractValue(e,t){return"date"===t?new Date(1e3*e.date).toUTCString():"monthYear"===t?e.monthYear.toString():e[t]}fillLogin(e,t,i){const r=this.getFieldName(e.title);return this.isNullOrWhitespace(i.login.username)&&"username"===r?(i.login.username=t,!0):this.isNullOrWhitespace(i.login.password)&&"password"===r?(i.login.password=t,!0):!(!this.isNullOrWhitespace(i.login.totp)||null==e.id||!e.id.startsWith("TOTP_")||(i.login.totp=t,0))}fillApiCredentials(e,t,i){const r=this.getFieldName(e.title);return this.isNullOrWhitespace(i.login.password)&&"credential"===r?(i.login.password=t,!0):!(!this.isNullOrWhitespace(i.login.uri)||"hostname"!==r||(i.login.uris=this.makeUriArray(t),0))}fillCreditCard(e,t,i){if(this.isNullOrWhitespace(i.card.number)&&"ccnum"===e.id)return i.card.number=t,i.card.brand=Hb.getCardBrandByPatterns(i.card.number),!0;if(this.isNullOrWhitespace(i.card.code)&&"cvv"===e.id)return i.card.code=t,!0;if(this.isNullOrWhitespace(i.card.cardholderName)&&"cardholder"===e.id)return i.card.cardholderName=t,!0;if(this.isNullOrWhitespace(i.card.expiration)&&"expiry"===e.id){const e=t.toString().trim();return i.card.expMonth=e.substring(4,6),"0"===i.card.expMonth[0]&&(i.card.expMonth=i.card.expMonth.substring(1,2)),i.card.expYear=e.substring(0,4),!0}return"type"===e.id}fillBankAccount(e,t,i){return!(!this.isNullOrWhitespace(i.card.cardholderName)||"owner"!==e.id||(i.card.cardholderName=t,0))}fillIdentity(e,t,i,r){if(this.isNullOrWhitespace(i.identity.firstName)&&"firstname"===e.id)return i.identity.firstName=t,!0;if(this.isNullOrWhitespace(i.identity.lastName)&&"lastname"===e.id)return i.identity.lastName=t,!0;if(this.isNullOrWhitespace(i.identity.middleName)&&"initial"===e.id)return i.identity.middleName=t,!0;if(this.isNullOrWhitespace(i.identity.phone)&&"defphone"===e.id)return i.identity.phone=t,!0;if(this.isNullOrWhitespace(i.identity.company)&&"company"===e.id)return i.identity.company=t,!0;if(this.isNullOrWhitespace(i.identity.email)){if("email"===r){const{email_address:t,provider:r}=e.value.email;return i.identity.email=this.getValueOrDefault(t),this.processKvp(i,"provider",r,am.Text),!0}if("email"===e.id)return i.identity.email=t,!0}return!(!this.isNullOrWhitespace(i.identity.username)||"username"!==e.id||(i.identity.username=t,0))}fillDriversLicense(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"fullname"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.address1)&&"address"===e.id?(i.identity.address1=t,!0):this.isNullOrWhitespace(i.identity.country)&&"country"===e.id?(i.identity.country=t,!0):this.isNullOrWhitespace(i.identity.state)&&"state"===e.id?(i.identity.state=t,!0):!(!this.isNullOrWhitespace(i.identity.licenseNumber)||"number"!==e.id||(i.identity.licenseNumber=t,0))}fillOutdoorLicense(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"name"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.country)&&"country"===e.id?(i.identity.country=t,!0):!(!this.isNullOrWhitespace(i.identity.state)||"state"!==e.id||(i.identity.state=t,0))}fillMembership(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"member_name"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.company)&&"org_name"===e.id?(i.identity.company=t,!0):!(!this.isNullOrWhitespace(i.identity.phone)||"phone"!==e.id||(i.identity.phone=t,0))}fillPassport(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"fullname"===e.id?(this.processFullName(i,t),!0):this.isNullOrWhitespace(i.identity.country)&&"issuing_country"===e.id?(i.identity.country=t,!0):!(!this.isNullOrWhitespace(i.identity.passportNumber)||"number"!==e.id||(i.identity.passportNumber=t,0))}fillRewardsProgram(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"member_name"===e.id?(this.processFullName(i,t),!0):!(!this.isNullOrWhitespace(i.identity.company)||"company_name"!==e.id||(i.identity.company=t,0))}fillSSN(e,t,i){return this.isNullOrWhitespace(i.identity.firstName)&&"name"===e.id?(this.processFullName(i,t),!0):!(!this.isNullOrWhitespace(i.identity.ssn)||"number"!==e.id||(i.identity.ssn=t,0))}parsePasswordHistory(e,t){if(null==e||0===e.length)return;const i=e.length>5?5:e.length;t.passwordHistory=e.filter(e=>!this.isNullOrWhitespace(e.value)&&null!=e.time).sort((e,t)=>t.time-e.time).slice(0,i).map(e=>{const t=new aw;return t.password=e.value,t.lastUsedDate=new Date((""+e.time).length>=13?e.time:1e3*e.time),t})}}class ZA{constructor(e,t,i){this.importRecord=e,this.property=t,this.cipher=i,this.lowerProperty=t.toLowerCase()}}const ej=["ainfo","autosubmit","notesplain","ps","scope","tags","title","uuid","notes"];class tj extends yP{constructor(){super(...arguments),this.loginPropertyParsers=[this.setLoginUsername,this.setLoginPassword,this.setLoginUris],this.creditCardPropertyParsers=[this.setCreditCardNumber,this.setCreditCardVerification,this.setCreditCardCardholderName,this.setCreditCardExpiry],this.identityPropertyParsers=[this.setIdentityFirstName,this.setIdentityInitial,this.setIdentityLastName,this.setIdentityUserName,this.setIdentityEmail,this.setIdentityPhone,this.setIdentityCompany]}parse(e){const t=new gP,i=this.parseCsv(e,!0,{quoteChar:'"',escapeChar:"\\"});return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(this.isNullOrWhitespace(this.getProp(e,"title")))return;const i=this.initLoginCipher();i.name=this.getValueOrDefault(this.getProp(e,"title"),"--"),this.setNotes(e,i),this.setCipherType(e,i);let r=null;for(const t in e){if(!e.hasOwnProperty(t)||this.isNullOrWhitespace(e[t]))continue;const n=new ZA(e,t,i);i.type===rm.Login&&this.setKnownLoginValue(n)||i.type===rm.Card&&this.setKnownCreditCardValue(n)||i.type===rm.Identity&&this.setKnownIdentityValue(n)||(r=this.setUnknownValue(n,r))}i.type===rm.Login&&!this.isNullOrWhitespace(r)&&this.isNullOrWhitespace(i.login.username)&&-1===r.indexOf("://")&&(i.login.username=r),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}getProp(e,t){return Object.entries(e).reduce((e,t)=>(e[t[0].toLowerCase()]=t[1],e),{})[t.toLowerCase()]}getPropByRegexp(e,t){const i=Object.keys(e).reduce((e,i)=>(i.match(t)&&e.push(i),e),[]);return 0===i.length?null:e[i[0]]}getPropIncluding(e,t){const i=Object.keys(e).reduce((e,i)=>(i.toLowerCase().includes(t.toLowerCase())&&e.push(i),e),[]);return 0===i.length?null:e[i[0]]}setNotes(e,t){t.notes=this.getValueOrDefault(this.getProp(e,"notesPlain"),"")+"\n"+this.getValueOrDefault(this.getProp(e,"notes"),"")+"\n",t.notes.trim()}setKnownLoginValue(e){return this.loginPropertyParsers.reduce((t,i)=>(t||(t=i.bind(this)(e)),t),!1)}setKnownCreditCardValue(e){return this.creditCardPropertyParsers.reduce((t,i)=>(t||(t=i.bind(this)(e)),t),!1)}setKnownIdentityValue(e){return this.identityPropertyParsers.reduce((t,i)=>(t||(t=i.bind(this)(e)),t),!1)}setUnknownValue(e,t){if(-1===ej.indexOf(e.lowerProperty)&&!e.lowerProperty.startsWith("section:")&&!e.lowerProperty.startsWith("section ")){if(null==t&&"email"===e.lowerProperty)return e.importRecord[e.property];if("created date"===e.lowerProperty||"modified date"===e.lowerProperty){const t=new Date(1e3*parseInt(e.importRecord[e.property],10)).toUTCString();return this.processKvp(e.cipher,"1Password "+e.property,t),null}e.lowerProperty.includes("password")||e.lowerProperty.includes("key")||e.lowerProperty.includes("secret")?this.processKvp(e.cipher,e.property,e.importRecord[e.property],am.Hidden):this.processKvp(e.cipher,e.property,e.importRecord[e.property])}return null}setIdentityFirstName(e){return!(!this.isNullOrWhitespace(e.cipher.identity.firstName)||!e.lowerProperty.includes("first name")||(e.cipher.identity.firstName=e.importRecord[e.property],0))}setIdentityInitial(e){return!(!this.isNullOrWhitespace(e.cipher.identity.middleName)||!e.lowerProperty.includes("initial")||(e.cipher.identity.middleName=e.importRecord[e.property],0))}setIdentityLastName(e){return!(!this.isNullOrWhitespace(e.cipher.identity.lastName)||!e.lowerProperty.includes("last name")||(e.cipher.identity.lastName=e.importRecord[e.property],0))}setIdentityUserName(e){return!(!this.isNullOrWhitespace(e.cipher.identity.username)||!e.lowerProperty.includes("username")||(e.cipher.identity.username=e.importRecord[e.property],0))}setIdentityCompany(e){return!(!this.isNullOrWhitespace(e.cipher.identity.company)||!e.lowerProperty.includes("company")||(e.cipher.identity.company=e.importRecord[e.property],0))}setIdentityPhone(e){return!(!this.isNullOrWhitespace(e.cipher.identity.phone)||!e.lowerProperty.includes("default phone")||(e.cipher.identity.phone=e.importRecord[e.property],0))}setIdentityEmail(e){return!(!this.isNullOrWhitespace(e.cipher.identity.email)||!e.lowerProperty.includes("email")||(e.cipher.identity.email=e.importRecord[e.property],0))}setCreditCardNumber(e){return!(!this.isNullOrWhitespace(e.cipher.card.number)||!e.lowerProperty.includes("number")||(e.cipher.card.number=e.importRecord[e.property],e.cipher.card.brand=Hb.getCardBrandByPatterns(e.cipher.card.number),0))}setCreditCardVerification(e){return!(!this.isNullOrWhitespace(e.cipher.card.code)||!e.lowerProperty.includes("verification number")||(e.cipher.card.code=e.importRecord[e.property],0))}setCreditCardCardholderName(e){return!(!this.isNullOrWhitespace(e.cipher.card.cardholderName)||!e.lowerProperty.includes("cardholder name")||(e.cipher.card.cardholderName=e.importRecord[e.property],0))}setCreditCardExpiry(e){return!(!this.isNullOrWhitespace(e.cipher.card.expiration)||!e.lowerProperty.includes("expiry date")||7!==e.importRecord[e.property].length||(e.cipher.card.expMonth=e.importRecord[e.property].substr(0,2),"0"===e.cipher.card.expMonth[0]&&(e.cipher.card.expMonth=e.cipher.card.expMonth.substr(1,1)),e.cipher.card.expYear=e.importRecord[e.property].substr(3,4),0))}setLoginPassword(e){return!(!this.isNullOrWhitespace(e.cipher.login.password)||"password"!==e.lowerProperty||(e.cipher.login.password=e.importRecord[e.property],0))}setLoginUsername(e){return!(!this.isNullOrWhitespace(e.cipher.login.username)||"username"!==e.lowerProperty||(e.cipher.login.username=e.importRecord[e.property],0))}setLoginUris(e){if((null==e.cipher.login.uris||0===e.cipher.login.uris.length)&&"urls"===e.lowerProperty){const t=e.importRecord[e.property].split(this.newLineRegex);return e.cipher.login.uris=this.makeUriArray(t),!0}return"url"===e.lowerProperty&&(null==e.cipher.login.uris&&(e.cipher.login.uris=[]),e.cipher.login.uris.concat(this.makeUriArray(e.importRecord[e.property])),!0)}}class ij extends tj{setCipherType(e,t){switch(this.getValueOrDefault(this.getProp(e,"type"),"Login")){case"Credit Card":t.type=rm.Card,t.card=new Hb,ej.push("type");break;case"Identity":t.type=rm.Identity,t.identity=new Yb,ej.push("type");break;case"Login":case"Secure Note":ej.push("type")}}}class rj extends tj{constructor(){super(),this.identityPropertyParsers.push(this.setIdentityAddress)}setCipherType(e,t){t.type=rm.Login,t.login=new nw,this.isNullOrWhitespace(this.getPropByRegexp(e,/\d+: number/i))||this.isNullOrWhitespace(this.getPropByRegexp(e,/\d+: expiry date/i))||(t.type=rm.Card,t.card=new Hb),this.isNullOrWhitespace(this.getPropByRegexp(e,/name \d+: first name/i))&&this.isNullOrWhitespace(this.getPropByRegexp(e,/name \d+: initial/i))&&this.isNullOrWhitespace(this.getPropByRegexp(e,/name \d+: last name/i))&&this.isNullOrWhitespace(this.getPropByRegexp(e,/internet \d+: email/i))||(t.type=rm.Identity,t.identity=new Yb)}setIdentityAddress(e){return!!e.lowerProperty.match(/address \d+: address/i)&&(this.processKvp(e.cipher,"address",e.importRecord[e.property]),!0)}setCreditCardExpiry(e){if(this.isNullOrWhitespace(e.cipher.card.expiration)&&e.lowerProperty.includes("expiry date")){const t=e.importRecord[e.property].split("/");return e.cipher.card.expMonth=t[0],"0"===e.cipher.card.expMonth[0]&&2===e.cipher.card.expMonth.length&&(e.cipher.card.expMonth=e.cipher.card.expMonth.substr(1,1)),e.cipher.card.expYear=t[2].length>4?t[2].substr(0,4):t[2],!0}return!1}}class nj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);if(null==i)return t.success=!1,Promise.resolve(t);let r=null;return i.forEach(e=>{if(null==r)return void(r=e.map(e=>e));if(e.length<2||e.length!==r.length)return;if(!this.isNullOrWhitespace(e[1]))if(this.organization)e[1].split(",").forEach(e=>{e=e.trim();let i=!0,r=t.collections.length;for(let n=0;n0?i[0].trim():null;this.processFolder(t,r)}const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--");for(let t=2;t-1?i.login.username=e[t]:this.passwordFieldNames.indexOf(n)>-1?i.login.password=e[t]:this.uriFieldNames.indexOf(n)>-1?i.login.uris=this.makeUriArray(e[t]):this.processKvp(i,r[t],e[t]))}this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t)}}class aj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{this.processFolder(t,this.getValue("category",e));const i=this.initLoginCipher();i.notes=this.getValue("description",e),i.name=this.getValueOrDefault(this.getValue("title",e),"--"),i.login.username=this.getValue("username",e),i.login.password=this.getValue("password",e),i.login.uris=this.makeUriArray(this.getValue("site",e)),this.processKvp(i,"Password 2",this.getValue("password2",e)),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}getValue(e,t){return this.getValueOrDefault(t[e],this.getValueOrDefault(t[" "+e]))}}class sj extends yP{parse(e){const t=new gP,i=JSON.parse(e);return null==i||null==i.passwords||0===i.passwords.length?(t.success=!1,Promise.resolve(t)):1==i.encrypted?(t.success=!1,t.errorMessage="Unable to import an encrypted passky backup.",Promise.resolve(t)):(i.passwords.forEach(e=>{const i=this.initLoginCipher();i.name=e.website,i.login.username=e.username,i.login.password=e.password,i.login.uris=this.makeUriArray(e.website),i.notes=e.message,this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class oj extends yP{parse(e){const t=new gP,i=JSON.parse(e);return null==i||0===i.length?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(null!=e.tags&&e.tags.length>0){const i=e.tags[0].text;this.processFolder(t,i)}const i=this.initLoginCipher();i.name=e.label,i.login.username=this.getValueOrDefault(e.username),this.isNullOrWhitespace(i.login.username)?i.login.username=this.getValueOrDefault(e.email):this.isNullOrWhitespace(e.email)||(i.notes="Email: "+e.email+"\n"),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.url),i.notes+=this.getValueOrDefault(e.description,""),null!=e.otp&&(i.login.totp=this.getValueOrDefault(e.otp.secret)),null!=e.custom_fields&&e.custom_fields.forEach(e=>{switch(e.field_type){case"text":case"password":this.processKvp(i,e.label,e.value)}}),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}class lj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.isNullOrWhitespace(e.Tags)?null:JSON.parse(e.Tags),r=null!=i&&null!=i.tags&&i.tags.length>0?i.tags.map(e=>{try{const t=JSON.parse(e);return this.getValueOrDefault(t.tag)}catch(e){}return null}).filter(e=>!this.isNullOrWhitespace(e)):null;this.organization&&null!=r&&r.length>0?r.forEach(e=>{let i=!0,r=t.collections.length;for(let n=0;n0&&this.processFolder(t,r[0]);const n=this.initLoginCipher();n.notes=this.getValueOrDefault(e.Notes,""),n.notes+="\n\n"+this.getValueOrDefault(e["Shared Notes"],"")+"\n",n.name=this.getValueOrDefault(e["Entry Name"],"--"),n.login.username=this.getValueOrDefault(e["User ID"]),n.login.password=this.getValueOrDefault(e.Password),n.login.uris=this.makeUriArray(e.URL),null!=e.__parsed_extra&&e.__parsed_extra.length>0&&e.__parsed_extra.forEach(e=>{this.isNullOrWhitespace(e)||(n.notes+="\n"+e)});const a=this.isNullOrWhitespace(e["Extra Fields"])?null:JSON.parse(e["Extra Fields"]),s=null!=a&&null!=a.extraFields&&a.extraFields.length>0?a.extraFields.map(e=>{try{return JSON.parse(e)}catch(e){}return null}):null;null!=s&&s.forEach(e=>{null!=e&&this.processKvp(n,e.name,e.data)}),this.cleanupCipher(n),t.ciphers.push(n)}),t.success=!0,Promise.resolve(t))}}class cj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);if(null==i)return t.success=!1,Promise.resolve(t);let r=!0;return i.forEach(e=>{if(5!==e.length&&e.length<9)return;const i=10===e.length&&"0"===e[0],n=this.initLoginCipher();if(n.name=this.getValueOrDefault(e[i?1:0],"--"),n.login.username=this.getValueOrDefault(e[i?2:1]),n.login.password=this.getValueOrDefault(e[i?3:2]),5===e.length)r=!1,n.notes=this.getValueOrDefault(e[4]),n.login.uris=this.makeUriArray(e[3]);else{const r=this.getValueOrDefault(e[i?9:8],"(None)");let a="(None)"!==r?r.split("\\").join("/"):null;null!=a&&(a=r.split(" > ").join("/"),a=r.split(">").join("/")),this.processFolder(t,a),n.notes=this.getValueOrDefault(e[i?5:3]),n.login.uris=this.makeUriArray(e[4])}this.convertToNoteIfNeeded(n),this.cleanupCipher(n),t.ciphers.push(n)}),r&&this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class uj extends yP{parse(e){const t=new gP,i=JSON.parse(e);if(null==i||null==i.items)return t.success=!1,Promise.resolve(t);const r=new Map;i.folders.forEach(e=>{r.set(e.id,e.name)});const n=new Map;return r.forEach((e,i)=>{n.set(i,t.folders.length);const r=new DC;r.name=e,t.folders.push(r)}),i.items.forEach(e=>{const i=this.initLoginCipher();if(i.name=this.getValueOrDefault(e.name,"--"),i.login.uris=this.makeUriArray(e.login_url),null!=e.folder&&n.has(e.folder)&&t.folderRelationships.push([t.ciphers.length,n.get(e.folder)]),null!=e.identifiers){this.isNullOrWhitespace(e.identifiers.notes)||(i.notes=e.identifiers.notes.split("\\r\\n").join("\n").split("\\n").join("\n")),"CreditCard"===e.type&&(i.card=new Hb,i.type=rm.Card);for(const t in e.identifiers){if(!e.identifiers.hasOwnProperty(t))continue;const r=e.identifiers[t],n=null!=r?r.toString():null;if(!this.isNullOrWhitespace(n)&&"notes"!==t&&"ignoreItemInSecurityScore"!==t)if("custom_fields"!==t){if(i.type===rm.Card){if("cardNumber"===t){i.card.number=n,i.card.brand=Hb.getCardBrandByPatterns(i.card.number);continue}if("nameOnCard"===t){i.card.cardholderName=n;continue}if("security_code"===t){i.card.code=n;continue}if("expires"===t){try{const e=new Date(n);i.card.expYear=e.getFullYear().toString(),i.card.expMonth=(e.getMonth()+1).toString()}catch(e){}continue}if("cardType"===t)continue}else{if(("username"===t||"email"===t)&&this.isNullOrWhitespace(i.login.username)){i.login.username=n;continue}if("password"===t){i.login.password=n;continue}if("totp"===t){i.login.totp=n;continue}if((null==i.login.uris||0===i.login.uris.length)&&this.uriFieldNames.indexOf(t)>-1){i.login.uris=this.makeUriArray(n);continue}}this.processKvp(i,t,n)}else r.forEach(e=>{this.processKvp(i,e.name,e.value)})}this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}}),t.success=!0,Promise.resolve(t)}}const dj=Object.freeze({Password:"0",CreditCard:"1",SoftwareLicense:"2",Identity:"3",Information:"4",Banking:"5",EncryptedFile:"6",Document:"7",RDP:"8",Putty:"9",TeamViewer:"10",Certificate:"11"}),hj=Object.freeze({Password:"1",Memo:"2",Date:"3",Number:"4",Boolean:"5",Decimal:"6",Email:"7",URL:"8"});class pj extends yP{constructor(){super(...arguments),this.result=new gP,this._favouritesLookupTable=new Set}parse(e){const t=this.parseXml(e);if(null==t)return this.result.success=!1,Promise.resolve(this.result);const i=t.querySelector("passwordfile");if(null==i)return this.result.errorMessage="Missing `passwordfile` node.",this.result.success=!1,Promise.resolve(this.result);const r=this.querySelectorDirectChild(i,"header");if(null==r)return this.result.success=!1,Promise.resolve(this.result);let n=this.querySelectorDirectChild(r,"version");if(null==n&&(n=this.querySelectorDirectChild(r,"dataformat"),null==n))return this.result.success=!1,Promise.resolve(this.result);if(!n.textContent.startsWith("17"))return this.result.errorMessage="Unsupported export version detected - (only 17.0 is supported)",this.result.success=!1,Promise.resolve(this.result);const a=this.querySelectorDirectChild(r,"encrypted");if(null!=a&&"True"==a.textContent)return this.result.errorMessage="Encrypted Password Depot files are not supported.",this.result.success=!1,Promise.resolve(this.result);const s=i.querySelector("passwords");return null==s?(this.result.errorMessage="Missing `passwordfile > passwords` node.",this.result.success=!1,Promise.resolve(this.result)):(this.buildFavouritesLookupTable(i),this.querySelectorAllDirectChild(s,"group").forEach(e=>{this.traverse(e,"")}),this.organization&&this.moveFoldersToCollections(this.result),this.result.success=!0,Promise.resolve(this.result))}traverse(e,t){const i=this.result.folders.length;let r=t;""!==r&&(r+="/");const n=e.attributes.getNamedItem("fingerprint");if(""!=(null==n?void 0:n.textContent)&&"null"!=n.textContent){const t=e.attributes.getNamedItem("name");r+=null==t?"-":t.textContent;const i=new DC;i.name=r,this.result.folders.push(i)}this.querySelectorAllDirectChild(e,"item").forEach(e=>{const t=this.result.ciphers.length,n=this.initLoginCipher();let a=dj.Password;const s=e.children;for(let e=0;e{this.parseBankingTANs(e,n)}):this.parseCustomFields(t,a,n));else switch(a=t.textContent,a){case dj.Password:case dj.RDP:case dj.Putty:case dj.TeamViewer:case dj.Banking:case dj.Certificate:case dj.EncryptedFile:n.type=rm.Login,n.login=new nw;break;case dj.CreditCard:n.type=rm.Card,n.card=new Hb;break;case dj.SoftwareLicense:case dj.Information:case dj.Document:n.type=rm.SecureNote,n.secureNote=new sw,n.secureNote.type=0;break;case dj.Identity:n.type=rm.Identity,n.identity=new Yb}else n.notes=t.textContent;else n.name=t.textContent}this.cleanupCipher(n),this.result.ciphers.push(n),""!==r&&this.result.folderRelationships.push([t,i])}),this.querySelectorAllDirectChild(e,"group").forEach(e=>{this.traverse(e,r)})}parseCustomFields(e,t,i){this.querySelectorAllDirectChild(e,"field").forEach(e=>{const r=this.parseCustomField(e);if(null!=r){switch(t){case dj.CreditCard:if(this.parseCreditCardCustomFields(r,i))return;break;case dj.Identity:if(this.parseIdentityCustomFields(r,i))return;break;case dj.Information:if(this.parseInformationCustomFields(r,i))return}this.processKvp(i,r.name,r.value,r.type)}})}parseLoginFields(e,t){return"username"===e.tagName?(t.login.username=e.textContent,!0):"password"===e.tagName?(t.login.password=e.textContent,!0):"url"===e.tagName&&(t.login.uris=this.makeUriArray(e.textContent),!0)}parseCustomField(e){let t,i,r,n=hj.Memo;if(e.hasAttributes()){if(t=e.getAttribute("name"),null==t)return null;i=e.getAttribute("value");const a=e.getAttribute("type");n=null!=a?a:hj.Memo,r=e.getAttribute("visible")}else{const a=this.querySelectorDirectChild(e,"name");if(t=null!=a?a.textContent:null,null==t)return null;const s=this.querySelectorDirectChild(e,"value");i=null!=s?s.textContent:null;const o=this.querySelectorDirectChild(e,"type");n=null!=o?o.textContent:hj.Memo;const l=this.querySelectorDirectChild(e,"visible");r=null!=l?l.textContent:null}if(n===hj.Date&&!isNaN(i)){const e=parseInt(i);i=new Date(864e5*(e-25569)).toLocaleDateString()}return n===hj.Password?{name:t,value:i,type:am.Hidden,linkedId:null}:n===hj.Boolean?{name:t,value:i,type:am.Boolean,linkedId:null}:"0"==r?{name:t,value:i,type:am.Hidden,linkedId:null}:{name:t,value:i,type:am.Text,linkedId:null}}parseCreditCardCustomFields(e,t){return"IDS_CardHolder"===e.name?(t.card.cardholderName=e.value,!0):"IDS_CardNumber"===e.name?(t.card.number=e.value,t.card.brand=Hb.getCardBrandByPatterns(t.card.number),!0):"IDS_CardExpires"===e.name?(this.setCardExpiration(t,e.value),!0):"IDS_CardCode"===e.name&&(t.card.code=e.value,!0)}parseIdentityCustomFields(e,t){return"IDS_IdentityName"===e.name?(this.processFullName(t,e.value),!0):"IDS_IdentityEmail"===e.name?(t.identity.email=e.value,!0):"IDS_IdentityFirstName"===e.name?(t.identity.firstName=e.value,!0):"IDS_IdentityLastName"===e.name?(t.identity.lastName=e.value,!0):"IDS_IdentityCompany"===e.name?(t.identity.company=e.value,!0):"IDS_IdentityAddress1"===e.name?(t.identity.address1=e.value,!0):"IDS_IdentityAddress2"===e.name?(t.identity.address2=e.value,!0):"IDS_IdentityCity"===e.name?(t.identity.city=e.value,!0):"IDS_IdentityState"===e.name?(t.identity.state=e.value,!0):"IDS_IdentityZIP"===e.name?(t.identity.postalCode=e.value,!0):"IDS_IdentityCountry"===e.name?(t.identity.country=e.value,!0):"IDS_IdentityPhone"===e.name&&(t.identity.phone=e.value,!0)}parseInformationCustomFields(e,t){return"IDS_InformationText"===e.name&&(t.notes=e.value,!0)}parseBankingTANs(e,t){let i="0";const r=e.children;for(let e=0;e0?i.split("\r\n").forEach(e=>{this._favouritesLookupTable.add(e)}):i.split("\n").forEach(e=>{this._favouritesLookupTable.add(e)})}}class mj extends yP{parse(e){const t=new gP,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);const r=i.querySelectorAll("PasswordManager > record");return Array.from(r).forEach(e=>{const i=this.querySelectorDirectChild(e,"Category"),r=null==i||this.isNullOrWhitespace(i.textContent)||"Unfiled"===i.textContent?null:i.textContent;this.processFolder(t,r);const n=this.querySelectorDirectChild(e,"Account-Name"),a=this.querySelectorDirectChild(e,"User-Id"),s=this.querySelectorDirectChild(e,"Password"),o=this.querySelectorDirectChild(e,"URL"),l=this.querySelectorDirectChild(e,"Notes"),c=this.initLoginCipher();c.name=null!=n?this.getValueOrDefault(n.textContent,"--"):"--",c.notes=null!=l?this.getValueOrDefault(l.textContent):"",c.login.username=null!=a?this.getValueOrDefault(a.textContent):null,c.login.password=null!=s?this.getValueOrDefault(s.textContent):null,c.login.uris=null!=o?this.makeUriArray(o.textContent):null;const u=[];for(let e=1;e<=10;e++)u.push("Attribute-"+e);this.querySelectorAllDirectChild(e,u.join(",")).forEach(e=>{this.isNullOrWhitespace(e.textContent)||"null"===e.textContent||this.processKvp(c,e.tagName,e.textContent)}),this.cleanupCipher(c),t.ciphers.push(c)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class gj extends yP{parse(e){const t=new gP,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);const r=i.querySelector("passwordsafe");if(null==r)return t.errorMessage="Missing `passwordsafe` node.",t.success=!1,Promise.resolve(t);const n=r.getAttribute("delimiter"),a=i.querySelectorAll("passwordsafe > entry");return Array.from(a).forEach(e=>{const i=this.querySelectorDirectChild(e,"group"),r=null==i||this.isNullOrWhitespace(i.textContent)?null:i.textContent.split(".").join("/");this.processFolder(t,r);const a=this.querySelectorDirectChild(e,"title"),s=this.querySelectorDirectChild(e,"username"),o=this.querySelectorDirectChild(e,"email"),l=this.querySelectorDirectChild(e,"password"),c=this.querySelectorDirectChild(e,"url"),u=this.querySelectorDirectChild(e,"notes"),d=this.initLoginCipher();d.name=null!=a?this.getValueOrDefault(a.textContent,"--"):"--",d.notes=null!=u?this.getValueOrDefault(u.textContent,"").split(n).join("\n"):null,d.login.username=null!=s?this.getValueOrDefault(s.textContent):null,d.login.password=null!=l?this.getValueOrDefault(l.textContent):null,d.login.uris=null!=c?this.makeUriArray(c.textContent):null,this.isNullOrWhitespace(d.login.username)&&null!=o?d.login.username=this.getValueOrDefault(o.textContent):null==o||this.isNullOrWhitespace(o.textContent)||(d.notes=this.isNullOrWhitespace(d.notes)?"Email: "+o.textContent:d.notes+"\nEmail: "+o.textContent),this.cleanupCipher(d),t.ciphers.push(d)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}}class fj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(e.length<1)return;e.length>5&&this.processFolder(t,e[5]);const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--"),e.length>4&&(i.notes=this.getValueOrDefault(e[4],"").split("¬").join("\n")),e.length>2&&(i.login.username=this.getValueOrDefault(e[2])),e.length>3&&(i.login.password=this.getValueOrDefault(e[3])),e.length>1&&(i.login.uris=this.makeUriArray(e[1])),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}}const yj={Titel:"Title",Gebruikersnaam:"Username",Wachtwoord:"Password",Gewijzigd:"Modified",Gemaakt:"Created","Verloopt op":"Expire on",Beschrijving:"Description","Gewijzigd door":"Modified by"},vj={Titel:"Title",Benutzername:"Username",Konto:"Account",Passwort:"Password","Geändert am":"Modified","Erstellt am":"Created","Läuft ab am":"Expire on",Beschreibung:"Description","Geändert von":"Modified by"},bj=new Set(["Title","Username","URL","Password","Description"]);function wj(e){return Object.assign(Object.assign({"User name":"Username"},vj),yj)[e]||e}class kj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0,{skipEmptyLines:!0,transformHeader:wj});if(null==i)return t.success=!1,Promise.resolve(t);if(!i[0].Title)return t.success=!1,Promise.resolve(t);let r="";return i.forEach(e=>{if(">>>"==e.Title)return;const i=e.Title;if(i.startsWith("[")&&i.endsWith("]"))return void(r=i.startsWith("/")?i.replace("/",""):i.substring(1,i.length-1));Tt.isNullOrWhitespace(r)||this.processFolder(t,r);const n=this.initLoginCipher();n.name=this.getValueOrDefault(e.Title),n.login.username=this.getValueOrDefault(e.Username),n.notes=this.getValueOrDefault(e.Description),n.login.uris=this.makeUriArray(e.URL),n.login.password=this.getValueOrDefault(e.Password),this.importUnmappedFields(n,e,bj),this.convertToNoteIfNeeded(n),this.cleanupCipher(n),t.ciphers.push(n)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}importUnmappedFields(e,t,i){Object.keys(t).filter(e=>!i.has(e)).forEach(i=>{const r=t;this.processKvp(e,i,r[i])})}}function Sj(e,t,i,r){let n=t,a=i,s=r;if(e){const o=e.trim().split(/\s+/);n=o[0]||t,s=o.length>1?o[o.length-1]:r,a=o.length>2?o.slice(1,-1).join(" "):i}return{mappedFirstName:n,mappedMiddleName:a,mappedLastName:s}}const _j=Object.freeze({ACTIVE:1,TRASHED:2});class xj extends yP{constructor(e){super(),this.i18nService=e,this.mappedIdentityItemKeys=["fullName","firstName","middleName","lastName","email","phoneNumber","company","socialSecurityNumber","passportNumber","licenseNumber","organization","streetAddress","floor","county","city","stateOrProvince","zipOrPostalCode","countryOrRegion"],this.identityItemExtraFieldsKeys=["extraPersonalDetails","extraAddressDetails","extraContactDetails","extraWorkDetails","extraSections"]}processIdentityItemUnmappedAndExtraFields(e,t){Object.keys(t).forEach(i=>{if(this.mappedIdentityItemKeys.includes(i)||this.identityItemExtraFieldsKeys.includes(i)){if(this.identityItemExtraFieldsKeys.includes(i))if("extraSections"!==i){const r=t[i];null==r||r.forEach(t=>{this.processKvp(e,t.fieldName,t.data.content,"hidden"===t.type?am.Hidden:am.Text)})}else{const r=t[i];null==r||r.forEach(t=>{var i;null===(i=t.sectionFields)||void 0===i||i.forEach(t=>{this.processKvp(e,t.fieldName,t.data.content,"hidden"===t.type?am.Hidden:am.Text)})})}}else this.processKvp(e,i,t[i])})}parse(e){var t,i;const r=new gP,n=JSON.parse(e);if(null==n||null==n.vaults)return r.success=!1,Promise.resolve(r);if(n.encrypted)return r.success=!1,r.errorMessage=this.i18nService.t("unsupportedEncryptedImport"),Promise.resolve(r);for(const[,e]of Object.entries(n.vaults))for(const n of e.items){if(n.state==_j.TRASHED)continue;const a=this.initLoginCipher();switch(a.name=this.getValueOrDefault(n.data.metadata.name,"--"),a.notes=this.getValueOrDefault(n.data.metadata.note),a.favorite=n.pinned,n.data.type){case"login":{const e=n.data.content;a.login.uris=this.makeUriArray(e.urls),a.login.username=this.getValueOrDefault(e.itemUsername),null==a.login.username?a.login.username=this.getValueOrDefault(e.itemEmail):this.processKvp(a,"email",e.itemEmail),a.login.password=this.getValueOrDefault(e.password),a.login.totp=this.getValueOrDefault(e.totpUri);for(const e of n.data.extraFields)this.processKvp(a,e.fieldName,"totp"==e.type?e.data.totpUri:e.data.content,"text"==e.type?am.Text:am.Hidden);break}case"note":a.type=rm.SecureNote,a.secureNote=new sw,a.secureNote.type=0;break;case"creditCard":{const e=n.data.content;a.type=rm.Card,a.card=new Hb,a.card.cardholderName=this.getValueOrDefault(e.cardholderName),a.card.number=this.getValueOrDefault(e.number),a.card.brand=Hb.getCardBrandByPatterns(e.number),a.card.code=this.getValueOrDefault(e.verificationNumber),this.isNullOrWhitespace(e.expirationDate)||(a.card.expMonth=e.expirationDate.substring(5,7),a.card.expMonth=a.card.expMonth.replace(/^0+/,""),a.card.expYear=e.expirationDate.substring(0,4)),this.isNullOrWhitespace(e.pin)||this.processKvp(a,"PIN",e.pin,am.Hidden);break}case"identity":{const e=n.data.content;a.type=rm.Identity,a.identity=new Yb;const{mappedFirstName:r,mappedMiddleName:s,mappedLastName:o}=Sj(this.getValueOrDefault(e.fullName),this.getValueOrDefault(e.firstName),this.getValueOrDefault(e.middleName),this.getValueOrDefault(e.lastName));a.identity.firstName=r,a.identity.middleName=s,a.identity.lastName=o,a.identity.email=this.getValueOrDefault(e.email),a.identity.phone=this.getValueOrDefault(e.phoneNumber),a.identity.company=this.getValueOrDefault(e.company),a.identity.ssn=this.getValueOrDefault(e.socialSecurityNumber),a.identity.passportNumber=this.getValueOrDefault(e.passportNumber),a.identity.licenseNumber=this.getValueOrDefault(e.licenseNumber);const l=`${null!==(t=e.floor)&&void 0!==t?t:""} ${null!==(i=e.county)&&void 0!==i?i:""}`.trim();a.identity.address1=this.getValueOrDefault(e.organization),a.identity.address2=this.getValueOrDefault(e.streetAddress),a.identity.address3=this.getValueOrDefault(l),a.identity.city=this.getValueOrDefault(e.city),a.identity.state=this.getValueOrDefault(e.stateOrProvince),a.identity.postalCode=this.getValueOrDefault(e.zipOrPostalCode),a.identity.country=this.getValueOrDefault(e.countryOrRegion),this.processIdentityItemUnmappedAndExtraFields(a,e);for(const e of n.data.extraFields)this.processKvp(a,e.fieldName,e.data.content,"hidden"===e.type?am.Hidden:am.Text);break}default:continue}this.processFolder(r,e.name),this.cleanupCipher(a),r.ciphers.push(a)}return this.organization&&this.moveFoldersToCollections(r),r.success=!0,Promise.resolve(r)}}class Cj extends yP{constructor(){super(...arguments),this.WEBSITE_mappedValues=new Set(["type","name","website_password_title","website_password_notes","website_password_username","website_password_password","website_password_url","autosubmit","website_password_auto_submit","urlfilter","website_password_url_filter"]),this.APP_PWD_mappedValues=new Set(["type","name","application_password_title","application_password_notes","application_password_username","application_password_password"]),this.BOOKMARK_mappedValues=new Set(["type","name","bookmark_title","bookmark_notes","bookmark_url"]),this.NOTES_mappedValues=new Set(["type","name","note_title","note_notes"]),this.TOTP_mappedValues=new Set(["type","name","totp_title","totp_notes","totp_code"]),this.ENV_VARIABLES_mappedValues=new Set(["type","name","environment_variables_title","environment_variables_notes","environment_variables_variables"]),this.GPG_mappedValues=new Set(["type","name","mail_gpg_own_key_title","mail_gpg_own_key_public","mail_gpg_own_key_name","mail_gpg_own_key_email","mail_gpg_own_key_private"])}parse(e){const t=new gP,i=JSON.parse(e);return null==i?(t.success=!1,Promise.resolve(t)):(this.parseFolders(t,i.folders),this.handleItemParsing(t,i.items),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}parseFolders(e,t,i){null!=t&&0!==t.length&&t.forEach(t=>{const r=null!=t.items&&t.items.length>0,n=null!=t.folders&&t.folders.length>0;(r||n)&&(Tt.isNullOrWhitespace(i)||(t.name=i+"/"+t.name),n&&this.parseFolders(e,t.folders,t.name),r?this.handleItemParsing(e,t.items,t.name):this.processFolder(e,t.name,r))})}handleItemParsing(e,t,i){null!=t&&0!==t.length&&t.forEach(t=>{const r=this.parsePsonoItem(t);this.processFolder(e,i,!0),this.cleanupCipher(r),e.ciphers.push(r)})}parsePsonoItem(e){const t=this.initLoginCipher();switch(e.type){case"website_password":this.parseWebsiteLogins(e,t);break;case"application_password":this.parseApplicationPasswords(e,t);break;case"environment_variables":this.parseEnvironmentVariables(e,t);break;case"totp":this.parseTOTP(e,t);break;case"bookmark":this.parseBookmarks(e,t);break;case"note":this.parseNotes(e,t)}return t}parseWebsiteLogins(e,t){var i;null!=e&&"website_password"==e.type&&(t.name=e.website_password_title,t.notes=e.website_password_notes,t.login.username=e.website_password_username,t.login.password=e.website_password_password,t.login.uris=this.makeUriArray(e.website_password_url),this.processKvp(t,"website_password_auto_submit",null===(i=e.website_password_auto_submit)||void 0===i?void 0:i.toString(),am.Boolean),this.processKvp(t,"website_password_url_filter",e.website_password_url_filter),this.importUnmappedFields(t,e,this.WEBSITE_mappedValues))}parseApplicationPasswords(e,t){null!=e&&"application_password"==e.type&&(t.name=e.application_password_title,t.notes=e.application_password_notes,t.login.username=e.application_password_username,t.login.password=e.application_password_password,this.importUnmappedFields(t,e,this.APP_PWD_mappedValues))}parseBookmarks(e,t){null!=e&&"bookmark"==e.type&&(t.name=e.bookmark_title,t.notes=e.bookmark_notes,t.login.uris=this.makeUriArray(e.bookmark_url),this.importUnmappedFields(t,e,this.BOOKMARK_mappedValues))}parseNotes(e,t){null!=e&&"note"==e.type&&(t.type=rm.SecureNote,t.secureNote=new sw,t.secureNote.type=0,t.name=e.note_title,t.notes=e.note_notes,this.importUnmappedFields(t,e,this.NOTES_mappedValues))}parseTOTP(e,t){null!=e&&"totp"==e.type&&(t.name=e.totp_title,t.notes=e.totp_notes,t.login.totp=e.totp_code,this.importUnmappedFields(t,e,this.TOTP_mappedValues))}parseEnvironmentVariables(e,t){null!=e&&"environment_variables"==e.type&&(t.type=rm.SecureNote,t.secureNote=new sw,t.secureNote.type=0,t.name=e.environment_variables_title,t.notes=e.environment_variables_notes,e.environment_variables_variables.forEach(e=>{this.processKvp(t,e.key,e.value)}),this.importUnmappedFields(t,e,this.ENV_VARIABLES_mappedValues))}parseGPG(e,t){null!=e&&"mail_gpg_own_key"==e.type&&(t.type=rm.SecureNote,t.secureNote=new sw,t.secureNote.type=0,t.name=e.mail_gpg_own_key_title,t.notes=e.mail_gpg_own_key_public,this.processKvp(t,"mail_gpg_own_key_name",e.mail_gpg_own_key_name),this.processKvp(t,"mail_gpg_own_key_email",e.mail_gpg_own_key_email),this.processKvp(t,"mail_gpg_own_key_private",e.mail_gpg_own_key_private,am.Hidden),this.importUnmappedFields(t,e,this.GPG_mappedValues))}importUnmappedFields(e,t,i){Object.keys(t).filter(e=>!i.has(e)).forEach(i=>{const r=t;this.processKvp(e,i,r[i].toString())})}}class Ij extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if("true"===e.trash)return;const i=this.initLoginCipher();if(i.name=this.getValueOrDefault(e.name),i.notes=this.getValueOrDefault(e.notes),"LoginItem"===e.type)i.login.uris=this.makeUriArray(e.website),i.login.password=this.getValueOrDefault(e.password),i.login.username=this.getValueOrDefault(e.username);else if("CreditCardItem"===e.type){i.type=rm.Card,i.card=new Hb,i.card.cardholderName=this.getValueOrDefault(e.cardholder),i.card.number=this.getValueOrDefault(e.number),i.card.brand=Hb.getCardBrandByPatterns(i.card.number),i.card.code=this.getValueOrDefault(e.verification);try{const t=this.getValueOrDefault(e.expiryMonth);if(null!=t){const e=parseInt(t,null);null!=e&&e>=1&&e<=12&&(i.card.expMonth=e.toString())}}catch(e){}try{const t=this.getValueOrDefault(e.expiryYear);if(null!=t){const e=parseInt(t,null);null!=e&&(i.card.expYear=e.toString())}}catch(e){}const t=this.getValueOrDefault(e.pin);null!=t&&this.processKvp(i,"PIN",t);const r=this.getValueOrDefault(e.zipCode);null!=r&&this.processKvp(i,"Zip Code",r)}this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class Ej extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);if(null==i)return t.success=!1,Promise.resolve(t);let r=1;return i.forEach(e=>{var n,a;const s=!this.isNullOrWhitespace(e.Folder)&&e.Folder.startsWith("/")?e.Folder.replace("/",""):e.Folder,o=this.isNullOrWhitespace(s)?null:s;this.processFolder(t,o);const l=this.initLoginCipher();l.notes=this.getValueOrDefault(e.Note),l.name=this.getValueOrDefault(e.Name,"--"),l.login.username=this.getValueOrDefault(e.Login),l.login.password=null!==(n=this.getValueOrDefault(e.Pwd))&&void 0!==n?n:this.getValueOrDefault(e.Password),l.login.uris=null!==(a=this.makeUriArray(e.Url))&&void 0!==a?a:this.makeUriArray(e.URL),this.isNullOrWhitespace(e.Rf_fields)?this.isNullOrWhitespace(e.RfFieldsV2)||this.parseRfFieldsV2(l,e):this.parseRfFields(l,e),this.convertToNoteIfNeeded(l),this.cleanupCipher(l),r===i.length&&"--"===l.name&&this.isNullOrWhitespace(l.login.password)||(t.ciphers.push(l),r++)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}parseRfFields(e,t){let i=[t.Rf_fields];null!=t.__parsed_extra&&t.__parsed_extra.length>0&&(i=i.concat(t.__parsed_extra)),i.forEach(t=>{const i=t.split(":");if(i.length<3)return;const r="-no-name-"===i[0]?null:i[0],n=4===i.length&&"rck"===i[2]?i[1]:i[2];this.processKvp(e,r,n)})}parseRfFieldsV2(e,t){let i=[t.RfFieldsV2];null!=t.__parsed_extra&&t.__parsed_extra.length>0&&(i=i.concat(t.__parsed_extra));let r=1,n=1;i.forEach(t=>{const i=t.split(",");if(i.length<5)return;const a="-no-name-"===i[0]?null:i[0],s="pwd"===i[3]?am.Hidden:am.Text,o=i[4];if("TOTP KEY$"===a)return void(e.login.totp=o);if("User ID$"===a&&o===e.login.username)return;if("Password$"===a&&o===e.login.password)return;let l=a;"User ID$"===a?l="Alternate User ID "+r++:"Password$"===a&&(l="Alternate Password "+n++),this.processKvp(e,l,o,s)})}}class zj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{var i;const r=this.initLoginCipher();r.name=this.getValueOrDefault(e.Title,"--"),r.login.username=this.getValueOrDefault(e.Username),r.login.password=this.getValueOrDefault(e.Password),r.login.uris=this.makeUriArray(null!==(i=e.Url)&&void 0!==i?i:e.URL),r.login.totp=this.getValueOrDefault(e.OTPAuth),r.notes=this.getValueOrDefault(e.Notes),this.cleanupCipher(r),t.ciphers.push(r)}),t.success=!0,Promise.resolve(t))}}class Pj extends yP{parse(e){const t=new gP,i=this.parseXml(e);if(null==i)return t.success=!1,Promise.resolve(t);if(null==i.querySelector("database"))return t.errorMessage="Missing `database` node.",t.success=!1,Promise.resolve(t);const r=new Map;return Array.from(i.querySelectorAll("database > label")).forEach(e=>{const i=e.getAttribute("name"),n=e.getAttribute("id");if(!this.isNullOrWhitespace(i)&&!this.isNullOrWhitespace(n)){r.set(n,t.folders.length);const e=new DC;e.name=i,t.folders.push(e)}}),Array.from(i.querySelectorAll("database > card")).forEach(e=>{if("true"===e.getAttribute("template")||"true"===e.getAttribute("deleted"))return;const i=this.querySelectorDirectChild(e,"label_id");if(null!=i){const e=i.textContent;!this.isNullOrWhitespace(e)&&r.has(e)&&t.folderRelationships.push([t.ciphers.length,r.get(e)])}const n=this.initLoginCipher();n.name=this.getValueOrDefault(e.getAttribute("title"),"--"),"true"===e.getAttribute("star")&&(n.favorite=!0),"note"===e.getAttribute("type")?(n.type=rm.SecureNote,n.secureNote=new sw,n.secureNote.type=0):Array.from(this.querySelectorAllDirectChild(e,"field")).forEach(e=>{const t=e.textContent;if(this.isNullOrWhitespace(t))return;const i=e.getAttribute("name"),r=this.getValueOrDefault(e.getAttribute("type"),"").toLowerCase();"login"===r?n.login.username=t:"password"===r||"secret"===r?this.processKvp(n,i,t,am.Hidden):"one_time_password"===r?n.login.totp=t:"notes"===r?n.notes+=t+"\n":"weblogin"===r||"website"===r?n.login.uris.push(...this.makeUriArray(t)):this.processKvp(n,i,t)}),Array.from(this.querySelectorAllDirectChild(e,"notes")).forEach(e=>{n.notes+=e.textContent+"\n"}),this.setPassword(n),this.cleanupCipher(n),t.ciphers.push(n)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}setPassword(e){const t=e.fields.filter(e=>e.type===am.Hidden);if(!t.length)return;let i;for(const r of t)if(this.passwordFieldNames.includes(r.name.toLowerCase())){i=r,e.fields=e.fields.filter(e=>e!==i);break}i||(i=t[0]),e.login.password=i.value}}class Aj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(this.nameFromUrl(e.url),"--"),i.notes=this.getValueOrDefault(e.notes),i.login.username=this.getValueOrDefault(e.username),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.url),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class jj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);if(null==i)return t.success=!1,Promise.resolve(t);const r=Object.keys(i[0]).find(e=>/url/i.test(e));return i.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.Title),i.notes=this.getValueOrDefault(e.Comment),i.login.uris=this.makeUriArray(e[r]),i.login.password=this.getValueOrDefault(e.Password),i.login.username=this.getValueOrDefault(e.Username),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t)}}class Tj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(e.length<3)return;this.processFolder(t,this.getValueOrDefault(e[e.length-1]));const i=this.initLoginCipher();i.notes=this.getValueOrDefault(e[e.length-2],""),i.name=this.getValueOrDefault(e[1],"--"),"Web Logins"===e[0]||"Servers"===e[0]||"Email Accounts"===e[0]?(i.login.username=this.getValueOrDefault(e[2]),i.login.password=this.getValueOrDefault(e[3]),i.login.uris=this.makeUriArray(e[4]),this.parseFieldsToNotes(i,5,e)):this.parseFieldsToNotes(i,2,e),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}parseFieldsToNotes(e,t,i){for(let r=t;r Database > Logins > Login");return Array.from(r).forEach(e=>{const r=e.getAttribute("ID");if(this.isNullOrWhitespace(r))return;const n=e.getAttribute("Name"),a=e.getAttribute("Password");let s=null,o=null,l=null,c=null,u=null;const d=i.querySelector('root > Database > Accounts > Account > LoginLinks > Login[SourceLoginID="'+r+'"]');if(null!=d){const e=d.parentElement.parentElement;null!=e&&(s=e.getAttribute("Name"),o=e.getAttribute("Link"),c=e.getAttribute("ParentID"),l=e.getAttribute("Comments"),this.isNullOrWhitespace(l)||(l=l.split("/n").join("\n")))}this.isNullOrWhitespace(c)||(u=this.buildGroupText(i,c,""),this.processFolder(t,u));const h=this.initLoginCipher();h.name=this.getValueOrDefault(s,"--"),h.notes=this.getValueOrDefault(l),h.login.username=this.getValueOrDefault(n),h.login.password=this.getValueOrDefault(a),h.login.uris=this.makeUriArray(o),this.cleanupCipher(h),t.ciphers.push(h)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t)}buildGroupText(e,t,i){const r=e.querySelector('root > Database > Groups > Group[ID="'+t+'"]');return null==r?i:(this.isNullOrWhitespace(i)||(i="/"+i),i=r.getAttribute("Name")+i,this.buildGroupText(e,r.getAttribute("ParentID"),i))}}const Oj=["kind","autologin","favorite","hexcolor","protectedwithpassword","subdomainonly","type","tk_export_version","note","title","document_content"];class Nj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher();if(i.favorite="true"===this.getValueOrDefault(e.favorite,"").toLowerCase(),i.name=this.getValueOrDefault(e.name,"--"),i.notes=this.getValueOrDefault(e.memo,""),i.login.username=this.getValueOrDefault(e.login),i.login.password=this.getValueOrDefault(e.password),i.login.uris=this.makeUriArray(e.url),"login"!==e.kind&&(i.name=this.getValueOrDefault(e.title,"--"),i.notes=this.getValueOrDefault(e.note,"")),"cc"===e.kind){if(i.type=rm.Card,i.card=new Hb,i.card.cardholderName=this.getValueOrDefault(e.cardholder),i.card.number=this.getValueOrDefault(e.number),i.card.brand=Hb.getCardBrandByPatterns(i.card.number),!this.isNullOrWhitespace(e.expiryDate))try{const t=new Date(e.expiryDate);i.card.expYear=t.getFullYear().toString(),i.card.expMonth=(t.getMonth()+1).toString()}catch(e){}}else if("login"!==e.kind){i.type=rm.SecureNote,i.secureNote=new sw,i.secureNote.type=0,this.isNullOrWhitespace(i.notes)||(i.notes=this.getValueOrDefault(e.document_content,""));for(const t in e)e.hasOwnProperty(t)&&Oj.indexOf(t.toLowerCase())<0&&!this.isNullOrWhitespace(e[t])&&this.processKvp(i,t,e[t])}this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class Rj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!1);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(5!==e.length)return;const i=this.initLoginCipher();i.name=this.getValueOrDefault(e[0],"--"),i.notes=this.getValueOrDefault(e[4]),i.login.username=this.getValueOrDefault(e[1]),i.login.password=this.getValueOrDefault(e[2]),i.login.uris=this.makeUriArray(e[3]),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class Uj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{const i=this.initLoginCipher();i.name=this.getValueOrDefault(e.Name,"--"),i.login.username=this.getValueOrDefault(e["User name"]),i.login.password=this.getValueOrDefault(e.Password),i.login.uris=this.makeUriArray(e.URL),this.cleanupCipher(i),t.ciphers.push(i)}),t.success=!0,Promise.resolve(t))}}class Fj extends yP{parse(e){const t=new gP,i=this.parseCsv(e,!0);return null==i?(t.success=!1,Promise.resolve(t)):(i.forEach(e=>{if(this.isNullOrWhitespace(e["Password Name"])&&this.isNullOrWhitespace(e["Secret Name"]))return;this.processFolder(t,this.getValueOrDefault(e["Folder Name"]));const i=this.initLoginCipher();i.favorite="1"===this.getValueOrDefault(e.Favorite,"0"),i.notes=this.getValueOrDefault(e.Notes),i.name=this.getValueOrDefault(e["Password Name"],this.getValueOrDefault(e["Secret Name"],"--")),i.login.uris=this.makeUriArray(this.getValueOrDefault(e["Password URL"],this.getValueOrDefault(e["Secret URL"]))),i.login.totp=this.getValueOrDefault(e.login_totp),this.parseData(i,e.SecretData),this.parseData(i,e.CustomData),this.convertToNoteIfNeeded(i),this.cleanupCipher(i),t.ciphers.push(i)}),this.organization&&this.moveFoldersToCollections(t),t.success=!0,Promise.resolve(t))}parseData(e,t){this.isNullOrWhitespace(t)||this.splitNewLine(t).forEach(t=>{const i=t.indexOf(":");if(i<0)return;const r=t.substring(0,i),n=t.length>i?t.substring(i+1):null;if(this.isNullOrWhitespace(r)||this.isNullOrWhitespace(n)||"SecretType"===r)return;const a=r.toLowerCase();null==e.login.username&&this.usernameFieldNames.indexOf(a)>-1?e.login.username=n:null==e.login.password&&this.passwordFieldNames.indexOf(a)>-1?e.login.password=n:this.processKvp(e,r,n)})}}const qj=[{id:"bitwardenjson",name:"Bitwarden (json)"},{id:"bitwardencsv",name:"Bitwarden (csv)"},{id:"chromecsv",name:"Chrome"},{id:"dashlanecsv",name:"Dashlane (csv)"},{id:"firefoxcsv",name:"Firefox (csv)"},{id:"keepass2xml",name:"KeePass 2 (xml)"},{id:"lastpasscsv",name:"LastPass"},{id:"safaricsv",name:"Safari and macOS (csv)"},{id:"1password1pux",name:"1Password (1pux/json)"}],Lj=[{id:"keepassxcsv",name:"KeePassX (csv)"},{id:"1password1pif",name:"1Password (1pif)"},{id:"1passwordwincsv",name:"1Password 6 and 7 Windows (csv)"},{id:"1passwordmaccsv",name:"1Password 6 and 7 Mac (csv)"},{id:"dashlanejson",name:"Dashlane (json)"},{id:"roboformcsv",name:"RoboForm (csv)"},{id:"keepercsv",name:"Keeper (csv)"},{id:"enpasscsv",name:"Enpass (csv)"},{id:"enpassjson",name:"Enpass (json)"},{id:"protonpass",name:"ProtonPass (zip/json)"},{id:"safeincloudxml",name:"SafeInCloud (xml)"},{id:"pwsafexml",name:"Password Safe - pwsafe.org (xml)"},{id:"stickypasswordxml",name:"Sticky Password (xml)"},{id:"msecurecsv",name:"mSecure (csv)"},{id:"truekeycsv",name:"True Key (csv)"},{id:"passwordbossjson",name:"Password Boss (json)"},{id:"zohovaultcsv",name:"Zoho Vault (csv)"},{id:"splashidcsv",name:"SplashID (csv)"},{id:"passworddragonxml",name:"Password Dragon (xml)"},{id:"padlockcsv",name:"Padlock (csv)"},{id:"passboltcsv",name:"Passbolt (csv)"},{id:"clipperzhtml",name:"Clipperz (html)"},{id:"aviracsv",name:"Avira (csv)"},{id:"saferpasscsv",name:"SaferPass (csv)"},{id:"upmcsv",name:"Universal Password Manager (csv)"},{id:"ascendocsv",name:"Ascendo DataVault (csv)"},{id:"meldiumcsv",name:"Meldium (csv)"},{id:"passkeepcsv",name:"PassKeep (csv)"},{id:"arccsv",name:"Arc"},{id:"edgecsv",name:"Edge"},{id:"operacsv",name:"Opera"},{id:"vivaldicsv",name:"Vivaldi"},{id:"bravecsv",name:"Brave"},{id:"gnomejson",name:"GNOME Passwords and Keys/Seahorse (json)"},{id:"blurcsv",name:"Blur (csv)"},{id:"passwordagentcsv",name:"Password Agent (csv)"},{id:"passpackcsv",name:"Passpack (csv)"},{id:"passmanjson",name:"Passman (json)"},{id:"avastcsv",name:"Avast Passwords (csv)"},{id:"avastjson",name:"Avast Passwords (json)"},{id:"fsecurefsk",name:"F-Secure KEY (fsk)"},{id:"kasperskytxt",name:"Kaspersky Password Manager (txt)"},{id:"remembearcsv",name:"RememBear (csv)"},{id:"passwordwallettxt",name:"PasswordWallet (txt)"},{id:"mykicsv",name:"Myki (csv)"},{id:"securesafecsv",name:"SecureSafe (csv)"},{id:"logmeoncecsv",name:"LogMeOnce (csv)"},{id:"blackberrycsv",name:"BlackBerry Password Keeper (csv)"},{id:"buttercupcsv",name:"Buttercup (csv)"},{id:"codebookcsv",name:"Codebook (csv)"},{id:"encryptrcsv",name:"Encryptr (csv)"},{id:"yoticsv",name:"Yoti (csv)"},{id:"nordpasscsv",name:"Nordpass (csv)"},{id:"psonojson",name:"Psono (json)"},{id:"passkyjson",name:"Passky (json)"},{id:"passwordxpcsv",name:"Password XP (csv)"},{id:"netwrixpasswordsecure",name:"Netwrix Password Secure (csv)"},{id:"passworddepot17xml",name:"Password Depot 17 (xml)"}];var Bj=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Mj{constructor(e,t,i,r,n,a,s,o,l,c){this.cipherService=e,this.folderService=t,this.importApiService=i,this.i18nService=r,this.collectionService=n,this.keyService=a,this.encryptService=s,this.keyGenerationService=o,this.accountService=l,this.restrictedItemTypesService=c,this.featuredImportOptions=qj,this.regularImportOptions=Lj}getImportOptions(){return this.featuredImportOptions.concat(this.regularImportOptions)}import(e,t){return Bj(this,arguments,void 0,function*(e,t,i=null,r=null,n){let a;try{a=yield e.parse(t)}catch(e){if(e instanceof SyntaxError)throw new Error(this.i18nService.t("importFormatError"));throw e}if(!a.success){if(!Tt.isNullOrWhitespace(a.errorMessage))throw new Error(a.errorMessage);throw new Error(this.i18nService.t("importFormatError"))}if(0===a.folders.length&&0===a.ciphers.length)throw new Error(this.i18nService.t("importNothingError"));if(a.ciphers.length>0){const e=Math.floor(a.ciphers.length/2),t=a.ciphers.length-1;if(this.badData(a.ciphers[0])&&this.badData(a.ciphers[e])&&this.badData(a.ciphers[t]))throw new Error(this.i18nService.t("importFormatError"))}const s=yield Ce(this.restrictedItemTypesService.restricted$.pipe(X(e=>e.map(e=>e.cipherType))));if(a.ciphers=a.ciphers.filter(e=>!s.includes(e.type)),i&&!r&&!n&&a.collectionRelationships.lengthi.folderRelationships.push(new mP(e[0],e[1]))),yield this.importApiService.postImportCiphers(i)})}handleOrganizationalImport(e,t,i){return Bj(this,void 0,void 0,function*(){const r=new pP;e.ciphers.forEach(e=>{e.organizationId=t});const n=yield this.cipherService.encryptMany(e.ciphers,i);for(const e of n)r.ciphers.push(new uC(e));if(null!=e.collections)for(let n=0;nr.collectionRelationships.push(new mP(e[0],e[1]))),yield this.importApiService.postImportOrganizationCiphers(t,r)})}badData(e){return(null==e.name||"--"===e.name)&&e.type===rm.Login&&null!=e.login&&Tt.isNullOrWhitespace(e.login.password)}handleServerError(e,t){if(null==e.validationErrors)return new Error(e.message);let i="";return Object.entries(e.validationErrors).forEach(([e,r],n)=>{let a,s;const o=Number(e.match(/[0-9]+/)[0]);switch(e.match(/^\w+/)[0]){case"Ciphers":a=t.ciphers[o],l=a.type,s=nm[l];break;case"Folders":a=t.folders[o],s="Folder";break;case"Collections":a=t.collections[o],s="Collection";break;default:return}var l;n>0&&(i+="\n\n"),"Folder"!==s&&"Collection"!==s&&(i+="["+(o+1)+"] "),i+="["+s+'] "'+a.name+'": '+r}),new Error(i)}setImportTarget(e,t,i){return Bj(this,void 0,void 0,function*(){if(!i)return;if(t){if(!(i instanceof qt))throw new Error(this.i18nService.t("errorAssigningTargetCollection"));const t=[];if(e.ciphers.forEach((i,r)=>{Array.isArray(e.collectionRelationships)&&e.collectionRelationships.some(([e])=>e===r)||t.push([r,0])}),1===i.type){e.collections=[i];const t=[];return e.ciphers.forEach((e,i)=>{t.push([i,0])}),void(e.collectionRelationships=t)}const r=[...e.collections];e.collections=[i],r.map(t=>{const r=new qt(t);r.name=`${i.name}/${t.name}`,e.collections.push(r)});const n=[...e.collectionRelationships];return e.collectionRelationships=[...t],void n.map(t=>{e.collectionRelationships.push([t[0],t[1]+1])})}if(!(i instanceof DC))throw new Error(this.i18nService.t("errorAssigningTargetFolder"));const r=[];e.ciphers.forEach((e,t)=>{Tt.isNullOrEmpty(e.folderId)&&(e.folderId=i.id,r.push([t,0]))});const n=[...e.folders];e.folders=[i],n.map(t=>{const r=`${i.name}/${t.name}`,n=new DC;n.name=r,e.folders.push(n)});const a=[...e.folderRelationships];e.folderRelationships=[...r],a.map(t=>{e.folderRelationships.push([t[0],t[1]+1])})})}}class Vj{constructor(e){this.system=e,this.importers=cP,this.logger=e.log({type:"ImportMetadataService"})}init(){return e=this,t=void 0,r=function*(){},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r}metadata$(e){const t=this.system.environment.getClientType(),i=e.pipe(X(e=>{var i;if(!this.importers)return{type:e,loaders:[]};const r=function(e,t,i){var r,n;if(e&&t in e)return(null!==(n=null===(r=e[t])||void 0===r?void 0:r.loaders)&&void 0!==n?n:[]).filter(e=>oP[e].includes(i))}(this.importers,e,t);if(!r||0===r.length)return{type:e,loaders:[]};const n={type:e,loaders:r};return e in this.importers&&(n.instructions=null===(i=this.importers[e])||void 0===i?void 0:i.instructions),this.logger.debug({importType:e,capabilities:n},"capabilities updated"),n}));return i}}class $j{constructor(e){this.taskSchedulerService=e}register(e){this.taskSchedulerService.registerTaskHandler(zu,e)}init(e=3e5){e=e<1?3e5:e,this.taskSchedulerService.setInterval(zu,e)}}var Kj=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Wj{constructor(e,t,i,r,n){this.accountService=e,this.authService=t,this.masterPasswordService=i,this.messagingService=r,this.pendingAuthRequestsState=n}activeUserMeetsConditionsToShowApprovalDialog(e){return Kj(this,void 0,void 0,function*(){return(yield Ce(this.accountService.activeAccount$.pipe(iu)))===e&&((yield Ce(this.authService.activeAccountStatus$))===cu.Unlocked&&(yield Ce(this.masterPasswordService.forceSetPasswordReason$(e)))===Nd.None)})}setupUnlockListenersForProcessingAuthRequests(e){this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id),Zl(),Ie(e=>null!=e),Le(e=>this.authService.authStatusFor$(e).pipe(ci(1))),Ie(e=>e===cu.Unlocked),ac(()=>{this.processPendingAuthRequests()}),m_(e)).subscribe(),this.authService.activeAccountStatus$.pipe(wb(null),g_(),Ie(([e,t])=>e!==cu.Unlocked&&t===cu.Unlocked),m_(e)).subscribe(()=>{this.processPendingAuthRequests()})}processPendingAuthRequests(){return Kj(this,void 0,void 0,function*(){var e;const t=yield Ce(this.accountService.activeAccount$.pipe(tu));if((yield Ce(this.masterPasswordService.forceSetPasswordReason$(t)))!==Nd.None)return;yield this.pendingAuthRequestsState.pruneOlderThan(9e5);const i=null!==(e=yield Ce(this.pendingAuthRequestsState.getAll$()))&&void 0!==e?e:[];i.length>0&&i.some(e=>e.userId===t)&&this.messagingService.send("openLoginApproval")})}handleAuthRequestNotificationClicked(e){return Kj(this,void 0,void 0,function*(){throw new Error("handleAuthRequestNotificationClicked() not implemented for this client")})}}const Hj=Object.freeze({FirstOptionalButton:0,SecondOptionalButton:1,NotificationButton:2});var Gj=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class Qj extends Wj{constructor(e,t,i,r,n,a,s,o,l,c){super(e,t,i,r,n),this.accountService=e,this.authService=t,this.masterPasswordService=i,this.messagingService=r,this.pendingAuthRequestsState=n,this.actionService=a,this.i18nService=s,this.platformUtilsService=o,this.systemNotificationsService=l,this.logService=c}receivedPendingAuthRequest(e,t){return Gj(this,void 0,void 0,function*(){if(!e)throw new Error("authRequestUserId required");if(!t)throw new Error("authRequestId required");if(yield this.pendingAuthRequestsState.add(e),yield this.activeUserMeetsConditionsToShowApprovalDialog(e))this.messagingService.send("openLoginApproval",{notificationId:t});else{const i=(yield Ce(this.accountService.accounts$))[e];if(!i)return void this.logService.error("Account not found for authRequestUserId");const r=i.email;yield this.systemNotificationsService.create({id:`${lp.AuthRequest}_${t}`,title:this.i18nService.t("accountAccessRequested"),body:this.i18nService.t("confirmAccessAttempt",r),buttons:[]})}})}activeUserMeetsConditionsToShowApprovalDialog(e){const t=Object.create(null,{activeUserMeetsConditionsToShowApprovalDialog:{get:()=>super.activeUserMeetsConditionsToShowApprovalDialog}});return Gj(this,void 0,void 0,function*(){const i=yield t.activeUserMeetsConditionsToShowApprovalDialog.call(this,e),r=yield this.platformUtilsService.isPopupOpen();return i&&r})}handleAuthRequestNotificationClicked(e){return Gj(this,void 0,void 0,function*(){e.buttonIdentifier===Hj.NotificationButton&&(yield this.systemNotificationsService.clear({id:`${e.id}`}),yield this.actionService.openPopup())})}}const Jj={Berry:{19:"/images/berry19.png",38:"/images/berry38.png"},LoggedOut:{19:"/images/icon19_gray.png",38:"/images/icon38_gray.png"},Locked:{19:"/images/icon19_locked.png",38:"/images/icon38_locked.png"},Unlocked:{19:"/images/icon19.png",38:"/images/icon38.png"}},Yj=Symbol("Unset badge state");class Xj{constructor(e,t,i){this.badgeService=e,this.accountService=t,this.authService=i,this.badgeService.setState("auth-status",e=>this.accountService.activeAccount$.pipe(Le(e=>e?this.authService.authStatusFor$(e.id):bt(cu.LoggedOut)),de(e=>{return t=this,i=void 0,n=function*(){switch(e){case cu.LoggedOut:return{priority:200,state:{icon:Jj.LoggedOut,backgroundColor:Yj,text:Yj}};case cu.Locked:return{priority:200,state:{icon:Jj.Locked,backgroundColor:Yj,text:Yj}};case cu.Unlocked:return{priority:0,state:{icon:Jj.Unlocked}}}},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n})))}}class Zj extends Ah{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g){super(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m),this.main=g}runPlatformOnLockActions(){return e=this,t=void 0,r=function*(){yield this.main.refreshMenu(!0)},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r}}function eT(e){if(e instanceof URL)return e;try{return new URL(e)}catch(e){return null}}function tT(e){return e.host?`${e.protocol}//${e.host}`:null}class iT{static sendMessageToApp(e,t=null,i=!1){return hT.isSafariApi?new Promise(i=>{const r=(new Date).getTime().toString()+"_"+Math.floor(Math.random()*Number.MAX_SAFE_INTEGER);browser.runtime.sendNativeMessage("com.bitwarden.desktop",{id:r,command:e,data:t,responseData:null},e=>{i(e)})}):Promise.resolve(null)}}var rT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class nT{static copy(e,t){return rT(this,void 0,void 0,function*(){if(nT.isClipboardApiSupported(e,"writeText"))try{yield e.navigator.clipboard.writeText(t)}catch(i){nT.consoleLogService.debug(`Error copying to clipboard using the clipboard API, attempting legacy method: ${i}`),this.useLegacyCopyMethod(e,t)}else this.useLegacyCopyMethod(e,t)})}static read(e){return rT(this,void 0,void 0,function*(){if(!nT.isClipboardApiSupported(e,"readText"))return this.useLegacyReadMethod(e);try{return yield e.navigator.clipboard.readText()}catch(t){return nT.consoleLogService.debug(`Error reading from clipboard using the clipboard API, attempting legacy method: ${t}`),this.useLegacyReadMethod(e)}})}static useLegacyCopyMethod(e,t){if(!nT.isLegacyClipboardMethodSupported(e,"copy"))return void nT.consoleLogService.warning("Legacy copy method not supported");const i=e.document.createElement("textarea");i.textContent=t||" ",i.style.position="fixed",e.document.body.appendChild(i),i.select();try{e.document.execCommand("copy")}catch(e){nT.consoleLogService.warning(`Error writing to clipboard: ${e}`)}finally{e.document.body.removeChild(i)}}static useLegacyReadMethod(e){if(!nT.isLegacyClipboardMethodSupported(e,"paste"))return nT.consoleLogService.warning("Legacy paste method not supported"),"";const t=e.document.createElement("textarea");t.style.position="fixed",e.document.body.appendChild(t),t.focus();try{return e.document.execCommand("paste")?t.value:""}catch(e){nT.consoleLogService.warning(`Error reading from clipboard: ${e}`)}finally{e.document.body.removeChild(t)}return""}static isClipboardApiSupported(e,t){return"clipboard"in e.navigator&&t in e.navigator.clipboard}static isLegacyClipboardMethodSupported(e,t){return"queryCommandSupported"in e.document&&e.document.queryCommandSupported(t)}}nT.consoleLogService=new r(!1);const aT=nT;var sT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class oT{constructor(e,t,i){this.clipboardWriteCallback=e,this.globalContext=t,this.offscreenDocumentService=i}static getDevice(e){return this.deviceCache||(oT.isFirefox()?this.deviceCache=Rd.FirefoxExtension:oT.isOpera(e)?this.deviceCache=Rd.OperaExtension:oT.isEdge()?this.deviceCache=Rd.EdgeExtension:oT.isVivaldi()?this.deviceCache=Rd.VivaldiExtension:oT.isChrome(e)?this.deviceCache=Rd.ChromeExtension:oT.isSafari(e)&&(this.deviceCache=Rd.SafariExtension)),this.deviceCache}getDevice(){return oT.getDevice(this.globalContext)}getDeviceString(){return Rd[this.getDevice()].toLowerCase().replace("extension","")}getClientType(){return Ku.Browser}static isFirefox(){return-1!==navigator.userAgent.indexOf(" Firefox/")||-1!==navigator.userAgent.indexOf(" Gecko/")}isFirefox(){return this.getDevice()===Rd.FirefoxExtension}static isChrome(e){return e.chrome&&-1!==navigator.userAgent.indexOf(" Chrome/")}isChrome(){return this.getDevice()===Rd.ChromeExtension}static isEdge(){return-1!==navigator.userAgent.indexOf(" Edg/")}isEdge(){return this.getDevice()===Rd.EdgeExtension}static isOpera(e){var t;return!!(null===(t=e.opr)||void 0===t?void 0:t.addons)||!!e.opera||navigator.userAgent.indexOf(" OPR/")>=0}isOpera(){return this.getDevice()===Rd.OperaExtension}static isVivaldi(){return-1!==navigator.userAgent.indexOf(" Vivaldi/")}isVivaldi(){return this.getDevice()===Rd.VivaldiExtension}static isSafari(e){return!oT.isOpera(e)&&-1!==navigator.userAgent.indexOf(" Safari/")}static safariVersion(){var e;return null===(e=navigator.userAgent.match("Version/([0-9.]*)"))||void 0===e?void 0:e[1]}isSafari(){return this.getDevice()===Rd.SafariExtension}isChromium(){return this.isChrome()||this.isEdge()||this.isOpera()||this.isVivaldi()}static shouldApplySafariHeightFix(e){var t;if(oT.getDevice(e)!==Rd.SafariExtension)return!1;const i=oT.safariVersion(),r=null===(t=null==i?void 0:i.split("."))||void 0===t?void 0:t.map(e=>Number(e));return(null==r?void 0:r[0])<16||16===(null==r?void 0:r[0])&&0===(null==r?void 0:r[1])}isIE(){return!1}isMacAppStore(){return!1}isPopupOpen(){return sT(this,void 0,void 0,function*(){return this.isSafari()?hT.isPopupOpen():new Promise((e,t)=>{chrome.runtime.sendMessage({command:"checkVaultPopupHeartbeat"},i=>{if(null!=chrome.runtime.lastError)return"Could not establish connection. Receiving end does not exist."===chrome.runtime.lastError.message?void e(!1):void t(chrome.runtime.lastError);e(Boolean(i))})})})}lockTimeout(){return null}launchUri(e,t){hT.createNewTab(e,t&&!0===t.extensionPage)}getApplicationVersion(){var e;const t=chrome.runtime.getManifest();return Promise.resolve(null!==(e=t.version_name)&&void 0!==e?e:t.version)}getApplicationVersionNumber(){const e=chrome.runtime.getManifest();return Promise.resolve(e.version.split(RegExp("[+|-]"))[0].trim())}supportsWebAuthn(e){return"undefined"!=typeof PublicKeyCredential}supportsDuo(){return!0}supportsAutofill(){return!0}supportsFileDownloads(){return!1}isDev(){return!1}isSelfHost(){return!1}copyToClipboard(e,t){const i=(null==t?void 0:t.window)||this.globalContext,r=Boolean(null==t?void 0:t.clearing),n=(null==t?void 0:t.clearMs)||null,a=()=>{r||null==this.clipboardWriteCallback||this.clipboardWriteCallback(e,n)};this.isSafari()?iT.sendMessageToApp("copyToClipboard",e).then(a):(this.isChrome()&&""===e&&(e="\0"),hT.isManifestVersion(3)&&this.offscreenDocumentService.offscreenApiSupported()?this.triggerOffscreenCopyToClipboard(e).then(a):aT.copy(i,e).then(a))}readFromClipboard(e){return sT(this,void 0,void 0,function*(){const t=(null==e?void 0:e.window)||this.globalContext;return this.isSafari()?yield iT.sendMessageToApp("readFromClipboard"):hT.isManifestVersion(3)&&this.offscreenDocumentService.offscreenApiSupported()?yield this.triggerOffscreenReadFromClipboard():yield aT.read(t)})}supportsSecureStorage(){return!1}getAutofillKeyboardShortcut(){return sT(this,void 0,void 0,function*(){let e;return this.isSafari()?e="Cmd+Shift+L":this.isFirefox()?(e=(yield browser.commands.getAll()).find(e=>e.name===Um).shortcut,"mac"===(yield browser.runtime.getPlatformInfo()).os&&"Ctrl+Shift+L"===e&&(e="Cmd+Shift+L")):yield new Promise(t=>chrome.commands.getAll(i=>t(e=i.find(e=>e.name===Um).shortcut))),e})}packageType(){return sT(this,void 0,void 0,function*(){switch(this.getDevice()){case Rd.ChromeExtension:return"Chrome Extension";case Rd.FirefoxExtension:return"Firefox Extension";case Rd.OperaExtension:return"Opera Extension";case Rd.EdgeExtension:return"Edge Extension";case Rd.VivaldiExtension:return"Vivaldi Extension";case Rd.SafariExtension:return"Safari Extension";default:return"Unknown Browser Extension"}})}triggerOffscreenCopyToClipboard(e){return sT(this,void 0,void 0,function*(){yield this.offscreenDocumentService.withDocument([chrome.offscreen.Reason.CLIPBOARD],"Write text to the clipboard.",()=>sT(this,void 0,void 0,function*(){yield hT.sendMessageWithResponse("offscreenCopyToClipboard",{text:e})}))})}triggerOffscreenReadFromClipboard(){return sT(this,void 0,void 0,function*(){const e=yield this.offscreenDocumentService.withDocument([chrome.offscreen.Reason.CLIPBOARD],"Read text from the clipboard.",()=>sT(this,void 0,void 0,function*(){return yield hT.sendMessageWithResponse("offscreenReadFromClipboard")}));return"string"==typeof e?e:""})}}oT.deviceCache=null;var lT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};let cT;function uT(e,t){return lT(this,void 0,void 0,function*(){return cT||(cT=function(){var e,t;const i=new r(!1),n=globalThis.chrome&&function e(t){return new Proxy(t,{get(t,i){if(t[i])return"function"!=typeof t[i]?e(t[i]):(...e)=>new Promise((r,n)=>{t[i](...e,e=>{chrome.runtime.lastError?n(new Error(chrome.runtime.lastError.message)):r(e)})})}})}(globalThis.chrome),a=/^(https?|wss?|file|ftp|\*):\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^file:\/\/\/.*$|^resource:\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^about:/,s=null===(e=globalThis.navigator)||void 0===e?void 0:e.userAgent.includes("Firefox/"),o=Boolean(null===(t=globalThis.chrome)||void 0===t?void 0:t.scripting),l="object"==typeof chrome&&"webNavigation"in chrome;function c(e){if(!function(e){return""===e||a.test(e)}(e))throw new Error(`${e} is an invalid pattern, it must match ${String(a)}`)}function u(...e){return 0===e.length?/$./:e.includes("")?/^(https?|file|ftp):[/]+/:e.includes("*://*/*")?s?/^(https?|wss?):[/][/][^/]+([/].*)?$/:/^https?:[/][/][^/]+([/].*)?$/:new RegExp(e.map(e=>function(e){c(e);let[,t,i="",r]=e.split(/(^[^:]+:[/][/])([^/]+)?/);return t=t.replace("*",s?"(https?|wss?)":"https?").replaceAll(/[/]/g,"[/]"),"*"===i?i="[^/]+":i&&(i=i.replace(/^[*][.]/,"([^/]+.)*").replaceAll(/[.]/g,"[.]").replace(/[*]$/,"[^.]+")),r=r.replaceAll(/[/]/g,"[/]").replaceAll(/[.]/g,"[.]").replaceAll(/[*]/g,".*"),"^"+t+i+"("+r+")?$"}(e)).join("|"))}function d(e){return Array.isArray(e)?e:[e]}function h(e,t,i){return void 0===t?{tabId:e,frameIds:void 0,allFrames:i}:{tabId:e,frameIds:[t],allFrames:void 0}}function p(e){return lT(this,arguments,void 0,function*({tabId:e,frameId:t,files:i,allFrames:r,matchAboutBlank:a,runAt:s},{ignoreTargetErrors:l}={}){const c=Promise.all(i.map(i=>lT(this,void 0,void 0,function*(){return"string"==typeof i&&(i={file:i}),o?"file"in i?chrome.scripting.insertCSS({target:h(e,t,r),files:[i.file]}):chrome.scripting.insertCSS({target:h(e,t,r),css:i.code}):n.tabs.insertCSS(e,Object.assign(Object.assign({},i),{matchAboutBlank:a,allFrames:r,frameId:t,runAt:null!=s?s:"document_start"}))})));l?yield f(c):yield c})}function m(e){return lT(this,arguments,void 0,function*({tabId:e,frameId:t,files:i,allFrames:r,matchAboutBlank:a,runAt:s},{ignoreTargetErrors:l}={}){const c=i.map(e=>"string"==typeof e?{file:e}:e);if(o){!function(e){if(e.some(e=>"code"in e))throw new Error("chrome.scripting does not support injecting strings of `code`")}(c);const i=chrome.scripting.executeScript({target:h(e,t,r),files:c.map(({file:e})=>e)});return void(l?yield f(i):yield i)}const u=[];for(const i of c)"code"in i&&(yield u.at(-1)),u.push(n.tabs.executeScript(e,Object.assign(Object.assign({},i),{matchAboutBlank:a,allFrames:r,frameId:t,runAt:s})));l?yield f(Promise.all(u)):yield Promise.all(u)})}function g(e,t){return lT(this,arguments,void 0,function*(e,t,i={}){const r=d(e);yield Promise.all(r.map(e=>lT(this,void 0,void 0,function*(){return function(e,t){return lT(this,arguments,void 0,function*({frameId:e,tabId:t,allFrames:i},r,n={}){const a=d(r).flatMap(r=>{var a,s,o,l,c,u;return[p({tabId:t,frameId:e,allFrames:i,files:null!==(a=r.css)&&void 0!==a?a:[],matchAboutBlank:null!==(s=r.matchAboutBlank)&&void 0!==s?s:r.match_about_blank,runAt:null!==(o=r.runAt)&&void 0!==o?o:r.run_at},n),m({tabId:t,frameId:e,allFrames:i,files:null!==(l=r.js)&&void 0!==l?l:[],matchAboutBlank:null!==(c=r.matchAboutBlank)&&void 0!==c?c:r.match_about_blank,runAt:null!==(u=r.runAt)&&void 0!==u?u:r.run_at},n)]});yield Promise.all(a)})}(function(e){return"object"==typeof e?Object.assign(Object.assign({},e),{allFrames:!1}):{tabId:e,frameId:void 0,allFrames:!0}}(e),t,i)})))})}function f(e){return lT(this,void 0,void 0,function*(){try{yield e}catch(e){if(!/^No frame with id \d+ in tab \d+.$|^No tab with id: \d+.$|^The tab was closed.$|^The frame was removed.$/.test(null==e?void 0:e.message))throw e}})}return(e,t)=>lT(this,void 0,void 0,function*(){const{js:r=[],css:a=[],matchAboutBlank:s,matches:o=[],excludeMatches:c,runAt:d}=e;let{allFrames:h}=e;if(l?h=!1:h&&i.warning("`allFrames: true` requires the `webNavigation` permission to work correctly: https://github.com/fregante/content-scripts-register-polyfill#permissions"),0===o.length)throw new Error("Type error for parameter contentScriptOptions (Error processing matches: Array requires at least 1 items; you have 0) for contentScripts.register.");yield Promise.all(o.map(e=>lT(this,void 0,void 0,function*(){if(!(yield n.permissions.contains({origins:[e]})))throw new Error(`Permission denied to register a content script for ${e}`)})));const p=u(...o),m=u(...null!=c?c:[]),f=(e,t,...i)=>lT(this,[e,t,...i],void 0,function*(e,t,i=0){p.test(e)&&!m.test(e)&&(yield function(e){return lT(this,void 0,void 0,function*(){return n.permissions.contains({origins:[new URL(e).origin+"/*"]})})}(e))&&(yield g({tabId:t,frameId:i},{css:a,js:r,matchAboutBlank:s,runAt:d},{ignoreTargetErrors:!0}))}),y=(e,t,i)=>lT(this,[e,t,i],void 0,function*(e,{status:t},{url:i}){"loading"===t&&i&&f(i,e)}),v=e=>lT(this,[e],void 0,function*({tabId:e,frameId:t,url:i}){f(i,e,t)});l?hT.addListener(chrome.webNavigation.onCommitted,v):hT.addListener(chrome.tabs.onUpdated,y);const b={unregister(){return lT(this,void 0,void 0,function*(){l?chrome.webNavigation.onCommitted.removeListener(v):chrome.tabs.onUpdated.removeListener(y)})}};return"function"==typeof t&&t(b),b})}()),cT(e,t)})}var dT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class hT{static get manifestVersion(){return chrome.runtime.getManifest().manifest_version}static isManifestVersion(e){return hT.manifestVersion===e}static senderIsInternal(e,t){var i;if(!(null==e?void 0:e.origin))return null==t||t.warning("[BrowserApi] Message sender has no origin"),!1;const r=null!==(i=hT.getRuntimeURL(""))&&void 0!==i?i:"";return r?function(e,t){const i=eT(e),r=eT(t);if(!i||!r)return!1;const n=tT(i),a=tT(r),s=null==n?void 0:n.replace(/\/$/,"").toLowerCase(),o=null==a?void 0:a.replace(/\/$/,"").toLowerCase();return!(!s||!o)&&s===o}(r,e.origin)?"frameId"in e&&0!==e.frameId?(null==t||t.warning("[BrowserApi] Message sender is not from the top-level frame"),!1):(null==t||t.info("[BrowserApi] Message sender appears to be internal"),!0):(null==t||t.warning(`[BrowserApi] Message sender origin (${e.origin}) does not match extension URL (${r})`),!1):(null==t||t.warning("[BrowserApi] Unable to determine extension URL"),!1)}static getWindows(){return dT(this,void 0,void 0,function*(){return new Promise(e=>chrome.windows.getAll({populate:!0},e))})}static getWindow(e){return dT(this,void 0,void 0,function*(){return e?yield hT.getWindowById(e):hT.getCurrentWindow()})}static getCurrentWindow(){return dT(this,void 0,void 0,function*(){return new Promise(e=>chrome.windows.getCurrent({populate:!0},e))})}static getWindowById(e){return dT(this,void 0,void 0,function*(){return new Promise(t=>chrome.windows.get(e,{populate:!0},t))})}static createWindow(e){return dT(this,void 0,void 0,function*(){return new Promise(t=>{chrome.windows.create(e,e=>dT(this,void 0,void 0,function*(){if(!hT.isSafariApi)return t(e);const i=yield new Promise(e=>{chrome.windows.getAll({windowTypes:["normal"]},t=>e(t))}),r=i.find(t=>t.id!==e.id);if(null==r||!r.id)return t(e);chrome.windows.update(r.id,{focused:!0},()=>{chrome.windows.update(e.id,{focused:!0},()=>{t(e)})})}))})})}static removeWindow(e){return dT(this,void 0,void 0,function*(){return new Promise(t=>chrome.windows.remove(e,()=>t()))})}static updateWindowProperties(e,t){return dT(this,void 0,void 0,function*(){return new Promise(i=>chrome.windows.update(e,t,()=>{i()}))})}static focusWindow(e){return dT(this,void 0,void 0,function*(){yield hT.updateWindowProperties(e,{focused:!0})})}static getTabFromCurrentWindowId(){return dT(this,void 0,void 0,function*(){return yield hT.tabsQueryFirstCurrentWindowForSafari({active:!0,windowId:chrome.windows.WINDOW_ID_CURRENT})})}static getBrowserClientVendor(e){switch(oT.getDevice(e)){case Rd.ChromeExtension:case Rd.ChromeBrowser:return"Chrome";case Rd.OperaExtension:case Rd.OperaBrowser:return"Opera";case Rd.EdgeExtension:case Rd.EdgeBrowser:return"Edge";case Rd.VivaldiExtension:case Rd.VivaldiBrowser:return"Vivaldi";default:return"Unknown"}}static getTab(e){return dT(this,void 0,void 0,function*(){return e?hT.isManifestVersion(3)?yield chrome.tabs.get(e):new Promise(t=>chrome.tabs.get(e,e=>{t(e)})):null})}static getTabFromCurrentWindow(){return dT(this,void 0,void 0,function*(){return yield hT.tabsQueryFirstCurrentWindowForSafari({active:!0,currentWindow:!0})})}static getActiveTabs(){return dT(this,void 0,void 0,function*(){return yield hT.tabsQuery({active:!0})})}static getCurrentTab(){return dT(this,void 0,void 0,function*(){return hT.isManifestVersion(3)?yield chrome.tabs.getCurrent():new Promise(e=>chrome.tabs.getCurrent(t=>{e(t)}))})}static closeTab(e){return dT(this,void 0,void 0,function*(){e&&(hT.isWebExtensionsApi?yield browser.tabs.remove(e).catch(e=>{throw new Error("[BrowserApi] Failed to remove current tab: "+e.message)}):hT.isChromeApi&&(yield chrome.tabs.remove(e).catch(e=>{throw new Error("[BrowserApi] Failed to remove current tab: "+e.message)})))})}static navigateTabToUrl(e,t){return dT(this,void 0,void 0,function*(){e&&(hT.isWebExtensionsApi?yield browser.tabs.update(e,{url:t.href}).catch(e=>{throw new Error("Failed to navigate tab to URL: "+e.message)}):hT.isChromeApi&&chrome.tabs.update(e,{url:t.href},()=>{if(chrome.runtime.lastError)throw new Error("Failed to navigate tab to URL: "+chrome.runtime.lastError.message)}))})}static tabsQuery(e){return dT(this,void 0,void 0,function*(){return new Promise(t=>{chrome.tabs.query(e,e=>{t(e)})})})}static tabsQueryFirst(e){return dT(this,void 0,void 0,function*(){const t=yield hT.tabsQuery(e);return t.length>0?t[0]:null})}static tabsQueryFirstCurrentWindowForSafari(e){return dT(this,void 0,void 0,function*(){var t;if(!hT.isSafariApi)return yield hT.tabsQueryFirst(e);const i=(yield hT.getCurrentWindow()).id,r=yield hT.tabsQuery(e);return r.length<=1||null==i?r[0]:null!==(t=r.find(e=>e.windowId===i))&&void 0!==t?t:r[0]})}static tabSendMessageData(e,t,i=null){const r={command:t};return null!=i&&(r.data=i),hT.tabSendMessage(e,r)}static tabSendMessage(e,t){return dT(this,arguments,void 0,function*(e,t,i=null,r=!1){if(e&&e.id)return new Promise((n,a)=>{chrome.tabs.sendMessage(e.id,t,i,e=>{chrome.runtime.lastError&&r&&a(),n(e)})})})}static sendTabsMessage(e,t,i,r){chrome.tabs.sendMessage(e,t,i,r)}static getRuntimeURL(e){return hT.isWebExtensionsApi?browser.runtime.getURL(e):hT.isChromeApi?chrome.runtime.getURL(e):void 0}static onWindowCreated(e){return dT(this,void 0,void 0,function*(){return chrome.windows.onCreated.addListener(e)})}static getBackgroundPage(){return void 0===chrome.extension.getBackgroundPage?null:chrome.extension.getBackgroundPage()}static isBackgroundPage(e){return void 0!==e&&e===hT.getBackgroundPage()}static getExtensionViews(e){return void 0===chrome.extension.getViews?[]:chrome.extension.getViews(e)}static isPopupOpen(){return dT(this,void 0,void 0,function*(){return Promise.resolve(hT.getExtensionViews({type:"popup"}).length>0)})}static createNewTab(e,t=!0){return new Promise(i=>chrome.tabs.create({url:e,active:t},e=>i(e)))}static getFrameDetails(e){return dT(this,void 0,void 0,function*(){return new Promise(t=>chrome.webNavigation.getFrame(e,t))})}static getAllFrameDetails(e){return dT(this,void 0,void 0,function*(){return new Promise(t=>chrome.webNavigation.getAllFrames({tabId:e},t))})}static messageListener(e,t){hT.addListener(chrome.runtime.onMessage,t)}static messageListener$(){return new $(e=>{const t=t=>{e.next(t)};return hT.addListener(chrome.runtime.onMessage,t),()=>hT.removeListener(chrome.runtime.onMessage,t)})}static storageChangeListener(e){hT.addListener(chrome.storage.onChanged,e)}static addListener(e,t){e.addListener(t),hT.isSafariApi&&!hT.isBackgroundPage(self)&&(hT.trackedChromeEventListeners.push([e,t]),hT.setupUnloadListeners())}static removeListener(e,t){if(e.removeListener(t),hT.isSafariApi&&!hT.isBackgroundPage(self)){const e=hT.trackedChromeEventListeners.findIndex(([e,i])=>i==t);-1!==e&&hT.trackedChromeEventListeners.splice(e,1)}}static setupUnloadListeners(){self.addEventListener("pagehide",()=>{for(const[e,t]of hT.trackedChromeEventListeners)e.removeListener(t)})}static sendMessage(e,t={}){const i=Object.assign({},{command:e},t);return chrome.runtime.sendMessage(i)}static sendMessageWithResponse(e,t={}){const i=Object.assign({},{command:e},t);return new Promise(e=>chrome.runtime.sendMessage(i,e))}static focusTab(e){return dT(this,void 0,void 0,function*(){chrome.tabs.update(e,{active:!0,highlighted:!0})})}static closePopup(e){hT.isWebExtensionsApi&&hT.isFirefoxOnAndroid?browser.tabs.update({active:!0}).finally(e.close):e.close()}static gaFilter(){return!1}static getUILanguage(){return chrome.i18n.getUILanguage()}static reloadExtension(){return this.isSafariApi?self.location.reload():chrome.runtime.reload()}static reloadOpenWindows(e=!1){const t=hT.getExtensionViews();if(!t.length)return;const i=self.location.href;t.filter(e=>null!=e.location.href&&!e.location.href.includes("background.html")).filter(t=>!e||t.location.href!==i).forEach(e=>e.location.reload())}static connectNative(e){return hT.isWebExtensionsApi?browser.runtime.connectNative(e):hT.isChromeApi?chrome.runtime.connectNative(e):void 0}static requestPermission(e){return hT.isWebExtensionsApi?browser.permissions.request(e):new Promise(t=>{chrome.permissions.request(e,t)})}static permissionsGranted(e){return dT(this,void 0,void 0,function*(){return new Promise(t=>chrome.permissions.contains({permissions:e},e=>t(e)))})}static getPlatformInfo(){return hT.isWebExtensionsApi?browser.runtime.getPlatformInfo():new Promise(e=>{chrome.runtime.getPlatformInfo(e)})}static getBrowserAction(){return hT.isManifestVersion(3)?chrome.action:chrome.browserAction}static getSidebarAction(e){var t;const i=oT.getDevice(e);return i===Rd.FirefoxExtension?browser.sidebarAction:i===Rd.OperaExtension?null===(t=e.opr)||void 0===t?void 0:t.sidebarAction:null}static captureVisibleTab(){return new Promise(e=>{chrome.tabs.captureVisibleTab(null,{format:"png"},e)})}static executeScriptInTab(e,t,i){if(hT.isManifestVersion(3)){let r;return r="number"==typeof t.frameId?{tabId:e,frameIds:[t.frameId]}:t.allFrames?{tabId:e,allFrames:!0}:{tabId:e},chrome.scripting.executeScript({target:r,files:t.file?[t.file]:null,injectImmediately:"document_start"===t.runAt,world:(null==i?void 0:i.world)||chrome.scripting.ExecutionWorld.ISOLATED})}return new Promise(i=>{chrome.tabs.executeScript(e,t,e=>{i(e)})})}static browserAutofillSettingsOverridden(){return dT(this,void 0,void 0,function*(){if(!(yield hT.permissionsGranted(["privacy"])))return!1;const e=e=>"controlled_by_this_extension"===e.levelOfControl&&!e.value,t=yield new Promise(t=>chrome.privacy.services.autofillAddressEnabled.get({},i=>t(e(i)))),i=yield new Promise(t=>chrome.privacy.services.autofillCreditCardEnabled.get({},i=>t(e(i)))),r=yield new Promise(t=>chrome.privacy.services.passwordSavingEnabled.get({},i=>t(e(i))));return t&&i&&r})}static updateDefaultBrowserAutofillSettings(e){return dT(this,void 0,void 0,function*(){yield chrome.privacy.services.autofillAddressEnabled.set({value:e}),yield chrome.privacy.services.autofillCreditCardEnabled.set({value:e}),yield chrome.privacy.services.passwordSavingEnabled.set({value:e})})}static registerContentScriptsMv2(e){return dT(this,void 0,void 0,function*(){var t;return"undefined"!=typeof browser&&(null===(t=browser.contentScripts)||void 0===t?void 0:t.register)?yield browser.contentScripts.register(e):yield uT(e)})}static registerContentScriptsMv3(e){return dT(this,void 0,void 0,function*(){yield chrome.scripting.registerContentScripts(e)})}static unregisterContentScriptsMv3(e){return dT(this,void 0,void 0,function*(){yield chrome.scripting.unregisterContentScripts(e)})}}hT.isWebExtensionsApi="undefined"!=typeof browser,hT.isSafariApi=-1!==navigator.userAgent.indexOf(" Safari/")&&-1===navigator.userAgent.indexOf(" Chrome/")&&-1===navigator.userAgent.indexOf(" Chromium/"),hT.isChromeApi=!hT.isSafariApi&&"undefined"!=typeof chrome,hT.isFirefoxOnAndroid=-1!==navigator.userAgent.indexOf("Firefox/")&&-1!==navigator.userAgent.indexOf("Android"),hT.trackedChromeEventListeners=[];var pT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class mT{constructor(e,t,i,r,n,a,s){this.logService=e,this.autofillService=t,this.scriptInjectorService=i,this.authService=r,this.platformUtilsService=n,this.policyService=a,this.accountService=s,this.validIdpHosts=new Set,this.validAutoSubmitHosts=new Set,this.mostRecentIdpHost={},this.currentAutoSubmitHostData={},this.isSafariBrowser=!1,this.extensionMessageHandlers={triggerAutoSubmitLogin:({message:e,sender:t})=>this.triggerAutoSubmitLogin(e,t),multiStepAutoSubmitLoginComplete:({sender:e})=>this.handleMultiStepAutoSubmitLoginComplete(e)},this.handleAutoSubmitLoginPolicySubscription=e=>{(null==e?void 0:e.enabled)?this.applyPolicyToActiveUser(e).catch(e=>this.logService.error(e)):this.destroy()},this.applyPolicyToActiveUser=e=>pT(this,void 0,void 0,function*(){(yield Ce(this.accountService.activeAccount$.pipe(tu,Le(e=>this.policyService.policyAppliesToUser$(Ye.AutomaticAppLogIn,e)))))?yield this.setupAutoSubmitLoginListeners(e):this.destroy()}),this.setupAutoSubmitLoginListeners=e=>pT(this,void 0,void 0,function*(){this.parseIpdHostsFromPolicy(null==e?void 0:e.data.idpHost),this.validIdpHosts.size?(hT.addListener(chrome.runtime.onMessage,this.handleExtensionMessage),chrome.webRequest.onBeforeRequest.addListener(this.handleOnBeforeRequest,{urls:[""],types:["main_frame","sub_frame"]}),chrome.webRequest.onBeforeRedirect.addListener(this.handleWebRequestOnBeforeRedirect,{urls:[""],types:["main_frame","sub_frame"]}),this.isSafariBrowser&&this.initSafari().catch(e=>this.logService.error(e))):this.destroy()}),this.parseIpdHostsFromPolicy=e=>{e&&e.split(",").forEach(e=>{const t=this.getUrlHost(null==e?void 0:e.trim());t&&this.validIdpHosts.add(t)})},this.handleOnBeforeRequest=e=>{const t=this.getRequestInitiator(e);if(!t&&0===this.validAutoSubmitHosts.size)return;const i=!!t&&this.isValidInitiator(t);this.postRequestEncounteredAfterSubmission(e,i)||this.requestRedirectsToInvalidHost(e,i)?this.clearAutoSubmitHostData():t&&i&&this.shouldRouteTriggerAutoSubmit(e,t)?this.setupAutoSubmitFlow(e):(t||this.validAutoSubmitHosts.size>0)&&this.disableAutoSubmitFlow(t||"",e).catch(e=>this.logService.error(e))},this.postRequestEncounteredAfterSubmission=(e,t)=>"POST"===e.method&&this.validAutoSubmitHosts.size>0&&t,this.requestRedirectsToInvalidHost=(e,t)=>this.validAutoSubmitHosts.size>0&&this.isRequestInMainFrame(e)&&(!t||!this.isValidAutoSubmitHost(e.url)),this.setupAutoSubmitFlow=e=>{this.isRequestInMainFrame(e)&&(this.currentAutoSubmitHostData={url:e.url,tabId:e.tabId});const t=this.getUrlHost(e.url);this.validAutoSubmitHosts.add(t),chrome.webNavigation.onCompleted.removeListener(this.handleAutoSubmitHostNavigationCompleted),chrome.webNavigation.onCompleted.addListener(this.handleAutoSubmitHostNavigationCompleted,{url:[{hostEquals:t}]})},this.handleAutoSubmitHostNavigationCompleted=e=>{e.tabId===this.currentAutoSubmitHostData.tabId&&this.urlContainsAutoSubmitHash(e.url)&&(this.injectAutoSubmitLoginScript(e.tabId).catch(e=>this.logService.error(e)),chrome.webNavigation.onCompleted.removeListener(this.handleAutoSubmitHostNavigationCompleted))},this.injectAutoSubmitLoginScript=e=>pT(this,void 0,void 0,function*(){(yield this.getAuthStatus())===cu.Unlocked&&(yield this.scriptInjectorService.inject({tabId:e,injectDetails:{file:"content/auto-submit-login.js",runAt:"document_start",frame:"all_frames"}}))}),this.getAuthStatus=()=>pT(this,void 0,void 0,function*(){return Ce(this.authService.activeAccountStatus$)}),this.handleWebRequestOnBeforeRedirect=e=>{this.isRequestInMainFrame(e)&&this.urlContainsAutoSubmitHash(e.redirectUrl)&&(this.validAutoSubmitHosts.add(this.getUrlHost(e.redirectUrl)),this.validAutoSubmitHosts.add(this.getUrlHost(e.url)))},this.isValidInitiator=e=>this.isValidIdpHost(e)||this.isValidAutoSubmitHost(e),this.isValidIdpHost=e=>{const t=this.getUrlHost(e);return!!t&&this.validIdpHosts.has(t)},this.isValidAutoSubmitHost=e=>{const t=this.getUrlHost(e);return!!t&&this.validAutoSubmitHosts.has(t)},this.removeUrlFromAutoSubmitHosts=e=>{this.validAutoSubmitHosts.delete(this.getUrlHost(e))},this.disableAutoSubmitFlow=(e,t)=>pT(this,void 0,void 0,function*(){if(this.isValidAutoSubmitHost(e))return void this.removeUrlFromAutoSubmitHosts(e);if(t.tabId<0)return;const i=yield hT.getTab(t.tabId),r=null==i?void 0:i.url;r&&this.isValidAutoSubmitHost(r)&&this.removeUrlFromAutoSubmitHosts(r)}),this.clearAutoSubmitHostData=()=>{this.validAutoSubmitHosts.clear(),this.currentAutoSubmitHostData={},this.mostRecentIdpHost={}},this.shouldRouteTriggerAutoSubmit=(e,t)=>this.isRequestInMainFrame(e)?!(!this.urlContainsAutoSubmitHash(e.url)&&!this.triggerAutoSubmitAfterRedirectOnSafari(e.url)):this.isValidAutoSubmitHost(t),this.urlContainsAutoSubmitHash=e=>{try{return-1!==new URL(e).hash.indexOf("autosubmit=1")}catch(e){return!1}},this.getUrlHost=e=>{let t=e;if(!t||"string"!=typeof t)return"";t.startsWith("http")||(t=`https://${t}`);try{return new URL(t).host}catch(e){return""}},this.getRequestInitiator=e=>this.isSafariBrowser?this.isRequestInMainFrame(e)?this.mostRecentIdpHost.url:this.mostRecentIdpHost.url?e.url:"":e.initiator||e.originUrl,this.isRequestInMainFrame=e=>this.isSafariBrowser?0===e.frameId:"main_frame"===e.type,this.triggerAutoSubmitLogin=(e,t)=>pT(this,void 0,void 0,function*(){null!=t.frameId&&t.tab&&e.pageDetails&&(yield this.autofillService.doAutoFillOnTab([{frameId:t.frameId,tab:t.tab,details:e.pageDetails}],t.tab,!0,!0))}),this.handleMultiStepAutoSubmitLoginComplete=e=>{e.url&&this.removeUrlFromAutoSubmitHosts(e.url)},this.handleSafariTabOnActivated=e=>pT(this,void 0,void 0,function*(){if(e.tabId<0)return;const t=yield hT.getTab(e.tabId);(null==t?void 0:t.url)&&null!=t.id&&t.id>=0&&this.setMostRecentIdpHost(t.url,t.id)}),this.handleSafariTabOnUpdated=(e,t)=>{t.url&&this.setMostRecentIdpHost(t.url,e)},this.handleSafariWebNavigationOnCompleted=e=>{0===e.frameId&&this.isValidIdpHost(e.url)&&(this.validAutoSubmitHosts.clear(),this.mostRecentIdpHost={url:e.url,tabId:e.tabId},chrome.tabs.onRemoved.addListener(this.handleSafariTabOnRemoved))},this.handleSafariTabOnRemoved=e=>{this.currentAutoSubmitHostData.tabId===e&&(this.clearAutoSubmitHostData(),chrome.tabs.onRemoved.removeListener(this.handleSafariTabOnRemoved))},this.triggerAutoSubmitAfterRedirectOnSafari=e=>this.isSafariBrowser&&this.isValidAutoSubmitHost(e),this.handleExtensionMessage=(e,t,i)=>{const{tab:r,url:n}=t;if(!n||(null==r?void 0:r.id)!==this.currentAutoSubmitHostData.tabId||!this.isValidAutoSubmitHost(n))return null;const a=this.extensionMessageHandlers[null==e?void 0:e.command];if(!a)return null;const s=a({message:e,sender:t});return void 0===s?null:(Promise.resolve(s).then(e=>i(e)).catch(e=>this.logService.error(e)),!0)},this.isSafariBrowser=this.platformUtilsService.isSafari()}init(){return pT(this,void 0,void 0,function*(){this.authService.activeAccountStatus$.pipe(Le(e=>e===cu.Unlocked?this.accountService.activeAccount$:bt(null)),Ie(e=>null!==e),tu,Le(e=>this.policyService.policiesByType$(Ye.AutomaticAppLogIn,e)),ad,Ie(e=>void 0!==e)).subscribe(this.handleAutoSubmitLoginPolicySubscription.bind(this))})}initSafari(){return pT(this,void 0,void 0,function*(){const e=yield hT.getTabFromCurrentWindow();(null==e?void 0:e.url)&&null!=e.id&&e.id>=0&&this.setMostRecentIdpHost(e.url,e.id),chrome.tabs.onActivated.addListener(this.handleSafariTabOnActivated),chrome.tabs.onUpdated.addListener(this.handleSafariTabOnUpdated),chrome.webNavigation.onCompleted.addListener(this.handleSafariWebNavigationOnCompleted)})}setMostRecentIdpHost(e,t){this.isValidIdpHost(e)&&(this.mostRecentIdpHost={url:e,tabId:t})}destroy(){hT.removeListener(chrome.runtime.onMessage,this.handleExtensionMessage),chrome.webRequest.onBeforeRequest.removeListener(this.handleOnBeforeRequest),chrome.webRequest.onBeforeRedirect.removeListener(this.handleWebRequestOnBeforeRedirect),chrome.webNavigation.onCompleted.removeListener(this.handleAutoSubmitHostNavigationCompleted),chrome.webNavigation.onCompleted.removeListener(this.handleSafariWebNavigationOnCompleted),chrome.tabs.onActivated.removeListener(this.handleSafariTabOnActivated),chrome.tabs.onUpdated.removeListener(this.handleSafariTabOnUpdated),chrome.tabs.onRemoved.removeListener(this.handleSafariTabOnRemoved)}}class gT{constructor(e){this.contextMenuClickedHandler=e,this.contextMenus=chrome.contextMenus}init(){this.contextMenus&&(this.contextMenus.onClicked.addListener((e,t)=>{if(t)return this.contextMenuClickedHandler.run(e,t)}),hT.messageListener("contextmenus.background",(e,t)=>{if("unlockCompleted"===e.command&&"contextmenus.background"===e.data.target){const i=e.data.commandToRetry.message.contextMenuOnClickData,r=e.data.commandToRetry.sender.tab;i&&r&&this.contextMenuClickedHandler.cipherAction(i,r).then(()=>{t.tab&&hT.tabSendMessageData(t.tab,"closeNotificationBar")})}}))}}const fT="openAtRiskPasswords";function yT(e,t,i){let r="bwi-globe",n=null,a="";const s={Visa:"card-visa",Mastercard:"card-mastercard",Amex:"card-amex",Discover:"card-discover","Diners Club":"card-diners-club",JCB:"card-jcb",Maestro:"card-maestro",UnionPay:"card-union-pay",RuPay:"card-ru-pay"};null==e&&(i=!1);const o=vC.getType(t),l=vC.uri(t),c=vC.getCard(t);switch(o){case rm.Login:if(r="bwi-globe",l){let t=l,r=!1;if(0===t.indexOf("androidapp://")||0===t.indexOf("iosapp://")?n=null:i&&-1===t.indexOf("://")&&t.indexOf(".")>-1?(t=`http://${t}`,r=!0):i&&(r=0===t.indexOf("http")&&t.indexOf(".")>-1),r&&(t.endsWith(".onion")||t.endsWith(".i2p"))){n=null,a="images/bwi-globe.png";break}if(i&&r)try{n=`${e}/${Tt.getHostname(t)}/icon.png`,a="images/bwi-globe.png"}catch(e){}}else n=null;break;case rm.SecureNote:r="bwi-sticky-note";break;case rm.Card:r="bwi-credit-card",i&&(null==c?void 0:c.brand)&&c.brand in s&&(r=`credit-card-icon ${s[c.brand]}`);break;case rm.Identity:r="bwi-id-card";break;case rm.SshKey:r="bwi-key"}return{imageEnabled:i,image:n,fallbackImage:a,icon:r}}var vT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const bT=Object.freeze({default:480,wide:600,narrow:380});class wT{static inSidebar(e){return wT.urlContainsSearchParams(e,"uilocation","sidebar")}static inPopout(e){return wT.urlContainsSearchParams(e,"uilocation","popout")}static isInTab(){return vT(this,void 0,void 0,function*(){var e;const t=null===(e=yield hT.getCurrentTab())||void 0===e?void 0:e.id;return null!=t&&hT.getExtensionViews({tabId:t,type:"tab"}).length>0})}static inSingleActionPopout(e,t){return wT.urlContainsSearchParams(e,"singleActionPopout",t)}static inPopup(e){return-1===e.location.href.indexOf("uilocation=")||e.location.href.indexOf("uilocation=popup")>-1}static getContentScrollY(e,t="main"){return e.document.getElementsByTagName(t)[0].scrollTop}static setContentScrollY(e,t){return vT(this,arguments,void 0,function*(e,t,i={delay:0,containerSelector:"main"}){const{delay:r,containerSelector:n}=i;return new Promise(i=>e.setTimeout(()=>{const r=e.document.querySelector(n);!isNaN(t)&&r&&(r.scrollTop=t),i()},r))})}static backgroundInitializationRequired(){return!hT.getBackgroundPage()||hT.isManifestVersion(3)}static openPopout(e){return vT(this,arguments,void 0,function*(e,t={}){const{senderWindowId:i,singleActionKey:r,forceCloseExistingWindows:n,windowOptions:a}=t,s={type:"popup",focused:!0,width:Math.max(bT.default,"undefined"==typeof document?bT.default:document.body.clientWidth),height:630},o=s.width,l=yield hT.getWindow(i),c=Object.assign(Object.assign(Object.assign({left:l.left+l.width-o-15,top:l.top+90},s),a),{url:wT.buildPopoutUrl(e,r)});if(!(yield wT.isSingleActionPopoutOpen(r,c,n))||n)return yield hT.createWindow(c)})}static closeSingleActionPopout(e){return vT(this,arguments,void 0,function*(e,t=0){const i=chrome.runtime.getURL("popup/index.html"),r=yield hT.tabsQuery({url:`${i}*`});for(const i of r)i.url.includes(`singleActionPopout=${e}`)&&setTimeout(()=>hT.removeWindow(i.windowId),t)})}static openCurrentPagePopout(e){return vT(this,arguments,void 0,function*(e,t=null){const i=t||e.location.href,r=new URL(i);let n=r.hash;n.startsWith("#/tabs/current")&&(n="#/tabs/vault"),yield wT.openPopout(`${r.pathname}${n}`),wT.inPopup(e)&&hT.closePopup(e)})}static waitForAllPopupsClose(){return vT(this,arguments,void 0,function*(e=1e3){var t,i;yield Ce((t=100,void 0===t&&(t=0),void 0===i&&(i=Te),t<0&&(t=0),sc(t,t,i)).pipe(Le(()=>hT.isPopupOpen()),nk(e=>e,!0),Ie(e=>!e),Fe({first:e,with:()=>bt(!0)})))})}static isSingleActionPopoutOpen(e,t){return vT(this,arguments,void 0,function*(e,t,i=!1){if(!e)return!1;const r=chrome.runtime.getURL("popup/index.html"),n=(yield hT.tabsQuery({url:`${r}*`})).filter(t=>t.url.includes(`singleActionPopout=${e}`));if(0===n.length)return!1;if(!i){const e=n.shift();yield hT.updateWindowProperties(e.windowId,{focused:!0,width:t.width,height:t.height,top:t.top,left:t.left})}return n.forEach(e=>hT.removeWindow(e.windowId)),!0})}static urlContainsSearchParams(e,t,i){return e.location.href.indexOf(`${t}=${i}`)>-1}static buildPopoutUrl(e,t){const i=new URL(chrome.runtime.getURL(e));return i.searchParams.set("uilocation","popout"),t&&i.searchParams.set("singleActionPopout",t),i.toString()}}var kT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ST="auth_unlockExtension",_T=new Set([chrome.runtime.getURL("popup/index.html#/lock"),chrome.runtime.getURL("popup/index.html#/login")]);function xT(e){return kT(this,void 0,void 0,function*(){(yield hT.tabsQuery({windowType:"popup"})).forEach(e=>{_T.has(e.url)&&hT.removeWindow(e.windowId)}),yield wT.openPopout("popup/index.html",{singleActionKey:ST,senderWindowId:e.windowId}),yield hT.tabSendMessageData(e,"bgUnlockPopoutOpened",{})})}var CT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const IT="vault_Fido2Popout";function ET(e,t){return CT(this,void 0,void 0,function*(){const{cipherId:i,action:r,forceCloseExistingWindows:n}=t;let a="popup/index.html#/view-cipher",s="?";const o=(e,t)=>{const i=`${s}${e}=${t}`;return s="&",i};i&&(a+=o("cipherId",i)),e.id&&(a+=o("senderTabId",String(e.id))),r&&(a+=o("action",r)),yield wT.openPopout(a,{singleActionKey:`vault_viewVaultItem_${i}`,senderWindowId:e.windowId,forceCloseExistingWindows:n})})}function zT(e,t){return CT(this,void 0,void 0,function*(){yield ET(e,Object.assign({forceCloseExistingWindows:!0},t)),yield hT.tabSendMessageData(e,"bgVaultItemRepromptPopoutOpened")})}function PT(e){return CT(this,arguments,void 0,function*(e,t={}){const{cipherId:i,cipherType:r}=t,{url:n,windowId:a}=e;let s="vault_AddEditVaultItem",o="popup/index.html#/edit-cipher",l="?";const c=(e,t)=>{const i=`${l}${e}=${t}`;return l="&",i};i&&!r&&(s+=`_${i}`,o+=c("cipherId",i)),r&&!i&&(s+=`_${r}`,o+=c("type",String(r))),e.url&&(o+=c("uri",n));const u=chrome.runtime.getURL("popup/index.html"),d=(yield hT.tabsQuery({url:`${u}*`})).find(e=>{var t;return null===(t=e.url)||void 0===t?void 0:t.includes(`singleActionPopout=${s}`)});try{yield chrome.runtime.sendMessage({command:"reloadAddEditCipherData",data:{cipherId:i,cipherType:r}}),yield hT.updateWindowProperties(d.windowId,{focused:!0})}catch(e){yield wT.openPopout(o,{singleActionKey:s,senderWindowId:a})}})}const AT="add",jT="change";var TT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class DT{getChangePasswordUrl(e){return TT(this,arguments,void 0,function*(e,t=!1){if(e.type!==rm.Login||null==e.login||!e.login.hasUris)return null;const i=e.login.uris.map(e=>Tt.getUrl(e.uri)).filter(e=>null!=e&&("http:"===e.protocol||"https:"===e.protocol));if(0===i.length)return null;for(const e of i){const[t,i]=yield Promise.all([this.hasReliableHttpStatusCode(e.origin),this.getWellKnownChangePasswordUrl(e.origin)]);if(t&&null!=i)return i}return t?i[0].href:null})}hasReliableHttpStatusCode(e){return TT(this,void 0,void 0,function*(){try{const t=new URL("./.well-known/resource-that-should-not-exist-whose-status-code-should-not-be-200",e),i=new Request(t,{method:"GET",mode:"same-origin",credentials:"omit",cache:"no-store",redirect:"follow"});return!(yield fetch(i)).ok}catch(e){return!1}})}getWellKnownChangePasswordUrl(e){return TT(this,void 0,void 0,function*(){try{const t=new URL("./.well-known/change-password",e),i=new Request(t,{method:"GET",mode:"same-origin",credentials:"omit",cache:"no-store",redirect:"follow"});return(yield fetch(i)).ok?t.toString():null}catch(e){return null}})}}var OT=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const NT={usernamePasswordNewPassword:"usernamePasswordNewPassword",usernameNewPassword:"usernameNewPassword",usernamePassword:"usernamePassword",username:"username",passwordNewPassword:"passwordNewPassword",newPassword:"newPassword",password:"password"};class RT{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p,m,g,f){this.accountService=e,this.authService=t,this.autofillService=i,this.cipherService=r,this.collectionService=n,this.configService=a,this.domainSettingsService=s,this.environmentService=o,this.folderService=l,this.logService=c,this.organizationService=u,this.policyService=d,this.themeStateService=h,this.userNotificationSettingsService=p,this.taskService=m,this.messagingService=g,this.fido2Background=f,this.openUnlockPopout=xT,this.openAddEditVaultItemPopout=PT,this.openViewVaultItemPopout=ET,this.notificationQueue=[],this.allowedRetryCommands=new Set([Um,Nm,Rm]),this.extensionMessageHandlers={bgAdjustNotificationBar:({message:e,sender:t})=>this.handleAdjustNotificationBarMessage(e,t),bgCloseNotificationBar:({message:e,sender:t})=>this.handleCloseNotificationBarMessage(e,t),bgOpenAtRiskPasswords:({message:e,sender:t})=>this.handleOpenAtRiskPasswordsMessage(e,t),bgGetActiveUserServerConfig:()=>this.getActiveUserServerConfig(),bgGetDecryptedCiphers:()=>this.getNotificationCipherData(),bgGetEnableChangedPasswordPrompt:()=>this.getEnableChangedPasswordPrompt(),bgGetEnableAddedLoginPrompt:()=>this.getEnableAddedLoginPrompt(),bgGetExcludedDomains:()=>this.getExcludedDomains(),bgGetFolderData:()=>this.getFolderData(),bgGetCollectionData:({message:e})=>this.getCollectionData(e),bgGetOrgData:()=>this.getOrgData(),bgNeverSave:({sender:e})=>this.saveNever(e.tab),bgOpenAddEditVaultItemPopout:({message:e,sender:t})=>this.openAddEditVaultItem(e,t.tab),bgOpenViewVaultItemPopout:({message:e,sender:t})=>this.viewItem(e,t.tab),bgRemoveTabFromNotificationQueue:({sender:e})=>this.removeTabFromNotificationQueue(e.tab),bgReopenUnlockPopout:({sender:e})=>this.openUnlockPopout(e.tab),bgSaveCipher:({message:e,sender:t})=>this.handleSaveCipherMessage(e,t),bgHandleReprompt:({message:e,sender:t})=>this.handleCipherUpdateRepromptResponse(e),checkNotificationQueue:({sender:e})=>this.checkNotificationQueue(e.tab),collectPageDetailsResponse:({message:e})=>this.handleCollectPageDetailsResponseMessage(e),getWebVaultUrlForNotification:()=>this.getWebVaultUrl(),unlockCompleted:({message:e,sender:t})=>this.handleUnlockCompleted(e,t)},this.useUndeterminedCipherScenarioTriggeringLogic$=this.configService.getFeatureFlag$(Ne.UseUndeterminedCipherScenarioTriggeringLogic),this.handleExtensionMessage=(e,t,i)=>{const r=this.extensionMessageHandlers[null==e?void 0:e.command];if(!r)return null;const n=r({message:e,sender:t});return void 0===n?null:(Promise.resolve(n).then(e=>i(e)).catch(e=>this.logService.error(e)),!0)}}init(){null!=chrome.runtime&&(this.setupExtensionMessageListener(),this.setupUnlockPopoutCloseListener(),this.cleanupNotificationQueue())}getEnableChangedPasswordPrompt(){return OT(this,void 0,void 0,function*(){return yield Ce(this.userNotificationSettingsService.enableChangedPasswordPrompt$)})}getEnableAddedLoginPrompt(){return OT(this,void 0,void 0,function*(){return yield Ce(this.userNotificationSettingsService.enableAddedLoginPrompt$)})}getExcludedDomains(){return OT(this,void 0,void 0,function*(){return yield Ce(this.domainSettingsService.neverDomains$)})}getNotificationCipherData(){return OT(this,void 0,void 0,function*(){const[e,t,i,r]=yield Promise.all([hT.getTabFromCurrentWindow(),Ce(this.domainSettingsService.showFavicons$),Ce(this.environmentService.environment$),Ce(this.accountService.activeAccount$.pipe(iu))]);if(!(null==e?void 0:e.url)||!r)return[];const[n,a]=yield Promise.all([this.cipherService.getAllDecryptedForUrl(e.url,r),Ce(this.organizationService.organizations$(r))]),s=i.getIconsUrl(),o=e=>{var t;return null===(t=a.find(t=>t.id===e))||void 0===t?void 0:t.productTierType},l=this.notificationQueue.find(e=>e.type===jT||e.type===AT);if(l){let e;if(l.type===jT){const{data:{cipherIds:e}}=l;return(yield this.cipherService.getAllDecrypted(r)).filter(t=>e.includes(t.id)).map(e=>{const i=o(e.organizationId);return this.convertToNotificationCipherData(e,s,t,i)})}e=this.convertAddLoginQueueMessageToCipherView(l);const i=o(e.organizationId);return[this.convertToNotificationCipherData(e,s,t,i)]}return n.map(e=>this.convertToNotificationCipherData(e,s,t,o(e.organizationId)))})}convertToNotificationCipherData(e,t,i,r){const{id:n,name:a,reprompt:s,favorite:o,login:l}=e,c=[];return null!=r&&([Kh.Teams,Kh.Enterprise,Kh.TeamsStarter].includes(r)&&c.push("business"),[Kh.Families,Kh.Free].includes(r)&&c.push("family")),Object.assign(Object.assign({id:n,name:a,type:rm.Login,reprompt:s,favorite:o},c.length>0?{organizationCategories:c}:{}),{icon:yT(t,e,i),login:l&&{username:l.username}})}getSecurityTaskAndCipherForLoginData(e,t){return OT(this,void 0,void 0,function*(){const i=yield this.getSecurityTasks(t);if(!((null==i?void 0:i.length)>0))return null;const r=yield this.cipherService.getAllDecryptedForUrl(e.uri,t);return(null==r?void 0:r.length)>0?r.reduce((t,r)=>{if(t||r.deletedDate||e.username!==r.login.username||e.password!==r.login.password)return t;const n=i.find(({cipherId:e,status:t})=>r.id===e&&0===t);return n?{securityTask:n,cipher:r,uri:e.uri}:t},null):null})}getActiveUserServerConfig(){return OT(this,void 0,void 0,function*(){return yield Ce(this.configService.serverConfig$)})}getAuthStatus(){return OT(this,void 0,void 0,function*(){return yield Ce(this.authService.activeAccountStatus$)})}checkNotificationQueue(){return OT(this,arguments,void 0,function*(e=null){if(0===this.notificationQueue.length)return;if(null!=e)return void(yield this.doNotificationQueueCheck(e));const t=yield hT.getTabFromCurrentWindow();null!=t&&(yield this.doNotificationQueueCheck(t))})}cleanupNotificationQueue(){for(let e=this.notificationQueue.length-1;e>=0;e--)this.notificationQueue[e].expiresthis.logService.error(e)),this.notificationQueue.splice(e,1));setTimeout(()=>this.cleanupNotificationQueue(),3e4)}doNotificationQueueCheck(e){return OT(this,void 0,void 0,function*(){const t=this.notificationQueue.find(t=>t.tab.id===e.id&&this.queueMessageIsFromTabOrigin(t,e));t&&(yield this.sendNotificationQueueMessage(e,t))})}sendNotificationQueueMessage(e,t){return OT(this,void 0,void 0,function*(){const{type:i,wasVaultLocked:r,launchTimestamp:n}=t,a=function(e,t){var i={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(i[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(e);n=0;t--)this.notificationQueue[t].tab.id===e.id&&this.notificationQueue.splice(t,1)}triggerAtRiskPasswordNotification(e,t){return OT(this,void 0,void 0,function*(){const i=yield Ce(this.accountService.activeAccount$.pipe(iu));if(!i)return!1;const r=yield this.getSecurityTaskAndCipherForLoginData(e,i);if(!r)return!1;const{securityTask:n,cipher:a}=r,s=Tt.getDomain(t.url),o=yield(new DT).getChangePasswordUrl(a),l=(yield this.getAuthStatus())===cu.Locked,c=yield Ce(this.organizationService.organizations$(i).pipe((u=n.organizationId,X(e=>e.find(e=>e.id===u)))));var u;this.removeTabFromNotificationQueue(t);const d=(new Date).getTime(),h={domain:s,wasVaultLocked:l,type:"at-risk-password",data:{passwordChangeUri:o,organizationName:c.name},tab:t,launchTimestamp:d,expires:new Date(d+Dm)};return this.notificationQueue.push(h),yield this.checkNotificationQueue(t),!0})}triggerAddLoginNotification(e,t){return OT(this,void 0,void 0,function*(){const i={url:e.uri,username:e.username,password:e.password||e.newPassword},r=yield this.getAuthStatus();if(r===cu.LoggedOut)return!1;const n=i.username?i.username.toLowerCase():"",a=Tt.getDomain(i.url);if(null==a)return!1;const s=yield this.getEnableAddedLoginPrompt();if(r===cu.Locked)return s&&(yield this.pushAddLoginToQueue(a,i,t,!0)),!1;const o=yield Ce(this.accountService.activeAccount$.pipe(iu));if(null==o)return!1;const l=(yield this.cipherService.getAllDecryptedForUrl(i.url,o)).filter(e=>null!=e.login.username&&e.login.username.toLowerCase()===n);return!(!s||0!==l.length||(yield this.pushAddLoginToQueue(a,i,t),0))})}pushAddLoginToQueue(e,t,i){return OT(this,arguments,void 0,function*(e,t,i,r=!1){this.removeTabFromNotificationQueue(i);const n=(new Date).getTime(),a={type:AT,data:{username:t.username,password:t.password,uri:t.url},domain:e,tab:i,launchTimestamp:n,expires:new Date(n+Dm),wasVaultLocked:r};this.notificationQueue.push(a),yield this.checkNotificationQueue(i)})}triggerCipherNotification(e,t){return OT(this,void 0,void 0,function*(){const i=e.username||null,r=e.password||null,n=e.newPassword||null;if(!i&&!r&&!n)return!1;const a=Tt.getDomain(e.uri);if(null===a)return!1;if(this.fido2Background.isCredentialRequestInProgress(t.id))return!1;const s=yield this.getEnableChangedPasswordPrompt(),o=yield this.getEnableAddedLoginPrompt();if(!s&&!o)return!1;const l=yield this.getAuthStatus();if(l===cu.LoggedOut)return!1;const c=yield Ce(this.accountService.activeAccount$.pipe(iu));if(null===c)return!1;const u=i?i.toLowerCase():"",d="string"==typeof r&&r.length>0,h="string"==typeof n&&n.length>0,p="string"==typeof i&&i.length>0;if(d&&h&&r===n)return!1;if(l===cu.Locked)return!!h&&(yield this.pushChangePasswordToQueue(null,a,n,t,!0),!0);const m=yield this.cipherService.getAllDecryptedForUrl(e.uri,c),g=m.reduce((e,{id:t,login:i})=>{var a;const s=p&&(null===(a=i.username)||void 0===a?void 0:a.toLowerCase())===u,o=d&&i.password===r,l=h&&i.password===n;return l||s||o?l&&s&&o?Object.assign(Object.assign({},e),{allFieldMatches:[...e.allFieldMatches,t]}):!l||s||o?!o||s||l?o&&l&&!s?Object.assign(Object.assign({},e),{passwordNewPasswordMatches:[...e.passwordNewPasswordMatches,t]}):!s||o||l?s&&o&&!l?Object.assign(Object.assign({},e),{usernamePasswordMatches:[...e.usernamePasswordMatches,t]}):s&&l&&!o?Object.assign(Object.assign({},e),{usernameNewPasswordMatches:[...e.usernameNewPasswordMatches,t]}):e:Object.assign(Object.assign({},e),{usernameOnlyMatches:[...e.usernameOnlyMatches,t]}):Object.assign(Object.assign({},e),{passwordOnlyMatches:[...e.passwordOnlyMatches,t]}):Object.assign(Object.assign({},e),{newPasswordOnlyMatches:[...e.newPasswordOnlyMatches,t]}):Object.assign(Object.assign({},e),{noFieldMatches:[...e.noFieldMatches,t]})},{allFieldMatches:[],newPasswordOnlyMatches:[],noFieldMatches:[],passwordNewPasswordMatches:[],passwordOnlyMatches:[],usernameNewPasswordMatches:[],usernameOnlyMatches:[],usernamePasswordMatches:[]}),f={upn:NT.usernamePasswordNewPassword,un:NT.usernameNewPassword,up:NT.usernamePassword,u:NT.username,pn:NT.passwordNewPassword,n:NT.newPassword,p:NT.password},y=(p?"u":"")+(d?"p":"")+(h?"n":""),v=y in f?f[y]:null;return!!v&&(yield this.handleInputMatchScenario({ciphersByInputMatchCategory:g,ciphersForURL:m,loginDomain:a,tab:t,data:e,inputScenario:v,changePasswordNotificationIsEnabled:s,newLoginNotificationIsEnabled:o}))})}triggerChangedPasswordNotification(e,t){return OT(this,void 0,void 0,function*(){if(!(yield this.getEnableChangedPasswordPrompt()))return!1;const i=yield this.getAuthStatus();if(i===cu.LoggedOut)return!1;const r=yield Ce(this.accountService.activeAccount$.pipe(iu));if(null===r)return!1;const n=Tt.getDomain(e.uri);if(null===n)return!1;const a=e.username||null,s=e.password||null,o=e.newPassword||null;if(i===cu.Locked&&null!==o)return yield this.pushChangePasswordToQueue(null,n,o,t,!0),!0;let l=yield this.cipherService.getAllDecryptedForUrl(e.uri,r);const c=a?a.toLowerCase():"";if("string"==typeof a&&a.length>0&&(l=l.filter(e=>null!==e.login.username&&e.login.username.toLowerCase()===c)),1===l.length){const[e]=l;if(null!==a&&null===o&&e.login.username.toLowerCase()===c&&e.login.password===s)return!1}if(l.length>0&&((null==s?void 0:s.length)||0)>0&&!o){const e=l.some(e=>{var t,i;return((null===(i=null===(t=e.login)||void 0===t?void 0:t.password)||void 0===i?void 0:i.length)||0)>0&&e.login.password===s});return!e&&(yield this.pushChangePasswordToQueue(l.map(e=>e.id),n,s,t),!0)}return!!(o&&l.length>0)&&(yield this.pushChangePasswordToQueue(l.map(e=>e.id),n,o,t),!0)})}handleInputMatchScenario(e){return OT(this,arguments,void 0,function*({inputScenario:e,ciphersByInputMatchCategory:t,ciphersForURL:i,loginDomain:r,tab:n,data:a,changePasswordNotificationIsEnabled:s,newLoginNotificationIsEnabled:o}){const{newPasswordOnlyMatches:l,noFieldMatches:c,passwordOnlyMatches:u,usernameNewPasswordMatches:d,usernameOnlyMatches:h,usernamePasswordMatches:p}=t;if(c.length===i.length)return[NT.usernamePasswordNewPassword,NT.usernameNewPassword,NT.usernamePassword,NT.username,NT.passwordNewPassword].includes(e)&&o?(yield this.pushAddLoginToQueue(r,{username:a.username,url:a.uri,password:a.newPassword||a.password},n),!0):!(![NT.password,NT.newPassword].includes(e)||!s||(yield this.pushChangePasswordToQueue(i.map(e=>e.id),r,a.newPassword||a.password,n),0));if(d.length>0&&[NT.usernamePasswordNewPassword,NT.usernameNewPassword].includes(e))return!1;if(p.length>0){if(e===NT.usernamePasswordNewPassword&&s)return yield this.pushChangePasswordToQueue(p,r,a.newPassword||a.password,n),!0;if(e===NT.usernamePassword)return!1}if(h.length>0){if([NT.usernamePasswordNewPassword,NT.usernameNewPassword,NT.usernamePassword].includes(e)&&s)return yield this.pushChangePasswordToQueue(h,r,a.newPassword||a.password,n),!0;if(e===NT.username)return!1}if(l.length>0){if([NT.usernameNewPassword,NT.password,NT.newPassword].includes(e))return!1;if(e===NT.usernamePasswordNewPassword&&o)return yield this.pushAddLoginToQueue(r,{username:a.username,url:a.uri,password:a.newPassword||a.password},n),!0}if(u.length>0){if([NT.usernamePasswordNewPassword,NT.usernamePassword,NT.passwordNewPassword].includes(e)&&s)return yield this.pushChangePasswordToQueue(u,r,a.newPassword||a.password,n),!0;if(e===NT.password)return!1}return!1})}handleCollectPageDetailsResponseMessage(e){return OT(this,void 0,void 0,function*(){if("notificationBar"!==e.sender)return;const t=this.autofillService.getFormsWithPasswordFields(e.details);yield hT.tabSendMessageData(e.tab,"notificationBarPageDetails",{details:e.details,forms:t})})}pushChangePasswordToQueue(e,t,i,r){return OT(this,arguments,void 0,function*(e,t,i,r,n=!1){this.removeTabFromNotificationQueue(r);const a=(new Date).getTime(),s={type:jT,data:{cipherIds:e,newPassword:i},domain:t,tab:r,launchTimestamp:a,expires:new Date(a+Dm),wasVaultLocked:n};this.notificationQueue.push(s),yield this.checkNotificationQueue(r)})}handleSaveCipherMessage(e,t){return OT(this,void 0,void 0,function*(){if((yield this.getAuthStatus())=0;a--){const s=this.notificationQueue[a];if(s.tab.id!==e.id||s.type!==AT&&s.type!==jT)continue;if(!this.queueMessageIsFromTabOrigin(s,e))continue;const o=yield Ce(this.accountService.activeAccount$.pipe(iu));if(s.type===jT){const{data:{newPassword:r}}=s,a=yield this.getDecryptedCipherById(t,o);return void(yield this.updatePassword(a,r,i,e,o,n))}if(this.notificationQueue.splice(a,1),s.wasVaultLocked){const t=(yield this.cipherService.getAllDecryptedForUrl(s.data.uri,o)).find(e=>null!=e.login.username&&e.login.username.toLowerCase()===s.data.username);if(null!=t)return void(yield this.updatePassword(t,s.data.password,i,e,o))}r=(yield this.folderExists(r,o))?r:null;const l=this.convertAddLoginQueueMessageToCipherView(s,r);if(i)return yield this.editItem(l,o,e),void(yield hT.tabSendMessage(e,{command:"closeNotificationBar"}));try{const t=yield this.cipherService.createWithServer(l,o);yield hT.tabSendMessageData(e,"saveCipherAttemptCompleted",{itemName:(null==l?void 0:l.name)&&String(null==l?void 0:l.name),cipherId:(null==t?void 0:t.id)&&String(null==t?void 0:t.id)}),yield hT.tabSendMessage(e,{command:"addedCipher"})}catch(t){yield hT.tabSendMessageData(e,"saveCipherAttemptCompleted",{error:(null==t?void 0:t.message)&&String(t.message)})}}})}updatePassword(e,t,i,r,n){return OT(this,arguments,void 0,function*(e,t,i,r,n,a=!1){var s;if(e.login.password=t,i)return yield this.editItem(e,n,r),yield hT.tabSendMessage(r,{command:"closeNotificationBar"}),void(yield hT.tabSendMessage(r,{command:"editedCipher"}));try{if(!e.edit)throw new Error("You do not have permission to edit this cipher.");const t=yield this.getSecurityTasks(n),i=t.find(t=>t.cipherId===(null==e?void 0:e.id)),o=!!(null==i?void 0:i.id);let l;o&&(null==i?void 0:i.organizationId)&&(l=null===(s=(yield this.getOrgData()).find(({id:e})=>e===i.organizationId))||void 0===s?void 0:s.name);const c=o?{remainingTasksCount:t.length-1,orgName:l}:void 0;if(e.reprompt&&!a)return void(yield this.autofillService.isPasswordRepromptRequired(e,r,"update-password"));yield this.cipherService.updateWithServer(e,n),yield hT.tabSendMessageData(r,"saveCipherAttemptCompleted",{itemName:(null==e?void 0:e.name)&&String(null==e?void 0:e.name),cipherId:(null==e?void 0:e.id)&&String(e.id),task:c}),o&&(yield Promise.all(t.map(t=>{if(t.cipherId===(null==e?void 0:e.id))return this.taskService.markAsComplete(t.id,n)})))}catch(e){yield hT.tabSendMessageData(r,"saveCipherAttemptCompleted",{error:(null==e?void 0:e.message)&&String(e.message)})}})}editItem(e,t,i){return OT(this,void 0,void 0,function*(){yield this.cipherService.setAddEditCipherInfo({cipher:e,collectionIds:e.collectionIds},t),yield this.openAddEditVaultItemPopout(i,{cipherId:null==e?void 0:e.id})})}openAddEditVaultItem(e,t){return OT(this,void 0,void 0,function*(){const{cipherId:i,organizationId:r,folder:n}=e,a=yield Ce(this.accountService.activeAccount$.pipe(iu));if(i)return void(yield this.openAddEditVaultItemPopout(t,{cipherId:i}));const s=this.notificationQueue.find(e=>e.tab.id===t.id);if((null==s?void 0:s.type)===AT){const e=this.convertAddLoginQueueMessageToCipherView(s);return e.organizationId=r,e.folderId=n,a&&(yield this.cipherService.setAddEditCipherInfo({cipher:e},a)),yield this.openAddEditVaultItemPopout(t),void this.removeTabFromNotificationQueue(t)}yield this.openAddEditVaultItemPopout(t)})}viewItem(e,t){return OT(this,void 0,void 0,function*(){yield Promise.all([this.openViewVaultItemPopout(t,{cipherId:e.cipherId,action:null}),hT.tabSendMessageData(t,"closeNotificationBar",{fadeOutNotification:!!e.fadeOutNotification})])})}folderExists(e,t){return OT(this,void 0,void 0,function*(){return!Tt.isNullOrWhitespace(e)&&"null"!==e&&(yield Ce(this.folderService.folderViews$(t))).some(t=>t.id===e)})}getDecryptedCipherById(e,t){return OT(this,void 0,void 0,function*(){const i=yield this.cipherService.get(e,t);return null!=i&&i.type===rm.Login?yield this.cipherService.decrypt(i,t):null})}getSecurityTasks(e){return OT(this,void 0,void 0,function*(){let t=[];return e&&(t=yield Ce(this.taskService.tasksEnabled$(e).pipe(Le(t=>t?this.taskService.pendingTasks$(e).pipe(X(e=>e.filter(({type:e})=>0===e))):bt([]))))),t})}saveNever(e){return OT(this,void 0,void 0,function*(){for(let t=this.notificationQueue.length-1;t>=0;t--){const i=this.notificationQueue[t];if(i.tab.id!==e.id||i.type!==AT)continue;if(!this.queueMessageIsFromTabOrigin(i,e))continue;this.notificationQueue.splice(t,1),yield hT.tabSendMessageData(e,"closeNotificationBar");const r=Tt.getHostname(e.url);yield this.cipherService.saveNeverDomain(r)}})}getFolderData(){return OT(this,void 0,void 0,function*(){const e=yield Ce(this.accountService.activeAccount$.pipe(iu));return yield Ce(this.folderService.folderViews$(e))})}getCollectionData(e){return OT(this,void 0,void 0,function*(){return yield Ce(this.accountService.activeAccount$.pipe(tu,Le(e=>this.collectionService.decryptedCollections$(e)),X(t=>t.reduce((t,i)=>(i.organizationId===(null==e?void 0:e.orgId)&&t.push({id:i.id,name:i.name,organizationId:i.organizationId}),t),[]))))})}getWebVaultUrl(){return OT(this,void 0,void 0,function*(){return(yield Ce(this.environmentService.environment$)).getWebVaultUrl()})}removeIndividualVault(){return OT(this,void 0,void 0,function*(){return yield Ce(this.accountService.activeAccount$.pipe(tu,Le(e=>this.policyService.policyAppliesToUser$(Ye.OrganizationDataOwnership,e))))})}getOrgData(){return OT(this,void 0,void 0,function*(){const e=yield Ce(this.accountService.activeAccount$.pipe(iu));return(yield Ce(this.organizationService.organizations$(e))).map(e=>{const{id:t,name:i,productTierType:r}=e;return{id:t,name:i,productTierType:r}})})}handleUnlockCompleted(e,t){return OT(this,void 0,void 0,function*(){this.unlockPopoutTabId=void 0;const i=e.data,r=i.commandToRetry.message.command;if(this.allowedRetryCommands.has(r)&&(yield hT.tabSendMessageData(t.tab,"closeNotificationBar")),"notification.background"!==i.target)return;const n=this.extensionMessageHandlers[r];n&&n({message:i.commandToRetry.message,sender:i.commandToRetry.sender})})}handleCloseNotificationBarMessage(e,t){return OT(this,void 0,void 0,function*(){yield hT.tabSendMessageData(t.tab,"closeNotificationBar",{fadeOutNotification:!!e.fadeOutNotification})})}handleOpenAtRiskPasswordsMessage(e,t){return OT(this,void 0,void 0,function*(){const i=hT.getBrowserAction();try{yield i.setPopup({popup:"popup/index.html#/at-risk-passwords"}),yield Promise.all([this.messagingService.send(fT),hT.tabSendMessageData(t.tab,"closeNotificationBar",{fadeOutNotification:!!e.fadeOutNotification})])}finally{yield i.setPopup({popup:"popup/index.html#/"})}})}handleAdjustNotificationBarMessage(e,t){return OT(this,void 0,void 0,function*(){yield hT.tabSendMessageData(t.tab,"adjustNotificationBar",e.data)})}convertAddLoginQueueMessageToCipherView(e,t){const i=new tw;i.uri=e.data.uri;const r=new nw;r.uris=[i],r.username=e.data.username,r.password=e.data.password;const n=new lw;return n.name=(Tt.getHostname(e.data.uri)||e.domain).replace(/^www\./,""),n.folderId=t,n.type=rm.Login,n.login=r,n}setupExtensionMessageListener(){hT.messageListener("notification.background",this.handleExtensionMessage)}queueMessageIsFromTabOrigin(e,t){const i=Tt.getDomain(t.url);return i===e.domain||i===Tt.getDomain(e.tab.url)}setupUnlockPopoutCloseListener(){chrome.tabs.onRemoved.addListener(e=>OT(this,void 0,void 0,function*(){yield this.handleUnlockPopoutClosed(e)}))}handleUnlockPopoutClosed(e){return OT(this,void 0,void 0,function*(){if((yield this.getAuthStatus())>=cu.Unlocked)return void(this.unlockPopoutTabId=void 0);if(this.unlockPopoutTabId===e)return this.unlockPopoutTabId=void 0,void this.messagingService.send("abandonAutofillPendingNotifications");if(this.unlockPopoutTabId)return;const t=hT.getRuntimeURL("popup/index.html"),i=(yield hT.tabsQuery({url:`${t}*`})).filter(e=>{var t;return null===(t=e.url)||void 0===t?void 0:t.includes(`singleActionPopout=${ST}`)});0===i.length?this.messagingService.send("abandonAutofillPendingNotifications"):i[0].id&&(this.unlockPopoutTabId=i[0].id)})}}const UT="autofill-injected-script-port";function FT(e){try{if(/^(chrome|chrome-extension|moz-extension|safari-web-extension):\/\/\/?/.test(e))return[];/^(https?|file):\/\/\/?/.test(e)||(e=`https://${e}`);let t="*://";e.startsWith("file:///")&&(t="*:///");const i=new URL(e),r=`${t}${i.hostname}/*`;return[r,`${t}*.${i.hostname.split(".").slice(-2).join(".")}/*`]}catch(e){return[]}}function qT(e){return e<200||e>=300}const LT={" ":"spaceCharacterDescriptor","~":"tildeCharacterDescriptor","`":"backtickCharacterDescriptor","!":"exclamationCharacterDescriptor","@":"atSignCharacterDescriptor","#":"hashSignCharacterDescriptor",$:"dollarSignCharacterDescriptor","%":"percentSignCharacterDescriptor","^":"caretCharacterDescriptor","&":"ampersandCharacterDescriptor","*":"asteriskCharacterDescriptor","(":"parenLeftCharacterDescriptor",")":"parenRightCharacterDescriptor","-":"hyphenCharacterDescriptor",_:"underscoreCharacterDescriptor","+":"plusCharacterDescriptor","=":"equalsCharacterDescriptor","{":"braceLeftCharacterDescriptor","}":"braceRightCharacterDescriptor","[":"bracketLeftCharacterDescriptor","]":"bracketRightCharacterDescriptor","|":"pipeCharacterDescriptor","\\":"backSlashCharacterDescriptor",":":"colonCharacterDescriptor",";":"semicolonCharacterDescriptor",'"':"doubleQuoteCharacterDescriptor","'":"singleQuoteCharacterDescriptor","<":"lessThanCharacterDescriptor",">":"greaterThanCharacterDescriptor",",":"commaCharacterDescriptor",".":"periodCharacterDescriptor","?":"questionCharacterDescriptor","/":"forwardSlashCharacterDescriptor"};function BT(e){return e.right>0&&e.left>0&&e.top>0&&e.bottom>0}function MT(e,t){return(t&&t.length>0?t:Object.keys(e)).every(t=>null==e[t])}const VT=Object.assign(Object.assign({},{Add:"add",Change:"change",Unlock:"unlock",AtRiskPassword:"at-risk-password"}),{Cipher:"cipher"});var $T=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class KT{constructor(e,t){this.logService=e,this.notificationBackground=t,this.websiteOriginsWithFields=new Map,this.activeFormSubmissionRequests=new Set,this.modifyLoginCipherFormData=new Map,this.clearLoginCipherFormDataSubject=new H,this.notificationFallbackTimeout=null,this.formSubmissionRequestMethods=new Set(["POST","PUT","PATCH"]),this.extensionMessageHandlers={generatedPasswordFilled:({message:e,sender:t})=>this.storeModifiedLoginFormData(e,t),formFieldSubmitted:({message:e,sender:t})=>this.storeModifiedLoginFormData(e,t),collectPageDetailsResponse:({message:e,sender:t})=>this.handleCollectPageDetailsResponse(e,t)},this.storeModifiedLoginFormData=(e,t)=>{var i;const r=null===(i=t.tab)||void 0===i?void 0:i.id;if(void 0===r||!this.websiteOriginsWithFields.has(r))return;const{uri:n,username:a,password:s,newPassword:o}=e;if(!a&&!s&&!o)return;this.clearLoginCipherFormDataSubject.next();const l={uri:n,username:a,password:s,newPassword:o},c=this.modifyLoginCipherFormData.get(r);c&&(l.username=l.username||c.username,l.password=l.password||c.password,l.newPassword=l.newPassword||c.newPassword),this.modifyLoginCipherFormData.set(r,l),this.clearNotificationFallbackTimeout(),this.notificationFallbackTimeout=setTimeout(()=>{const e=this.modifyLoginCipherFormData.get(r);e&&this.setupNotificationInitTrigger(r,"",e).catch(e=>this.logService.error(e))},1500)},this.handleOnBeforeRequestEvent=e=>{if(this.isPostSubmissionFormRedirection(e)){const t=this.modifyLoginCipherFormData.get(e.tabId);return void(t&&this.setupNotificationInitTrigger(e.tabId,e.requestId,t).catch(e=>this.logService.error(e)))}if(!this.isValidFormSubmissionRequest(e))return;const{requestId:t,tabId:i,frameId:r}=e;this.activeFormSubmissionRequests.add(t),this.notificationDataIncompleteOnBeforeRequest(i)&&this.getFormFieldDataFromTab(i,r).catch(e=>this.logService.error(e))},this.notificationDataIncompleteOnBeforeRequest=e=>{const t=this.modifyLoginCipherFormData.get(e);return!t||(this.shouldAttemptNotification(t,VT.Add)||this.shouldAttemptNotification(t,VT.Change),!1)},this.isPostSubmissionFormRedirection=e=>{var t;return"GET"===(null===(t=e.method)||void 0===t?void 0:t.toUpperCase())&&this.activeFormSubmissionRequests.has(e.requestId)&&this.modifyLoginCipherFormData.has(e.tabId)},this.isValidFormSubmissionRequest=e=>{var t;return!this.requestHostIsInvalid(e)&&this.formSubmissionRequestMethods.has(null===(t=e.method)||void 0===t?void 0:t.toUpperCase())},this.getFormFieldDataFromTab=(e,t)=>$T(this,void 0,void 0,function*(){const i=yield hT.getTab(e);if(!i)return;const r=yield hT.tabSendMessage(i,{command:"getInlineMenuFormFieldData"},{frameId:t});r&&this.storeModifiedLoginFormData(r,{tab:i})}),this.handleOnCompletedRequestEvent=e=>$T(this,void 0,void 0,function*(){if(this.requestHostIsInvalid(e)||!this.activeFormSubmissionRequests.has(e.requestId))return;if(qT(e.statusCode))return void this.clearNotificationFallbackTimeout();const t=this.modifyLoginCipherFormData.get(e.tabId);t&&this.setupNotificationInitTrigger(e.tabId,e.requestId,t).catch(e=>this.logService.error(e))}),this.setupNotificationInitTrigger=(e,t,i)=>$T(this,void 0,void 0,function*(){this.clearNotificationFallbackTimeout();const r=yield hT.getTab(e);r&&("complete"===r.status?yield this.processNotifications(t,i,r):yield this.delayNotificationInitUntilTabIsComplete(e,t,i))}),this.delayNotificationInitUntilTabIsComplete=(e,t,i)=>$T(this,void 0,void 0,function*(){const r=()=>$T(this,void 0,void 0,function*(){chrome.webNavigation.onCompleted.removeListener(r);const n=yield hT.getTab(e);n&&(yield this.processNotifications(t,i,n))});chrome.webNavigation.onCompleted.addListener(r)}),this.processNotifications=(e,t,i,...r)=>$T(this,[e,t,i,...r],void 0,function*(e,t,i,r={skippable:[]}){const n=((yield Ce(this.notificationBackground.useUndeterminedCipherScenarioTriggeringLogic$))?[{type:VT.Cipher,trigger:this.notificationBackground.triggerCipherNotification},{type:VT.AtRiskPassword,trigger:this.notificationBackground.triggerAtRiskPasswordNotification}]:[{type:VT.Change,trigger:this.notificationBackground.triggerChangedPasswordNotification},{type:VT.Add,trigger:this.notificationBackground.triggerAddLoginNotification},{type:VT.AtRiskPassword,trigger:this.notificationBackground.triggerAtRiskPasswordNotification}]).filter(e=>this.shouldAttemptNotification(t,e.type)||r.skippable.includes(e.type)),a=[];for(const{trigger:e,type:r}of n){if(yield e.bind(this.notificationBackground)(t,i)){a.push(`Success: ${r}`);break}a.push(`Unqualified ${r} notification attempt.`)}return this.clearCompletedWebRequest(e,i.id),a.join(" ")}),this.shouldAttemptNotification=(e,t)=>{if(t===VT.Cipher)return!0;const i=!!((null==e?void 0:e.username)||"").length,r=!!((null==e?void 0:e.password)||"").length,n=!!((null==e?void 0:e.newPassword)||"").length,a=i&&r,s=r&&n;switch(t){case VT.Add:return i&&(r||n);case VT.Change:return a||s;case VT.AtRiskPassword:return!n;case VT.Unlock:return!1;default:return this.logService.error(`Unknown notification type: ${t}`),!1}},this.clearCompletedWebRequest=(e,t)=>{this.activeFormSubmissionRequests.delete(e),this.modifyLoginCipherFormData.delete(t),this.websiteOriginsWithFields.delete(t),this.setupWebRequestsListeners()},this.requestHostIsInvalid=e=>{var t;return!(null===(t=e.url)||void 0===t?void 0:t.startsWith("http"))||e.tabId<0},this.handleExtensionMessage=(e,t,i)=>{const r=this.extensionMessageHandlers[e.command];if(!r)return null;const n=r({message:e,sender:t});return void 0===n?null:(Promise.resolve(n).then(e=>i(e)).catch(e=>this.logService.error(e)),!0)},this.handleTabRemoved=e=>{this.modifyLoginCipherFormData.delete(e),this.websiteOriginsWithFields.has(e)&&(this.websiteOriginsWithFields.delete(e),this.setupWebRequestsListeners())},this.handleTabUpdated=(e,t)=>{if("loading"!==t.status||!t.url)return;const i=this.websiteOriginsWithFields.get(e);i&&(FT(t.url).some(e=>i.has(e))||this.websiteOriginsWithFields.delete(e))}}init(){return $T(this,void 0,void 0,function*(){this.setupExtensionListeners(),this.clearLoginCipherFormDataSubject.pipe(Le(()=>sc(6e4))).subscribe(()=>this.modifyLoginCipherFormData.clear())})}handleCollectPageDetailsResponse(e,t){return $T(this,void 0,void 0,function*(){var i;if(yield this.shouldInitAddLoginOrChangePasswordNotification(e,t)){const e=null===(i=t.tab)||void 0===i?void 0:i.id;if(void 0===e)return;this.websiteOriginsWithFields.set(e,this.getSenderUrlMatchPatterns(t)),this.setupWebRequestsListeners()}})}shouldInitAddLoginOrChangePasswordNotification(e,t){return $T(this,void 0,void 0,function*(){var i,r,n,a;const s=null===(i=t.tab)||void 0===i?void 0:i.id;return void 0!==s&&(yield this.isAddLoginOrChangePasswordNotificationEnabled())&&!(yield this.isSenderFromExcludedDomain(t))&&(null!==(a=null===(n=null===(r=e.details)||void 0===r?void 0:r.fields)||void 0===n?void 0:n.length)&&void 0!==a?a:0)>0&&!this.websiteOriginsWithFields.has(s)})}isAddLoginOrChangePasswordNotificationEnabled(){return $T(this,void 0,void 0,function*(){return(yield this.notificationBackground.getEnableChangedPasswordPrompt())||(yield this.notificationBackground.getEnableAddedLoginPrompt())})}getSenderUrlMatchPatterns(e){var t;return new Set([...e.url?FT(e.url):[],...(null===(t=e.tab)||void 0===t?void 0:t.url)?FT(e.tab.url):[]])}clearNotificationFallbackTimeout(){this.notificationFallbackTimeout&&(clearTimeout(this.notificationFallbackTimeout),this.notificationFallbackTimeout=null)}isSenderFromExcludedDomain(e){return $T(this,void 0,void 0,function*(){var t;try{const i=e.origin;if(!i)return!1;const r=yield this.notificationBackground.getActiveUserServerConfig();if((null===(t=null==r?void 0:r.environment)||void 0===t?void 0:t.vault)===i)return!0;const n=yield this.notificationBackground.getExcludedDomains();return!!n&&void 0!==n[new URL(i).hostname]}catch(e){return!0}})}setupWebRequestsListeners(){if(chrome.webRequest.onBeforeRequest.removeListener(this.handleOnBeforeRequestEvent),chrome.webRequest.onCompleted.removeListener(this.handleOnCompletedRequestEvent),this.websiteOriginsWithFields.size){const e=this.generateRequestFilter();chrome.webRequest.onBeforeRequest.addListener(this.handleOnBeforeRequestEvent,e),chrome.webRequest.onCompleted.addListener(this.handleOnCompletedRequestEvent,e)}}generateRequestFilter(){const e=Array.from(this.websiteOriginsWithFields.values()),t=[];return e.forEach(e=>t.push(...e)),{urls:t,types:["main_frame","sub_frame","xmlhttprequest"]}}setupExtensionListeners(){hT.addListener(chrome.runtime.onMessage,this.handleExtensionMessage),chrome.tabs.onRemoved.addListener(this.handleTabRemoved),chrome.tabs.onUpdated.addListener(this.handleTabUpdated)}}function WT(e,t,i){void 0===t&&(t=Te);var r=sc(e,t);return function(e,t){return Q(function(e,i){var n=null!=t?t:{},a=n.leading,s=void 0===a||a,o=n.trailing,l=void 0!==o&&o,c=!1,u=null,d=null,h=!1,p=function(){null==d||d.unsubscribe(),d=null,l&&(f(),h&&i.complete())},m=function(){d=null,h&&i.complete()},g=function(e){return d=le(r).subscribe(J(i,p,m))},f=function(){if(c){c=!1;var e=u;u=null,i.next(e),!h&&g()}};e.subscribe(J(i,function(e){c=!0,u=e,(!d||d.closed)&&(s?f():g())},function(){h=!0,(!(l&&c&&d)||d.closed)&&i.complete()}))})}(0,i)}function HT(e,t){return void 0===t&&(t=Te),Q(function(i,r){var n=null,a=null,s=null,o=function(){if(n){n.unsubscribe(),n=null;var e=a;a=null,r.next(e)}};function l(){var i=s+e,a=t.now();if(athis.overlayElementClosed(e,t),autofillOverlayAddNewVaultItem:({message:e,sender:t})=>this.addNewVaultItem(e,t),triggerAutofillOverlayReposition:({sender:e})=>this.triggerOverlayReposition(e),checkIsInlineMenuCiphersPopulated:({sender:e})=>this.checkIsInlineMenuCiphersPopulated(e),updateFocusedFieldData:({message:e,sender:t})=>this.setFocusedFieldData(e,t),updateIsFieldCurrentlyFocused:({message:e,sender:t})=>this.updateIsFieldCurrentlyFocused(e,t),checkIsFieldCurrentlyFocused:()=>this.checkIsFieldCurrentlyFocused(),updateIsFieldCurrentlyFilling:({message:e})=>this.updateIsFieldCurrentlyFilling(e),checkIsFieldCurrentlyFilling:()=>this.checkIsFieldCurrentlyFilling(),getAutofillInlineMenuVisibility:()=>this.getInlineMenuVisibility(),openAutofillInlineMenu:({message:e,sender:t})=>this.openInlineMenu(t,e.isOpeningFullInlineMenu),getInlineMenuCardsVisibility:()=>this.getInlineMenuCardsVisibility(),getInlineMenuIdentitiesVisibility:()=>this.getInlineMenuIdentitiesVisibility(),closeAutofillInlineMenu:({message:e,sender:t})=>this.closeInlineMenu(t,e),checkAutofillInlineMenuFocused:({sender:e})=>this.checkInlineMenuFocused(e),focusAutofillInlineMenuList:()=>this.focusInlineMenuList(),getAutofillInlineMenuPosition:()=>this.getInlineMenuPosition(),updateAutofillInlineMenuElementIsVisibleStatus:({message:e,sender:t})=>this.updateInlineMenuElementIsVisibleStatus(e,t),checkIsAutofillInlineMenuButtonVisible:()=>this.checkIsInlineMenuButtonVisible(),checkIsAutofillInlineMenuListVisible:()=>this.checkIsInlineMenuListVisible(),getCurrentTabFrameId:({sender:e})=>this.getSenderFrameId(e),updateSubFrameData:({message:e,sender:t})=>this.updateSubFrameData(e,t),triggerSubFrameFocusInRebuild:({sender:e})=>this.triggerSubFrameFocusInRebuild(e),destroyAutofillInlineMenuListeners:({message:e,sender:t})=>this.triggerDestroyInlineMenuListeners(t.tab,e.subFrameData.frameId),collectPageDetailsResponse:({message:e,sender:t})=>this.storePageDetails(e,t),unlockCompleted:({message:e})=>this.unlockCompleted(e),doFullSync:()=>this.updateOverlayCiphers(),addedCipher:()=>this.updateOverlayCiphers(),addEditCipherSubmitted:()=>this.updateOverlayCiphers(),editedCipher:()=>this.updateOverlayCiphers(),deletedCipher:()=>this.updateOverlayCiphers(),bgSaveCipher:()=>this.updateOverlayCiphers(),updateOverlayCiphers:()=>this.updateOverlayCiphers(),fido2AbortRequest:({sender:e})=>this.abortFido2ActiveRequest(e.tab.id)},this.inlineMenuButtonPortMessageHandlers={triggerDelayedAutofillInlineMenuClosure:()=>this.startInlineMenuDelayedClose$.next(),autofillInlineMenuButtonClicked:({port:e})=>this.handleInlineMenuButtonClicked(e),autofillInlineMenuBlurred:()=>this.checkInlineMenuListFocused(),redirectAutofillInlineMenuFocusOut:({message:e,port:t})=>this.redirectInlineMenuFocusOut(e,t),updateAutofillInlineMenuColorScheme:()=>this.updateInlineMenuButtonColorScheme()},this.inlineMenuListPortMessageHandlers={checkAutofillInlineMenuButtonFocused:({port:e})=>this.checkInlineMenuButtonFocused(e.sender),autofillInlineMenuBlurred:({port:e})=>this.checkInlineMenuButtonFocused(e.sender),unlockVault:({port:e})=>this.unlockVault(e),fillAutofillInlineMenuCipher:({message:e,port:t})=>this.fillInlineMenuCipher(e,t),addNewVaultItem:({message:e,port:t})=>this.getNewVaultItemDetails(e,t),viewSelectedCipher:({message:e,port:t})=>this.viewSelectedCipher(e,t),redirectAutofillInlineMenuFocusOut:({message:e,port:t})=>this.redirectInlineMenuFocusOut(e,t),updateAutofillInlineMenuListHeight:({message:e})=>this.updateInlineMenuListHeight(e),refreshGeneratedPassword:()=>this.updateGeneratedPassword(!0),fillGeneratedPassword:({port:e})=>this.fillGeneratedPassword(e),refreshOverlayCiphers:()=>this.updateOverlayCiphers(!1)},this.handlePasskeyAuthenticationOnCompleted=e=>{if(chrome.webRequest.onCompleted.removeListener(this.handlePasskeyAuthenticationOnCompleted),qT(e.statusCode))return this.closeInlineMenu({tab:{id:e.tabId}},{forceCloseInlineMenu:!0}),void this.abortFido2ActiveRequest(e.tabId).catch(e=>this.logService.error(e));globalThis.setTimeout(()=>this.triggerDelayedInlineMenuClosure(),3e3)},this.repositionInlineMenu=e=>iD(this,void 0,void 0,function*(){var t,i;this.cancelInlineMenuFadeInAndPositionUpdate(),(this.isFieldCurrentlyFocused||this.isInlineMenuButtonVisible)&&(yield hT.tabSendMessage(e.tab,{command:"checkIsMostRecentlyFocusedFieldWithinViewport"},{frameId:null===(t=this.focusedFieldData)||void 0===t?void 0:t.frameId}))?((null===(i=this.focusedFieldData)||void 0===i?void 0:i.frameId)>0&&this.rebuildSubFrameOffsets$.next(e),this.startUpdateInlineMenuPosition$.next(e)):yield this.closeInlineMenuAfterReposition(e)}),this.handleExtensionMessage=(e,t,i)=>{const r=this.extensionMessageHandlers[null==e?void 0:e.command];if(!r)return null;const n=r({message:e,sender:t});return void 0===n?null:(Promise.resolve(n).then(e=>i(e)).catch(e=>this.logService.error(e)),!0)},this.handleWebNavigationOnCommitted=e=>{const{frameId:t,tabId:i}=e,r=this.subFrameOffsetsForTab[i];if(0===t)return this.removePageDetails(i),void(r&&(r.clear(),delete this.subFrameOffsetsForTab[i]));r&&r.has(t)&&r.delete(t)},this.handlePortOnConnect=e=>iD(this,void 0,void 0,function*(){var t;if(!this.validPortConnections.has(e.name))return;this.storeOverlayPort(e),e.onMessage.addListener(this.handleOverlayElementPortMessage);const i=e.name===XT,r=e.name===JT;if(!i&&!r)return;this.portKeyForTab[e.sender.tab.id]||(this.portKeyForTab[e.sender.tab.id]=function(e){const t=[],i=new Uint8Array(e);globalThis.crypto.getRandomValues(i);for(let e=0;ethis.logService.error(e))}),this.postMessageToPort=(e,t)=>{if(e)try{e.postMessage(t)}catch(e){}},this.handleOverlayElementPortMessage=(e,t)=>{const i=this.portKeyForTab[t.sender.tab.id];if(!i||i!==(null==e?void 0:e.portKey))return;const r=e.command;let n;t.name===YT&&(n=this.inlineMenuButtonPortMessageHandlers[r]),t.name===ZT&&(n=this.inlineMenuListPortMessageHandlers[r]),n&&n({message:e,port:t})},this.handlePortOnDisconnect=e=>{var t,i;const r={isVisible:!1,forceUpdate:!0};e.name===XT&&(this.inlineMenuListPort=null,null===(t=this.inlineMenuListMessageConnectorPort)||void 0===t||t.disconnect(),this.inlineMenuListMessageConnectorPort=null,this.updateInlineMenuElementIsVisibleStatus(Object.assign(r,{overlayElement:QT}),e.sender),this.inlineMenuPosition.list=null),e.name===JT&&(this.inlineMenuButtonPort=null,null===(i=this.inlineMenuButtonMessageConnectorPort)||void 0===i||i.disconnect(),this.inlineMenuButtonMessageConnectorPort=null,this.updateInlineMenuElementIsVisibleStatus(Object.assign(r,{overlayElement:QT}),e.sender),this.inlineMenuPosition.button=null)},this.initOverlayEventObservables()}init(){return iD(this,void 0,void 0,function*(){this.setupExtensionListeners();const e=yield Ce(this.environmentService.environment$);this.iconsServerUrl=e.getIconsUrl()})}initOverlayEventObservables(){this.updateOverlayCiphers$.pipe(WT(100,null,{leading:!0,trailing:!0}),Le(e=>this.handleOverlayCiphersUpdate(e))).subscribe(),this.storeInlineMenuFido2Credentials$.pipe(Le(e=>this.availablePasskeyAuthCredentials$(e))).subscribe(e=>this.storeInlineMenuFido2Credentials(e)),this.repositionInlineMenu$.pipe(HT(1e3),Le(e=>this.repositionInlineMenu(e))).subscribe(),this.rebuildSubFrameOffsets$.pipe(WT(100,null,{leading:!0,trailing:!0}),Le(e=>this.rebuildSubFrameOffsets(e))).subscribe(),this.addNewVaultItem$.pipe(HT(100),Le(e=>this.buildCipherAndOpenAddEditVaultItemPopout(e))).subscribe(),_e(this.startInlineMenuDelayedClose$.pipe(HT(100)),this.cancelInlineMenuDelayedClose$).pipe(Le(e=>this.triggerDelayedInlineMenuClosure(!!e))).subscribe(),_e(this.startUpdateInlineMenuPosition$.pipe(HT(150)),this.cancelUpdateInlineMenuPosition$).pipe(Le(e=>this.updateInlineMenuPositionAfterRepositionEvent(e))).subscribe(),_e(this.startInlineMenuFadeIn$.pipe(HT(150)),this.cancelInlineMenuFadeIn$).pipe(Le(e=>this.triggerInlineMenuFadeIn(!!e))).subscribe()}removePageDetails(e){this.pageDetailsForTab[e]&&(this.pageDetailsForTab[e].clear(),delete this.pageDetailsForTab[e]),this.portKeyForTab[e]&&delete this.portKeyForTab[e],this.generatedPassword=null,this.focusedFieldData=null}updateOverlayCiphers(){return iD(this,arguments,void 0,function*(e=!0,t=!1){(yield Ce(this.authService.activeAccountStatus$))===cu.Unlocked&&(this.inlineMenuCiphers=new Map,this.updateOverlayCiphers$.next({updateAllCipherTypes:e,refocusField:t}))})}handleOverlayCiphersUpdate(e){return iD(this,arguments,void 0,function*({updateAllCipherTypes:e,refocusField:t}){var i;const r=yield hT.getTabFromCurrentWindowId();if(this.focusedFieldData&&(null==r?void 0:r.id)!==this.focusedFieldData.tabId){const e=yield hT.getTab(this.focusedFieldData.tabId);this.closeInlineMenu({tab:e},{forceCloseInlineMenu:!0})}if(!r||!(null===(i=r.url)||void 0===i?void 0:i.startsWith("http")))return void(e&&(this.cardAndIdentityCiphers=null));const n=this.fido2ActiveRequestManager.getActiveRequest(r.id);n&&n.subject.next({type:kb}),this.inlineMenuFido2Credentials.clear(),this.storeInlineMenuFido2Credentials$.next(r.id);const a=yield this.getCipherViews(r,e);for(let e=0;ethis.cipherService.sortCiphersByLastUsedThenName(e,t));return this.cardAndIdentityCiphers?r.concat(...this.cardAndIdentityCiphers):r})}getAllCipherTypeViews(e,t){return iD(this,void 0,void 0,function*(){var i;this.cardAndIdentityCiphers||(this.cardAndIdentityCiphers=new Set([])),this.cardAndIdentityCiphers.clear();const r=(yield this.cipherService.getAllDecryptedForUrl(e.url||"",t,[rm.Card,rm.Identity])).sort((e,t)=>this.cipherService.sortCiphersByLastUsedThenName(e,t));if(!this.cardAndIdentityCiphers)return r;for(let e=0;e0&&r.length>0,n.concat(r)):r})}showCipherAsPasskey(e,t){return iD(this,void 0,void 0,function*(){var i;if(e.type!==rm.Login||!(null===(i=this.focusedFieldData)||void 0===i?void 0:i.showPasskeys))return!1;const r=e.login.fido2Credentials;if(!(null==r?void 0:r.length))return!1;const n=r[0].credentialId,a=At(r[0].rpId,{allowPrivateDomains:!0});return!(null==t?void 0:t.has(a.domain))&&this.inlineMenuFido2Credentials.has(n)})}isTotpFieldForCurrentField(){var e;if(!this.focusedFieldData)return!1;const t=this.getTotpFields();return!!t&&t.length>0&&(null===(e=this.focusedFieldData)||void 0===e?void 0:e.accountCreationFieldType)===tD}buildCipherData(e){return iD(this,arguments,void 0,function*({inlineMenuCipherId:e,cipher:t,showFavicons:i,showInlineMenuAccountCreation:r,hasPasskey:n,identityData:a}){var s,o;const l={id:e,name:t.name,type:t.type,reprompt:t.reprompt,favorite:t.favorite,icon:yT(this.iconsServerUrl,t,i),accountCreationFieldType:null===(s=this.focusedFieldData)||void 0===s?void 0:s.accountCreationFieldType};if(t.type===rm.Login){const e=(null===(o=t.login)||void 0===o?void 0:o.totp)?yield Ce(this.totpService.getCode$(t.login.totp)):void 0;return l.login={username:t.login.username,totp:null==e?void 0:e.code,totpField:this.isTotpFieldForCurrentField(),totpCodeTimeInterval:null==e?void 0:e.period,passkey:n?{rpName:t.login.fido2Credentials[0].rpName,userName:t.login.fido2Credentials[0].userName}:null},l}return t.type===rm.Card?(l.card=t.card.subTitle,l):(l.identity=a||this.getIdentityCipherData(t,r),l)})}getIdentityCipherData(e,t=!1){var i;const{firstName:r,lastName:n}=e.identity;let a="";return r&&(a+=r),n&&(a+=` ${n}`,a=a.trim()),t&&(null===(i=this.focusedFieldData)||void 0===i?void 0:i.accountCreationFieldType)&&!this.focusedFieldMatchesAccountCreationType(eD)?{fullName:a,username:this.focusedFieldMatchesAccountCreationType("email")?e.identity.email:e.identity.username}:{fullName:a}}focusedFieldMatchesAccountCreationType(e){var t;return(null===(t=this.focusedFieldData)||void 0===t?void 0:t.accountCreationFieldType)===e}focusedFieldMatchesFillType(e,t){var i;const r=t?t.inlineMenuFillType:null===(i=this.focusedFieldData)||void 0===i?void 0:i.inlineMenuFillType;return 7===r&&e===rm.Login||r===e}shouldShowInlineMenuAccountCreation(){return!!this.focusedFieldMatchesFillType(5)||!!this.focusedFieldMatchesFillType(rm.Login)&&(this.cardAndIdentityCiphers?this.inlineMenuCiphers.size===this.cardAndIdentityCiphers.size:0===this.inlineMenuCiphers.size)}storeInlineMenuFido2Credentials(e){this.inlineMenuFido2Credentials.clear(),e.forEach(e=>(null==e?void 0:e.credentialId)&&this.inlineMenuFido2Credentials.add(e.credentialId))}availablePasskeyAuthCredentials$(e){return this.fido2ActiveRequestManager.getActiveRequest$(e).pipe(X(e=>{var t;return null!==(t=null==e?void 0:e.credentials)&&void 0!==t?t:[]}))}abortFido2ActiveRequest(e){return iD(this,void 0,void 0,function*(){this.fido2ActiveRequestManager.removeActiveRequest(e),yield this.updateOverlayCiphers(!1)})}getExcludedDomains(){return iD(this,void 0,void 0,function*(){return yield Ce(this.domainSettingsService.neverDomains$)})}storePageDetails(e,t){const i={frameId:t.frameId,tab:t.tab,details:e.details};0!==i.frameId&&i.details.fields.length&&(this.buildSubFrameOffsets(i.tab,i.frameId,i.details.url).catch(e=>this.logService.error(e)),hT.tabSendMessage(i.tab,{command:"setupRebuildSubFrameOffsetsListeners"}).catch(e=>this.logService.error(e)));const r=this.pageDetailsForTab[t.tab.id];r?r.set(t.frameId,i):this.pageDetailsForTab[t.tab.id]=new Map([[t.frameId,i]])}getSenderFrameId(e){return e.frameId}updateSubFrameData(e,t){const i=this.subFrameOffsetsForTab[t.tab.id];i&&i.set(e.subFrameData.frameId,e.subFrameData)}buildSubFrameOffsets(e,t,i){return iD(this,arguments,void 0,function*(e,t,i,r=!1){let n=0;const a=e.id;let s=this.subFrameOffsetsForTab[a];if(s||(this.subFrameOffsetsForTab[a]=new Map,s=this.subFrameOffsetsForTab[a]),!r&&s.get(t))return;const o={url:i,top:0,left:0,parentFrameIds:[0]};let l=yield hT.getFrameDetails({tabId:a,frameId:t});for(;l&&l.parentFrameId>-1;){if(n++,n>=8)return s.set(t,null),void this.triggerDestroyInlineMenuListeners(e,t);const i=yield hT.tabSendMessage(e,{command:"getSubFrameOffsets",subFrameUrl:l.url,subFrameId:l.documentId},{frameId:l.parentFrameId});if(!i)return s.set(t,null),void hT.tabSendMessage(e,{command:"getSubFrameOffsetsFromWindowMessage",subFrameId:t},{frameId:t}).catch(e=>this.logService.error(e));o.top+=i.top,o.left+=i.left,o.parentFrameIds.includes(l.parentFrameId)||o.parentFrameIds.push(l.parentFrameId),l=yield hT.getFrameDetails({tabId:a,frameId:l.parentFrameId})}s.set(t,o)})}triggerDestroyInlineMenuListeners(e,t){this.logService.error("Excessive frame depth encountered, destroying inline menu on field within frame",e,t),hT.tabSendMessage(e,{command:"destroyAutofillInlineMenuListeners"},{frameId:t}).catch(e=>this.logService.error(e))}rebuildSubFrameOffsets(e){return iD(this,void 0,void 0,function*(){this.cancelUpdateInlineMenuPosition$.next(),this.cancelInlineMenuDelayedClose$.next(!0);const t=this.subFrameOffsetsForTab[e.tab.id];if(t){const i=Array.from(t.keys());for(const t of i)yield this.buildSubFrameOffsets(e.tab,t,e.url,!0)}})}updateInlineMenuPositionAfterRepositionEvent(e){return iD(this,void 0,void 0,function*(){e&&this.isFieldCurrentlyFocused&&(this.checkIsInlineMenuButtonVisible()||this.toggleInlineMenuHidden({isInlineMenuHidden:!1,setTransparentInlineMenu:!0},e).catch(e=>this.logService.error(e)),this.updateInlineMenuPosition(e,GT).catch(e=>this.logService.error(e)),(this.inlineMenuListPort||1!==(yield this.getInlineMenuVisibility()))&&((yield this.checkFocusedFieldHasValue(e.tab))&&(this.checkIsInlineMenuCiphersPopulated(e)||(yield this.getAuthStatus())!==cu.Unlocked)||this.updateInlineMenuPosition(e,QT).catch(e=>this.logService.error(e))))})}checkFocusedFieldHasValue(e){return iD(this,void 0,void 0,function*(){var t;return!!(yield hT.tabSendMessage(e,{command:"checkMostRecentlyFocusedFieldHasValue"},{frameId:(null===(t=this.focusedFieldData)||void 0===t?void 0:t.frameId)||0}))})}fillInlineMenuCipher(e,t){return iD(this,arguments,void 0,function*({inlineMenuCipherId:e,usePasskey:t},{sender:i}){var r,n,a,s,o,l;yield hT.tabSendMessage(i.tab,{command:"collectPageDetails"},{frameId:null===(r=this.focusedFieldData)||void 0===r?void 0:r.frameId});const c=this.pageDetailsForTab[i.tab.id];if(!e||!(null==c?void 0:c.size))return;const u=this.inlineMenuCiphers.get(e);if(t&&(null===(n=u.login)||void 0===n?void 0:n.hasFido2Credentials)){if(yield this.authenticatePasskeyCredential(i,u.login.fido2Credentials[0].credentialId),this.updateLastUsedInlineMenuCipher(e,u),null===(a=u.login)||void 0===a?void 0:a.totp){const e=yield Ce(this.totpService.getCode$(u.login.totp));(null==e?void 0:e.code)?this.platformUtilsService.copyToClipboard(e.code):this.logService.error("Failed to get TOTP code for inline menu cipher")}return}if(yield this.autofillService.isPasswordRepromptRequired(u,i.tab))return;let d=Array.from(c.values());this.focusedFieldMatchesFillType(7)&&(d=this.getFilteredPageDetails(d,this.inlineMenuFieldQualificationService.isUpdateCurrentPasswordField));const h=yield this.autofillService.doAutoFill({tab:i.tab,cipher:u,pageDetails:d,fillNewPassword:!0,allowTotpAutofill:!0,focusedFieldForm:null===(s=this.focusedFieldData)||void 0===s?void 0:s.focusedFieldForm,focusedFieldOpid:null===(o=this.focusedFieldData)||void 0===o?void 0:o.focusedFieldOpid,inlineMenuFillType:null===(l=this.focusedFieldData)||void 0===l?void 0:l.inlineMenuFillType});h&&this.platformUtilsService.copyToClipboard(h),this.updateLastUsedInlineMenuCipher(e,u)})}getFilteredPageDetails(e,t){let i=structuredClone(e);return(null==i?void 0:i.length)?(i=i.map(e=>(e.details.fields=e.details.fields.filter(t),e)),i):[]}authenticatePasskeyCredential(e,t){return iD(this,void 0,void 0,function*(){const i=this.fido2ActiveRequestManager.getActiveRequest(e.tab.id);i?(chrome.webRequest.onCompleted.addListener(this.handlePasskeyAuthenticationOnCompleted,{urls:FT(e.tab.url)}),i.subject.next({type:"continue-fido2-active-request",credentialId:t})):this.logService.error("Could not complete passkey autofill due to missing active Fido2 request")})}updateLastUsedInlineMenuCipher(e,t){this.inlineMenuCiphers=new Map([[e,t],...this.inlineMenuCiphers])}checkInlineMenuFocused(e){this.senderTabHasFocusedField(e)&&(this.inlineMenuListPort?this.checkInlineMenuListFocused():this.checkInlineMenuButtonFocused(e))}checkInlineMenuButtonFocused(e){this.inlineMenuButtonPort?this.postMessageToPort(this.inlineMenuButtonPort,{command:"checkAutofillInlineMenuButtonFocused"}):this.closeInlineMenu(e,{forceCloseInlineMenu:!0})}checkInlineMenuListFocused(){this.postMessageToPort(this.inlineMenuListPort,{command:"checkAutofillInlineMenuListFocused"})}closeInlineMenu(e,{forceCloseInlineMenu:t,overlayElement:i}={}){const r="closeAutofillInlineMenu",n={frameId:0},a={overlayElement:i,isVisible:!1,forceUpdate:!0};if(this.generatedPassword=null,t)return hT.tabSendMessage(e.tab,{command:r,overlayElement:i},n).catch(e=>this.logService.error(e)),void this.updateInlineMenuElementIsVisibleStatus(a,e);if(!this.isFieldCurrentlyFocused){if(this.isFieldCurrentlyFilling)return hT.tabSendMessage(e.tab,{command:r,overlayElement:QT},n).catch(e=>this.logService.error(e)),void this.updateInlineMenuElementIsVisibleStatus(Object.assign(a,{overlayElement:QT}),e);hT.tabSendMessage(e.tab,{command:r,overlayElement:i},n).catch(e=>this.logService.error(e)),this.updateInlineMenuElementIsVisibleStatus(a,e)}}triggerDelayedInlineMenuClosure(){return iD(this,arguments,void 0,function*(e=!1){if(e||this.isFieldCurrentlyFocused)return;const t={command:"triggerDelayedAutofillInlineMenuClosure"};this.postMessageToPort(this.inlineMenuButtonPort,t),this.postMessageToPort(this.inlineMenuListPort,t)})}overlayElementClosed({overlayElement:e},t){var i,r,n,a;return this.senderTabHasFocusedField(t)?e===GT?(null===(i=this.inlineMenuButtonPort)||void 0===i||i.disconnect(),this.inlineMenuButtonPort=null,null===(r=this.inlineMenuButtonMessageConnectorPort)||void 0===r||r.disconnect(),this.inlineMenuButtonMessageConnectorPort=null,void(this.isInlineMenuButtonVisible=!1)):(null===(n=this.inlineMenuListPort)||void 0===n||n.disconnect(),this.inlineMenuListPort=null,null===(a=this.inlineMenuListMessageConnectorPort)||void 0===a||a.disconnect(),this.inlineMenuListMessageConnectorPort=null,void(this.isInlineMenuListVisible=!1)):(this.expiredPorts.forEach(e=>e.disconnect()),void(this.expiredPorts=[]))}getTotpFields(){var e,t,i;const r=null===(e=this.focusedFieldData)||void 0===e?void 0:e.tabId,n=null===(t=this.focusedFieldData)||void 0===t?void 0:t.frameId,a=this.pageDetailsForTab[r],s=null==a?void 0:a.get(n);return((null===(i=null==s?void 0:s.details)||void 0===i?void 0:i.fields)||[]).filter(e=>this.inlineMenuFieldQualificationService.isTotpField(e))}calculateTotpMultiInputMenuBounds(e){const t=this.allFieldData.filter(t=>e.some(e=>e.opid===t.opid));if(0===t.length)return null;const i=Math.min(...t.filter(e=>BT(e.rect)).map(e=>e.rect.left));return{left:i,width:Math.max(...t.filter(e=>BT(e.rect)).map(e=>e.rect.right))-i}}calculateTotpMultiInputButtonBounds(e){const t=this.allFieldData.filter(t=>e.some(e=>e.opid===t.opid));if(0===t.length)return null;const i=Math.max(...t.map(e=>e.rect.right)),r=t.find(e=>e.rect.right===i),n=r.rect.top-.39*r.rect.height;return{left:i-.3*r.rect.height,top:n}}updateInlineMenuPosition(e,t){return iD(this,void 0,void 0,function*(){var i;if(!t||!this.senderTabHasFocusedField(e))return;this.cancelInlineMenuFadeInAndPositionUpdate(),yield hT.tabSendMessage(e.tab,{command:"appendAutofillInlineMenuToDom",overlayElement:t},{frameId:0});const r=this.subFrameOffsetsForTab[null===(i=this.focusedFieldData)||void 0===i?void 0:i.tabId];let n;return r&&(n=r.get(this.focusedFieldData.frameId),null===n)?(this.rebuildSubFrameOffsets$.next(e),void this.startUpdateInlineMenuPosition$.next(e)):t===GT?(this.postMessageToPort(this.inlineMenuButtonPort,{command:"updateAutofillInlineMenuPosition",styles:this.getInlineMenuButtonPosition(n)}),void this.startInlineMenuFadeIn$.next()):(this.postMessageToPort(this.inlineMenuListPort,{command:"updateAutofillInlineMenuPosition",styles:this.getInlineMenuListPosition(n)}),void this.startInlineMenuFadeIn$.next())})}updateInlineMenuElementIsVisibleStatus({overlayElement:e,isVisible:t,forceUpdate:i},r){(i||this.senderTabHasFocusedField(r))&&(e&&e!==GT||(this.isInlineMenuButtonVisible=t),e&&e!==QT||(this.isInlineMenuListVisible=t))}getInlineMenuPosition(){return this.inlineMenuPosition}triggerInlineMenuFadeIn(){return iD(this,arguments,void 0,function*(e=!1){if(e)return;const t={command:"fadeInAutofillInlineMenuIframe"};this.postMessageToPort(this.inlineMenuButtonPort,t),this.postMessageToPort(this.inlineMenuListPort,t)})}getInlineMenuButtonPosition(e){const t=(null==e?void 0:e.top)||0,i=(null==e?void 0:e.left)||0,{width:r,height:n}=this.focusedFieldData.focusedFieldRects;let{top:a,left:s}=this.focusedFieldData.focusedFieldRects;const{paddingRight:o,paddingLeft:l}=this.focusedFieldData.focusedFieldStyles;if(this.isTotpFieldForCurrentField()){const e=this.getTotpFields();e.length>1&&({left:s,top:a}=this.calculateTotpMultiInputButtonBounds(e))}let c=.37*n;n>=35&&(c=n>=50?.47*n:.42*n);const u=parseInt(o,10),d=n-c,h=t+a+c/2,p=u>parseInt(l,10)?i+s+r-n-(u-c+2):i+s+r-n+c/2;return this.inlineMenuPosition.button={top:Math.round(h),left:Math.round(p),height:Math.round(d),width:Math.round(d)},{top:`${this.inlineMenuPosition.button.top}px`,left:`${this.inlineMenuPosition.button.left}px`,height:`${this.inlineMenuPosition.button.height}px`,width:`${this.inlineMenuPosition.button.width}px`}}getInlineMenuListPosition(e){const t=(null==e?void 0:e.top)||0,i=(null==e?void 0:e.left)||0,{top:r,height:n}=this.focusedFieldData.focusedFieldRects;let{left:a,width:s}=this.focusedFieldData.focusedFieldRects;if(this.isTotpFieldForCurrentField()){const e=this.getTotpFields();e.length>1&&({left:a,width:s}=this.calculateTotpMultiInputMenuBounds(e))}return this.inlineMenuPosition.list={top:Math.round(r+n+t),left:Math.round(a+i),height:0,width:Math.round(s)},{width:`${this.inlineMenuPosition.list.width}px`,top:`${this.inlineMenuPosition.list.top}px`,left:`${this.inlineMenuPosition.list.left}px`}}setFocusedFieldData({focusedFieldData:e,allFieldsRect:t},i){this.focusedFieldData&&this.senderTabHasFocusedField(i)&&!this.senderFrameHasFocusedField(i)&&hT.tabSendMessage(i.tab,{command:"unsetMostRecentlyFocusedField"},{frameId:this.focusedFieldData.frameId}).catch(e=>this.logService.error(e));const r=this.focusedFieldData;if(this.focusedFieldData=Object.assign(Object.assign({},e),{tabId:i.tab.id,frameId:i.frameId}),this.allFieldData=t,this.isFieldCurrentlyFocused=!0,this.shouldUpdatePasswordGeneratorMenuOnFieldFocus())this.updateInlineMenuGeneratedPasswordOnFocus(i.tab).catch(e=>this.logService.error(e));else if(this.shouldUpdateAccountCreationMenuOnFieldFocus(r))this.updateInlineMenuAccountCreationDataOnFocus(r,i).catch(e=>this.logService.error(e));else if(!this.focusedFieldMatchesFillType(null==e?void 0:e.inlineMenuFillType,r)||1===[e,r].filter(e=>(null==e?void 0:e.accountCreationFieldType)===tD).length){const t=!this.focusedFieldMatchesFillType(rm.Login,e);this.updateOverlayCiphers(t).catch(e=>this.logService.error(e))}}shouldUpdatePasswordGeneratorMenuOnFieldFocus(){return this.isInlineMenuButtonVisible&&this.focusedFieldMatchesFillType(6)}updateInlineMenuGeneratedPasswordOnFocus(e){return iD(this,void 0,void 0,function*(){(yield this.shouldShowSaveLoginInlineMenuList(e))?this.showSaveLoginInlineMenuList():yield this.updateGeneratedPassword()})}updateInlineMenuAccountCreationDataOnFocus(e,t){return iD(this,void 0,void 0,function*(){(yield this.shouldShowSaveLoginInlineMenuList(t.tab))?this.showSaveLoginInlineMenuList():e&&this.isInlineMenuButtonVisible&&(yield this.getAuthStatus())===cu.Unlocked&&(this.focusedFieldMatchesFillType(rm.Login)&&this.focusedFieldMatchesAccountCreationType(eD)?yield this.updateGeneratedPassword():yield this.updateInlineMenuListCiphers(t.tab))})}shouldUpdateAccountCreationMenuOnFieldFocus(e){return this.focusedFieldMatchesFillType(5,e)&&!this.focusedFieldMatchesFillType(5)||this.shouldShowInlineMenuAccountCreation()}showSaveLoginInlineMenuList(){this.postMessageToPort(this.inlineMenuListPort,{command:"showSaveLoginInlineMenuList"})}generatePassword(){return iD(this,void 0,void 0,function*(){this.generatedPassword=yield this.generatePasswordCallback(),yield this.addPasswordCallback(this.generatedPassword)})}updateGeneratedPassword(){return iD(this,arguments,void 0,function*(e=!1){this.generatedPassword&&!e||(yield this.generatePassword()),this.postMessageToPort(this.inlineMenuListPort,{command:"updateAutofillInlineMenuGeneratedPassword",generatedPassword:this.generatedPassword,refreshPassword:e})})}fillGeneratedPassword(e){return iD(this,void 0,void 0,function*(){var t,i;if(!this.generatedPassword)return;const r=this.pageDetailsForTab[e.sender.tab.id];if(!r)return;let n=Array.from(r.values());if(!n.length)return;this.focusedFieldMatchesFillType(rm.Login)||(n=this.getFilteredPageDetails(n,this.inlineMenuFieldQualificationService.isNewPasswordField));const a=this.buildLoginCipherView({username:"",password:this.generatedPassword,hostname:"",uri:""});yield this.autofillService.doAutoFill({tab:e.sender.tab,cipher:a,pageDetails:n,fillNewPassword:!0,allowTotpAutofill:!1,focusedFieldForm:null===(t=this.focusedFieldData)||void 0===t?void 0:t.focusedFieldForm,focusedFieldOpid:null===(i=this.focusedFieldData)||void 0===i?void 0:i.focusedFieldOpid,inlineMenuFillType:6}),globalThis.setTimeout(()=>iD(this,void 0,void 0,function*(){yield hT.tabSendMessage(e.sender.tab,{command:"generatedPasswordModifyLogin"},{frameId:this.focusedFieldData.frameId||0})}),300)})}shouldShowSaveLoginInlineMenuList(e){return iD(this,void 0,void 0,function*(){var t;if((null===(t=this.focusedFieldData)||void 0===t?void 0:t.tabId)!==e.id)return!1;const i=yield this.getInlineMenuFormFieldData(e);return!!i&&(this.shouldShowInlineMenuAccountCreation()||this.focusedFieldMatchesFillType(6))&&!(!i.password&&!i.newPassword)})}getInlineMenuFormFieldData(e){return iD(this,void 0,void 0,function*(){return yield hT.tabSendMessage(e,{command:"getInlineMenuFormFieldData",ignoreFieldFocus:!0},{frameId:this.focusedFieldData.frameId||0})})}toggleInlineMenuHidden(e,t){return iD(this,arguments,void 0,function*({isInlineMenuHidden:e,setTransparentInlineMenu:t},i){if(!this.senderTabHasFocusedField(i))return;this.cancelInlineMenuFadeIn$.next(!0);let r={display:e?"none":"block"};if(void 0!==t){const e=t?"0":"1";r=Object.assign(Object.assign({},r),{opacity:e})}const n={command:"toggleAutofillInlineMenuHidden",styles:r};this.inlineMenuButtonPort&&(this.updateInlineMenuElementIsVisibleStatus({overlayElement:GT,isVisible:!e},i),this.postMessageToPort(this.inlineMenuButtonPort,n)),this.inlineMenuListPort&&(this.isInlineMenuListVisible=!e,this.updateInlineMenuElementIsVisibleStatus({overlayElement:QT,isVisible:!e},i),this.postMessageToPort(this.inlineMenuListPort,n)),t&&this.startInlineMenuFadeIn$.next()})}openInlineMenu(e){return iD(this,arguments,void 0,function*(e,t=!1){if(this.cancelInlineMenuDelayedClose$.next(!0),t)return yield this.updateInlineMenuPosition(e,GT),void(yield this.updateInlineMenuPosition(e,QT));(yield this.checkFocusedFieldHasValue(e.tab))?yield this.openInlineMenuOnFilledField(e):yield this.openInlineMenuOnEmptyField(e)})}openInlineMenuOnEmptyField(e){return iD(this,void 0,void 0,function*(){if(2===(yield this.getInlineMenuVisibility()))return yield this.updateInlineMenuPosition(e,GT),void(yield this.updateInlineMenuPosition(e,QT));this.inlineMenuListPort&&this.closeInlineMenu(e,{forceCloseInlineMenu:!0,overlayElement:QT}),yield this.updateInlineMenuPosition(e,GT)})}openInlineMenuOnFilledField(e){return iD(this,void 0,void 0,function*(){if(yield this.shouldShowSaveLoginInlineMenuList(e.tab))return yield this.updateInlineMenuPosition(e,GT),void(yield this.updateInlineMenuPosition(e,QT));this.isInlineMenuListVisible&&this.closeInlineMenu(e,{forceCloseInlineMenu:!0,overlayElement:QT}),yield this.updateInlineMenuPosition(e,GT)})}getInlineMenuVisibility(){return iD(this,void 0,void 0,function*(){return yield Ce(this.autofillSettingsService.inlineMenuVisibility$)})}getInlineMenuCardsVisibility(){return iD(this,void 0,void 0,function*(){return yield Ce(this.autofillSettingsService.showInlineMenuCards$)})}getInlineMenuIdentitiesVisibility(){return iD(this,void 0,void 0,function*(){return yield Ce(this.autofillSettingsService.showInlineMenuIdentities$)})}getAuthStatus(){return iD(this,void 0,void 0,function*(){return yield Ce(this.authService.activeAccountStatus$)})}updateInlineMenuButtonAuthStatus(){return iD(this,void 0,void 0,function*(){this.postMessageToPort(this.inlineMenuButtonPort,{command:"updateInlineMenuButtonAuthStatus",authStatus:yield this.getAuthStatus()})})}handleInlineMenuButtonClicked(e){return iD(this,void 0,void 0,function*(){this.cancelInlineMenuDelayedClose$.next(!0),this.cancelInlineMenuFadeInAndPositionUpdate(),(yield this.getAuthStatus())===cu.Unlocked?yield this.openInlineMenu(e.sender,!0):yield this.unlockVault(e)})}unlockVault(e){return iD(this,void 0,void 0,function*(){const{sender:t}=e;this.closeInlineMenu(e.sender,{forceCloseInlineMenu:!0});const i={commandToRetry:{message:{command:"openAutofillInlineMenu"},sender:t},target:"overlay.background"};yield hT.tabSendMessageData(t.tab,"addToLockedVaultPendingNotifications",i),yield this.openUnlockPopout(t.tab)})}viewSelectedCipher(e,t){return iD(this,arguments,void 0,function*({inlineMenuCipherId:e},{sender:t}){const i=this.inlineMenuCiphers.get(e);i&&(this.closeInlineMenu(t),yield this.openViewVaultItemPopout(t.tab,{cipherId:i.id,action:"show-autofill-button"}))})}focusInlineMenuList(){this.postMessageToPort(this.inlineMenuListPort,{command:"focusAutofillInlineMenuList"})}unlockCompleted(e){return iD(this,void 0,void 0,function*(){var t,i,r;yield this.updateInlineMenuButtonAuthStatus();const n="openAutofillInlineMenu"===(null===(r=null===(i=null===(t=e.data)||void 0===t?void 0:t.commandToRetry)||void 0===i?void 0:i.message)||void 0===r?void 0:r.command);yield this.updateOverlayCiphers(!0,n)})}getInlineMenuTranslations(){if(!this.inlineMenuPageTranslations){const e=["addNewCardItemAria","addNewIdentityItemAria","addNewLoginItemAria","addNewVaultItem","authenticating","cardNumberEndsWith","fillCredentialsFor","fillGeneratedPassword","fillVerificationCode","fillVerificationCodeAria","generatedPassword","lowercaseAriaLabel","logInWithPasskeyAriaLabel","newCard","newIdentity","newItem","newLogin","noItemsToShow","opensInANewWindow","passkeys","passwordRegenerated","passwords","regeneratePassword","saveToBitwarden","toggleBitwardenVaultOverlay","totpCodeAria","totpSecondsSpanAria","unlockAccount","unlockAccountAria","unlockYourAccountToViewAutofillSuggestions","uppercaseAriaLabel","username","view",...Object.values(LT)];this.inlineMenuPageTranslations=e.reduce((e,t)=>(e[t]=this.i18nService.translate(t),e),{})}return this.inlineMenuPageTranslations}redirectInlineMenuFocusOut({direction:e},{sender:t}){e&&hT.tabSendMessageData(t.tab,"redirectAutofillInlineMenuFocusOut",{direction:e}).catch(e=>this.logService.error(e))}getNewVaultItemDetails({addNewCipherType:e},{sender:t}){e&&this.senderTabHasFocusedField(t)&&(this.currentAddNewItemData={addNewCipherType:e,sender:t},hT.tabSendMessage(t.tab,{command:"addNewVaultItemFromOverlay",addNewCipherType:e}).catch(e=>this.logService.error(e)))}addNewVaultItem(e,t){return iD(this,arguments,void 0,function*({addNewCipherType:e,login:t,card:i,identity:r},n){this.currentAddNewItemData&&n.tab.id===this.currentAddNewItemData.sender.tab.id&&e&&this.currentAddNewItemData.addNewCipherType===e&&(t&&this.isAddingNewLogin()&&this.updateCurrentAddNewItemLogin(t,n),i&&this.isAddingNewCard()&&this.updateCurrentAddNewItemCard(i),r&&this.isAddingNewIdentity()&&this.updateCurrentAddNewItemIdentity(r),this.addNewVaultItem$.next(this.currentAddNewItemData))})}isAddingNewLogin(){return this.currentAddNewItemData.addNewCipherType===rm.Login}isAddingNewCard(){return this.currentAddNewItemData.addNewCipherType===rm.Card}isAddingNewIdentity(){return this.currentAddNewItemData.addNewCipherType===rm.Identity}updateCurrentAddNewItemLogin(e,t){const{username:i,password:r}=e;if(this.partialLoginDataFoundInSubFrame(t,e)&&(e.uri="",e.hostname=""),!this.currentAddNewItemData.login)return void(this.currentAddNewItemData.login=e);const n=this.currentAddNewItemData.login;0!==t.frameId||!n.hostname||i||r||(e.uri="",e.hostname=""),this.currentAddNewItemData.login={uri:e.uri||n.uri,hostname:e.hostname||n.hostname,username:i||n.username,password:r||n.password}}partialLoginDataFoundInSubFrame(e,t){const{frameId:i}=e,{username:r,password:n}=t;return!(0===i||r&&n)}updateCurrentAddNewItemCard(e){if(!this.currentAddNewItemData.card)return void(this.currentAddNewItemData.card=e);const t=this.currentAddNewItemData.card;this.currentAddNewItemData.card={cardholderName:e.cardholderName||t.cardholderName,number:e.number||t.number,expirationMonth:e.expirationMonth||t.expirationMonth,expirationYear:e.expirationYear||t.expirationYear,expirationDate:e.expirationDate||t.expirationDate,cvv:e.cvv||t.cvv}}updateCurrentAddNewItemIdentity(e){if(!this.currentAddNewItemData.identity)return void(this.currentAddNewItemData.identity=e);const t=this.currentAddNewItemData.identity;this.currentAddNewItemData.identity={title:e.title||t.title,firstName:e.firstName||t.firstName,middleName:e.middleName||t.middleName,lastName:e.lastName||t.lastName,fullName:e.fullName||t.fullName,address1:e.address1||t.address1,address2:e.address2||t.address2,address3:e.address3||t.address3,city:e.city||t.city,state:e.state||t.state,postalCode:e.postalCode||t.postalCode,country:e.country||t.country,company:e.company||t.company,phone:e.phone||t.phone,email:e.email||t.email,username:e.username||t.username}}buildCipherAndOpenAddEditVaultItemPopout(e){return iD(this,arguments,void 0,function*({login:e,card:t,identity:i,sender:r,addNewCipherType:n}){const a=this.buildNewVaultItemCipherView({login:e,card:t,identity:i});if(a){try{this.closeInlineMenu(r);const e=yield Ce(this.accountService.activeAccount$.pipe(tu));yield this.cipherService.setAddEditCipherInfo({cipher:a,collectionIds:a.collectionIds},e),yield this.openAddEditVaultItemPopout(r.tab,{cipherId:a.id,cipherType:n})}catch(e){this.logService.error("Error building cipher and opening add/edit vault item popout",e)}this.currentAddNewItemData=null}else this.currentAddNewItemData=null})}buildNewVaultItemCipherView({login:e,card:t,identity:i}){return e&&this.isAddingNewLogin()?this.buildLoginCipherView(e):t&&this.isAddingNewCard()?this.buildCardCipherView(t):i&&this.isAddingNewIdentity()?this.buildIdentityCipherView(i):void 0}buildLoginCipherView(e){const t=new tw;t.uri=e.uri;const i=new nw;i.uris=[t],i.username=e.username||"",i.password=e.password||"";const r=new lw;return r.name=(Tt.getHostname(e.uri)||e.hostname).replace(/^www\./,""),r.folderId=null,r.type=rm.Login,r.login=i,r}buildCardCipherView(e){const t=new Hb;if(t.cardholderName=e.cardholderName||"",t.number=e.number||"",t.code=e.cvv||"",t.brand=e.number?Hb.getCardBrandByPatterns(e.number):"",!e.expirationDate||e.expirationMonth||e.expirationYear)t.expMonth=e.expirationMonth||"",t.expYear=e.expirationYear||"";else{const[i,r]=function(e){var t,i;let r=null,n=null;const a=function(e){var t;let i=e.replace(fm,"").trim();const r=(null===(t=i.match(gm))||void 0===t?void 0:t[0])||null;let n=[i];if(null==r?void 0:r.length){const e=/\s/.test(r)?"\\s":"\\"+r;i=i.replace(new RegExp(`[^\\d${e}]`,"g"),"").replace(new RegExp(`[${e}]{2,}`,"g"),r),n=i.split(r)}return n.filter(e=>null==e?void 0:e.length)}(e);if(a.length<1)return[null,null];const s=(null===(t=a[0])||void 0===t?void 0:t.replace(fm,""))||"",o=(null===(i=a[1])||void 0===i?void 0:i.replace(fm,""))||"";if(1===a.length){const[e,t]=function(e){if(e.length>4){const[t,i]=e.split(new RegExp(`(?=${mm})|(?<=${mm})`,"g")).sort((e,t)=>e.length>t.length?-1:1);return[t,i]}if(4===e.length){const t=e.slice(0,2),i=e.slice(-2);let r=i,n=t;return ym.test(t)||(r=t,n=i),[r,n]}let t=null,i=null;const r=e.split(/(?<=0[1-9]{1})|(?=0[1-9]{1})/);if(r.length>1)t=r[0],i=r[1],r[0].startsWith("0")&&(i=r[0],t=r[1]);else{t=e.slice(0,2),i=e.slice(-1);const r=(new Date).getFullYear(),n=dg(t),a=n&&parseInt(n,10),s=dg(e.slice(-2)),o=s&&parseInt(s,10);a&&a=r&&(t=e.slice(-2),i=e.slice(0,1))}return[t,i]}(s);r=e,n=t}else{const[e,t]=function([e,t]){if(vm.test(e))return[e,t];if(vm.test(t))return[t,e];if(/\d{2}/.test(e)&&!ym.test(e))return[e,t];if(/\d{2}/.test(t)&&!ym.test(t))return[t,e];let i=e,r=t;return ym.test(e)&&(i=t,r=e),[i,r]}([s,o]);r=e,n=t}const l=r?dg(r):null,c=null==n?void 0:n.replace(/^0+/,"").slice(0,2);return r=(null==l?void 0:l.length)?l:null,n=(null==c?void 0:c.length)?c:null,[r,n]}(e.expirationDate);t.expMonth=r||"",t.expYear=i||""}const i=new lw;return i.name="",i.folderId=null,i.type=rm.Card,i.card=t,i}buildIdentityCipherView(e){const t=new Yb;t.title=e.title||"",t.firstName=e.firstName||"",t.middleName=e.middleName||"",t.lastName=e.lastName||"",t.address1=e.address1||"",t.address2=e.address2||"",t.address3=e.address3||"",t.city=e.city||"",t.state=e.state||"",t.postalCode=e.postalCode||"",t.country=e.country||"",t.company=e.company||"",t.phone=e.phone||"",t.email=e.email||"",t.username=e.username||"",!e.fullName||t.firstName||t.lastName||this.buildIdentityNameParts(e,t);const i=new lw;return i.name="",i.folderId=null,i.type=rm.Identity,i.identity=t,i}buildIdentityNameParts(e,t){const i=e.fullName.split(" ");if(1!==i.length){if(2===i.length)return t.firstName=i[0]||"",void(t.lastName=i[1]||"");t.firstName=i[0]||"",t.middleName=i[1]||"",t.lastName=i[2]||""}else t.firstName=i[0]||""}updateIsFieldCurrentlyFocused(e,t){this.focusedFieldData&&!this.senderFrameHasFocusedField(t)||(this.isFieldCurrentlyFocused=e.isFieldCurrentlyFocused)}checkIsFieldCurrentlyFocused(){return this.isFieldCurrentlyFocused}updateIsFieldCurrentlyFilling(e){this.isFieldCurrentlyFilling=e.isFieldCurrentlyFilling}checkIsFieldCurrentlyFilling(){return this.isFieldCurrentlyFilling}checkIsInlineMenuButtonVisible(){return this.isInlineMenuButtonVisible}checkIsInlineMenuListVisible(){return this.isInlineMenuListVisible}checkIsInlineMenuCiphersPopulated(e){return this.senderTabHasFocusedField(e)&&this.currentInlineMenuCiphersCount>0}updateInlineMenuButtonColorScheme(){this.postMessageToPort(this.inlineMenuButtonPort,{command:"updateAutofillInlineMenuColorScheme"})}updateInlineMenuListHeight(e){var t;const i=parseInt(null===(t=e.styles)||void 0===t?void 0:t.height);this.inlineMenuPosition.list&&i>0&&(this.inlineMenuPosition.list.height=i),this.postMessageToPort(this.inlineMenuListPort,{command:"updateAutofillInlineMenuPosition",styles:e.styles})}checkShouldRepositionInlineMenu(e){if(!this.focusedFieldData||!this.senderTabHasFocusedField(e))return!1;if(this.senderFrameHasFocusedField(e))return!0;const t=this.subFrameOffsetsForTab[e.tab.id];if(t)for(const i of t.values())if(null==i?void 0:i.parentFrameIds.includes(e.frameId))return!0;return!1}senderTabHasFocusedField(e){var t;return e.tab.id===(null===(t=this.focusedFieldData)||void 0===t?void 0:t.tabId)}senderFrameHasFocusedField(e){if(!this.focusedFieldData)return!1;const{tabId:t,frameId:i}=this.focusedFieldData;return e.tab.id===t&&e.frameId===i}triggerOverlayReposition(e){return iD(this,void 0,void 0,function*(){this.checkShouldRepositionInlineMenu(e)&&(this.resetFocusedFieldSubFrameOffsets(e),this.cancelInlineMenuFadeInAndPositionUpdate(),this.toggleInlineMenuHidden({isInlineMenuHidden:!0},e).catch(e=>this.logService.error(e)),this.repositionInlineMenu$.next(e))})}resetFocusedFieldSubFrameOffsets(e){var t;(null===(t=this.focusedFieldData)||void 0===t?void 0:t.frameId)>0&&this.subFrameOffsetsForTab[e.tab.id]&&this.subFrameOffsetsForTab[e.tab.id].set(this.focusedFieldData.frameId,null)}triggerSubFrameFocusInRebuild(e){return iD(this,void 0,void 0,function*(){this.cancelInlineMenuFadeInAndPositionUpdate(),this.resetFocusedFieldSubFrameOffsets(e),this.rebuildSubFrameOffsets$.next(e),this.repositionInlineMenu$.next(e)})}closeInlineMenuAfterReposition(e){return iD(this,void 0,void 0,function*(){yield this.toggleInlineMenuHidden({isInlineMenuHidden:!1,setTransparentInlineMenu:!0},e),this.closeInlineMenu(e,{forceCloseInlineMenu:!0})})}cancelInlineMenuFadeInAndPositionUpdate(){this.cancelInlineMenuFadeIn$.next(!0),this.cancelUpdateInlineMenuPosition$.next()}setupExtensionListeners(){hT.messageListener("overlay.background",this.handleExtensionMessage),hT.addListener(chrome.webNavigation.onCommitted,this.handleWebNavigationOnCommitted),hT.addListener(chrome.runtime.onConnect,this.handlePortOnConnect)}storeOverlayPort(e){return e.name===XT?(this.storeExpiredOverlayPort(this.inlineMenuListPort),void(this.inlineMenuListPort=e)):e.name===JT?(this.storeExpiredOverlayPort(this.inlineMenuButtonPort),void(this.inlineMenuButtonPort=e)):e.name===YT?(this.storeExpiredOverlayPort(this.inlineMenuButtonMessageConnectorPort),void(this.inlineMenuButtonMessageConnectorPort=e)):e.name===ZT?(this.storeExpiredOverlayPort(this.inlineMenuListMessageConnectorPort),void(this.inlineMenuListMessageConnectorPort=e)):void 0}storeExpiredOverlayPort(e){e&&this.expiredPorts.push(e)}shouldInitInlineMenuPasswordGenerator(e,t,i){return iD(this,void 0,void 0,function*(){return!(!t||e!==cu.Unlocked)&&(!!(this.focusedFieldMatchesFillType(6)||i&&this.focusedFieldMatchesAccountCreationType(eD))&&(this.generatedPassword||(yield this.generatePassword()),!0))})}}var nD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class aD{constructor(e,t,i){this.main=e,this.notificationBackground=t,this.overlayBackground=i,this.focusedWindowId=-1,this.handleWindowOnFocusChanged=e=>nD(this,void 0,void 0,function*(){null==e||e<0||(this.focusedWindowId=e,yield this.updateCurrentTabData(),this.main.messagingService.send("windowChanged"))}),this.handleTabOnActivated=()=>nD(this,void 0,void 0,function*(){yield this.updateCurrentTabData(),this.main.messagingService.send("tabChanged")}),this.handleTabOnReplaced=()=>nD(this,void 0,void 0,function*(){this.main.onReplacedRan||(this.main.onReplacedRan=!0,yield this.notificationBackground.checkNotificationQueue(),yield this.updateCurrentTabData(),this.main.messagingService.send("tabChanged"))}),this.handleTabOnUpdated=(e,t,i)=>nD(this,void 0,void 0,function*(){this.focusedWindowId>0&&i.windowId!==this.focusedWindowId||i.active&&(yield this.overlayBackground.updateOverlayCiphers(!1),this.main.onUpdatedRan||(this.main.onUpdatedRan=!0,yield this.notificationBackground.checkNotificationQueue(i),yield this.main.refreshMenu(),this.main.messagingService.send("tabChanged")))}),this.handleTabOnRemoved=e=>nD(this,void 0,void 0,function*(){this.overlayBackground.removePageDetails(e)}),this.updateCurrentTabData=()=>nD(this,void 0,void 0,function*(){yield Promise.all([this.main.refreshMenu(),this.overlayBackground.updateOverlayCiphers(!1)])})}init(){return nD(this,void 0,void 0,function*(){chrome.tabs&&chrome.windows&&(this.updateCurrentTabData(),this.setupTabEventListeners())})}setupTabEventListeners(){chrome.windows.onFocusChanged.addListener(this.handleWindowOnFocusChanged),chrome.tabs.onActivated.addListener(this.handleTabOnActivated),chrome.tabs.onReplaced.addListener(this.handleTabOnReplaced),chrome.tabs.onUpdated.addListener(this.handleTabOnUpdated),chrome.tabs.onRemoved.addListener(this.handleTabOnRemoved)}}var sD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class oD{constructor(e,t,i,r,n){this.cipherService=t,this.authService=i,this.accountService=r,this.webRequest=n,this.pendingAuthRequests=new Set([]),this.isFirefox=e.isFirefox()}startListening(){this.webRequest.onAuthRequired.addListener((e,t)=>sD(this,void 0,void 0,function*(){if(e.url&&!this.pendingAuthRequests.has(e.requestId)){if(this.pendingAuthRequests.add(e.requestId),this.isFirefox)return new Promise((t,i)=>sD(this,void 0,void 0,function*(){yield this.resolveAuthCredentials(e.url,t,i)}));yield this.resolveAuthCredentials(e.url,t,t)}else t&&t(null)}),{urls:["http://*/*","https://*/*"]},[this.isFirefox?"blocking":"asyncBlocking"]),this.webRequest.onCompleted.addListener(e=>this.completeAuthRequest(e),{urls:["http://*/*","https://*/*"]}),this.webRequest.onErrorOccurred.addListener(e=>this.completeAuthRequest(e),{urls:["http://*/*","https://*/*"]})}resolveAuthCredentials(e,t,i){return sD(this,void 0,void 0,function*(){var r,n;const a=yield Ce(this.accountService.activeAccount$.pipe(iu));if(null!=a)if((yield Ce(this.authService.authStatusFor$(a)))e.cipherType===rm.Card);for(const t of this.initContextMenuItems){const{requiresPremiumAccess:n,requiresUnblockedUri:a}=t,s=uD(t,["requiresPremiumAccess","requiresUnblockedUri"]);n&&!i||(null===(e=t.id)||void 0===e?void 0:e.startsWith(bm))&&r||(yield lD.create(Object.assign(Object.assign({},s),{contexts:["all"]})))}}catch(e){e instanceof Error&&this.logService.warning(e.message)}finally{this.initRunning=!1}return!0})}static removeAll(){return cD(this,void 0,void 0,function*(){return new Promise((e,t)=>{chrome.contextMenus.removeAll(()=>{chrome.runtime.lastError?t(chrome.runtime.lastError):e()}),this.existingMenuItems=new Set})})}static remove(e){return new Promise((t,i)=>{const r=chrome.contextMenus.remove(e,()=>{chrome.runtime.lastError?i(chrome.runtime.lastError):t()});this.existingMenuItems.delete(`${r}`)})}loadOptions(e,t,i){return cD(this,void 0,void 0,function*(){var r,n,a,s,o,l,c;try{const u=lD.sanitizeContextMenuTitle(e),d=e=>cD(this,void 0,void 0,function*(){const i=`${e}_${t}`;if(!lD.existingMenuItems.has(i))return yield lD.create({type:"normal",id:i,parentId:e,title:u,contexts:["all"]})});i&&(i.type!==rm.Login||Tt.isNullOrEmpty(null===(r=i.login)||void 0===r?void 0:r.username)&&Tt.isNullOrEmpty(null===(n=i.login)||void 0===n?void 0:n.password)&&Tt.isNullOrEmpty(null===(a=i.login)||void 0===a?void 0:a.totp))||(yield d(wm)),i&&(i.type!==rm.Login||Tt.isNullOrEmpty(null===(s=i.login)||void 0===s?void 0:s.password))||(null===(o=null==i?void 0:i.viewPassword)||void 0===o||o)&&(yield d(_m)),i&&(i.type!==rm.Login||Tt.isNullOrEmpty(null===(l=i.login)||void 0===l?void 0:l.username))||(yield d(xm));const h=yield Ce(this.accountService.activeAccount$);!((null==h?void 0:h.id)&&(yield Ce(this.billingAccountProfileStateService.hasPremiumFromAnySource$(h.id))))||i&&Tt.isNullOrEmpty(null===(c=i.login)||void 0===c?void 0:c.totp)||(yield d(Cm)),i&&i.type!==rm.Card||t===zm||(yield d(bm)),i&&i.type!==rm.Identity||t===zm||(yield d(km))}catch(e){e instanceof Error&&this.logService.warning(e.message)}})}static sanitizeContextMenuTitle(e){return e.replace(/&/g,"&&")}noAccess(){return cD(this,void 0,void 0,function*(){if(yield this.init()){const e=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id))),t=null!=e&&(yield Ce(this.tokenService.hasAccessToken$(e)));this.loadOptions(this.i18nService.t(t?"unlockVaultMenu":"loginToVaultMenu"),Am).catch(e=>{if(e instanceof Error)return this.logService.warning(e.message)})}})}removeBlockedUriMenuItems(){return cD(this,void 0,void 0,function*(){try{for(const e of this.initContextMenuItems)e.requiresUnblockedUri&&e.id&&(yield lD.remove(e.id))}catch(e){e instanceof Error&&this.logService.warning(e.message)}})}noCards(){return cD(this,void 0,void 0,function*(){try{for(const e of this.noCardsContextMenuItems)yield lD.create(e)}catch(e){e instanceof Error&&this.logService.warning(e.message)}})}noIdentities(){return cD(this,void 0,void 0,function*(){try{for(const e of this.noIdentitiesContextMenuItems)yield lD.create(e)}catch(e){e instanceof Error&&this.logService.warning(e.message)}})}noLogins(){return cD(this,void 0,void 0,function*(){try{for(const e of this.noLoginsContextMenuItems)yield lD.create(e);yield this.loadOptions(this.i18nService.t("addLoginMenu"),zm)}catch(e){e instanceof Error&&this.logService.warning(e.message)}})}}lD=dD,dD.existingMenuItems=new Set,dD.create=e=>cD(void 0,void 0,void 0,function*(){if(chrome.contextMenus)return new Promise((t,i)=>{const r=chrome.contextMenus.create(e,()=>{if(chrome.runtime.lastError)return i(chrome.runtime.lastError);t()});return lD.existingMenuItems.add(`${r}`),r})});var hD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class pD{constructor(e,t,i,r){this.mainContextMenuHandler=e,this.authService=t,this.cipherService=i,this.accountService=r}update(e){return hD(this,arguments,void 0,function*(e,t=!1){if(this.mainContextMenuHandler.initRunning)return;const i=yield this.authService.getAuthStatus();if(yield dD.removeAll(),i!==cu.Unlocked)return void(yield this.mainContextMenuHandler.noAccess());if(!(yield this.mainContextMenuHandler.init()))return;const r=yield Ce(this.accountService.activeAccount$.pipe(iu));if(null==r)return;const n=yield this.cipherService.getAllDecryptedForUrl(e,r,[rm.Card,rm.Identity]);n.sort((e,t)=>this.cipherService.sortCiphersByLastUsedThenName(e,t));const a=n.reduce((e,t)=>{if(!(null==t?void 0:t.type))return e;const i=e[t.type]||[];return Object.assign(Object.assign({},e),{[t.type]:[...i,t]})},{[rm.Login]:[],[rm.Card]:[],[rm.Identity]:[]});0===a[rm.Login].length&&(yield this.mainContextMenuHandler.noLogins()),0===a[rm.Identity].length&&(yield this.mainContextMenuHandler.noIdentities()),0===a[rm.Card].length&&(yield this.mainContextMenuHandler.noCards());for(const e of n)yield this.updateForCipher(e);t&&(yield this.mainContextMenuHandler.removeBlockedUriMenuItems())})}updateForCipher(e){return hD(this,void 0,void 0,function*(){var t,i;if(null==e||!new Set([rm.Login,rm.Card,rm.Identity]).has(e.type))return;let r=e.name;e.type===rm.Login&&!Tt.isNullOrEmpty(r)&&(null===(t=e.login)||void 0===t?void 0:t.username)&&(r+=` (${e.login.username})`),e.type===rm.Card&&(null===(i=e.card)||void 0===i?void 0:i.subTitle)&&(r+=` ${e.card.subTitle}`),yield this.mainContextMenuHandler.loadOptions(r,e.id,e)})}}var mD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class gD{constructor(e,t,i,r,n,a,s,o,l){this.copyToClipboard=e,this.generatePasswordToClipboard=t,this.autofillAction=i,this.authService=r,this.cipherService=n,this.totpService=a,this.eventCollectionService=s,this.userVerificationService=o,this.accountService=l}run(e,t){return mD(this,void 0,void 0,function*(){if(t)switch(e.menuItemId){case Pm:yield this.generatePasswordToClipboard(t);break;case Sm:if(!t.id)return;this.copyToClipboard({text:yield this.getIdentifier(t,e),tab:t});break;default:yield this.cipherAction(e,t)}})}cipherAction(e,t){return mD(this,void 0,void 0,function*(){var i,r,n;if(!t)return;if((yield this.authService.getAuthStatus())e===a);if(s||o)switch(yield this.accountService.setAccountActivity(l,new Date),e.parentMenuItemId){case wm:case km:case bm:{const e=this.getCipherCreationType(a);if(e){yield PT(t,{cipherType:e});break}if(!s)break;(yield this.isPasswordRepromptRequired(s))?yield zT(t,{cipherId:s.id,action:wm}):yield this.autofillAction(t,s);break}case xm:if(a===zm){yield PT(t,{cipherType:rm.Login});break}if(!s||!(null===(i=s.login)||void 0===i?void 0:i.username))break;this.copyToClipboard({text:s.login.username,tab:t});break;case _m:if(a===zm){yield PT(t,{cipherType:rm.Login});break}if(!s||!(null===(r=s.login)||void 0===r?void 0:r.password))break;(yield this.isPasswordRepromptRequired(s))?yield zT(t,{cipherId:s.id,action:_m}):(this.copyToClipboard({text:s.login.password,tab:t}),this.eventCollectionService.collect(oh.Cipher_ClientCopiedPassword,s.id));break;case Cm:if(a===zm){yield PT(t,{cipherType:rm.Login});break}if(!s||!(null===(n=s.login)||void 0===n?void 0:n.totp))break;if(yield this.isPasswordRepromptRequired(s))yield zT(t,{cipherId:s.id,action:Cm});else{const e=yield Ce(this.totpService.getCode$(s.login.totp));this.copyToClipboard({text:e.code,tab:t})}}}})}isPasswordRepromptRequired(e){return mD(this,void 0,void 0,function*(){return e.reprompt===tm.Password&&(yield this.userVerificationService.hasMasterPasswordAndMasterKeyHash())})}getCipherCreationType(e){return e===Em?rm.Identity:e===Im?rm.Card:e===zm?rm.Login:null}getIdentifier(e,t){return mD(this,void 0,void 0,function*(){const i=e.id;return new Promise((e,r)=>{hT.sendTabsMessage(i,{command:"getClickedElement"},{frameId:t.frameId},t=>{chrome.runtime.lastError?r(chrome.runtime.lastError):e(t)})})})}}class fD{constructor(){this.abortControllers=new Map}runWithAbortController(e,t){const i=new AbortController;return this.abortControllers.set(e,i),t(i).finally(()=>{this.abortControllers.delete(e)})}abort(e){var t;null===(t=this.abortControllers.get(e))||void 0===t||t.abort()}}const yD="content/fido2-page-script.js",vD="content/fido2-content-script.js",bD="fido2-page-script-registration",wD="fido2-content-script-registration",kD="fido2-injected-content-script-port";var SD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class _D{constructor(e,t,i,r,n,a){this.logService=e,this.fido2ActiveRequestManager=t,this.fido2ClientService=i,this.vaultSettingsService=r,this.scriptInjectorService=n,this.authService=a,this.abortManager=new fD,this.fido2ContentScriptPortsSet=new Set,this.activeCredentialRequests=new Set,this.sharedInjectionDetails={runAt:"document_start"},this.sharedRegistrationOptions=Object.assign({matches:["https://*/*","http://localhost/*"],excludeMatches:["https://*/*.xml*"],allFrames:!0},this.sharedInjectionDetails),this.extensionMessageHandlers={fido2AbortRequest:({message:e})=>this.abortRequest(e),fido2RegisterCredentialRequest:({message:e,sender:t})=>this.registerCredentialRequest(e,t),fido2GetCredentialRequest:({message:e,sender:t})=>this.getCredentialRequest(e,t)},this.handleCredentialRequest=(e,t,i)=>SD(this,[e,t,i],void 0,function*({requestId:e,data:t},i,r){this.activeCredentialRequests.add(i.id);try{return yield this.abortManager.runWithAbortController(e,e=>SD(this,void 0,void 0,function*(){try{return yield r(t,i,e)}finally{yield hT.focusTab(i.id),yield hT.focusWindow(i.windowId)}}))}finally{this.activeCredentialRequests.delete(i.id)}}),this.handleExtensionMessage=(e,t,i)=>{const r=this.extensionMessageHandlers[null==e?void 0:e.command];if(!r)return null;const n=r({message:e,sender:t});return void 0===n?null:(Promise.resolve(n).then(e=>i(e),e=>i({error:Object.assign(Object.assign({},e),{message:e.message})})).catch(this.logService.error),!0)},this.handleInjectedScriptPortConnection=e=>SD(this,void 0,void 0,function*(){var t;if(e.name===kD&&(null===(t=e.sender)||void 0===t?void 0:t.url))try{const{hostname:t,origin:i}=new URL(e.sender.url);if(!(yield this.fido2ClientService.isFido2FeatureEnabled(t,i)))return void e.disconnect();this.fido2ContentScriptPortsSet.add(e),e.onDisconnect.addListener(this.handleInjectScriptPortOnDisconnect)}catch(t){this.logService.error(t),e.disconnect()}}),this.handleInjectScriptPortOnDisconnect=e=>{e.name===kD&&this.fido2ContentScriptPortsSet.delete(e)}}isCredentialRequestInProgress(e){return this.activeCredentialRequests.has(e)}init(){hT.messageListener("fido2.background",this.handleExtensionMessage),hT.addListener(chrome.runtime.onConnect,this.handleInjectedScriptPortConnection),this.vaultSettingsService.enablePasskeys$.pipe(wb(void 0),g_()).subscribe(([e,t])=>this.handleEnablePasskeysUpdate(e,t)),this.currentAuthStatus$=this.authService.activeAccountStatus$.pipe(wb(void 0),g_()).subscribe(([e,t])=>this.handleAuthStatusUpdate(t))}handleAuthStatusUpdate(e){return SD(this,void 0,void 0,function*(){if(e===cu.LoggedOut)return;const t=yield this.isPasskeySettingEnabled();yield this.handleEnablePasskeysUpdate(t,t),this.currentAuthStatus$.unsubscribe()})}injectFido2ContentScriptsInAllTabs(){return SD(this,void 0,void 0,function*(){var e;const t=yield hT.tabsQuery({});for(let i=0;i{e.disconnect(),this.fido2ContentScriptPortsSet.delete(e)})}abortRequest(e){this.abortManager.abort(e.abortedRequestId)}registerCredentialRequest(e,t){return SD(this,void 0,void 0,function*(){return yield this.handleCredentialRequest(e,t.tab,this.fido2ClientService.createCredential.bind(this.fido2ClientService))})}getCredentialRequest(e,t){return SD(this,void 0,void 0,function*(){return yield this.handleCredentialRequest(e,t.tab,this.fido2ClientService.assertCredential.bind(this.fido2ClientService))})}isPasskeySettingEnabled(){return SD(this,void 0,void 0,function*(){return yield Ce(this.vaultSettingsService.enablePasskeys$)})}getFido2PageScriptAppendFileName(){return SD(this,void 0,void 0,function*(){return"content/fido2-page-script-delay-append-mv2.js"})}}function xD(e){return new $(t=>{const i=(...e)=>{chrome.runtime.lastError?t.error(chrome.runtime.lastError):t.next(e)};return hT.addListener(e,i),()=>hT.removeListener(e,i)})}var CD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ID="ConfirmNewCredentialResponse",ED="AbortResponse";class zD extends Error{constructor(){super("Fido2UserInterfaceSession was closed")}}class PD{constructor(e){this.authService=e}newSession(e,t,i){return CD(this,void 0,void 0,function*(){return yield AD.create(this.authService,e,t,i)})}}class AD{static create(e,t,i,r){return CD(this,void 0,void 0,function*(){return new AD(e,t,i,r)})}static sendMessage(e){hT.sendMessage("BrowserFido2UserInterfaceServiceMessage",e)}static abortPopout(e,t=!1){this.sendMessage({sessionId:e,type:ED,fallbackRequested:t})}static confirmNewCredentialResponse(e,t,i){this.sendMessage({sessionId:e,type:ID,cipherId:t,userVerified:i})}constructor(e,t,i,r=new AbortController,n=Tt.newGuid()){this.authService=e,this.fallbackSupported=t,this.tab=i,this.abortController=r,this.sessionId=n,this.closed=!1,this.messages$=hT.messageListener$().pipe(Ie(e=>e.sessionId===this.sessionId)),this.connected$=new $c(!1),this.destroy$=new H,this.messages$.pipe(Ie(e=>"ConnectResponse"===e.type),ci(1),m_(this.destroy$)).subscribe(()=>{this.connected$.next(!0)}),ey(r.signal,"abort").pipe(m_(this.destroy$)).subscribe(()=>{this.close(),AD.sendMessage({type:"AbortRequest",sessionId:this.sessionId})}),this.messages$.pipe(Ie(e=>e.type===ED),ci(1),m_(this.destroy$)).subscribe(e=>{e.type===ED&&(this.close(),this.abort(e.fallbackRequested))}),this.windowClosed$=xD(chrome.windows.onRemoved).pipe(X(([e])=>e)),AD.sendMessage({type:"NewSessionCreatedRequest",sessionId:n})}pickCredential(e){return CD(this,arguments,void 0,function*({cipherIds:e,userVerification:t,assumeUserPresence:i,masterPasswordRepromptRequired:r}){if(i&&1===e.length&&!r)return{cipherId:e[0],userVerified:t};const n={type:"PickCredentialRequest",cipherIds:e,sessionId:this.sessionId,userVerification:t,fallbackSupported:this.fallbackSupported};yield this.send(n);const a=yield this.receive("PickCredentialResponse");return{cipherId:a.cipherId,userVerified:a.userVerified}})}confirmNewCredential(e){return CD(this,arguments,void 0,function*({credentialName:e,userName:t,userHandle:i,userVerification:r,rpId:n}){const a={type:"ConfirmNewCredentialRequest",sessionId:this.sessionId,credentialName:e,userName:t,userHandle:i,userVerification:r,fallbackSupported:this.fallbackSupported,rpId:n};yield this.send(a);const s=yield this.receive(ID);return{cipherId:s.cipherId,userVerified:s.userVerified}})}informExcludedCredential(e){return CD(this,void 0,void 0,function*(){const t={type:"InformExcludedCredentialRequest",sessionId:this.sessionId,existingCipherIds:e,fallbackSupported:this.fallbackSupported};yield this.send(t),yield this.receive(ED)})}ensureUnlockedVault(){return CD(this,void 0,void 0,function*(){(yield this.authService.getAuthStatus())!==cu.Unlocked&&(yield this.connect())})}informCredentialNotFound(){return CD(this,void 0,void 0,function*(){const e={type:"InformCredentialNotFoundRequest",sessionId:this.sessionId,fallbackSupported:this.fallbackSupported};yield this.send(e),yield this.receive(ED)})}close(){return CD(this,void 0,void 0,function*(){yield function(e){return CT(this,void 0,void 0,function*(){yield wT.closeSingleActionPopout(`${IT}_${e}`)})}(this.sessionId),this.closed=!0,this.destroy$.next(),this.destroy$.complete()})}abort(){return CD(this,arguments,void 0,function*(e=!1){this.abortController.abort(e?Mw:void 0)})}send(e){return CD(this,void 0,void 0,function*(){this.connected$.value||(yield this.connect()),AD.sendMessage(e)})}receive(e){return CD(this,void 0,void 0,function*(){try{return yield Ce(this.messages$.pipe(Ie(t=>t.sessionId===this.sessionId&&t.type===e),m_(this.destroy$)))}catch(e){if(e instanceof xe)throw new zD;throw e}})}connect(){return CD(this,void 0,void 0,function*(){if(this.closed)throw new Error("Cannot re-open closed session");const e=Ce(_e(this.connected$.pipe(Ie(e=>!0===e)),ey(this.abortController.signal,"abort").pipe(Le(()=>tc(()=>new zD)))));yield hT.tabSendMessageData(this.tab,"closeNotificationBar");const t=yield function(e,t){return CT(this,void 0,void 0,function*(){const{sessionId:i,fallbackSupported:r}=t,n=`popup/index.html#/fido2?sessionId=${i}&fallbackSupported=${r}&senderTabId=${e.id}&senderUrl=${encodeURIComponent(e.url)}`;return(yield wT.openPopout(n,{singleActionKey:`${IT}_${i}`,senderWindowId:e.windowId,forceCloseExistingWindows:!0,windowOptions:{height:570}})).id})}(this.tab,{sessionId:this.sessionId,fallbackSupported:this.fallbackSupported});this.windowClosed$.pipe(Ie(e=>t===e),m_(this.destroy$)).subscribe(()=>{this.close(),this.abort(!0)}),yield e})}}function jD(e,t){void 0===t&&(t=Te);var i=sc(e,t);return di(function(){return i})}var TD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class DD{constructor(e,t,i,r,n){this.badgeService=e,this.accountService=t,this.cipherService=i,this.badgeSettingsService=r,this.logService=n}init(){const e=this.accountService.activeAccount$.pipe(Le(e=>(null==e?void 0:e.id)?this.cipherService.ciphers$(null==e?void 0:e.id):bt([])));this.badgeService.setState("autofill-badge-updater",t=>ai({account:this.accountService.activeAccount$,enableBadgeCounter:this.badgeSettingsService.enableBadgeCounter$.pipe(Zl()),ciphers:e.pipe(jD(100))}).pipe(de(e=>TD(this,[e],void 0,function*({account:e,enableBadgeCounter:i}){if(e&&i)return{state:{text:yield this.calculateCountText(t,e.id)},priority:100}}))))}calculateCountText(e,t){return TD(this,void 0,void 0,function*(){if(!e.tabId)return void this.logService.warning("Tab event received but tab id is undefined");const i=(e.url?yield this.cipherService.getAllDecryptedForUrl(e.url,t):[]).length;return 0!==i?i>9?"9+":i.toString():void 0})}}const OD="collectPageDetailsFromTabObservable";class ND{constructor(){this.script=[],this.properties={}}}const RD=new Wf("collectPageDetailsResponse");class UD{}UD.EmailFieldNames=["email","email address","e-mail","e-mail address","email adresse","e-mail adresse"],UD.UsernameFieldNames=["username","user name","userid","user id","customer id","login id","login","benutzername","benutzer name","benutzerid","benutzer id",...UD.EmailFieldNames],UD.TotpFieldNames=["totp","totpcode","2facode","approvals_code","mfacode","otc-code","onetimecode","otp-code","otpcode","onetimepassword","security_code","second-factor","twofactor","twofa","twofactorcode","verificationcode","verification code"],UD.RecoveryCodeFieldNames=["backup","recovery"],UD.AmbiguousTotpFieldNames=["code","pin","otc","otp","2fa","mfa"],UD.SearchFieldNames=["search","query","find","go"],UD.NewEmailFieldKeywords=["new-email","newemail","new email","neue e-mail"],UD.RegistrationKeywords=["register","signup","sign-up","join","create"],UD.NewsletterFormNames=["newsletter"],UD.FieldIgnoreList=["captcha","findanything","forgot"],UD.PasswordFieldExcludeList=["hint",...UD.FieldIgnoreList,...UD.TotpFieldNames],UD.ExcludedAutofillLoginTypes=["hidden","file","button","image","reset","search"],UD.ExcludedAutofillTypes=["radio","checkbox",...UD.ExcludedAutofillLoginTypes],UD.ExcludedInlineMenuTypes=["textarea",...UD.ExcludedAutofillTypes],UD.ExcludedIdentityAutocompleteTypes=new Set(["current-password","new-password"]);class FD{}FD.CardAttributes=["autoCompleteType","data-stripe","htmlName","htmlID","title","label-tag","placeholder","label-left","label-top","data-recurly"],FD.CardAttributesExtended=[...FD.CardAttributes,"label-right"],FD.CardHolderFieldNames=["accountholdername","cc-name","card-name","cardholder-name","cardholder","name","nom"],FD.CardHolderFieldNameValues=["accountholdername","cc-name","card-name","cardholder-name","cardholder","tbName"],FD.CardNumberFieldNames=["cc-number","cc-num","card-number","card-num","number","cc","cc-no","card-no","credit-card","numero-carte","carte","carte-credit","num-carte","cb-num","card-pan"],FD.CardNumberFieldNameValues=["cc-number","cc-num","card-number","card-num","cc-no","card-no","numero-carte","num-carte","cb-num"],FD.CardExpiryFieldNames=["cc-exp","card-exp","cc-expiration","card-expiration","cc-ex","card-ex","card-expire","card-expiry","validite","expiration","expiry","mm-yy","mm-yyyy","yy-mm","yyyy-mm","expiration-date","payment-card-expiration","payment-cc-date"],FD.CardExpiryFieldNameValues=["mm-yy","mm-yyyy","yy-mm","yyyy-mm","expiration-date","payment-card-expiration"],FD.ExpiryMonthFieldNames=["exp-month","cc-exp-month","cc-month","card-month","cc-mo","card-mo","exp-mo","card-exp-mo","cc-exp-mo","card-expiration-month","expiration-month","cc-mm","cc-m","card-mm","card-m","card-exp-mm","cc-exp-mm","exp-mm","exp-m","expire-month","expire-mo","expiry-month","expiry-mo","card-expire-month","card-expire-mo","card-expiry-month","card-expiry-mo","mois-validite","mois-expiration","m-validite","m-expiration","expiry-date-field-month","expiration-date-month","expiration-date-mm","exp-mon","validity-mo","exp-date-mo","cb-date-mois","date-m"],FD.ExpiryYearFieldNames=["exp-year","cc-exp-year","cc-year","card-year","cc-yr","card-yr","exp-yr","card-exp-yr","cc-exp-yr","card-expiration-year","expiration-year","cc-yy","cc-y","card-yy","card-y","card-exp-yy","cc-exp-yy","exp-yy","exp-y","cc-yyyy","card-yyyy","card-exp-yyyy","cc-exp-yyyy","expire-year","expire-yr","expiry-year","expiry-yr","card-expire-year","card-expire-yr","card-expiry-year","card-expiry-yr","an-validite","an-expiration","annee-validite","annee-expiration","expiry-date-field-year","expiration-date-year","cb-date-ann","expiration-date-yy","expiration-date-yyyy","validity-year","exp-date-year","date-y"],FD.CVVFieldNames=["cvv","cvc","cvv2","cc-csc","cc-cvv","card-csc","card-cvv","cvd","cid","cvc2","cnv","cvn2","cc-code","card-code","code-securite","security-code","crypto","card-verif","verification-code","csc","ccv"],FD.CardBrandFieldNames=["cc-type","card-type","card-brand","cc-brand","cb-type"],FD.CardExpiryDateFormats=[{Month:"mm",MonthShort:"m",Year:"yyyy",YearShort:"yy"},{Month:"mm",MonthShort:"m",Year:"åååå",YearShort:"åå"},{Month:"mm",MonthShort:"m",Year:"jjjj",YearShort:"jj"},{Month:"mm",MonthShort:"m",Year:"aa",YearShort:"aa"},{Month:"мм",MonthShort:"м",Year:"гггг",YearShort:"гг"},{Month:"mm",MonthShort:"m",Year:"rrrr",YearShort:"rr"}],FD.MonthAbbr=["mm","mm","mm","mm","мм","mm"],FD.YearAbbrShort=["yy","åå","jj","aa","гг","rr"],FD.YearAbbrLong=["yyyy","åååå","jjjj","aa","гггг","rrrr"];class qD{}qD.IdentityAttributes=["autoCompleteType","data-stripe","htmlName","htmlID","label-tag","placeholder","label-left","label-top","data-recurly","accountCreationFieldType"],qD.FullNameFieldNames=["name","full-name","your-name"],qD.FullNameFieldNameValues=["full-name","your-name"],qD.TitleFieldNames=["honorific-prefix","prefix","title","anrede"],qD.FirstnameFieldNames=["f-name","first-name","given-name","first-n","vorname"],qD.MiddlenameFieldNames=["m-name","middle-name","additional-name","middle-initial","middle-n","middle-i"],qD.LastnameFieldNames=["l-name","last-name","s-name","surname","family-name","family-n","last-n","nachname","familienname"],qD.EmailFieldNames=["e-mail","email-address"],qD.AddressFieldNames=["address","street-address","addr","street","mailing-addr","billing-addr","mail-addr","bill-addr","strasse","adresse"],qD.AddressFieldNameValues=["mailing-addr","billing-addr","mail-addr","bill-addr"],qD.Address1FieldNames=["address-1","address-line-1","addr-1","street-1"],qD.Address2FieldNames=["address-2","address-line-2","addr-2","street-2","address-ext"],qD.Address3FieldNames=["address-3","address-line-3","addr-3","street-3"],qD.PostalCodeFieldNames=["postal","zip","zip2","zip-code","postal-code","post-code","postcode","address-zip","address-postal","address-code","address-postal-code","address-zip-code","plz","postleitzahl"],qD.CityFieldNames=["city","town","address-level-2","address-city","address-town","ort","stadt","wohnort"],qD.StateFieldNames=["state","province","provence","address-level-1","address-state","address-province","bundesland"],qD.CountryFieldNames=["country","country-code","country-name","address-country","address-country-name","address-country-code","land"],qD.PhoneFieldNames=["phone","mobile","mobile-phone","tel","telephone","phone-number","telefon","telefonnummer","mobil","handy"],qD.UserNameFieldNames=["user-name","user-id","screen-name"],qD.CompanyFieldNames=["company","company-name","organization","organization-name","firma"],qD.IsoCountries={afghanistan:"AF","aland islands":"AX",albania:"AL",algeria:"DZ","american samoa":"AS",andorra:"AD",angola:"AO",anguilla:"AI",antarctica:"AQ","antigua and barbuda":"AG",argentina:"AR",armenia:"AM",aruba:"AW",australia:"AU",austria:"AT",azerbaijan:"AZ",bahamas:"BS",bahrain:"BH",bangladesh:"BD",barbados:"BB",belarus:"BY",belgium:"BE",belize:"BZ",benin:"BJ",bermuda:"BM",bhutan:"BT",bolivia:"BO","bosnia and herzegovina":"BA",botswana:"BW","bouvet island":"BV",brazil:"BR","british indian ocean territory":"IO","brunei darussalam":"BN",bulgaria:"BG","burkina faso":"BF",burundi:"BI",cambodia:"KH",cameroon:"CM",canada:"CA","cape verde":"CV","cayman islands":"KY","central african republic":"CF",chad:"TD",chile:"CL",china:"CN","christmas island":"CX","cocos (keeling) islands":"CC",colombia:"CO",comoros:"KM",congo:"CG","congo, democratic republic":"CD","cook islands":"CK","costa rica":"CR","cote d'ivoire":"CI",croatia:"HR",cuba:"CU",cyprus:"CY","czech republic":"CZ",denmark:"DK",djibouti:"DJ",dominica:"DM","dominican republic":"DO",ecuador:"EC",egypt:"EG","el salvador":"SV","equatorial guinea":"GQ",eritrea:"ER",estonia:"EE",ethiopia:"ET","falkland islands":"FK","faroe islands":"FO",fiji:"FJ",finland:"FI",france:"FR","french guiana":"GF","french polynesia":"PF","french southern territories":"TF",gabon:"GA",gambia:"GM",georgia:"GE",germany:"DE",ghana:"GH",gibraltar:"GI",greece:"GR",greenland:"GL",grenada:"GD",guadeloupe:"GP",guam:"GU",guatemala:"GT",guernsey:"GG",guinea:"GN","guinea-bissau":"GW",guyana:"GY",haiti:"HT","heard island & mcdonald islands":"HM","holy see (vatican city state)":"VA",honduras:"HN","hong kong":"HK",hungary:"HU",iceland:"IS",india:"IN",indonesia:"ID","iran, islamic republic of":"IR",iraq:"IQ",ireland:"IE","isle of man":"IM",israel:"IL",italy:"IT",jamaica:"JM",japan:"JP",jersey:"JE",jordan:"JO",kazakhstan:"KZ",kenya:"KE",kiribati:"KI","republic of korea":"KR","south korea":"KR","democratic people's republic of korea":"KP","north korea":"KP",kuwait:"KW",kyrgyzstan:"KG","lao people's democratic republic":"LA",latvia:"LV",lebanon:"LB",lesotho:"LS",liberia:"LR","libyan arab jamahiriya":"LY",liechtenstein:"LI",lithuania:"LT",luxembourg:"LU",macao:"MO",macedonia:"MK",madagascar:"MG",malawi:"MW",malaysia:"MY",maldives:"MV",mali:"ML",malta:"MT","marshall islands":"MH",martinique:"MQ",mauritania:"MR",mauritius:"MU",mayotte:"YT",mexico:"MX","micronesia, federated states of":"FM",moldova:"MD",monaco:"MC",mongolia:"MN",montenegro:"ME",montserrat:"MS",morocco:"MA",mozambique:"MZ",myanmar:"MM",namibia:"NA",nauru:"NR",nepal:"NP",netherlands:"NL","netherlands antilles":"AN","new caledonia":"NC","new zealand":"NZ",nicaragua:"NI",niger:"NE",nigeria:"NG",niue:"NU","norfolk island":"NF","northern mariana islands":"MP",norway:"NO",oman:"OM",pakistan:"PK",palau:"PW","palestinian territory, occupied":"PS",panama:"PA","papua new guinea":"PG",paraguay:"PY",peru:"PE",philippines:"PH",pitcairn:"PN",poland:"PL",portugal:"PT","puerto rico":"PR",qatar:"QA",reunion:"RE",romania:"RO","russian federation":"RU",rwanda:"RW","saint barthelemy":"BL","saint helena":"SH","saint kitts and nevis":"KN","saint lucia":"LC","saint martin":"MF","saint pierre and miquelon":"PM","saint vincent and grenadines":"VC",samoa:"WS","san marino":"SM","sao tome and principe":"ST","saudi arabia":"SA",senegal:"SN",serbia:"RS",seychelles:"SC","sierra leone":"SL",singapore:"SG",slovakia:"SK",slovenia:"SI","solomon islands":"SB",somalia:"SO","south africa":"ZA","south georgia and sandwich isl.":"GS",spain:"ES","sri lanka":"LK",sudan:"SD",suriname:"SR","svalbard and jan mayen":"SJ",swaziland:"SZ",sweden:"SE",switzerland:"CH","syrian arab republic":"SY",taiwan:"TW",tajikistan:"TJ",tanzania:"TZ",thailand:"TH","timor-leste":"TL",togo:"TG",tokelau:"TK",tonga:"TO","trinidad and tobago":"TT",tunisia:"TN",turkey:"TR",turkmenistan:"TM","turks and caicos islands":"TC",tuvalu:"TV",uganda:"UG",ukraine:"UA","united arab emirates":"AE","united kingdom":"GB","united states":"US","united states outlying islands":"UM",uruguay:"UY",uzbekistan:"UZ",vanuatu:"VU",venezuela:"VE",vietnam:"VN","virgin islands, british":"VG","virgin islands, u.s.":"VI","wallis and futuna":"WF","western sahara":"EH",yemen:"YE",zambia:"ZM",zimbabwe:"ZW"},qD.IsoStates={alabama:"AL",alaska:"AK","american samoa":"AS",arizona:"AZ",arkansas:"AR",california:"CA",colorado:"CO",connecticut:"CT",delaware:"DE","district of columbia":"DC","federated states of micronesia":"FM",florida:"FL",georgia:"GA",guam:"GU",hawaii:"HI",idaho:"ID",illinois:"IL",indiana:"IN",iowa:"IA",kansas:"KS",kentucky:"KY",louisiana:"LA",maine:"ME","marshall islands":"MH",maryland:"MD",massachusetts:"MA",michigan:"MI",minnesota:"MN",mississippi:"MS",missouri:"MO",montana:"MT",nebraska:"NE",nevada:"NV","new hampshire":"NH","new jersey":"NJ","new mexico":"NM","new york":"NY","north carolina":"NC","north dakota":"ND","northern mariana islands":"MP",ohio:"OH",oklahoma:"OK",oregon:"OR",palau:"PW",pennsylvania:"PA","puerto rico":"PR","rhode island":"RI","south carolina":"SC","south dakota":"SD",tennessee:"TN",texas:"TX",utah:"UT",vermont:"VT","virgin islands":"VI",virginia:"VA",washington:"WA","west virginia":"WV",wisconsin:"WI",wyoming:"WY"},qD.IsoProvinces={alberta:"AB","british columbia":"BC",manitoba:"MB","new brunswick":"NB","newfoundland and labrador":"NL","nova scotia":"NS",ontario:"ON","prince edward island":"PE",quebec:"QC",saskatchewan:"SK"};const LD=["login","signin","submit","continue","next","verify"],BD=["change","save","savepassword","updatepassword","changepassword","resetpassword"];var MD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class VD{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p){this.cipherService=e,this.autofillSettingsService=t,this.totpService=i,this.eventCollectionService=r,this.logService=n,this.domainSettingsService=a,this.userVerificationService=s,this.billingAccountProfileStateService=o,this.scriptInjectorService=l,this.accountService=c,this.authService=u,this.configService=d,this.userNotificationSettingsService=h,this.messageListener=p,this.openVaultItemPasswordRepromptPopout=zT,this.currentlyOpeningPasswordRepromptPopout=!1,this.autofillScriptPortsSet=new Set,this.handleInjectedScriptPortConnection=e=>{e.name===UT&&(this.autofillScriptPortsSet.add(e),e.onDisconnect.addListener(this.handleInjectScriptPortOnDisconnect))},this.handleInjectScriptPortOnDisconnect=e=>{e.name===UT&&this.autofillScriptPortsSet.delete(e)}}collectPageDetailsFromTab$(e){const t=new Ht(1),i=this.messageListener.messages$(RD).pipe(Ie(t=>t.tab.id===e.id&&t.sender===OD),hx((e,t)=>[...e,{frameId:t.webExtSender.frameId,tab:t.tab,details:t.details}],[]));hT.tabSendMessage(e,{tab:e,command:"collectPageDetails",sender:OD},null,!0).catch(()=>{t.next([])});const r=["moz-extension://","chrome-extension://","safari-web-extension://"].some(t=>e.url.startsWith(t));e.url&&!r||t.next([]);const n=i.pipe(Gt()),a=sc(1e3).pipe(X(()=>[]),m_(n));return _e(n,t,a)}loadAutofillScriptsOnInstall(){return MD(this,void 0,void 0,function*(){hT.addListener(chrome.runtime.onConnect,this.handleInjectedScriptPortConnection),this.injectAutofillScriptsInAllTabs(),this.autofillSettingsService.inlineMenuVisibility$.pipe(wb(void 0),g_()).subscribe(([e,t])=>this.handleInlineMenuVisibilitySettingsChange(e,t)),this.autofillSettingsService.showInlineMenuCards$.pipe(wb(void 0),g_()).subscribe(([e,t])=>this.handleInlineMenuVisibilitySettingsChange(e,t)),this.autofillSettingsService.showInlineMenuIdentities$.pipe(wb(void 0),g_()).subscribe(([e,t])=>this.handleInlineMenuVisibilitySettingsChange(e,t))})}reloadAutofillScripts(){return MD(this,void 0,void 0,function*(){this.autofillScriptPortsSet.forEach(e=>{e.disconnect(),this.autofillScriptPortsSet.delete(e)}),this.injectAutofillScriptsInAllTabs()})}injectAutofillScripts(e){return MD(this,arguments,void 0,function*(e,t=0,i=!0){const r=yield Ce(this.accountService.activeAccount$),n=(yield Ce(this.authService.activeAccountStatus$))===cu.Unlocked;let a=!1;const s=[yield this.getBootstrapAutofillContentScript(r)];r&&n&&(a=yield this.getAutofillOnPageLoad()),i&&a&&s.push("autofiller.js"),i||(yield this.scriptInjectorService.inject({tabId:e.id,injectDetails:{file:"content/content-message-handler.js",runAt:"document_start"}})),s.push("contextMenuHandler.js");for(const i of s)yield this.scriptInjectorService.inject({tabId:e.id,injectDetails:{file:`content/${i}`,runAt:"document_start",frame:t}})})}getBootstrapAutofillContentScript(e){return MD(this,void 0,void 0,function*(){let t=0;e&&(t=yield this.getInlineMenuVisibility());const i=yield Ce(this.userNotificationSettingsService.enableChangedPasswordPrompt$),r=yield Ce(this.userNotificationSettingsService.enableAddedLoginPrompt$),n=i||r;return t||n?!t&&n?"bootstrap-autofill-overlay-notifications.js":t&&!n?"bootstrap-autofill-overlay-menu.js":"bootstrap-autofill-overlay.js":"bootstrap-autofill.js"})}getFormsWithPasswordFields(e){const t=[],i=VD.loadPasswordFields(e,!0,!0,!1,!0);if(0===i.length)return t;const r=i.filter(e=>void 0===e.form),n=Object.keys(e.forms),a=n.length;if(3===i.length&&1==a&&r.length>0){const e=n[0];i.filter(t=>null!==t.form&&t.form===e).length>0&&r.forEach(t=>{t.form=e})}for(const r in e.forms){if(!e.forms.hasOwnProperty(r))continue;const n=i.filter(e=>r===e.form);if(n.length>0){let i=this.findUsernameField(e,n[0],!1,!1,!1);null==i&&(i=this.findUsernameField(e,n[0],!0,!0,!1)),t.push({form:e.forms[r],password:n[0],username:i,passwords:n})}}return t}getInlineMenuVisibility(){return MD(this,void 0,void 0,function*(){return yield Ce(this.autofillSettingsService.inlineMenuVisibility$)})}getShouldAutoCopyTotp(){return MD(this,void 0,void 0,function*(){return yield Ce(this.autofillSettingsService.autoCopyTotp$)})}getAutofillOnPageLoad(){return MD(this,void 0,void 0,function*(){return yield Ce(this.autofillSettingsService.autofillOnPageLoad$)})}getDefaultUriMatchStrategy(){return MD(this,void 0,void 0,function*(){return yield Ce(this.domainSettingsService.resolvedDefaultUriMatchStrategy$)})}doAutoFill(e){return MD(this,void 0,void 0,function*(){const t=e.tab;if(!(t&&e.cipher&&e.pageDetails&&e.pageDetails.length))throw new Error("Nothing to autofill.");let i=null;const r=yield Ce(this.accountService.activeAccount$),n=yield Ce(this.billingAccountProfileStateService.hasPremiumFromAnySource$(r.id)),a=yield this.getDefaultUriMatchStrategy();n||(e.cipher.login.totp=null);let s=!1;if(yield Promise.all(e.pageDetails.map(o=>MD(this,void 0,void 0,function*(){if(o.tab.id!==t.id||o.tab.url!==t.url)return;const l=e.focusedFieldForm?Object.assign(Object.assign({},o.details),{fields:o.details.fields.filter(t=>t.form===e.focusedFieldForm)}):o.details,c=yield this.generateFillScript(l,{skipUsernameOnlyFill:e.skipUsernameOnlyFill||!1,onlyEmptyFields:e.onlyEmptyFields||!1,fillNewPassword:e.fillNewPassword||!1,allowTotpAutofill:e.allowTotpAutofill||!1,autoSubmitLogin:e.autoSubmitLogin||!1,cipher:e.cipher,tabUrl:t.url,defaultUriMatch:a,focusedFieldOpid:e.focusedFieldOpid,inlineMenuFillType:e.inlineMenuFillType});if(!c||!c.script||!c.script.length)return;if(c.untrustedIframe&&null!=e.allowUntrustedIframe&&!e.allowUntrustedIframe)return void this.logService.info("Autofill on page load was blocked due to an untrusted iframe.");if(c.properties.delay_between_operations=20,s=!0,e.skipLastUsed||(yield this.cipherService.updateLastUsedDate(e.cipher.id,r.id)),hT.tabSendMessage(t,{command:e.autoSubmitLogin?"triggerAutoSubmitLogin":"fillForm",fillScript:c,url:t.url,pageDetailsUrl:o.details.url},{frameId:o.frameId}),e.cipher.type!==rm.Login||null!==i||!e.cipher.login.totp||!n&&!e.cipher.organizationUseTotp)return;const u=yield this.getShouldAutoCopyTotp();i=u?(yield Ce(this.totpService.getCode$(e.cipher.login.totp))).code:null}))),s)return yield this.eventCollectionService.collect(oh.Cipher_ClientAutofilled,e.cipher.id),null!==i?i:null;throw new Error("Did not autofill.")})}doAutoFillOnTab(e,t,i){return MD(this,arguments,void 0,function*(e,t,i,r=!1){var n,a;let s;const o=yield Ce(this.accountService.activeAccount$.pipe(iu));if(null==o)return null;if(i)s=yield this.cipherService.getNextCipherForUrl(t.url,o);else{const e=yield this.cipherService.getLastLaunchedForUrl(t.url,o,!0);s=e&&Date.now().valueOf()-(null===(a=null===(n=e.localData)||void 0===n?void 0:n.lastLaunched)||void 0===a?void 0:a.valueOf())<3e4?e:yield this.cipherService.getLastUsedForUrl(t.url,o,!0)}if(null==s||s.reprompt===tm.Password&&!i)return null;if(yield this.isPasswordRepromptRequired(s,t))return i&&this.cipherService.updateLastUsedIndexForUrl(t.url),null;const l=yield this.doAutoFill({tab:t,cipher:s,pageDetails:e,skipLastUsed:!i,skipUsernameOnlyFill:!i,onlyEmptyFields:!i,fillNewPassword:i,allowUntrustedIframe:i,allowTotpAutofill:i,autoSubmitLogin:r});return i&&this.cipherService.updateLastUsedIndexForUrl(t.url),l})}isPasswordRepromptRequired(e,t,i){return MD(this,void 0,void 0,function*(){const r=yield this.userVerificationService.hasMasterPasswordAndMasterKeyHash();return!(e.reprompt!==tm.Password||!r||(this.isDebouncingPasswordRepromptPopout()||(yield this.openVaultItemPasswordRepromptPopout(t,{cipherId:e.id,action:null!=i?i:"autofill"})),0))})}doAutoFillActiveTab(e,t,i){return MD(this,void 0,void 0,function*(){var r,n,a;if(!(null===(a=null===(n=null===(r=e[0])||void 0===r?void 0:r.details)||void 0===n?void 0:n.fields)||void 0===a?void 0:a.length))return null;const s=yield this.getActiveTab();if(!s||!s.url)return null;if(!i||i===rm.Login)return yield this.doAutoFillOnTab(e,s,t);let o,l="";const c=yield Ce(this.accountService.activeAccount$.pipe(iu));if(null==c)return null;if(i===rm.Card?(l="cardCiphers",o=yield this.cipherService.getNextCardCipher(c)):(l="identityCiphers",o=yield this.cipherService.getNextIdentityCipher(c)),!o||!l||o.reprompt===tm.Password&&!t)return null;if(yield this.isPasswordRepromptRequired(o,s))return t&&this.cipherService.updateLastUsedIndexForUrl(l),null;const u=yield this.doAutoFill({tab:s,cipher:o,pageDetails:e,skipLastUsed:!t,skipUsernameOnlyFill:!t,onlyEmptyFields:!t,fillNewPassword:!1,allowUntrustedIframe:t,allowTotpAutofill:!1});return t&&this.cipherService.updateLastUsedIndexForUrl(l),u})}setAutoFillOnPageLoadOrgPolicy(){return MD(this,void 0,void 0,function*(){(yield Ce(this.autofillSettingsService.activateAutofillOnPageLoadFromPolicy$))&&(yield this.autofillSettingsService.setAutofillOnPageLoad(!0))})}getActiveTab(){return MD(this,void 0,void 0,function*(){const e=yield hT.getTabFromCurrentWindow();if(!e)throw new Error("No tab found.");return e})}generateFillScript(e,t){return MD(this,void 0,void 0,function*(){if(!e||!t.cipher)return null;let i=new ND;const r={},n=t.cipher.fields;if(n&&n.length){const a=[];n.forEach(e=>{VD.hasValue(e.name)&&a.push(e.name.toLowerCase())}),e.fields.forEach(e=>{if(r.hasOwnProperty(e.opid))return;if(!e.viewable&&"span"!==e.tagName)return;if(VD.isSearchField(e))return;const s=this.findMatchingFieldIndex(e,a);if(s>-1){const a=n[s];let o;a.type===am.Linked?o=t.cipher.linkedFieldValue(a.linkedId):(o=a.value,null==o&&a.type===am.Boolean&&(o="false")),r[e.opid]=e,VD.fillByOpid(i,e,o)}})}switch(t.cipher.type){case rm.Login:i=yield this.generateLoginFillScript(i,e,r,t);break;case rm.Card:i=yield this.generateCardFillScript(i,e,r,t);break;case rm.Identity:i=yield this.generateIdentityFillScript(i,e,r,t);break;default:return null}return i})}generateLoginFillScript(e,t,i,r){return MD(this,void 0,void 0,function*(){var n,a;if(!r.cipher.login)return null;const s=[],o=new Map,l=[];let c=null,u=null,d=null;const h=r.cipher.login;e.savedUrls=null!==(a=null===(n=null==h?void 0:h.uris)||void 0===n?void 0:n.filter(e=>e.match!=Xm.Never).map(e=>e.uri))&&void 0!==a?a:[],e.untrustedIframe=yield this.inUntrustedIframe(t.url,r);const p=VD.loadPasswordFields(t,!1,!1,r.onlyEmptyFields,r.fillNewPassword),m=[],g=[];p.forEach(e=>{this.isRegistrationPasswordField(t,e)?g.push(e):m.push(e)});const f=m.length>0?m:g,y=r.focusedFieldOpid&&t.fields.find(e=>e.opid===r.focusedFieldOpid),v=null==y?void 0:y.form,b=y&&r.allowTotpAutofill&&("text"===y.type||"number"===y.type||"tel"===y.type)&&(VD.fieldIsFuzzyMatch(y,[...UD.TotpFieldNames,...UD.AmbiguousTotpFieldNames])||"one-time-code"===y.autoCompleteType)&&!VD.fieldIsFuzzyMatch(y,[...UD.RecoveryCodeFieldNames]),w=y&&!b&&h.username&&("text"===y.type||"email"===y.type||"tel"===y.type)&&y,k=e=>{var i;return!y||(null!=v?e.form===v:w&&null==e.form&&(null===(i=this.findUsernameField(t,e,!1,!1,!0))||void 0===i?void 0:i.opid)===w.opid)},S=(e,i)=>w&&k(e)?w:this.findUsernameField(t,e,!1,!1,i);if(w&&!f.some(k)&&!Object.prototype.hasOwnProperty.call(i,w.opid))return i[w.opid]=w,VD.fillByOpid(e,w,h.username),r.autoSubmitLogin&&w.form&&(e.autosubmit=[w.form]),VD.setFillScriptForFocus({[w.opid]:w},e);for(const e in t.forms)t.forms.hasOwnProperty(e)&&f.forEach(e=>{y&&!k(e)||(c=e,s.push(c),h.username&&(u=S(c,!1),u&&o.set(u.opid,u)),r.allowTotpAutofill&&h.totp&&(d=b&&k(e)?y:this.findTotpField(t,c,!1,!1,!1),d&&l.push(d)))});if(p.length&&!s.length){const e=6===r.inlineMenuFillType,i=7===r.inlineMenuFillType;if((e||i)&&y){const e=y.form;[...m,...g].forEach(t=>{t.form===e&&s.push(t)})}if(!s.length){const e=y&&f.find(k)||f[0];e&&s.push(e)}const n=s[0];n&&(h.username&&n.elementNumber>0&&(u=S(n,!0),u&&o.set(u.opid,u)),r.allowTotpAutofill&&h.totp&&n.elementNumber>0&&(d=b&&k(n)?y:this.findTotpField(t,n,!1,!1,!0),d&&l.push(d)))}p.length||t.fields.forEach(e=>{if(!e.viewable)return;const t=r.allowTotpAutofill&&["number","tel","text"].some(t=>t===e.type)&&(VD.fieldIsFuzzyMatch(e,[...UD.TotpFieldNames,...UD.AmbiguousTotpFieldNames])||"one-time-code"===e.autoCompleteType)&&!VD.fieldIsFuzzyMatch(e,[...UD.RecoveryCodeFieldNames]),i=!r.skipUsernameOnlyFill&&["email","tel","text"].some(t=>t===e.type)&&VD.fieldIsFuzzyMatch(e,UD.UsernameFieldNames);switch(!0){case t:return void l.push(e);case i:return void o.set(e.opid,e);default:return}});const _=new Set;return(w?[w]:[...o.values()]).forEach(t=>{Object.prototype.hasOwnProperty.call(i,t.opid)||(i[t.opid]=t,VD.fillByOpid(e,t,h.username),_.add(t.form))}),s.forEach(t=>{i.hasOwnProperty(t.opid)||(i[t.opid]=t,VD.fillByOpid(e,t,h.password),_.add(t.form))}),r.autoSubmitLogin&&_.size&&(e.autosubmit=Array.from(_)),r.allowTotpAutofill&&(null==h?void 0:h.totp)&&(yield Promise.all(l.map((t,r)=>MD(this,void 0,void 0,function*(){if(Object.prototype.hasOwnProperty.call(i,t.opid))return;i[t.opid]=t;let n=(yield Ce(this.totpService.getCode$(h.totp))).code;n.length==l.length&&(n=n.charAt(r)),VD.fillByOpid(e,t,n)})))),e=VD.setFillScriptForFocus(i,e)})}generateCardFillScript(e,t,i,r){return MD(this,void 0,void 0,function*(){if(!r.cipher.card)return null;const n={};t.fields.forEach(e=>{if(!VD.isExcludedFieldType(e,UD.ExcludedAutofillTypes))for(let t=0;t1&&(t=r[1])}}else!this.fieldAttrsContain(n.expMonth,"mm")&&2!==n.expMonth.maxLength||1!==t.length||(t="0"+t);i[n.expMonth.opid]=n.expMonth,VD.fillByOpid(e,n.expMonth,t)}if(n.expYear&&VD.hasValue(a.expYear)){let t=a.expYear;if(n.expYear.selectInfo&&n.expYear.selectInfo.options)for(let e=0;e-1&&i[1].length>r+1){const e=i[1].substring(r+2);if(null!=e&&""!==e.trim()&&e===a.expYear){t=i[1];break}}}else this.fieldAttrsContain(n.expYear,"yyyy")||4===n.expYear.maxLength?2===t.length&&(t=dg(t)):(this.fieldAttrsContain(n.expYear,"yy")||2===n.expYear.maxLength)&&4===t.length&&(t=t.substr(2));i[n.expYear.opid]=n.expYear,VD.fillByOpid(e,n.expYear,t)}if(n.exp&&VD.hasValue(a.expMonth)&&VD.hasValue(a.expYear)){const t=this.generateCombinedExpiryValue(a,n.exp);this.makeScriptActionWithValue(e,t,n.exp,i)}return e})}inUntrustedIframe(e,t){return MD(this,void 0,void 0,function*(){if(e===t.tabUrl)return!1;const i=yield Ce(this.domainSettingsService.getUrlEquivalentDomains(e));return!t.cipher.login.matchesUri(e,i,t.defaultUriMatch)})}fieldAttrsContain(e,t){if(!e)return!1;let i=!1;return FD.CardAttributesExtended.forEach(r=>{if(i||!e[r])return;let n=e[r];n=n.replace(/ /g,"").toLowerCase(),i=n.indexOf(t)>-1}),i}generateCombinedExpiryValue(e,t){var i;let r=!0,n=!1,a="/",s=!1;const o=`${(new Date).getFullYear()}`.slice(0,2),[l,c]=this.getExpectedExpiryDateFormat(t);if(l){const{Month:e,MonthShort:t,Year:o}=c,u="\\"+hm.join("\\");a=(null===(i=l.match(new RegExp(`[${u}]`,"g")))||void 0===i?void 0:i[0])||"",0===l.indexOf(e+a)?(r=!0,s=!1):0===l.indexOf(t+a)?(r=!1,s=!1):(s=!0,r=new RegExp(`${e}`,"i").test(l)),n=new RegExp(`${o}`,"i").test(l)}const u=r?("0"+e.expMonth).slice(-2):e.expMonth.replaceAll("0",""),d=(o+e.expYear).slice(n?-4:-2);return(s?[d,u]:[u,d]).join(a)}getExpectedExpiryDateFormat(e){let t=null,i=null;const r="\\"+hm.join("\\");return FD.CardExpiryDateFormats.find(n=>{i=n;const{Month:a,MonthShort:s,YearShort:o,Year:l}=n,c=new RegExp(`((${a}|${s})[${r}]{0,1}(${l}|${o}))|((${l}|${o})[${r}]{0,1}(${a}|${s}))`,"gi");return FD.CardAttributesExtended.find(i=>{var n;const a=null===(n=e[i])||void 0===n?void 0:n.toLocaleLowerCase(),s=null==a?void 0:a.match(c);if(null==s?void 0:s.length){t=s[0];const e=new RegExp(`[^\\w${r}]|[\\d]`,"gi");return t.replaceAll(e,""),!0}return!1})}),[t,i]}generateIdentityFillScript(e,t,i,r){const n=r.cipher.identity;if(!n)return null;for(let r=0;rVD.isFieldMatch(e,qD.FullNameFieldNames,qD.FullNameFieldNameValues))}shouldMakeIdentityFirstNameFillScript(e,t){return!e.firstName&&VD.isFieldMatch(t,qD.FirstnameFieldNames)}shouldMakeIdentityMiddleNameFillScript(e,t){return!e.middleName&&VD.isFieldMatch(t,qD.MiddlenameFieldNames)}shouldMakeIdentityLastNameFillScript(e,t){return!e.lastName&&VD.isFieldMatch(t,qD.LastnameFieldNames)}shouldMakeIdentityEmailFillScript(e,t){return!e.email&&VD.isFieldMatch(t,qD.EmailFieldNames)}shouldMakeIdentityAddressFillScript(e,t){return!e.address&&t.some(e=>VD.isFieldMatch(e,qD.AddressFieldNames,qD.AddressFieldNameValues))}shouldMakeIdentityAddress1FillScript(e,t){return!e.address1&&VD.isFieldMatch(t,qD.Address1FieldNames)}shouldMakeIdentityAddress2FillScript(e,t){return!e.address2&&VD.isFieldMatch(t,qD.Address2FieldNames)}shouldMakeIdentityAddress3FillScript(e,t){return!e.address3&&VD.isFieldMatch(t,qD.Address3FieldNames)}shouldMakeIdentityPostalCodeFillScript(e,t){return!e.postalCode&&VD.isFieldMatch(t,qD.PostalCodeFieldNames)}shouldMakeIdentityCityFillScript(e,t){return!e.city&&VD.isFieldMatch(t,qD.CityFieldNames)}shouldMakeIdentityStateFillScript(e,t){return!e.state&&VD.isFieldMatch(t,qD.StateFieldNames)}shouldMakeIdentityCountryFillScript(e,t){return!e.country&&VD.isFieldMatch(t,qD.CountryFieldNames)}shouldMakeIdentityPhoneFillScript(e,t){return!e.phone&&VD.isFieldMatch(t,qD.PhoneFieldNames)}shouldMakeIdentityUserNameFillScript(e,t){return!e.username&&VD.isFieldMatch(t,qD.UserNameFieldNames)}shouldMakeIdentityCompanyFillScript(e,t){return!e.company&&VD.isFieldMatch(t,qD.CompanyFieldNames)}makeIdentityNameFillScript(e,t,i,r){let n="";r.firstName&&(n+=r.firstName),r.middleName&&(n+=n?` ${r.middleName}`:r.middleName),r.lastName&&(n+=n?` ${r.lastName}`:r.lastName),this.makeScriptActionWithValue(e,n,i,t)}makeIdentityAddressFillScript(e,t,i,r){if(!r.address1)return;let n=r.address1;r.address2&&(n+=`, ${r.address2}`),r.address3&&(n+=`, ${r.address3}`),this.makeScriptActionWithValue(e,n,i,t)}makeIdentityStateFillScript(e,t,i,r){if(!r.state)return;if(r.state.length<=2)return void this.makeScriptActionWithValue(e,r.state,i,t);const n=r.state.toLowerCase(),a=qD.IsoStates[n]||qD.IsoProvinces[n];a&&this.makeScriptActionWithValue(e,a,i,t)}makeIdentityCountryFillScript(e,t,i,r){if(!r.country)return;if(r.country.length<=2)return void this.makeScriptActionWithValue(e,r.country,i,t);const n=r.country.toLowerCase(),a=qD.IsoCountries[n];a&&this.makeScriptActionWithValue(e,a,i,t)}static isExcludedType(e,t){return t.indexOf(e)>-1}static isSearchField(e){const t=[e.type,e.htmlName,e.htmlID,e.placeholder];for(let e=0;e-1;if(n=n.toLowerCase().replace(/-/g,""),e===n||a&&e.indexOf(n)>-1)return!0}return!1}makeScriptAction(e,t,i,r,n,a){a=a||n,this.makeScriptActionWithValue(e,t[n],i[a],r)}makeScriptActionWithValue(e,t,i,r){let n=!1;if(VD.hasValue(t)&&i)if("select-one"===i.type&&i.selectInfo&&i.selectInfo.options)for(let e=0;e1&&(t=r[1]);break}if(n)break}else n=!0;n&&(r[i.opid]=i,VD.fillByOpid(e,i,t))}static valueIsLikePassword(e){if(null==e)return!1;const t=e.toLowerCase().replace(/[\s_-]/g,"");return!(t.indexOf("password")<0||UD.PasswordFieldExcludeList.some(e=>t.indexOf(e)>-1))}static fieldHasDisqualifyingAttributeValue(e){const t=[e.htmlID,e.htmlName,e.placeholder];let i=!1;for(let e=0;en.indexOf(e)>-1)),i)break}return i}static loadPasswordFields(e,t,i,r,n){const a=[];return e.fields.forEach(e=>{const s="password"===e.type;!s&&VD.isExcludedFieldType(e,UD.ExcludedAutofillLoginTypes)||VD.fieldHasDisqualifyingAttributeValue(e)||VD.fieldIsFuzzyMatch(e,UD.TotpFieldNames)||e.disabled||!i&&e.readonly||!s&&!(()=>{if("text"!==e.type)return!1;const t=[e.htmlID,e.htmlName,e.placeholder];for(let e=0;eUD.RegistrationKeywords.some(t=>e.includes(t)))}findUsernameField(e,t,i,r,n){let a=null,s=null;for(let o=0;o=t.elementNumber)break;const c=this.findMatchingFieldIndex(l,UD.UsernameFieldNames)>-1,u=null!=l.form&&null!=t.form&&l.form===t.form,d=u&&("email"===l.type||"tel"===l.type);if(!l.disabled&&(r||!l.readonly)&&(n||u||c)&&(i||l.viewable||d)&&("text"===l.type||"email"===l.type||"tel"===l.type))if(u){if(s=l,c)return l}else a=l}return s||a}findTotpField(e,t,i,r,n){let a=null;for(let s=0;s-1||"one-time-code"===o.autoCompleteType)))break}return a}findMatchingFieldIndex(e,t){for(let i=0;i-1){if(this.fieldPropertyIsPrefixMatch(e,"htmlID",t[i],"id"))return i;if(this.fieldPropertyIsPrefixMatch(e,"htmlName",t[i],"name"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-left",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-right",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-tag",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"label-aria",t[i],"label"))return i;if(this.fieldPropertyIsPrefixMatch(e,"placeholder",t[i],"placeholder"))return i}if(this.fieldPropertyIsMatch(e,"htmlID",t[i]))return i;if(this.fieldPropertyIsMatch(e,"htmlName",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-left",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-right",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-tag",t[i]))return i;if(this.fieldPropertyIsMatch(e,"label-aria",t[i]))return i;if(this.fieldPropertyIsMatch(e,"placeholder",t[i]))return i}return-1}fieldPropertyIsPrefixMatch(e,t,i,r,n="="){if(0===i.indexOf(r+n)){const r=i.indexOf(n),a=i.substring(r+1);return null!=a&&this.fieldPropertyIsMatch(e,t,a)}return!1}fieldPropertyIsMatch(e,t,i){let r=e[t];if(!VD.hasValue(r))return!1;if(r=r.trim().replace(/(?:\r\n|\r|\n)/g,""),i.startsWith("regex="))try{const e=i.split("=",2);if(2===e.length)return new RegExp(e[1],"i").test(r)}catch(e){this.logService.error(e)}else if(i.startsWith("csv=")){const e=i.split("=",2);if(2===e.length){const t=e[1].split(",");for(let e=0;e-1)return!0;return!1}static hasValue(e){return Boolean(e&&""!==e)}static setFillScriptForFocus(e,t){let i=null,r=null;for(const t in e)e.hasOwnProperty(t)&&e[t].viewable&&(i=e[t],"password"===e[t].type&&(r=e[t]));return r?t.script.push(["focus_by_opid",r.opid]):i&&t.script.push(["focus_by_opid",i.opid]),t}static fillByOpid(e,t,i){t.maxLength&&i&&i.length>t.maxLength&&(i=i.substr(0,i.length)),"span"!==t.tagName&&(e.script.push(["click_on_opid",t.opid]),e.script.push(["focus_by_opid",t.opid])),e.script.push(["fill_by_opid",t.opid,i])}static forCustomFieldsOnly(e){return"span"===e.tagName}isDebouncingPasswordRepromptPopout(){return!!this.currentlyOpeningPasswordRepromptPopout||(this.currentlyOpeningPasswordRepromptPopout=!0,clearTimeout(this.openPasswordRepromptPopoutDebounce),this.openPasswordRepromptPopoutDebounce=setTimeout(()=>{this.currentlyOpeningPasswordRepromptPopout=!1},100),!1)}injectAutofillScriptsInAllTabs(){return MD(this,void 0,void 0,function*(){var e;const t=yield hT.tabsQuery({});for(let i=0;ithis.injectAutofillScripts(r,e.frameId,!1))}}})}handleInlineMenuVisibilitySettingsChange(e,t){return MD(this,void 0,void 0,function*(){null!=e&&e!==t&&("boolean"==typeof e||"boolean"==typeof t||0===e||0===t)&&(yield this.reloadAutofillScripts())})}}VD.searchFieldNamesSet=new Set(UD.SearchFieldNames);const $D=VD;class KD{isExplicitIdentityEmailField(e){const t=[e.type,e.htmlName,e.htmlID,e.placeholder];for(let e=0;e!!this.fieldContainsAutocompleteValues(e,this.creditCardNameAutocompleteValues)||this.keywordsFoundInFieldData(e,FD.CardHolderFieldNames,!1),this.isFieldForCardNumber=e=>!!this.fieldContainsAutocompleteValues(e,this.creditCardNumberAutocompleteValue)||this.keywordsFoundInFieldData(e,FD.CardNumberFieldNames,!1),this.isFieldForCardExpirationDate=e=>!!this.fieldContainsAutocompleteValues(e,this.creditCardExpirationDateAutocompleteValue)||this.keywordsFoundInFieldData(e,FD.CardExpiryFieldNames,!1),this.isFieldForCardExpirationMonth=e=>!!this.fieldContainsAutocompleteValues(e,this.creditCardExpirationMonthAutocompleteValue)||this.keywordsFoundInFieldData(e,FD.ExpiryMonthFieldNames,!1),this.isFieldForCardExpirationYear=e=>!!this.fieldContainsAutocompleteValues(e,this.creditCardExpirationYearAutocompleteValue)||this.keywordsFoundInFieldData(e,FD.ExpiryYearFieldNames,!1),this.isFieldForCardCvv=e=>!!this.fieldContainsAutocompleteValues(e,this.creditCardCvvAutocompleteValue)||this.keywordsFoundInFieldData(e,FD.CVVFieldNames,!1),this.isFieldForIdentityTitle=e=>!!this.fieldContainsAutocompleteValues(e,this.identityHonorificPrefixAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.TitleFieldNames,!1),this.isFieldForIdentityFirstName=e=>!!this.fieldContainsAutocompleteValues(e,this.identityFirstNameAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.FirstnameFieldNames,!1),this.isFieldForIdentityMiddleName=e=>!!this.fieldContainsAutocompleteValues(e,this.identityMiddleNameAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.MiddlenameFieldNames,!1),this.isFieldForIdentityLastName=e=>!!this.fieldContainsAutocompleteValues(e,this.identityLastNameAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.LastnameFieldNames,!1),this.isFieldForIdentityFullName=e=>!!this.fieldContainsAutocompleteValues(e,this.identityFullNameAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.FullNameFieldNames,!1),this.isFieldForIdentityAddress1=e=>!!this.fieldContainsAutocompleteValues(e,this.identityAddressLine1AutocompleteValue)||this.keywordsFoundInFieldData(e,[...qD.AddressFieldNames,...qD.Address1FieldNames],!1),this.isFieldForIdentityAddress2=e=>!!this.fieldContainsAutocompleteValues(e,this.identityAddressLine2AutocompleteValue)||this.keywordsFoundInFieldData(e,qD.Address2FieldNames,!1),this.isFieldForIdentityAddress3=e=>!!this.fieldContainsAutocompleteValues(e,this.identityAddressLine3AutocompleteValue)||this.keywordsFoundInFieldData(e,qD.Address3FieldNames,!1),this.isFieldForIdentityCity=e=>!!this.fieldContainsAutocompleteValues(e,this.identityAddressCityAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.CityFieldNames,!1),this.isFieldForIdentityState=e=>!!this.fieldContainsAutocompleteValues(e,this.identityAddressStateAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.StateFieldNames,!1),this.isFieldForIdentityPostalCode=e=>!!this.fieldContainsAutocompleteValues(e,this.identityPostalCodeAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.PostalCodeFieldNames,!1),this.isFieldForIdentityCountry=e=>!!this.fieldContainsAutocompleteValues(e,this.identityCountryAutocompleteValues)||this.keywordsFoundInFieldData(e,qD.CountryFieldNames,!1),this.isFieldForIdentityCompany=e=>!!this.fieldContainsAutocompleteValues(e,this.identityCompanyAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.CompanyFieldNames,!1),this.isFieldForIdentityPhone=e=>!!this.fieldContainsAutocompleteValues(e,this.identityPhoneAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.PhoneFieldNames,!1),this.isFieldForIdentityEmail=e=>!!this.isExplicitIdentityEmailField(e)||!(!this.fieldContainsAutocompleteValues(e,this.emailAutocompleteValue)&&"email"!==e.type&&"email"!==e.htmlName)||this.keywordsFoundInFieldData(e,qD.EmailFieldNames,!1),this.isFieldForIdentityUsername=e=>!!this.fieldContainsAutocompleteValues(e,this.usernameAutocompleteValue)||this.keywordsFoundInFieldData(e,qD.UserNameFieldNames,!1),this.isUsernameField=e=>{const t=e.type;return!(!t||!this.usernameFieldTypes.has(t)||this.isExcludedFieldType(e,this.excludedAutofillFieldTypesSet)||this.fieldHasDisqualifyingAttributeValue(e)||this.isTotpField(e))&&this.keywordsFoundInFieldData(e,UD.UsernameFieldNames)},this.isEmailField=e=>"email"===e.type||!this.isExcludedFieldType(e,this.excludedAutofillFieldTypesSet)&&this.keywordsFoundInFieldData(e,UD.EmailFieldNames),this.isCurrentPasswordField=e=>!this.fieldContainsAutocompleteValues(e,this.newPasswordAutoCompleteValue)&&!this.keywordsFoundInFieldData(e,this.accountCreationFieldKeywords)&&this.isPasswordField(e),this.isUpdateCurrentPasswordField=e=>!this.fieldContainsAutocompleteValues(e,this.newPasswordAutoCompleteValue)&&this.isPasswordField(e)&&this.keywordsFoundInFieldData(e,this.updatePasswordFieldKeywords),this.isNewPasswordField=e=>!this.fieldContainsAutocompleteValues(e,this.currentPasswordAutocompleteValue)&&this.isPasswordField(e)&&this.keywordsFoundInFieldData(e,this.accountCreationFieldKeywords),this.isPasswordField=e=>{const t="password"===e.type;return!(!t&&this.isExcludedFieldType(e,this.excludedAutofillFieldTypesSet)||this.fieldHasDisqualifyingAttributeValue(e)||this.isTotpField(e))&&(t||this.isLikePasswordField(e))},this.isTotpField=e=>!$D.fieldIsFuzzyMatch(e,[...UD.RecoveryCodeFieldNames])&&(!!this.fieldContainsAutocompleteValues(e,this.totpFieldAutocompleteValue)||!this.isExcludedFieldType(e,this.excludedAutofillFieldTypesSet)&&this.keywordsFoundInFieldData(e,UD.TotpFieldNames)),this.isElementLoginSubmitButton=e=>{const t=this.getSubmitButtonKeywords(e);return LD.some(e=>t.indexOf(e)>-1)},this.isElementChangePasswordSubmitButton=e=>{const t=this.getSubmitButtonKeywords(e);return BD.some(e=>t.indexOf(e)>-1)},function(e){return t=this,i=arguments,n=function*(e,t={}){return"undefined"!=typeof browser&&void 0!==browser.runtime&&void 0!==browser.runtime.sendMessage?browser.runtime.sendMessage(Object.assign({command:e},t)):new Promise(i=>chrome.runtime.sendMessage(Object.assign({command:e},t),e=>{chrome.runtime.lastError&&i(null),i(e)}))},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}("getUserPremiumStatus").then(e=>{this.premiumEnabled=!!(null==e?void 0:e.result)})}isFieldForLoginForm(e,t){if(this.premiumEnabled){const t=this.isTotpField(e),i="password"===e.type;if(t&&!i)return!0}return this.isCurrentPasswordField(e)?this.isPasswordFieldForLoginForm(e,t):!!this.isUsernameField(e)&&this.isUsernameFieldForLoginForm(e,t)}isFieldForCreditCardForm(e,t){if(this.fieldContainsAutocompleteValues(e,this.creditCardAutocompleteValues))return!0;let i;const r=e.form;if(r&&(i=t.forms[r]),!i)return 1===t.fields.filter(this.isFieldForCardNumber).length&&(1===t.fields.filter(this.isFieldForCardCvv).length&&this.keywordsFoundInFieldData(e,this.creditCardFieldKeywords));const n=t.fields.filter(t=>t.form===e.form);return 1===n.filter(this.isFieldForCardNumber).length&&(1===n.filter(this.isFieldForCardCvv).length&&this.keywordsFoundInFieldData(e,[...this.creditCardFieldKeywords]))}isFieldForAccountCreationForm(e,t){if(this.isExcludedFieldType(e,this.excludedAutofillFieldTypesSet)||this.isTotpField(e))return!1;if(!this.isUsernameField(e)&&!this.isPasswordField(e))return!1;let i;const r=e.form;return r&&(i=t.forms[r]),i?t.fields.filter(t=>t.form===e.form).filter(this.isNewPasswordField).length>=1||this.keywordsFoundInFieldData(e,this.accountCreationFieldKeywords):t.fields.filter(this.isNewPasswordField).length>=1||this.keywordsFoundInFieldData(e,this.accountCreationFieldKeywords)}isFieldForIdentityForm(e,t){return!this.isExcludedFieldType(e,this.excludedAutofillFieldTypesSet)&&(this.isFieldForIdentityEmail(e)||this.fieldContainsAutocompleteValues(e,this.identityAutocompleteValues))}isPasswordFieldForLoginForm(e,t){let i;const r=e.form;if(r&&(i=t.forms[r]),this.fieldContainsAutocompleteValues(e,this.currentPasswordAutocompleteValue))return i?0===t.fields.filter(this.isNewPasswordField).filter(t=>t.viewable&&t.form===e.form).length:0===t.fields.filter(this.isNewPasswordField).filter(e=>e.viewable).length;const n=t.fields.filter(this.isUsernameField),a=t.fields.filter(this.isCurrentPasswordField);return 1===n.length&&1===a.length||(i?!(a.filter(t=>t.form===e.form&&t.viewable).length>1)&&(n.filter(t=>t.form===e.form&&t.viewable).length,!0):!(a.length>1)&&!(n.filter(e=>e.viewable).length>1))}isUsernameFieldForLoginForm(e,t){if(this.isExplicitIdentityEmailField(e))return!1;if(this.fieldContainsAutocompleteValues(e,this.loginUsernameAutocompleteValues)){const e=t.fields.filter(e=>e.viewable&&this.isNewPasswordField(e));return 0===e.length}if(this.keywordsFoundInFieldData(e,this.accountCreationFieldKeywords))return!1;let i;const r=e.form;r&&(i=t.forms[r]);const n=t.fields.filter(this.isCurrentPasswordField);if(this.isNewsletterForm(i))return!1;if(!i){const e=n.filter(e=>e.viewable);return 1===e.length||!(e.length>1)&&(n.length,!0)}if(0===n.length){const i=t.fields.filter(t=>t.form===e.form);return 1===i.length||1===i.filter(e=>e.viewable).length}const a=n.filter(t=>t.form===e.form&&t.viewable);return 1===a.length||!(a.length>1)&&(n.length,!0)}isLikePasswordField(e){if("text"!==e.type)return!1;const t=[e.htmlID,e.htmlName,e.placeholder];for(let e=0;et.indexOf(e)>-1))}fieldHasDisqualifyingAttributeValue(e){const t=[e.htmlID,e.htmlName,e.placeholder];for(let e=0;e-1)return!0}return!1}isExcludedFieldType(e,t){const i=e.type;return!(!i||!t.has(i))||this.isSearchField(e)}isSearchField(e){const t=[e.type,e.htmlName,e.htmlID,e.placeholder];for(let e=0;e{e&&i.add(e)})}return i}(e);this.submitButtonKeywordsMap.set(e,Array.from(t).join(","))}return this.submitButtonKeywordsMap.get(e)||""}keywordsFoundInFieldData(e,t,i=!0){const r=this.getAutofillFieldDataKeywords(e,i),n=t.map(e=>e.replace(/-/g,""));return"string"==typeof r?n.some(e=>r.indexOf(e)>-1):n.some(e=>r.has(e))}getAutofillFieldDataKeywords(e,t){if(!this.autofillFieldKeywordsMap.has(e)){const t=[e.htmlID,e.htmlName,e.htmlClass,e.type,e.title,e.placeholder,e.autoCompleteType,e.dataSetValues,e["label-data"],e["label-aria"],e["label-left"],e["label-right"],e["label-tag"],e["label-top"]],i=new Set;for(let e=0;e{e&&i.add(e)}),e.replace(/\s/g,"").split(/[^\p{L}\d]+/gu).forEach(e=>{e&&i.add(e)})}}const r=Array.from(i).join(",");this.autofillFieldKeywordsMap.set(e,{keywordsSet:i,stringValue:r})}const i=this.autofillFieldKeywordsMap.get(e);return i?t?i.stringValue:i.keywordsSet:""}fieldContainsAutocompleteValues(e,t){const i=e.autoCompleteType;if(!i||"string"!=typeof i)return!1;const r=i.split(" ");if("string"==typeof t)return r.indexOf(t)>-1;for(let e=0;e{if(!t)return!1;const i=t.trim().toLowerCase().replace(/\/$/,"").replace(/^https?:\/\//,"");if(i===e.hostname.toLowerCase())return!0;const r=e.href.toLowerCase().replace(/https?:\/\//,"").replace(/\/$/,"");return r===i||r.startsWith(i+"/")}}],[HD.Links]:[{name:"Phishing.Database Links",primaryUrl:"https://assets.bitwarden.com/security/v1/link-blocklist.txt",checksumUrl:"https://raw.githubusercontent.com/Phishing-Database/checksums/refs/heads/master/phishing-links-ACTIVE.txt.md5",todayUrl:"https://raw.githubusercontent.com/Phishing-Database/Phishing.Database/refs/heads/master/phishing-links-NEW-today.txt",match:(e,t)=>{if(!t)return!1;const i=e=>e.replace(/&/g,"&"),r=i(t.trim()).toLowerCase().replace(/\/$/,""),n=i(e.href).toLowerCase().replace(/\/$/,"").replace(/^https?:\/\//,""),a=r.replace(/^https?:\/\//,"");return n===a||!(!n.startsWith(a+"?")&&!n.startsWith(a+"#"))}}]};function QD(e,t=0){var i;return(null!==(i=GD[e])&&void 0!==i?i:[])[t]}var JD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class YD{constructor(e){this.logService=e,this.DB_NAME="bitwarden-phishing",this.STORE_NAME="phishing-urls",this.DB_VERSION=1,this.CHUNK_SIZE=5e4}openDatabase(){return new Promise((e,t)=>{const i=indexedDB.open(this.DB_NAME,this.DB_VERSION);i.onerror=()=>t(i.error),i.onsuccess=()=>e(i.result),i.onupgradeneeded=e=>{const t=e.target.result;t.objectStoreNames.contains(this.STORE_NAME)||t.createObjectStore(this.STORE_NAME,{keyPath:"url"})}})}clearStore(e){return new Promise((t,i)=>{const r=e.transaction(this.STORE_NAME,"readwrite").objectStore(this.STORE_NAME).clear();r.onerror=()=>i(r.error),r.onsuccess=()=>t()})}saveUrls(e){return JD(this,void 0,void 0,function*(){this.logService.debug(`[PhishingIndexedDbService] Clearing and saving ${e.length} to the store...`);let t=null;try{return t=yield this.openDatabase(),yield this.clearStore(t),yield this.saveChunked(t,e),!0}catch(e){return this.logService.error("[PhishingIndexedDbService] Save failed",e),!1}finally{null==t||t.close()}})}addUrls(e){return JD(this,void 0,void 0,function*(){this.logService.debug(`[PhishingIndexedDbService] Adding ${e.length} to the store...`);let t=null;try{return t=yield this.openDatabase(),yield this.saveChunked(t,e),!0}catch(e){return this.logService.error("[PhishingIndexedDbService] Add failed",e),!1}finally{null==t||t.close()}})}saveChunked(e,t){return JD(this,void 0,void 0,function*(){const i=t.map(e=>e.trim()).filter(Boolean);for(let t=0;tsetTimeout(e,0))})}saveChunk(e,t){return new Promise((i,r)=>{const n=e.transaction(this.STORE_NAME,"readwrite"),a=n.objectStore(this.STORE_NAME);for(const e of t)a.put({url:e});n.oncomplete=()=>i(),n.onerror=()=>r(n.error)})}hasUrl(e){return JD(this,void 0,void 0,function*(){this.logService.debug(`[PhishingIndexedDbService] Checking if store contains ${e}...`);let t=null;try{return t=yield this.openDatabase(),yield this.checkUrlExists(t,e)}catch(e){return this.logService.error("[PhishingIndexedDbService] Check failed",e),!1}finally{null==t||t.close()}})}checkUrlExists(e,t){return new Promise((i,r)=>{const n=e.transaction(this.STORE_NAME,"readonly").objectStore(this.STORE_NAME).get(t);n.onerror=()=>r(n.error),n.onsuccess=()=>i(void 0!==n.result)})}loadAllUrls(){return JD(this,void 0,void 0,function*(){this.logService.debug("[PhishingIndexedDbService] Loading all urls from store...");let e=null;try{return e=yield this.openDatabase(),yield this.getAllUrls(e)}catch(e){return this.logService.error("[PhishingIndexedDbService] Load failed",e),[]}finally{null==e||e.close()}})}getAllUrls(e){return new Promise((t,i)=>{const r=[],n=e.transaction(this.STORE_NAME,"readonly").objectStore(this.STORE_NAME).openCursor();n.onerror=()=>i(n.error),n.onsuccess=e=>{const i=e.target.result;i?(r.push(i.value.url),i.continue()):t(r)}})}findMatchingUrl(e){return JD(this,void 0,void 0,function*(){this.logService.debug("[PhishingIndexedDbService] Searching for matching URL with cursor...");let t=null;try{return t=yield this.openDatabase(),yield this.cursorSearch(t,e)}catch(e){return this.logService.error("[PhishingIndexedDbService] Cursor search failed",e),!1}finally{null==t||t.close()}})}cursorSearch(e,t){return new Promise((i,r)=>{const n=e.transaction(this.STORE_NAME,"readonly").objectStore(this.STORE_NAME).openCursor();n.onerror=()=>r(n.error),n.onsuccess=e=>{const r=e.target.result;if(r){const e=r.value.url;if(t(e))return void i(!0);r.continue()}else i(!1)}})}saveUrlsFromStream(e){return JD(this,void 0,void 0,function*(){this.logService.debug("[PhishingIndexedDbService] Saving urls to the store from stream...");let t=null;try{return t=yield this.openDatabase(),yield this.clearStore(t),yield this.processStream(t,e),this.logService.info("[PhishingIndexedDbService] Finished saving urls to the store from stream."),!0}catch(e){return this.logService.error("[PhishingIndexedDbService] Stream save failed",e),!1}finally{null==t||t.close()}})}processStream(e,t){return JD(this,void 0,void 0,function*(){var i;const r=t.getReader(),n=new TextDecoder;let a="",s=[];try{for(;;){const{done:t,value:o}=yield r.read();if(a+=n.decode(o,{stream:!t}),t){const t=a.split("\n");for(const e of t){const t=e.trim();t&&s.push(t)}s.length>0&&(yield this.saveChunk(e,s));break}const l=a.split("\n");a=null!==(i=l.pop())&&void 0!==i?i:"";for(const t of l){const i=t.trim();i&&s.push(i),s.length>=this.CHUNK_SIZE&&(yield this.saveChunk(e,s),s=[],yield new Promise(e=>setTimeout(e,0)))}}}finally{r.releaseLock()}})}}var XD=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const ZD=new fi(Qi,"phishingDomainsMeta",{deserializer:e=>{var t,i,r;return{checksum:null!==(t=null==e?void 0:e.checksum)&&void 0!==t?t:"",timestamp:null!==(i=null==e?void 0:e.timestamp)&&void 0!==i?i:0,applicationVersion:null!==(r=null==e?void 0:e.applicationVersion)&&void 0!==r?r:""}}});new fi(Qi,"phishingDomainsBlob",{deserializer:e=>null!=e?e:""});class eO{constructor(e,t,i,r,n,a=HD.Links){this.apiService=e,this.taskSchedulerService=t,this.globalStateProvider=i,this.logService=r,this.platformUtilsService=n,this.resourceType=a,this._destroy$=new H,this._testWebAddresses=this.getTestWebAddresses(),this._phishingMetaState=this.globalStateProvider.get(ZD),this.UPDATE_INTERVAL_DURATION=864e5,this._backgroundUpdateTrigger$=new H,this._triggerUpdate$=new H,this.update$=this._triggerUpdate$.pipe(wb(void 0),Le(()=>this._phishingMetaState.state$.pipe(v_(),ac(e=>{this._backgroundUpdateTrigger$.next(e)}),Hu(e=>(this.logService.error("[PhishingDataService] Background update failed to start.",e),pe)))),m_(this._destroy$),Gt()),this.logService.debug("[PhishingDataService] Initializing service..."),this.indexedDbService=new YD(this.logService),this.taskSchedulerService.registerTaskHandler(Tu,()=>{this._triggerUpdate$.next()}),this.taskSchedulerService.setInterval(Tu,this.UPDATE_INTERVAL_DURATION),this._backgroundUpdateTrigger$.pipe(WD(e=>this._backgroundUpdate(e)),m_(this._destroy$)).subscribe()}dispose(){this._destroy$.next(),this._destroy$.complete()}isPhishingWebAddress(e){return XD(this,void 0,void 0,function*(){if("http:"!==e.protocol&&"https:"!==e.protocol)return!1;if(this._testWebAddresses.includes(e.href))return this.logService.info("[PhishingDataService] Found test web address: "+e.href),!0;const t=QD(this.resourceType);try{const t=e.href,i=t.endsWith("/")?t.slice(0,-1):null;let r=yield this.indexedDbService.hasUrl(t);if(!r&&i&&(r=yield this.indexedDbService.hasUrl(i)),r)return this.logService.info("[PhishingDataService] Found phishing URL: "+t),!0}catch(e){this.logService.error("[PhishingDataService] IndexedDB lookup failed",e)}if(t&&t.match&&eO.USE_CUSTOM_MATCHER)try{const i=yield this.indexedDbService.findMatchingUrl(i=>t.match(e,i));return i&&this.logService.info("[PhishingDataService] Found phishing URL via matcher: "+e.href),i}catch(e){return this.logService.error("[PhishingDataService] Custom matcher failed",e),!1}return!1})}fetchPhishingChecksum(){return XD(this,arguments,void 0,function*(e=HD.Domains){const t=QD(e).checksumUrl;this.logService.debug(`[PhishingDataService] Fetching checksum from: ${t}`);try{const e=yield this.apiService.nativeFetch(new Request(t));if(!e.ok)throw new Error(`[PhishingDataService] Failed to fetch checksum: ${e.status} ${e.statusText}`);return yield e.text()}catch(e){throw this.logService.error(`[PhishingDataService] Checksum fetch failed from ${t}`,e),e}})}fetchToday(e){return XD(this,void 0,void 0,function*(){const t=yield this.apiService.nativeFetch(new Request(e));if(!t.ok)throw new Error(`[PhishingDataService] Failed to fetch web addresses: ${t.status}`);return t.text().then(e=>e.split("\n"))})}getTestWebAddresses(){return[new URL("http://phishing.testcategory.com").href,new URL("https://phishing.testcategory.com").href,new URL("https://phishing.testcategory.com/block").href]}_getUpdatedMeta(){return nc(()=>{const e=Date.now();return Gu({applicationVersion:Se(this.platformUtilsService.getApplicationVersion()),remoteChecksum:Se(this.fetchPhishingChecksum(this.resourceType))}).pipe(X(({applicationVersion:t,remoteChecksum:i})=>({checksum:i,timestamp:e,applicationVersion:t})))})}_updateFullDataSet(){const e=QD(this.resourceType);return(null==e?void 0:e.primaryUrl)?(this.logService.info(`[PhishingDataService] Starting FULL update using ${e.primaryUrl}`),Se(this.apiService.nativeFetch(new Request(e.primaryUrl))).pipe(Le(e=>e.ok&&e.body?Se(this.indexedDbService.saveUrlsFromStream(e.body)):tc(()=>new Error(`[PhishingDataService] Full fetch failed: ${e.status}, ${e.statusText}`))))):tc(()=>new Error("Invalid resource URL"))}_updateDailyDataSet(){var e;this.logService.info("[PhishingDataService] Starting DAILY update...");const t=null===(e=QD(this.resourceType))||void 0===e?void 0:e.todayUrl;return t?Se(this.fetchToday(t)).pipe(Le(e=>Se(this.indexedDbService.addUrls(e)))):tc(()=>new Error("Today URL missing"))}_backgroundUpdate(e){return nc(()=>{const t=Date.now();return this.logService.info("[PhishingDataService] Update triggered..."),this._getUpdatedMeta().pipe(gc(t=>Zg(()=>{const i=t.applicationVersion!==(null==e?void 0:e.applicationVersion),r=t.checksum!==(null==e?void 0:e.checksum);return this.logService.info(`[PhishingDataService] Checking if full update is needed: appVersionChanged=${i}, checksumChanged=${r}`),i||r},this._updateFullDataSet().pipe(X(()=>({meta:t,updated:!0}))),bt({meta:t,updated:!1}))),gc(t=>Zg(()=>{var t;return Date.now()-(null!==(t=null==e?void 0:e.timestamp)&&void 0!==t?t:0)>this.UPDATE_INTERVAL_DURATION},this._updateDailyDataSet().pipe(X(()=>({meta:t.meta,updated:!0}))),bt(t))),gc(i=>i.updated?(this.logService.debug("[PhishingDataService] Updated phishing meta data:",i.meta),Se(this._phishingMetaState.update(()=>i.meta)).pipe(ac(()=>{const e=Date.now()-t;this.logService.info(`[PhishingDataService] Updated data set in ${e}ms`)}))):(this.logService.debug("[PhishingDataService] No update needed, metadata unchanged"),bt(e))),function(e){var t;void 0===e&&(e=1/0);var i=(t=e&&"object"==typeof e?e:{count:e}).count,r=void 0===i?1/0:i,n=t.delay,a=t.resetOnSuccess,s=void 0!==a&&a;return r<=0?B:Q(function(e,t){var i,a=0,o=function(){var l=!1;i=e.subscribe(J(t,function(e){s&&(a=0),t.next(e)},void 0,function(e){if(a++(this.logService.error(`[PhishingDataService] Attempt ${t} failed. Retrying in 5m...`,e),sc(3e5))}),Hu(i=>{const r=Date.now()-t;return this.logService.error(`[PhishingDataService] Retries unsuccessful after ${r}ms.`,i),bt(e)}))})}}eO.USE_CUSTOM_MATCHER=!1;var tO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const iO=new Wf("phishing-detection-continue"),rO=new Wf("phishing-detection-cancel");class nO{static initialize(e,t,i,r){if(this._didInit)return void e.debug("[PhishingDetectionService] Initialize already called. Aborting.");e.debug("[PhishingDetectionService] Initialize called. Checking prerequisites..."),hT.addListener(chrome.tabs.onUpdated,this._handleTabUpdated.bind(this));const n=r.messages$(iO).pipe(ac(t=>e.debug(`[PhishingDetectionService] user selected continue for ${t.url}`)),Le(e=>tO(this,void 0,void 0,function*(){const t=new URL(e.url);this._ignoredHostnames.add(t.hostname),yield hT.navigateTabToUrl(e.tabId,t)}))),a=this._tabUpdated$.pipe(Ie(e=>"complete"===e.changeInfo.status&&!!e.tab.url&&!this._isExtensionPage(e.tab.url)),X(({tab:e,tabId:t})=>{const i=new URL(e.url);return{tabId:t,url:i,ignored:this._ignoredHostnames.has(i.hostname)}}),Zl((e,t)=>e.url.toString()===t.url.toString()&&e.tabId===t.tabId&&e.ignored===t.ignored),ac(t=>e.debug("[PhishingDetectionService] processing event:",t)),Le(e=>tO(this,[e],void 0,function*({tabId:e,url:i,ignored:r}){if(r)return void this._ignoredHostnames.delete(i.hostname);if(!(yield t.isPhishingWebAddress(i)))return;const n=new URL(hT.getRuntimeURL("popup/index.html#/security/phishing-warning")+`?phishingUrl=${i.toString()}`);yield hT.navigateTabToUrl(e,n)}))),s=r.messages$(rO).pipe(Le(e=>hT.closeTab(e.tabId))),o=i.on$.pipe(Zl(),Le(i=>i?(e.debug("[PhishingDetectionService] Enabling phishing detection service"),_e(t.update$,n,a,s)):(e.debug("[PhishingDetectionService] User does not have access to phishing detection service."),pe))).subscribe();return this._didInit=!0,()=>{t.dispose(),o.unsubscribe(),this._didInit=!1,hT.removeListener(chrome.tabs.onUpdated,nO._handleTabUpdated)}}static _handleTabUpdated(e,t,i){return this._tabUpdated$.next({tabId:e,changeInfo:t,tab:i}),!0}static _isExtensionPage(e){return e.startsWith("chrome-extension://")||e.startsWith("moz-extension://")||e.startsWith("safari-extension://")||e.startsWith("safari-web-extension://")}}nO._tabUpdated$=new H,nO._ignoredHostnames=new Set,nO._didInit=!1;var aO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class sO extends $u{constructor(e,t,i,r,n,a,s){super(),this.nativeMessagingBackground=e,this.logService=t,this.keyService=i,this.biometricStateService=r,this.messagingService=n,this.vaultTimeoutSettingsService=a,this.pinService=s,this.BACKGROUND_POLLING_INTERVAL=3e4;const o=this.biometricStateService.biometricUnlockEnabled$();ai([sc(0,this.BACKGROUND_POLLING_INTERVAL),o]).pipe(Ie(([e,t])=>t),Ie(([e])=>!this.nativeMessagingBackground().connected),gc(()=>aO(this,void 0,void 0,function*(){try{yield this.nativeMessagingBackground().connect(),yield this.getBiometricsStatus()}catch(e){}}))).subscribe()}authenticateWithBiometrics(){return aO(this,void 0,void 0,function*(){try{return yield this.ensureConnected(),(yield this.nativeMessagingBackground().callCommand({command:Lu.AuthenticateWithBiometrics})).response}catch(e){return this.logService.info("Biometric authentication failed",e),!1}})}getBiometricsStatus(){return aO(this,void 0,void 0,function*(){if(!(yield hT.permissionsGranted(["nativeMessaging"])))return qu.NativeMessagingPermissionMissing;try{const e=yield this.nativeMessagingBackground().callCommand({command:Lu.GetBiometricsStatus});return e.response?e.response:qu.Available}catch(e){return qu.DesktopDisconnected}})}unlockWithBiometricsForUser(e){return aO(this,void 0,void 0,function*(){try{yield this.ensureConnected();const t=yield this.nativeMessagingBackground().callCommand({command:Lu.UnlockWithBiometricsForUser,userId:e});if(!t.response)return null;{const i=Tt.fromB64ToArray(t.userKeyB64),r=new gu(i);if(yield this.keyService.validateUserKey(r,e))return yield this.biometricStateService.setBiometricUnlockEnabled(!0),yield this.keyService.setUserKey(r,e),yield this.pinService.userUnlocked(e),this.messagingService.send("switchAccount",{userId:e}),r}}catch(e){throw this.logService.info("Biometric unlock for user failed",e),new Error("Biometric unlock failed")}return null})}getBiometricsStatusForUser(e){return aO(this,void 0,void 0,function*(){try{return yield this.ensureConnected(),(yield this.nativeMessagingBackground().callCommand({command:Lu.GetBiometricsStatusForUser,userId:e})).response}catch(e){return qu.DesktopDisconnected}})}ensureConnected(){return aO(this,void 0,void 0,function*(){this.nativeMessagingBackground().connected||(yield this.nativeMessagingBackground().callCommand({command:Lu.GetBiometricsStatus}))})}getShouldAutopromptNow(){return aO(this,void 0,void 0,function*(){return!1})}setShouldAutopromptNow(e){return aO(this,void 0,void 0,function*(){})}canEnableBiometricUnlock(){return aO(this,void 0,void 0,function*(){const e=yield this.getBiometricsStatus(),t=yield this.vaultTimeoutSettingsService.isBiometricLockSet();return e!==qu.DesktopDisconnected&&e!==qu.NotEnabledInConnectedDesktopApp&&e!==qu.HardwareUnavailable||t})}}var oO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class lO{constructor(e){this.platformUtilsService=e}isAvailable(e){return oO(this,void 0,void 0,function*(){switch(e){case 0:case cd:case ld:case"custom":return!0;case ud:return!(this.platformUtilsService.isFirefox()||this.platformUtilsService.isSafari()||this.platformUtilsService.isOpera()&&"MacIntel"===navigator.platform);default:if(pd(e))return!0}return!1})}getOrPromoteToAvailable(e){return oO(this,void 0,void 0,function*(){return(yield this.isAvailable(e))?e:cd})}}class cO extends bd{startCheck(){if(this.platformUtilsService.isSafari())return this.checkVaultTimeout().catch(e=>this.logService.error(e)),void this.checkSafari().catch(e=>this.logService.error(e));super.startCheck()}checkSafari(){return e=this,t=void 0,r=function*(){for(;;)try{yield iT.sendMessageToApp("sleep"),this.checkVaultTimeout()}catch(e){console.log("Exception Safari VaultTimeout",e)}},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r}}class uO{constructor(e,t){this.logService=e,this.platformUtilsService=t}openPopup(){return e=this,t=void 0,r=function*(){const e=this.platformUtilsService.getDevice();try{switch(e){case Rd.FirefoxExtension:case Rd.ChromeExtension:{const t=hT.getBrowserAction();if("openPopup"in t&&"function"==typeof t.openPopup)return void(yield t.openPopup());this.logService.warning(`No openPopup function found on browser actions. On browser: ${Rd[e]} and manifest version: ${hT.manifestVersion}`);break}case Rd.SafariExtension:return void(yield iT.sendMessageToApp("showPopover",null,!0));default:this.logService.warning(`Tried to open the popup from an unsupported device type: ${Rd[e]}`)}}catch(t){this.logService.error(`Failed to open the popup on ${Rd[e]} with manifest ${hT.manifestVersion} and error: ${t}`)}},new((i=void 0)||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())});var e,t,i,r}}var dO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};function hO(e){return{tabId:e.id,url:e.url}}class pO{getActiveTabs(){return dO(this,void 0,void 0,function*(){return(yield hT.getActiveTabs()).filter(e=>null!=e.id&&null!=e.url).map(hO)})}constructor(e){this.platformUtilsService=e,this.badgeAction=hT.getBrowserAction(),this.sidebarAction=hT.getSidebarAction(self),this.onTabActivated$=xD(chrome.tabs.onActivated).pipe(X(([e])=>e),Jt({bufferSize:1,refCount:!0})),this.createdOrUpdatedTabEvents$=li(nc(()=>dO(this,void 0,void 0,function*(){return yield this.getActiveTabs()})).pipe(Le(e=>bt(...e.map(e=>({type:"activated",tab:e}))))),_e(this.onTabActivated$.pipe(Le(e=>dO(this,void 0,void 0,function*(){return yield hT.getTab(e.tabId)})),Ie(e=>!(null==e||null==e.id||null==e.url)),Le(e=>dO(this,void 0,void 0,function*(){return{type:"activated",tab:hO(e)}}))),xD(chrome.tabs.onUpdated).pipe(Ie(([e,t])=>null!=t.url),X(([e,t,i])=>({type:"updated",tab:hO(i)}))),xD(chrome.webNavigation.onCommitted).pipe(Ie(([e])=>"reload"===e.transitionType),X(([e])=>({type:"updated",tab:{tabId:e.tabId,url:e.url}})))).pipe(Jt({bufferSize:1,refCount:!0}))),this.tabEvents$=_e(this.createdOrUpdatedTabEvents$,this.createdOrUpdatedTabEvents$.pipe(gc(()=>dO(this,void 0,void 0,function*(){return this.getActiveTabs()})),g_(),X(([e,t])=>{const i=e.map(e=>e.tabId),r=t.map(e=>e.tabId);return i.filter(e=>!r.includes(e)).map(e=>({type:"deactivated",tabId:e}))}),Le(e=>bt(...e)))),this.activeTabs$=this.tabEvents$.pipe(gc(()=>dO(this,void 0,void 0,function*(){return this.getActiveTabs()})))}setState(e,t){return dO(this,void 0,void 0,function*(){yield Promise.all([void 0!==e.backgroundColor?this.setIcon(e.icon,t):void 0,this.setText(e.text,t),void 0!==e.backgroundColor?this.setBackgroundColor(e.backgroundColor,t):void 0])})}setIcon(e,t){return Promise.all([this.setActionIcon(e,t),this.setSidebarActionIcon(e,t)])}setText(e,t){return Promise.all([this.setActionText(e,t),this.setSideBarText(e,t)])}setActionIcon(e,t){return dO(this,void 0,void 0,function*(){var i;(null===(i=this.badgeAction)||void 0===i?void 0:i.setIcon)&&(this.useSyncApiCalls?yield this.badgeAction.setIcon({path:e,tabId:t}):yield new Promise(i=>this.badgeAction.setIcon({path:e,tabId:t},i)))})}setSidebarActionIcon(e,t){return dO(this,void 0,void 0,function*(){var i;(null===(i=this.sidebarAction)||void 0===i?void 0:i.setIcon)&&("opr"in self&&hT.isManifestVersion(3)||(this.isOperaSidebar(this.sidebarAction)?yield new Promise(i=>this.sidebarAction.setIcon({path:e,tabId:t},()=>i())):yield this.sidebarAction.setIcon({path:e,tabId:t})))})}setActionText(e,t){return dO(this,void 0,void 0,function*(){var i;(null===(i=this.badgeAction)||void 0===i?void 0:i.setBadgeText)&&(yield this.badgeAction.setBadgeText({text:e,tabId:t}))})}setSideBarText(e,t){return dO(this,void 0,void 0,function*(){if(this.sidebarAction)if(this.isOperaSidebar(this.sidebarAction))this.sidebarAction.setBadgeText({text:e,tabId:t});else if(this.sidebarAction){const i="Bitwarden"+(Tt.isNullOrEmpty(e)?"":` [${e}]`);yield this.sidebarAction.setTitle({title:i,tabId:t})}})}setBackgroundColor(e,t){return dO(this,void 0,void 0,function*(){var i;this.badgeAction&&(null===(i=this.badgeAction)||void 0===i?void 0:i.setBadgeBackgroundColor)&&(yield this.badgeAction.setBadgeBackgroundColor({color:e,tabId:t})),this.sidebarAction&&this.isOperaSidebar(this.sidebarAction)&&this.sidebarAction.setBadgeBackgroundColor({color:e,tabId:t})})}get useSyncApiCalls(){return this.platformUtilsService.isFirefox()||this.platformUtilsService.isSafari()}isOperaSidebar(e){return null!=e&&null!=e.setBadgeText}}const mO={text:"",backgroundColor:"#294e5f",icon:Jj.LoggedOut};var gO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class fO{constructor(e,t,i=100){this.badgeApi=e,this.logService=t,this.debounceTimeMs=i,this.stateFunctions=new $c({})}startListening(){const e=e=>bt({priority:0,state:{}});return this.badgeApi.tabEvents$.pipe((t=e=>"deactivated"===e.type?e.tabId:e.tab.tabId,i={duration:e=>e.pipe(Ie(e=>"deactivated"===e.type))},Q(function(e,a){var s;i&&"function"!=typeof i?(r=i.duration,s=i.element,n=i.connector):s=i;var o=new Map,l=function(e){o.forEach(e),e(a)},c=function(e){return l(function(t){return t.error(e)})},u=0,d=!1,h=new Y(a,function(e){try{var i=t(e),l=o.get(i);if(!l){o.set(i,l=n?n():new H);var p=(g=i,f=l,(y=new $(function(e){u++;var t=f.subscribe(e);return function(){t.unsubscribe(),0===--u&&d&&h.unsubscribe()}})).key=g,y);if(a.next(p),r){var m=J(l,function(){l.complete(),null==m||m.unsubscribe()},void 0,void 0,function(){return o.delete(i)});h.add(le(r(p)).subscribe(m))}}l.next(s?s(e):e)}catch(e){c(e)}var g,f,y},function(){return l(function(e){return e.complete()})},c,function(){return o.clear()},function(){return d=!0,0===u});e.subscribe(h)})),de(t=>t.pipe(Ie(e=>"deactivated"!==e.type),X(e=>e.tab),Gc(this.stateFunctions),Le(([t,i])=>ai([...Object.entries(i),["default",e]].map(([e,i])=>i(t).pipe(wb(void 0),Hu(t=>(this.logService.error(`BadgeService: State function "${e}" threw an error`,t),bt(void 0)))))).pipe(X(e=>({tab:t,states:e.filter(e=>void 0!==e)})),HT(this.debounceTimeMs))),m_(t.pipe(Ie(e=>"deactivated"===e.type))))),gc(e=>gO(this,void 0,void 0,function*(){yield this.updateBadge(e.states,e.tab.tabId)}))).subscribe({error:e=>{this.logService.error("BadgeService: Fatal error updating badge state. Badge will no longer be updated.",e)}});var t,i,r,n}setState(e,t){this.stateFunctions.next(Object.assign(Object.assign({},this.stateFunctions.value),{[e]:t}))}clearState(e){const t=this.stateFunctions.value,i=Object.assign({},t);delete i[e],this.stateFunctions.next(i)}calculateState(e){const t=e.sort((e,t)=>e.priority-t.priority).map(e=>e.state).reduce((e,t)=>{const i=Object.assign({},e);for(const e in t)yO(i,t,e);return i},mO);return Object.assign(Object.assign({},mO),t)}updateBadge(e,t){return gO(this,void 0,void 0,function*(){const i=this.calculateState(e);try{yield this.badgeApi.setState(i,t)}catch(e){this.logService.error("Failed to set badge state",e)}})}}function yO(e,t,i){t[i]===Yj?delete e[i]:void 0!==t[i]&&(e[i]=t[i])}var vO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class bO extends Ff{constructor(e,t,i){super(),this.platformUtilsService=e,this.logService=t,this.sessionRepository=i}init(){const e=Object.create(null,{initWithClient:{get:()=>super.initWithClient}});return vO(this,void 0,void 0,function*(){try{yield xg.Ready,this.communicationBackend=new Sg.v5M({send(e){return vO(this,void 0,void 0,function*(){if("object"!=typeof e.destination||null==e.destination.Web)throw new Error("Destination not supported.");yield hT.tabSendMessage({id:e.destination.Web.id},{type:"bitwarden-ipc-message",message:{destination:e.destination,payload:[...e.payload],topic:e.topic}},{frameId:0})})}}),hT.messageListener("platform.ipc",(e,t)=>{var i,r;(function(e){return"bitwarden-ipc-message"===e.type})(e)&&"BrowserBackground"===e.message.destination&&void 0!==(null===(i=t.tab)||void 0===i?void 0:i.id)&&t.tab.id!==chrome.tabs.TAB_ID_NONE&&(null===(r=this.communicationBackend)||void 0===r||r.receive(new Sg.ILj(new Uint8Array(e.message.payload),e.message.destination,{Web:{id:t.tab.id}},e.message.topic)))}),yield e.initWithClient.call(this,Sg.CXO.newWithClientManagedSessions(this.communicationBackend,this.sessionRepository)),this.platformUtilsService.isDev()&&(yield(0,Sg.le5)(this.client,{version:yield this.platformUtilsService.getApplicationVersion()}))}catch(e){this.logService.error("[IPC] Initialization failed",e)}})}}const wO="ipc-content-script";class kO{constructor(e){hT.isManifestVersion(3)&&e.getFeatureFlag$(Ne.ContentScriptIpcChannelFramework).pipe(de(e=>{return t=this,i=void 0,n=function*(){if(e){try{yield hT.unregisterContentScriptsMv3({ids:[wO]})}catch(e){}yield hT.registerContentScriptsMv3([{id:wO,matches:["https://*/*"],js:["content/ipc-content-script.js"]}])}},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n})).subscribe()}}const SO={"Could not establish connection. Receiving end does not exist.":(e,t)=>e.debug(`Receiving end didn't exist for command '${t}'`),"The message port closed before a response was received.":(e,t)=>e.debug(`Port was closed for command '${t}'`)};class _O{constructor(e){this.logService=e}send(e,t={}){const i=Qf(e);chrome.runtime.sendMessage(Object.assign(t,{command:i}),()=>{if(chrome.runtime.lastError){const e=SO[chrome.runtime.lastError.message];if(null!=e)return void e(this.logService,i);this.logService.warning(`Unhandled error while sending message with command '${i}': ${chrome.runtime.lastError.message}`)}})}}var xO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class CO{constructor(e){this.logService=e,this.workerCount=0}offscreenApiSupported(){return void 0!==chrome.offscreen}withDocument(e,t,i){return xO(this,void 0,void 0,function*(){this.workerCount++;try{return(yield this.documentExists())||(yield this.create(e,t)),yield i()}finally{this.workerCount--,0===this.workerCount&&(yield this.close())}})}create(e,t){return xO(this,void 0,void 0,function*(){try{yield chrome.offscreen.createDocument({url:"offscreen-document/index.html",reasons:e,justification:t})}catch(e){if("Only a single offscreen document may be created."===e.message)return void this.logService.info("Ignoring offscreen document creation error.");throw e}})}close(){return xO(this,void 0,void 0,function*(){yield chrome.offscreen.closeDocument()})}documentExists(){return xO(this,void 0,void 0,function*(){return yield chrome.offscreen.hasDocument()})}}var IO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class EO{static fromJSON(e){return Object.assign(new EO,e)}}const zO=new fi(Xi,"environment",{deserializer:EO.fromJSON}),PO=new wi(Xi,"environment",{deserializer:EO.fromJSON,clearOn:["logout"]}),AO=new fi(Zi,"cloudRegion",{deserializer:e=>e}),jO=new wi(Zi,"cloudRegion",{deserializer:e=>e,clearOn:["logout"]}),TO=[{key:nf.US,domain:"bitwarden.com",urls:{base:null,api:"https://api.bitwarden.com",identity:"https://identity.bitwarden.com",icons:"https://icons.bitwarden.net",webVault:"https://vault.bitwarden.com",notifications:"https://notifications.bitwarden.com",events:"https://events.bitwarden.com",scim:"https://scim.bitwarden.com"}},{key:nf.EU,domain:"bitwarden.eu",urls:{base:null,api:"https://api.bitwarden.eu",identity:"https://identity.bitwarden.eu",icons:"https://icons.bitwarden.eu",webVault:"https://vault.bitwarden.eu",notifications:"https://notifications.bitwarden.eu",events:"https://events.bitwarden.eu",scim:"https://scim.bitwarden.eu"}}],DO=nf.US,OO=TO.find(e=>e.key===DO);class NO{constructor(e,t,i=[]){this.stateProvider=e,this.accountService=t,this.additionalRegionConfigs=i,this.activeAccountId$=this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id)),this.globalState=this.stateProvider.getGlobal(zO),this.globalCloudRegionState=this.stateProvider.getGlobal(AO);const r=this.activeAccountId$.pipe(Zl((e,t)=>e==t));this.globalEnvironment$=this.stateProvider.getGlobal(zO).state$.pipe(X(e=>this.buildEnvironment(null==e?void 0:e.region,null==e?void 0:e.urls))),this.environment$=r.pipe(Le(e=>e?this.stateProvider.getUser(e,PO).state$:this.stateProvider.getGlobal(zO).state$),X(e=>this.buildEnvironment(null==e?void 0:e.region,null==e?void 0:e.urls))),this.cloudWebVaultUrl$=r.pipe(Le(e=>e?this.stateProvider.getUser(e,jO).state$:this.stateProvider.getGlobal(AO).state$),X(e=>{if(null!=e){const t=this.getRegionConfig(e);if(null!=t)return t.urls.webVault}return OO.urls.webVault}))}availableRegions(){return TO.concat(this.additionalRegionConfigs)}getRegionConfig(e){return this.availableRegions().find(t=>t.key===e)}setEnvironment(e,t){return IO(this,void 0,void 0,function*(){return null==this.getRegionConfig(e)&&(e=nf.SelfHosted),e==nf.SelfHosted&&UO(t)&&(e=DO),e!=nf.SelfHosted?(yield this.globalState.update(()=>({region:e,urls:null})),null):(t.base=RO(t.base),t.webVault=RO(t.webVault),t.api=RO(t.api),t.identity=RO(t.identity),t.icons=RO(t.icons),t.notifications=RO(t.notifications),t.events=RO(t.events),t.keyConnector=RO(t.keyConnector),t.scim=null,yield this.globalState.update(()=>({region:e,urls:{base:t.base,api:t.api,identity:t.identity,webVault:t.webVault,icons:t.icons,notifications:t.notifications,events:t.events,keyConnector:t.keyConnector}})),t)})}buildEnvironment(e,t){if(null==this.getRegionConfig(e)&&(e=nf.SelfHosted),e==nf.SelfHosted&&UO(t)&&(e=DO),e!=nf.SelfHosted){const t=this.getRegionConfig(e);if(null!=t)return new qO(t)}return new LO(t)}setCloudRegion(e,t){return IO(this,void 0,void 0,function*(){null==e?yield this.globalCloudRegionState.update(()=>t):yield this.stateProvider.getUser(e,jO).update(()=>t)})}getEnvironment$(e){return this.stateProvider.getUser(e,PO).state$.pipe(X(e=>this.buildEnvironment(null==e?void 0:e.region,null==e?void 0:e.urls)))}getEnvironment(e){return IO(this,void 0,void 0,function*(){const t=null!=e?e:yield Ce(this.activeAccountId$);return Ce(this.getEnvironment$(t))})}seedUserEnvironment(e){return IO(this,void 0,void 0,function*(){const t=yield Ce(this.globalState.state$);yield this.stateProvider.getUser(e,PO).update(()=>t)})}}function RO(e){return null==e||""===e?null:((e=e.replace(/\/+$/g,"")).startsWith("http://")||e.startsWith("https://")||(e="https://"+e),e.trim())}function UO(e){return null==e||null==e.base&&null==e.webVault&&null==e.api&&null==e.identity&&null==e.icons&&null==e.notifications&&null==e.events}class FO{constructor(e,t){this.region=e,this.urls=t,e==nf.SelfHosted&&(this.urls.scim=null)}getRegion(){return this.region}getUrls(){return{base:this.urls.base,webVault:this.urls.webVault,api:this.urls.api,identity:this.urls.identity,icons:this.urls.icons,notifications:this.urls.notifications,events:this.urls.events,keyConnector:this.urls.keyConnector,scim:this.urls.scim}}hasBaseUrl(){return null!=this.urls.base}getWebVaultUrl(){return this.getUrl("webVault","")}getApiUrl(){return this.getUrl("api","/api")}getEventsUrl(){return this.getUrl("events","/events")}getIconsUrl(){return this.getUrl("icons","/icons")}getIdentityUrl(){return this.getUrl("identity","/identity")}getKeyConnectorUrl(){return this.urls.keyConnector}getNotificationsUrl(){return this.getUrl("notifications","/notifications")}getScimUrl(){return null!=this.urls.scim?this.urls.scim+"/v2":"https://vault.bitwarden.com"===this.getWebVaultUrl()?"https://scim.bitwarden.com/v2":this.getWebVaultUrl()+"/scim/v2"}getSendUrl(){return"https://vault.bitwarden.com"===this.getWebVaultUrl()?"https://send.bitwarden.com/#":this.getWebVaultUrl()+"/#/send/"}isCloud(){return this.region!==nf.SelfHosted}getUrl(e,t){return null!=this.urls[e]?this.urls[e]:this.urls.base?this.urls.base+t:OO.urls[e]}}class qO extends FO{constructor(e){super(e.key,e.urls),this.config=e}getHostname(){return this.config.domain}}class LO extends FO{constructor(e){super(nf.SelfHosted,e)}getHostname(){return Tt.getHost(this.getWebVaultUrl())}}var BO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class MO extends NO{constructor(e,t,i,r=[]){super(t,i,r),this.logService=e}hasManagedEnvironment(){return BO(this,void 0,void 0,function*(){try{return null!=(yield this.getManagedEnvironment())}catch(e){return this.logService.error(e),!1}})}settingsHaveChanged(){return BO(this,void 0,void 0,function*(){if(!(yield this.hasManagedEnvironment()))return!1;const e=yield this.getManagedEnvironment(),t=(yield Ce(this.environment$)).getUrls();return e.base!=t.base||e.webVault!=t.webVault||e.api!=t.api||e.identity!=t.identity||e.icons!=t.icons||e.notifications!=t.notifications||e.events!=t.events})}getManagedEnvironment(){return new Promise((e,t)=>{if(null==chrome.storage.managed)return e(null);chrome.storage.managed.get("environment",i=>{if(chrome.runtime.lastError)return t(chrome.runtime.lastError);e(i.environment)})})}setUrlsToManagedEnvironment(){return BO(this,void 0,void 0,function*(){const e=yield this.getManagedEnvironment();yield this.setEnvironment(nf.SelfHosted,{base:e.base,webVault:e.webVault,api:e.api,identity:e.identity,icons:e.icons,notifications:e.notifications,events:e.events})})}}const VO=new fi(sr,"extensionInstalled",{deserializer:e=>e});class $O{constructor(e){this.stateProvider=e,this.extensionInstalled=this.stateProvider.getGlobal(VO),this.extensionInstalled$=this.extensionInstalled.state$.pipe(X(e=>null!=e&&e))}setExtensionInstalled(e){return t=this,i=void 0,n=function*(){yield this.extensionInstalled.update(()=>e)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}}var KO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const WO="__json__";class HO{constructor(e){this.chromeStorageApi=e,this.updates$=xD(this.chromeStorageApi.onChanged).pipe(Ie(([e])=>1===Object.keys(e).length),de(([e])=>Object.entries(e).map(([e,t])=>({key:e,updateType:"newValue"in t?"save":"remove"}))))}get valuesRequireDeserialization(){return!0}get(e){return KO(this,void 0,void 0,function*(){return new Promise((t,i)=>{this.chromeStorageApi.get(e,r=>{if(chrome.runtime.lastError)return i(chrome.runtime.lastError);null==r||null==r[e]?t(null):t(this.processGetObject(r[e]))})})})}has(e){return KO(this,void 0,void 0,function*(){return null!=(yield this.get(e))})}save(e,t){return KO(this,void 0,void 0,function*(){if(null==(t=(e=>null==e?null:(e instanceof Set&&(e=Array.from(e)),{[WO]:!0,value:JSON.stringify(e)}))(t)))return this.remove(e);const i={[e]:t};return new Promise((e,t)=>{this.chromeStorageApi.set(i,()=>{if(chrome.runtime.lastError)return t(chrome.runtime.lastError);e()})})})}remove(e){return KO(this,void 0,void 0,function*(){return new Promise((t,i)=>{this.chromeStorageApi.remove(e,()=>{if(chrome.runtime.lastError)return i(chrome.runtime.lastError);t()})})})}processGetObject(e){return this.isSerialized(e)&&(e=JSON.parse(e.value)),e}isSerialized(e){const t=e;return null!=t&&t[WO]&&"string"==typeof t.value}}var GO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class QO extends HO{constructor(e){super(chrome.storage.local),this.logService=e}get(e){return GO(this,void 0,void 0,function*(){return yield this.getWithRetries(e,0)})}getKeys(){return GO(this,void 0,void 0,function*(){return"getKeys"in this.chromeStorageApi?this.chromeStorageApi.getKeys():[]})}getWithRetries(e,t){return GO(this,void 0,void 0,function*(){const i=yield this.getStore(e);if(null==i){if(t>=5)throw new Error(`Failed to get a value for key '${e}', see logs for more details.`);return t++,this.logService.warning(`Retrying attempt to get value for key '${e}' in 200ms`),yield new Promise(e=>setTimeout(e,200)),yield this.getWithRetries(e,t)}return this.processGetObject(i[e])})}getStore(e){return GO(this,void 0,void 0,function*(){return null==this.chromeStorageApi?(this.logService.warning(`chrome.storage.local was not initialized while retrieving key '${e}'.`),null):new Promise(t=>{this.chromeStorageApi.get(e,i=>chrome.runtime.lastError?(this.logService.warning(`Failed to get value for key '${e}'`,chrome.runtime.lastError),void t(null)):null==i?(this.logService.warning(`Store was empty while retrieving value for key '${e}'`),void t(null)):void t(i))})})}fillBuffer(){return GO(this,void 0,void 0,function*(){const e="0".repeat(1048576);yield new Promise((t,i)=>{this.chromeStorageApi.set({fake_data_1:e,fake_data_2:e,fake_data_3:e,fake_data_4:e},()=>{if(chrome.runtime.lastError)return i(chrome.runtime.lastError);t()})}),yield new Promise((e,t)=>{this.chromeStorageApi.remove(["fake_data_1","fake_data_2","fake_data_3","fake_data_4"],()=>{if(chrome.runtime.lastError)return t(chrome.runtime.lastError);e()})})})}}class JO extends HO{constructor(){super(chrome.storage.session)}}class YO{}class XO extends YO{constructor(e,t,i){super(),this.domainSettingsService=e,this.platformUtilsService=t,this.logService=i,this.blockedDomains=null}inject(e){return t=this,i=void 0,n=function*(){var t;const{tabId:i,injectDetails:r,mv3Details:n}=e,a=this.getScriptFile(e);if(!a)throw new Error("No file specified for script injection");const s=i&&(yield hT.getTab(i));let o=!0;const l=yield Ce(this.domainSettingsService.blockedInteractionsUris$);if(l&&(null==s?void 0:s.url)&&(o=!hg(null==s?void 0:s.url,l)),!o)return void this.logService.warning(`${r.file} was not injected because ${(null==s?void 0:s.url)||"the tab URL"} is on the user's blocked domains list.`);const c=this.buildInjectionDetails(r,a);if(hT.isManifestVersion(3))try{yield hT.executeScriptInTab(i,c,{world:null!==(t=null==n?void 0:n.world)&&void 0!==t?t:chrome.scripting.ExecutionWorld.ISOLATED})}catch(e){if("Cannot access contents of the page. Extension manifest must request permission to access the respective host."!==e.message)throw e;this.platformUtilsService.isDev()&&this.logService.warning(`BrowserApi.executeScriptInTab exception for ${r.file} in tab ${i}: ${e.message}`)}else yield hT.executeScriptInTab(i,c)},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n}getScriptFile(e){var t,i;const{injectDetails:r,mv2Details:n,mv3Details:a}=e;return hT.isManifestVersion(3)?null!==(t=null==a?void 0:a.file)&&void 0!==t?t:null==r?void 0:r.file:null!==(i=null==n?void 0:n.file)&&void 0!==i?i:null==r?void 0:r.file}buildInjectionDetails(e,t){const{frame:i,runAt:r}=e,n={file:t};return r&&(n.runAt=r),i?"all_frames"!==i?Object.assign(Object.assign({},n),{frameId:i}):Object.assign(Object.assign({},n),{allFrames:!0}):Object.assign(Object.assign({},n),{frameId:0})}}var ZO=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class eN{constructor(e,t,i){this.systemLanguage=e,this.localesDirectory=t,this.getLocalesJson=i,this.supportedTranslationLocales=["en"],this.defaultLocale="en",this.localeNames=new Map([["af","Afrikaans"],["ar","العربية الفصحى"],["az","Azərbaycanca"],["be","Беларуская"],["bg","български"],["bn","বাংলা"],["bs","bosanski jezik"],["ca","català"],["cs","čeština"],["cy","Cymraeg, y Gymraeg"],["da","dansk"],["de","Deutsch"],["el","Ελληνικά"],["en","English"],["en-GB","English (British)"],["en-IN","English (India)"],["eo","Esperanto"],["es","español"],["et","eesti"],["eu","euskara"],["fa","فارسی"],["fi","suomi"],["fil","Wikang Filipino"],["fr","français"],["gl","galego"],["he","עברית"],["hi","हिन्दी"],["hr","hrvatski"],["hu","magyar"],["id","Bahasa Indonesia"],["it","italiano"],["ja","日本語"],["ka","ქართული"],["km","ខ្មែរ, ខេមរភាសា, ភាសាខ្មែរ"],["kn","ಕನ್ನಡ"],["ko","한국어"],["lt","lietuvių kalba"],["lv","Latvietis"],["me","црногорски"],["ml","മലയാളം"],["mr","मराठी"],["my","ဗမာစကား"],["nb","norsk (bokmål)"],["ne","नेपाली"],["nl","Nederlands"],["nn","Norsk Nynorsk"],["or","ଓଡ଼ିଆ"],["pl","polski"],["pt-BR","português do Brasil"],["pt-PT","português"],["ro","română"],["ru","русский"],["si","සිංහල"],["sk","slovenčina"],["sl","Slovenski jezik, Slovenščina"],["sr","Српски"],["sv","svenska"],["ta","தமிழ்"],["te","తెలుగు"],["th","ไทย"],["tr","Türkçe"],["uk","українська"],["vi","Tiếng Việt"],["zh-CN","中文(中国大陆)"],["zh-TW","中文(台灣)"]]),this.defaultMessages={},this.localeMessages={},this.systemLanguage=e.replace("_","-")}init(e){return ZO(this,void 0,void 0,function*(){if(this.inited)throw new Error("i18n already initialized.");if(null==this.supportedTranslationLocales||0===this.supportedTranslationLocales.length)throw new Error("supportedTranslationLocales not set.");this.inited=!0,this.translationLocale=null!=e?e:this.systemLanguage;try{this.collator=new Intl.Collator(this.translationLocale,{numeric:!0,sensitivity:"base"})}catch(e){this.collator=null}-1===this.supportedTranslationLocales.indexOf(this.translationLocale)&&(this.translationLocale=this.translationLocale.slice(0,2),-1===this.supportedTranslationLocales.indexOf(this.translationLocale)&&(this.translationLocale=this.defaultLocale)),null!=this.localesDirectory&&(yield this.loadMessages(this.translationLocale,this.localeMessages),this.translationLocale!==this.defaultLocale&&(yield this.loadMessages(this.defaultLocale,this.defaultMessages)))})}t(e,t,i,r){return this.translate(e,t,i,r)}translate(e,t,i,r){let n;return n=this.localeMessages.hasOwnProperty(e)&&this.localeMessages[e]?this.localeMessages[e]:this.defaultMessages.hasOwnProperty(e)&&this.defaultMessages[e]?this.defaultMessages[e]:"",""!==n&&(null!=t&&(n=n.split("__$1__").join(t.toString())),null!=i&&(n=n.split("__$2__").join(i.toString())),null!=r&&(n=n.split("__$3__").join(r.toString()))),n}loadMessages(e,t){return ZO(this,void 0,void 0,function*(){const i=e.replace("-","_"),r=yield this.getLocalesJson(i);for(const e in r)if(r.hasOwnProperty(e)&&(t[e]=r[e].message,r[e].placeholders))for(const i in r[e].placeholders){if(!r[e].placeholders.hasOwnProperty(i)||!r[e].placeholders[i].content)continue;const n="\\$"+i.toUpperCase()+"\\$";let a=r[e].placeholders[i].content;"$1"!==a&&"$2"!==a&&"$3"!==a||(a="__$"+a+"__"),t[e]=t[e].replace(new RegExp(n,"g"),a)}})}}var tN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const iN=new fi(nr,"locale",{deserializer:e=>e});class rN extends eN{constructor(e,t,i,r){super(e,t,i),this.systemLanguage=e,this.localesDirectory=t,this.getLocalesJson=i,this.translationLocaleState=r.get(iN),this.userSetLocale$=this.translationLocaleState.state$,this.locale$=this.userSetLocale$.pipe(X(e=>null!=e?e:this.translationLocale))}setLocale(e){return tN(this,void 0,void 0,function*(){yield this.translationLocaleState.update(()=>e)})}init(){const e=Object.create(null,{init:{get:()=>super.init}});return tN(this,void 0,void 0,function*(){const t=yield Ce(this.translationLocaleState.state$);yield e.init.call(this,t)})}}class nN extends rN{constructor(e,t){super(e,null,e=>{return t=this,i=void 0,n=function*(){const t=yield fetch(this.localesDirectory+e+"/messages.json");return yield t.json()},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n},t),this.supportedTranslationLocales=["en","ar","az","be","bg","bn","bs","ca","cs","cy","da","de","el","en-GB","en-IN","es","et","eu","fa","fi","fil","fr","gl","he","hi","hr","hu","id","it","ja","ka","km","kn","ko","lt","lv","ml","mr","my","nb","ne","nl","nn","or","pl","pt-BR","pt-PT","ro","ru","si","sk","sl","sr","sv","ta","te","th","tr","uk","vi","zh-CN","zh-TW"]}t(e,t,i,r){return this.translate(e,t,i,r)}translate(e,t,i,r){if(null==this.localesDirectory){const n=[];return null!=t&&n.push(t),null!=i&&n.push(i),null!=r&&n.push(r),n.length?chrome.i18n.getMessage(e,n):chrome.i18n.getMessage(e)}return super.translate(e,t,i,r)}}function aN(e){switch(e){case chrome.storage.local:return"local";case chrome.storage.sync:return"sync";case chrome.storage.session:return"session";default:throw new Error("Unknown storage location")}}var sN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const oN="session_";class lN{constructor(e,t){this.storageService=e,this.keyGenerationService=t}get(){return sN(this,void 0,void 0,function*(){const e=yield this.storageService.get("session-key");return e?this.storageService.valuesRequireDeserialization?gu.fromJSON(e):e:null})}create(){return sN(this,void 0,void 0,function*(){const{derivedKey:e}=yield this.keyGenerationService.createKeyWithPurpose(128,"ephemeral","bitwarden-ephemeral");return yield this.storageService.save("session-key",e.toJSON()),e})}}class cN extends ut{constructor(e,t,i,r,n,a){super(),this.memoryStorage=e,this.localStorage=t,this.keyGenerationService=i,this.encryptService=r,this.platformUtilsService=n,this.logService=a,this.valuesRequireDeserialization=!0,this.ports=new Set([]),this.cache={},this.updatesSubject=new H,this.updates$=this.updatesSubject.asObservable(),this.sessionKeyResolveService=new lN(this.memoryStorage,this.keyGenerationService),hT.addListener(chrome.runtime.onConnect,e=>{if(e.name!==aN(chrome.storage.session))return;if(!hT.senderIsInternal(e.sender,this.logService))return;this.ports.add(e);const t=this.onMessageFromForeground.bind(this);e.onDisconnect.addListener(()=>{this.ports.delete(e),e.onMessage.removeListener(t)}),e.onMessage.addListener(t),this.sendMessageTo(e,{action:"initialization",data:Array.from(Object.keys(this.cache))}),this.updates$.subscribe(e=>{this.broadcastMessage({action:"subject_update",data:e})})})}get(e,t){return sN(this,void 0,void 0,function*(){if(null!=this.cache[e])return this.cache[e];const t=yield this.getLocalSessionValue(yield this.getSessionKey(),e);return null==this.cache[e]&&null!=t?(this.cache[e]=t,t):null==this.cache[e]&&null==t?t:null!=this.cache[e]&&null!=t?(this.logService.warning(`Conflict while reading from local session storage, both cache and storage have values. Key: ${e}. Using cached value.`),this.cache[e]):null!=this.cache[e]&&null==t?(this.logService.warning(`Conflict while reading from local session storage, cache has value but storage does not. Key: ${e}. Using cached value.`),this.cache[e]):void 0})}has(e){return sN(this,void 0,void 0,function*(){return null!=(yield this.get(e))})}save(e,t){return sN(this,void 0,void 0,function*(){if(this.platformUtilsService.isDev()){const i=this.cache[e];try{this.compareValues(i,t)&&this.logService.warning(`Possible unnecessary write to local session storage. Key: ${e}`)}catch(t){this.logService.warning(`Error while comparing values for key: ${e}`),this.logService.warning(t)}}if(null==t)return yield this.remove(e);this.cache[e]=t,yield this.updateLocalSessionValue(e,t),this.updatesSubject.next({key:e,updateType:"save"})})}remove(e){return sN(this,void 0,void 0,function*(){this.cache[e]=null,yield this.updateLocalSessionValue(e,null),this.updatesSubject.next({key:e,updateType:"remove"})})}broadcastMessage(e){this.ports.forEach(t=>{this.sendMessageTo(t,e)})}getSessionKey(){return sN(this,void 0,void 0,function*(){const e=yield this.sessionKeyResolveService.get();return null!=e?e:(yield this.clear(),yield this.sessionKeyResolveService.create())})}clear(){return sN(this,void 0,void 0,function*(){const e=(yield this.localStorage.getKeys()).filter(e=>e.startsWith(oN));this.logService.debug(`[LocalBackedSessionStorageService] Clearing local session storage. Found ${e}`);for(const t of e){const e=t.substring(8);yield this.remove(e)}})}getLocalSessionValue(e,t){return sN(this,void 0,void 0,function*(){const i=yield this.localStorage.get(this.sessionStorageKey(t));if(null==i)return null;try{const t=yield this.encryptService.decryptString(new Nt(i),e);return JSON.parse(t)}catch(e){return yield this.localStorage.remove(this.sessionStorageKey(t)),null}})}updateLocalSessionValue(e,t){return sN(this,void 0,void 0,function*(){if(null==t)return void(yield this.localStorage.remove(this.sessionStorageKey(e)));const i=JSON.stringify(t),r=yield this.encryptService.encryptString(i,yield this.getSessionKey());yield this.localStorage.save(this.sessionStorageKey(e),r.encryptedString)})}onMessageFromForeground(e,t){return sN(this,void 0,void 0,function*(){var i;if("background"===e.originator)return;let r=null;switch(e.action){case"get":case"has":r=yield this[e.action](e.key);break;case"save":yield this.save(e.key,JSON.parse(null!==(i=e.data)&&void 0!==i?i:null));break;case"remove":yield this.remove(e.key)}this.sendMessageTo(t,{id:e.id,key:e.key,data:JSON.stringify(r)})})}sendMessageTo(e,t){e.postMessage(Object.assign(Object.assign({},t),{originator:"background"}))}sessionStorageKey(e){return`${oN}${e}`}compareValues(e,t){try{return ok(e,t)}catch(i){return this.logService.error(`error comparing values\n${JSON.stringify(e)}\n${JSON.stringify(t)}`),!0}}}class uN extends oT{constructor(e,t,i,r){super(t,i,r),this.messagingService=e}showToast(e,t,i,r){this.messagingService.send("showToast",{text:i,title:t,type:e,options:r})}}var dN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const hN=fi.record(tr,"popup-view-cache",{deserializer:e=>e}),pN=new fi(tr,"popup-route-history-details",{deserializer:e=>e}),mN=new Wf("save-view-cache"),gN=new Wf("clear-view-cache");class fN{constructor(e,t,i){this.messageListener=e,this.globalStateProvider=t,this.taskSchedulerService=i,this.popupViewCacheState=this.globalStateProvider.get(hN),this.popupRouteHistoryState=this.globalStateProvider.get(pN),this.taskSchedulerService.registerTaskHandler(ju,()=>dN(this,void 0,void 0,function*(){yield this.clearState()}))}startObservingMessages(){this.messageListener.messages$(mN).pipe(gc(e=>dN(this,[e],void 0,function*({key:e,value:t,options:i}){return this.popupViewCacheState.update(r=>Object.assign(Object.assign({},r),{[e]:{value:t,options:i}}))}))).subscribe(),this.messageListener.messages$(gN).pipe(gc(({routeChange:e})=>this.popupViewCacheState.update(t=>e&&t?Object.fromEntries(Object.entries(t).filter(([,{options:e}])=>null==e?void 0:e.persistNavigation)):null))).subscribe(),xD(chrome.runtime.onConnect).pipe(Ie(([e])=>"new_popup"===e.name&&hT.senderIsInternal(e.sender)),Le(([e])=>{return xD(e.onDisconnect).pipe(jD(12e4,(t=this.taskSchedulerService,new _u(t,ju))));var t})).subscribe(),xD(chrome.tabs.onActivated).pipe(Le(e=>hT.getTab(e[0].tabId)),Le(e=>"about:blank"!==e.url?bt(e):xD(chrome.tabs.onUpdated).pipe(v_(),Le(([e])=>hT.getTab(e)))),X(e=>e.url||e.pendingUrl),Ie(e=>!(null==e?void 0:e.startsWith(chrome.runtime.getURL("")))),Le(()=>this.popupViewCacheState.update(e=>e?Object.fromEntries(Object.entries(e).filter(([,{options:e}])=>!(null==e?void 0:e.clearOnTabChange))):null))).subscribe()}clearState(){return dN(this,void 0,void 0,function*(){return Promise.all([this.popupViewCacheState.update(()=>({}),{shouldUpdate:this.objNotEmpty}),this.popupRouteHistoryState.update(()=>[],{shouldUpdate:this.objNotEmpty})])})}objNotEmpty(e){return 0!==Object.keys(null!=e?e:{}).length}}class yN{constructor(e){this.globalStateProvider=e,this.popupRouteHistoryState=this.globalStateProvider.get(pN)}init(){xD(chrome.tabs.onActivated).pipe(Le(e=>hT.getTab(e[0].tabId)),Le(e=>"about:blank"!==e.url?bt(e):xD(chrome.tabs.onUpdated).pipe(v_(),Le(([e])=>hT.getTab(e)))),X(e=>e.url||e.pendingUrl),Ie(e=>!(null==e?void 0:e.startsWith(chrome.runtime.getURL("")))),Le(()=>this.popupRouteHistoryState.update(e=>{var t;if(!e||0===e.length)return e;const i=e.at(-1);return i&&(null===(t=i.options)||void 0===t?void 0:t.resetRouterCacheOnTabChange)?[]:e}))).subscribe()}}var vN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const bN=(()=>{try{if("object"==typeof WebAssembly&&"function"==typeof WebAssembly.instantiate){const e=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(e instanceof WebAssembly.Module)return new WebAssembly.Instance(e)instanceof WebAssembly.Instance}}catch(e){}return!1})();let wN;hT.isManifestVersion(3)&&(bN?(console.info("WebAssembly is supported in this environment"),wN=o.e(719).then(o.bind(o,719))):wN=new Promise((e,t)=>{t(new Error("WebAssembly is not supported in this environment"))}));class kN extends xg{constructor(e){super(),this.logService=e}load(){return vN(this,void 0,void 0,function*(){const e=performance.now();yield function(){return vN(this,void 0,void 0,function*(){if(hT.isManifestVersion(3))yield wN;else{if(!bN)throw new Error("WebAssembly is not supported in this environment");console.info("WebAssembly is supported in this environment"),yield o.e(719).then(o.bind(o,719))}return globalThis.initSdk})}().then(e=>e());const t=performance.now();this.logService.info(`WASM SDK loaded in ${Math.round(t-e)}ms`)})}}const SN="browser-task-scheduler-port";var _N=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const xN=new fi(ar,"activeAlarms",{deserializer:e=>null!=e?e:[]});class CN extends Cu{constructor(e,t){super(e),this.stateProvider=t,this.handleOnAlarm=e=>_N(this,void 0,void 0,function*(){const{name:t,periodInMinutes:i}=e;yield this.triggerTask(t,i)}),this.activeAlarmsState=this.stateProvider.getGlobal(xN),this.activeAlarms$=this.activeAlarmsState.state$.pipe(X(e=>null!=e?e:[])),this.setupOnAlarmListener()}setTimeout(e,t){let i;this.validateRegisteredTask(e);const r=t/1e3/60;return this.scheduleAlarm(e,{delayInMinutes:this.getUpperBoundDelayInMinutes(r)}).catch(e=>this.logService.error("Failed to schedule alarm",e)),r_N(this,void 0,void 0,function*(){yield this.clearScheduledAlarm(e),yield this.triggerTask(e)}),t)),new f(()=>{i&&globalThis.clearTimeout(i),this.clearScheduledAlarm(e).catch(e=>this.logService.error("Failed to clear alarm",e))})}setInterval(e,t,i){this.validateRegisteredTask(e);const r=t/1e3/60,n=i?i/1e3/60:r;return rthis.logService.error("Failed to schedule alarm",e)),new f(()=>this.clearScheduledAlarm(e).catch(e=>this.logService.error("Failed to clear alarm",e))))}setupSteppedIntervalAlarms(e,t){const i=this.getAlarmMinDelayInMinutes(),r=t/1e3/60,n=Math.ceil(Math.ceil(1/r)/2)+1,a=i+r,s=[];for(let t=0;tthis.scheduleAlarm(n,{periodInMinutes:a,delayInMinutes:o}).catch(e=>this.logService.error("Failed to schedule alarm",e))).catch(e=>this.logService.error("Failed to clear alarm",e))}let o=0;const l=globalThis.setInterval(()=>_N(this,void 0,void 0,function*(){o+=t,o/1e3/60>=i?globalThis.clearInterval(l):yield this.triggerTask(e,r)}),t);return new f(()=>{l&&globalThis.clearInterval(l),s.forEach(e=>this.clearScheduledAlarm(e).catch(e=>this.logService.error("Failed to clear alarm",e)))})}clearAllScheduledTasks(){return _N(this,void 0,void 0,function*(){yield this.clearAllAlarms(),yield this.updateActiveAlarms([])})}verifyAlarmsState(){return _N(this,void 0,void 0,function*(){const e=Date.now(),t=yield this.getActiveAlarms();for(const i of t){const{alarmName:t,startTime:r,createInfo:n}=i;if(yield this.getAlarm(t))continue;const a=n.when&&n.whenthis.logService.error("Failed to schedule alarm",e))}})}scheduleAlarm(e,t){return _N(this,void 0,void 0,function*(){(yield this.getAlarm(e))?this.logService.debug(`Alarm ${e} already exists. Skipping creation.`):(yield this.createAlarm(e,t),yield this.setActiveAlarm(e,t))})}getActiveAlarms(){return _N(this,void 0,void 0,function*(){return yield Ce(this.activeAlarms$)})}setActiveAlarm(e,t){return _N(this,void 0,void 0,function*(){const i=(yield this.getActiveAlarms()).filter(t=>t.alarmName!==e);i.push({alarmName:e,startTime:Date.now(),createInfo:t}),yield this.updateActiveAlarms(i)})}deleteActiveAlarm(e){return _N(this,void 0,void 0,function*(){const t=(yield this.getActiveAlarms()).filter(t=>t.alarmName!==e);yield this.updateActiveAlarms(t||[])})}clearScheduledAlarm(e){return _N(this,void 0,void 0,function*(){(yield this.clearAlarm(e))&&(yield this.deleteActiveAlarm(e))})}updateActiveAlarms(e){return _N(this,void 0,void 0,function*(){yield this.activeAlarmsState.update(()=>e)})}setupOnAlarmListener(){hT.addListener(chrome.alarms.onAlarm,this.handleOnAlarm)}triggerTask(e,t){return _N(this,void 0,void 0,function*(){const i=this.getTaskFromAlarmName(e),r=this.taskHandlers.get(i);t||(yield this.deleteActiveAlarm(e)),r&&r()})}getTaskFromAlarmName(e){return e.split("__")[0]}clearAlarm(e){return _N(this,void 0,void 0,function*(){return this.isNonChromeEnvironment()?browser.alarms.clear(e):new Promise(t=>chrome.alarms.clear(e,t))})}clearAllAlarms(){return this.isNonChromeEnvironment()?browser.alarms.clearAll():new Promise(e=>chrome.alarms.clearAll(e))}createAlarm(e,t){return _N(this,void 0,void 0,function*(){return this.isNonChromeEnvironment()?browser.alarms.create(e,t):new Promise(i=>chrome.alarms.create(e,t,i))})}getAlarm(e){return this.isNonChromeEnvironment()?browser.alarms.get(e):new Promise(t=>chrome.alarms.get(e,t))}isNonChromeEnvironment(){return"undefined"!=typeof browser&&!!browser.alarms}getAlarmMinDelayInMinutes(){return this.isNonChromeEnvironment()?1:.5}getUpperBoundDelayInMinutes(e){return Math.max(this.getAlarmMinDelayInMinutes(),e)}}class IN extends CN{constructor(e,t){super(e,t),this.ports=new Set,this.handlePortOnConnect=e=>{e.name===SN&&hT.senderIsInternal(e.sender,this.logService)&&(this.ports.add(e),e.onMessage.addListener(this.handlePortMessage),e.onDisconnect.addListener(this.handlePortOnDisconnect))},this.handlePortOnDisconnect=e=>{e.onMessage.removeListener(this.handlePortMessage),e.onDisconnect.removeListener(this.handlePortOnDisconnect),this.ports.delete(e)},this.handlePortMessage=(e,t)=>{const i=t.name===SN,{action:r,taskName:n,alarmName:a,delayInMs:s,intervalInMs:o}=e;i&&"setTimeout"===r?super.setTimeout(n,s):i&&"setInterval"===r?super.setInterval(n,o):i&&"clearAlarm"===r&&super.clearScheduledAlarm(a).catch(e=>this.logService.error(e))},hT.addListener(chrome.runtime.onConnect,this.handlePortOnConnect)}}class EN extends mt{constructor(e){super(),this.logService=e,this._ports=[],hT.addListener(chrome.runtime.onConnect,e=>{if(e.name!==aN(chrome.storage.session))return;if(!hT.senderIsInternal(e.sender,this.logService))return;this._ports.push(e);const t=this.onMessageFromForeground.bind(this);e.onDisconnect.addListener(()=>{this._ports.splice(this._ports.indexOf(e),1),e.onMessage.removeListener(t)}),e.onMessage.addListener(t),this.sendMessageTo(e,{action:"initialization",data:Array.from(Object.keys(this.store))})}),this.updates$.subscribe(e=>{this.broadcastMessage({action:"subject_update",data:e})})}onMessageFromForeground(e,t){return i=this,r=void 0,a=function*(){var i;if("background"===e.originator)return;let r=null;switch(e.action){case"get":case"has":r=yield this[e.action](e.key);break;case"save":yield this.save(e.key,JSON.parse(null!==(i=e.data)&&void 0!==i?i:null));break;case"remove":yield this.remove(e.key)}this.sendMessageTo(t,{id:e.id,key:e.key,data:JSON.stringify(r)})},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a}broadcastMessage(e){this._ports.forEach(t=>{this.sendMessageTo(t,e)})}sendMessageTo(e,t){e.postMessage(Object.assign(Object.assign({},t),{originator:"background"}))}}class zN extends gt{constructor(e,t,i,r){super(e,t),this.largeObjectMemoryStorageService=i,this.diskBackupLocalStorage=r}get(e,t){var i;const r=null!==(i=t.browser)&&void 0!==i?i:e;switch(r){case"memory-large-object":return["memory-large-object",this.largeObjectMemoryStorageService];case"disk-backup-local-storage":return["disk-backup-local-storage",this.diskBackupLocalStorage];default:return super.get(r,t)}}}var PN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class AN{constructor(e){this.offscreenDocumentService=e}get valuesRequireDeserialization(){return!0}get(e,t){return PN(this,void 0,void 0,function*(){return yield this.offscreenDocumentService.withDocument([chrome.offscreen.Reason.LOCAL_STORAGE],"backup storage of user data",()=>PN(this,void 0,void 0,function*(){const t=yield hT.sendMessageWithResponse("localStorageGet",{key:e});return null!=t?JSON.parse(t):t}))})}has(e,t){return PN(this,void 0,void 0,function*(){return null!=(yield this.get(e,t))})}save(e,t,i){return PN(this,void 0,void 0,function*(){yield this.offscreenDocumentService.withDocument([chrome.offscreen.Reason.LOCAL_STORAGE],"backup storage of user data",()=>PN(this,void 0,void 0,function*(){return yield hT.sendMessageWithResponse("localStorageSave",{key:e,value:JSON.stringify(t)})}))})}remove(e,t){return PN(this,void 0,void 0,function*(){yield this.offscreenDocumentService.withDocument([chrome.offscreen.Reason.LOCAL_STORAGE],"backup storage of user data",()=>PN(this,void 0,void 0,function*(){return yield hT.sendMessageWithResponse("localStorageRemove",{key:e})}))})}}const jN=new Wf("doFullSync");var TN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const DN=new Wf("fullSyncFinished");class ON{constructor(e,t,i,r){this.syncService=e,this.messageListener=t,this.messageSender=i,this.logService=r}listener$(){return this.messageListener.messages$(jN).pipe(Ie(e=>Gf(e)),gc(e=>TN(this,[e],void 0,function*({forceSync:e,options:t,requestId:i}){yield this.doFullSync(e,t,i)})))}doFullSync(e,t,i){return TN(this,void 0,void 0,function*(){var r;try{const r=yield this.syncService.fullSync(e,t);this.messageSender.send(DN,{successfully:r,errorMessage:null,requestId:i})}catch(e){this.logService.warning("Error while doing full sync in SyncServiceListener",e),this.messageSender.send(DN,{successfully:!1,errorMessage:null!==(r=null==e?void 0:e.message)&&void 0!==r?r:"Unknown Sync Error",requestId:i})}})}}var NN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class RN{constructor(e){this.platformUtilsService=e,this.notificationClicked$=_e(xD(chrome.notifications.onButtonClicked).pipe(X(([e,t])=>({id:e,buttonIdentifier:t}))),xD(chrome.notifications.onClicked).pipe(X(([e])=>({id:e,buttonIdentifier:Hj.NotificationButton}))))}create(e){return NN(this,void 0,void 0,function*(){return new Promise(t=>{const i=this.platformUtilsService.getDevice(),r={iconUrl:chrome.runtime.getURL("images/icon128.png"),message:e.body,type:"basic",title:e.title,buttons:e.buttons.map(e=>({title:e.title}))};i===Rd.FirefoxExtension&&delete r.buttons,null!=e.id?chrome.notifications.create(e.id,r,e=>t(e)):chrome.notifications.create(r,e=>t(e))})})}clear(e){return NN(this,void 0,void 0,function*(){yield chrome.notifications.clear(e.id)})}isSupported(){return"notifications"in chrome}}class UN{constructor(e,t,i,r){this.badgeService=e,this.accountService=t,this.cipherService=i,this.taskService=r,this.activeUserData$=this.accountService.activeAccount$.pipe(Hx(),Le(e=>ai([bt(e.id),this.taskService.pendingTasks$(e.id).pipe(X(e=>e.filter(e=>0===e.type))),this.cipherService.cipherViews$(e.id).pipe(Hx())])))}init(){this.badgeService.setState("at-risk-cipher-badge",e=>this.activeUserData$.pipe(gc(t=>{return i=this,r=[t],a=function*([t,i]){const r=e.url?yield this.cipherService.getAllDecryptedForUrl(e.url,t,[],void 0,!0):[];if(i.some(e=>r.some(t=>t.id===e.cipherId&&!t.isDeleted)))return{priority:200,state:{icon:Jj.Berry,text:Yj,backgroundColor:Yj}}},new((n=void 0)||(n=Promise))(function(e,t){function s(e){try{l(a.next(e))}catch(e){t(e)}}function o(e){try{l(a.throw(e))}catch(e){t(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof n?i:new n(function(e){e(i)})).then(s,o)}l((a=a.apply(i,r||[])).next())});var i,r,n,a})))}}var FN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class qN{constructor(e,t,i,r,n,a){this.main=e,this.platformUtilsService=t,this.authService=i,this.generatePasswordToClipboard=r,this.accountService=n,this.lockService=a,this.isSafari=this.platformUtilsService.isSafari(),this.isVivaldi=this.platformUtilsService.isVivaldi()}init(){hT.messageListener("commands.background",e=>{"unlockCompleted"===e.command&&"commands.background"===e.data.target&&this.processCommand(e.data.commandToRetry.message.command,e.data.commandToRetry.sender).catch(e=>this.main.logService.error(e))}),chrome&&chrome.commands&&chrome.commands.onCommand.addListener(e=>FN(this,void 0,void 0,function*(){yield this.processCommand(e)}))}processCommand(e,t){return FN(this,void 0,void 0,function*(){switch(e){case"generate_password":yield this.generatePasswordToClipboard();break;case Um:yield this.triggerAutofillCommand(t?t.tab:null,Om);break;case Nm:yield this.triggerAutofillCommand(t?t.tab:null,Nm);break;case Rm:yield this.triggerAutofillCommand(t?t.tab:null,Rm);break;case"open_popup":yield this.openPopup();break;case"lock_vault":{const e=yield Ce(tu(this.accountService.activeAccount$));yield this.lockService.lock(e);break}}})}triggerAutofillCommand(e,t){return FN(this,void 0,void 0,function*(){if(e||(e=yield hT.getTabFromCurrentWindowId()),null!=e&&t){if((yield this.authService.getAuthStatus()){"active"===e?this.serverNotificationsService.reconnectFromActivity():this.serverNotificationsService.disconnectFromInactivity()};this.idle.onStateChanged&&this.idle.setDetectionInterval?(this.idle.setDetectionInterval(300),this.idle.onStateChanged.addListener(e)):this.pollIdle(e),this.idle.onStateChanged&&this.idle.onStateChanged.addListener(e=>{return t=this,i=void 0,n=function*(){if("locked"===e){const e=yield Ce(this.accountService.accounts$);for(const t in e)(yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutByUserId$(t)))===ud&&((yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutActionByUserId$(t)))===od.LogOut?yield this.logoutService.logout(t,"vaultTimeout"):yield this.lockService.lock(t))}},new((r=void 0)||(r=Promise))(function(e,a){function s(e){try{l(n.next(e))}catch(e){a(e)}}function o(e){try{l(n.throw(e))}catch(e){a(e)}}function l(t){var i;t.done?e(t.value):(i=t.value,i instanceof r?i:new r(function(e){e(i)})).then(s,o)}l((n=n.apply(t,i||[])).next())});var t,i,r,n})}pollIdle(e){var t;null!=this.idleTimer&&(globalThis.clearTimeout(this.idleTimer),this.idleTimer=null),null===(t=this.idle)||void 0===t||t.queryState(300,t=>{t!==this.idleState&&(this.idleState=t,e(t)),this.idleTimer=globalThis.setTimeout(()=>this.pollIdle(e),5e3)})}}var BN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class MN{constructor(e,t,i,r,n,a,s,o,l,c,u){var d;this.keyService=e,this.encryptService=t,this.cryptoFunctionService=i,this.runtimeBackground=r,this.messagingService=n,this.appIdService=a,this.platformUtilsService=s,this.logService=o,this.authService=l,this.biometricStateService=c,this.accountService=u,this.connected=!1,this.connecting=!1,this.messageId=0,this.callbacks=new Map,(null===(d=null===chrome||void 0===chrome?void 0:chrome.permissions)||void 0===d?void 0:d.onAdded)&&chrome.permissions.onAdded.addListener(e=>{var t;(null===(t=e.permissions)||void 0===t?void 0:t.includes("nativeMessaging"))&&hT.reloadExtension()})}connect(){return BN(this,void 0,void 0,function*(){if(!(yield hT.permissionsGranted(["nativeMessaging"])))return void this.logService.warning("[Native Messaging IPC] Native messaging permission is missing for biometrics");if(this.connected||this.connecting)return;this.logService.info("[Native Messaging IPC] Connecting to Bitwarden Desktop app...");const e=yield this.appIdService.getAppId();return this.appId=e,yield this.biometricStateService.setFingerprintValidated(!1),new Promise((t,i)=>{const r=hT.connectNative("com.8bit.bitwarden");this.port=r,this.connecting=!0;const n=()=>{this.platformUtilsService.isSafari()?this.logService.info("[Native Messaging IPC] Connection to Safari swift module established!"):this.logService.info("[Native Messaging IPC] Connection to Bitwarden Desktop app established!"),this.connected=!0,this.connecting=!1,t()};this.platformUtilsService.isSafari()&&n(),r.onMessage.addListener(t=>BN(this,void 0,void 0,function*(){var a,s;const o=t;switch(o.command){case"connected":n();break;case"disconnected":this.logService.info("[Native Messaging IPC] Disconnected from Bitwarden Desktop app."),this.connecting&&i(new Error("startDesktop")),this.connected=!1,r.disconnect();for(const e of this.callbacks.values())e.rejecter("disconnected");this.callbacks.clear();break;case"setupEncryption":{if(o.appId!==e)return;if(null==o.sharedSecret)return void this.logService.info("[Native Messaging IPC] Unable to create secureChannel channel, no shared secret");if(null==this.secureChannel)return void this.logService.info("[Native Messaging IPC] Unable to create secureChannel channel, no secureChannel communication setup");const t=Tt.fromB64ToArray(o.sharedSecret),i=yield this.cryptoFunctionService.rsaDecrypt(t,this.secureChannel.privateKey,"sha1");this.secureChannel.sharedSecret=new gu(i),this.logService.info("[Native Messaging IPC] Secure channel established"),this.secureChannel.setupResolve();break}case"invalidateEncryption":if(o.appId!==e)return;return this.logService.warning("[Native Messaging IPC] Secure channel encountered an error; disconnecting and wiping keys..."),this.secureChannel=void 0,this.connected=!1,void(null!=o.messageId&&this.callbacks.has(o.messageId)&&(null===(a=this.callbacks.get(o.messageId))||void 0===a||a.rejecter({message:"invalidateEncryption"})));case"verifyFingerprint":this.logService.info("[Native Messaging IPC] Legacy app is requesting fingerprint"),this.messagingService.send("showUpdateDesktopAppOrDisableFingerprintDialog",{});break;case"verifyDesktopIPCFingerprint":this.logService.info("[Native Messaging IPC] Desktop app requested trust verification by fingerprint."),yield this.showFingerprintDialog();break;case"verifiedDesktopIPCFingerprint":yield this.biometricStateService.setFingerprintValidated(!0),this.messagingService.send("hideNativeMessagingFingerprintDialog",{});break;case"rejectedDesktopIPCFingerprint":this.messagingService.send("hideNativeMessagingFingerprintDialog",{});break;case"wrongUserId":return void(null!=o.messageId&&this.callbacks.has(o.messageId)&&(null===(s=this.callbacks.get(o.messageId))||void 0===s||s.rejecter({message:"wrongUserId"})));default:if(!this.platformUtilsService.isSafari()&&o.appId!==e)return;null!=o.message&&this.onMessage(o.message)}})),this.port.onDisconnect.addListener(e=>{var t;let r;r=hT.isWebExtensionsApi?e.error.message:null===(t=chrome.runtime.lastError)||void 0===t?void 0:t.message,this.secureChannel=void 0,this.connected=!1,this.logService.error("NativeMessaging port disconnected because of error: "+r),i(new Error(null!=r?"desktopIntegrationDisabled":void 0))})})})}callCommand(e){return BN(this,void 0,void 0,function*(){const t=this.messageId++,i=new Promise((e,i)=>{this.callbacks.set(t,{resolver:e,rejecter:i})});e.messageId=t;try{yield this.send(e)}catch(i){this.logService.info(`[Native Messaging IPC] Error sending message of type ${e.command} to Bitwarden Desktop app. Error: ${i}`);const r=this.callbacks.get(t);this.callbacks.delete(t),null==r||r.rejecter("errorConnecting")}return setTimeout(()=>{this.callbacks.has(t)&&(this.logService.info("[Native Messaging IPC] Message timed out and received no response"),this.callbacks.get(t).rejecter({message:"timeout"}),this.callbacks.delete(t))},6e4),i})}send(e){return BN(this,void 0,void 0,function*(){var t;this.connected||(yield this.connect()),e.userId=null===(t=yield Ce(this.accountService.activeAccount$))||void 0===t?void 0:t.id,e.timestamp=Date.now(),this.platformUtilsService.isSafari()?this.postMessage(e):this.postMessage({appId:this.appId,message:yield this.encryptMessage(e)})})}encryptMessage(e){return BN(this,void 0,void 0,function*(){var t;return null==(null===(t=this.secureChannel)||void 0===t?void 0:t.sharedSecret)&&(yield this.secureCommunication()),yield this.encryptService.encryptString(JSON.stringify(e),this.secureChannel.sharedSecret)})}postMessage(e,t){try{const t=e;e.message instanceof Nt&&(t.message={encryptedString:e.message.encryptedString,encryptionType:e.message.encryptionType,data:e.message.data,iv:e.message.iv,mac:e.message.mac}),this.port.postMessage(t)}catch(e){this.logService.info("[Native Messaging IPC] Disconnected from Bitwarden Desktop app because of the native port disconnecting."),this.secureChannel=void 0,this.connected=!1,null!=t&&this.callbacks.has(t)&&this.callbacks.get(t).rejecter("invalidateEncryption")}}onMessage(e){return BN(this,void 0,void 0,function*(){var t;let i;if(this.platformUtilsService.isSafari())i=e;else{if(null==(null===(t=this.secureChannel)||void 0===t?void 0:t.sharedSecret))return;i=JSON.parse(yield this.encryptService.decryptString(e,this.secureChannel.sharedSecret))}if(Math.abs(i.timestamp-Date.now())>1e4)return void this.logService.info("[Native Messaging IPC] Received an old native message, ignoring...");const r=i.messageId;if(this.callbacks.has(r)){const e=this.callbacks.get(r);this.callbacks.delete(r),e.resolver(i)}else this.logService.info("[Native Messaging IPC] Received message without a callback",i)})}secureCommunication(){return BN(this,void 0,void 0,function*(){var e;const[t,i]=yield this.cryptoFunctionService.rsaGenerateKeyPair(2048),r=null===(e=yield Ce(this.accountService.activeAccount$))||void 0===e?void 0:e.id;return this.sendUnencrypted({command:"setupEncryption",publicKey:Tt.fromBufferToB64(t),userId:r,messageId:this.messageId++}),new Promise(e=>{this.secureChannel={publicKey:t,privateKey:i,setupResolve:e}})})}sendUnencrypted(e){return BN(this,void 0,void 0,function*(){this.connected||(yield this.connect()),e.timestamp=Date.now(),this.postMessage({appId:this.appId,message:e})})}showFingerprintDialog(){return BN(this,void 0,void 0,function*(){var e;if(null==(null===(e=this.secureChannel)||void 0===e?void 0:e.publicKey))return;const t=yield this.keyService.getFingerprint(this.appId,this.secureChannel.publicKey);this.messagingService.send("showNativeMessagingFingerprintDialog",{fingerprint:t})})}}var VN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};class $N{constructor(e,t,i,r,n,a,s,o,l,c,u,d,h,p){this.main=e,this.autofillService=t,this.platformUtilsService=i,this.autofillSettingsService=r,this.processReloadService=n,this.environmentService=a,this.messagingService=s,this.logService=o,this.configService=l,this.messageListener=c,this.accountService=u,this.lockService=d,this.billingAccountProfileStateService=h,this.browserInitialInstallService=p,this.pageDetailsToAutoFill=[],this.onInstalledReason=null,this.lockedVaultPendingNotifications=[],chrome.runtime.onInstalled.addListener(e=>{this.onInstalledReason=e.reason})}init(){return VN(this,void 0,void 0,function*(){chrome.runtime&&(yield this.checkOnInstalled(),this.messageListener.allMessages$.pipe(de(e=>VN(this,void 0,void 0,function*(){try{yield this.processMessage(e)}catch(e){this.logService.error(e)}}))).subscribe(),hT.messageListener("runtime.background",(e,t,i)=>[Lu.AuthenticateWithBiometrics,Lu.GetBiometricsStatus,Lu.UnlockWithBiometricsForUser,Lu.GetBiometricsStatusForUser,Lu.CanEnableBiometricUnlock,"getUserPremiumStatus"].includes(e.command)?(this.processMessageWithSender(e,t).then(e=>i({result:e}),e=>i({error:Object.assign(Object.assign({},e),{message:e.message})})),!0):(this.processMessageWithSender(e,t).catch(t=>this.logService.error(`Error while processing message in RuntimeBackground '${null==e?void 0:e.command}'.`,t)),!1)))})}processMessageWithSender(e,t){return VN(this,void 0,void 0,function*(){switch(e.command){case"triggerAutofillScriptInjection":yield this.autofillService.injectAutofillScripts(t.tab,t.frameId);break;case"bgCollectPageDetails":yield this.main.collectPageDetailsForContentScript(t.tab,e.sender,t.frameId);break;case"collectPageDetailsResponse":switch(e.sender){case"autofiller":case Om:{const i=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id)));yield this.accountService.setAccountActivity(i,new Date);const r=yield this.autofillService.doAutoFillActiveTab([{frameId:t.frameId,tab:e.tab,details:e.details}],e.sender===Om);null!=r&&this.platformUtilsService.copyToClipboard(r),yield this.main.updateOverlayCiphers();break}case Nm:yield this.autofillService.doAutoFillActiveTab([{frameId:t.frameId,tab:e.tab,details:e.details}],e.sender===Nm,rm.Card);break;case Rm:yield this.autofillService.doAutoFillActiveTab([{frameId:t.frameId,tab:e.tab,details:e.details}],e.sender===Rm,rm.Identity);break;case"contextMenu":clearTimeout(this.autofillTimeout),this.pageDetailsToAutoFill.push({frameId:t.frameId,tab:e.tab,details:e.details}),this.autofillTimeout=setTimeout(()=>VN(this,void 0,void 0,function*(){return yield this.autofillPage(e.tab)}),300)}break;case Lu.AuthenticateWithBiometrics:return yield this.main.biometricsService.authenticateWithBiometrics();case Lu.GetBiometricsStatus:return yield this.main.biometricsService.getBiometricsStatus();case Lu.UnlockWithBiometricsForUser:return yield this.main.biometricsService.unlockWithBiometricsForUser(e.userId);case Lu.GetBiometricsStatusForUser:return yield this.main.biometricsService.getBiometricsStatusForUser(e.userId);case Lu.CanEnableBiometricUnlock:return yield this.main.biometricsService.canEnableBiometricUnlock();case"getUserPremiumStatus":{const e=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id)));return yield Ce(this.billingAccountProfileStateService.hasPremiumFromAnySource$(e))}}})}processMessage(e){return VN(this,void 0,void 0,function*(){var t;switch(e.command){case"loggedIn":case"unlocked":{let i;"loggedIn"===e.command&&(yield this.main.initOverlayAndTabsBackground(),yield this.sendBwInstalledMessageToVault(),yield this.autofillService.reloadAutofillScripts()),(null===(t=this.lockedVaultPendingNotifications)||void 0===t?void 0:t.length)>0&&(i=this.lockedVaultPendingNotifications.pop(),yield function(){return kT(this,void 0,void 0,function*(){yield wT.closeSingleActionPopout(ST)})}()),this.processReloadService.cancelProcessReload(),i&&(yield hT.focusWindow(i.commandToRetry.sender.tab.windowId),yield hT.focusTab(i.commandToRetry.sender.tab.id),yield hT.tabSendMessageData(i.commandToRetry.sender.tab,"unlockCompleted",i)),yield this.main.refreshMenu(!1),yield this.autofillService.setAutoFillOnPageLoadOrgPolicy();break}case"addToLockedVaultPendingNotifications":this.lockedVaultPendingNotifications.push(e.data);break;case"abandonAutofillPendingNotifications":this.lockedVaultPendingNotifications=[];break;case"lockVault":yield this.lockService.lock(e.userId);break;case"lockAll":yield this.lockService.lockAll(),this.messagingService.send("lockAllFinished",{requestId:e.requestId});break;case"lockUser":yield this.lockService.lock(e.userId),this.messagingService.send("lockUserFinished",{requestId:e.requestId});break;case"logout":yield this.main.logout(e.expired,e.userId);break;case"syncCompleted":e.successfully&&(setTimeout(()=>VN(this,void 0,void 0,function*(){yield this.main.refreshMenu()}),2e3),yield this.configService.ensureConfigFetched(),yield this.main.updateOverlayCiphers(),yield this.autofillService.setAutoFillOnPageLoadOrgPolicy());break;case"openPopup":yield this.executeMessageActionOrOpenPopup(e,this.openPopup.bind(this));break;case fT:yield this.executeMessageActionOrOpenPopup(e,this.main.openAtRisksPasswordsPage.bind(this)),this.announcePopupOpen();break;case"openBrowserExtensionToUrl":yield this.executeMessageActionOrOpenPopup(e,this.main.openTheExtensionToPage.bind(this,e.url)),this.announcePopupOpen();break;case"bgUpdateContextMenu":case"editedCipher":case"addedCipher":case"deletedCipher":yield this.main.refreshMenu();break;case"bgReseedStorage":yield this.main.reseedStorage();break;case"authResult":if(!(yield this.isValidVaultReferrer(e.referrer)))return;if(e.lastpass)this.messagingService.send("importCallbackLastPass",{code:e.code,state:e.state});else try{yield function(e){return kT(this,void 0,void 0,function*(){const{code:t,state:i}=e,r=`popup/index.html#/sso?code=${encodeURIComponent(t)}&state=${encodeURIComponent(i)}`;yield wT.openPopout(r,{singleActionKey:"auth_ssoAuthResult"})})}(e)}catch(e){this.logService.error("Unable to open sso popout tab")}break;case"webAuthnResult":if(!(yield this.isValidVaultReferrer(e.referrer)))return;yield function(e){return kT(this,void 0,void 0,function*(){const{data:t,remember:i}=e,r=`popup/index.html#/2fa;webAuthnResponse=${encodeURIComponent(t)};remember=${encodeURIComponent(i)}`;yield wT.openPopout(r,{singleActionKey:"auth_twoFactorAuthWebAuthn"})})}(e);break;case"reloadPopup":Gf(e)&&this.messagingService.send("reloadPopup");break;case"emailVerificationRequired":this.messagingService.send("showDialog",{title:{key:"emailVerificationRequired"},content:{key:"emailVerificationRequiredDesc"},acceptButtonText:{key:"ok"},cancelButtonText:null,type:"info"});break;case"getClickedElementResponse":this.platformUtilsService.copyToClipboard(e.identifier);break;case"switchAccount":yield this.main.switchAccount(e.userId);break;case"clearClipboard":yield this.main.clearClipboard(e.clipboardValue,e.timeoutMs)}})}executeMessageActionOrOpenPopup(e,t){return VN(this,void 0,void 0,function*(){var i;(yield Ce(this.accountService.accounts$.pipe(X(e=>Object.keys(e).length>0))))?!(yield this.isValidVaultReferrer(Tt.getHostname(null===(i=null==e?void 0:e.webExtSender)||void 0===i?void 0:i.origin)))&&Gf(e)||(yield t()):yield this.openPopup()})}isValidVaultReferrer(e){return VN(this,void 0,void 0,function*(){if(!e)return!1;const t=yield Ce(this.environmentService.environment$),i=this.environmentService.availableRegions().map(e=>{var t;return null!==(t=e.urls.webVault)&&void 0!==t?t:e.urls.base});return[...i,t.getWebVaultUrl()].some(t=>Tt.getHostname(t)===e)})}autofillPage(e){return VN(this,void 0,void 0,function*(){const t=yield this.autofillService.doAutoFill({tab:e,cipher:this.main.loginToAutoFill,pageDetails:this.pageDetailsToAutoFill,fillNewPassword:!0,allowTotpAutofill:!0});null!=t&&this.platformUtilsService.copyToClipboard(t),this.main.loginToAutoFill=null,this.pageDetailsToAutoFill=[]})}checkOnInstalled(){return VN(this,void 0,void 0,function*(){setTimeout(()=>VN(this,void 0,void 0,function*(){this.autofillService.loadAutofillScriptsOnInstall(),null!=this.onInstalledReason&&("install"!==this.onInstalledReason||(yield Ce(this.browserInitialInstallService.extensionInstalled$))||(hT.createNewTab("https://bitwarden.com/browser-start/"),yield this.autofillSettingsService.setInlineMenuVisibility(2),(yield this.environmentService.hasManagedEnvironment())&&(yield this.environmentService.setUrlsToManagedEnvironment()),yield this.browserInitialInstallService.setExtensionInstalled(!0)),this.onInstalledReason=null)}),100)})}getBwTabs(){return VN(this,void 0,void 0,function*(){const e=(yield Ce(this.environmentService.environment$)).getWebVaultUrl(),t=new URL(e);return yield hT.tabsQuery({url:`${t.href}*`})})}openPopup(){return VN(this,void 0,void 0,function*(){yield this.main.openPopup()})}sendBwInstalledMessageToVault(){return VN(this,void 0,void 0,function*(){try{const e=yield this.getBwTabs();if(!(null==e?void 0:e.length))return;for(const t of e)yield hT.executeScriptInTab(t.id,{file:"content/send-on-installed-message.js",runAt:"document_end"})}catch(e){this.logService.error(`Error sending on installed message to vault: ${e}`)}})}announcePopupOpen(){setTimeout(()=>VN(this,void 0,void 0,function*(){const e=yield this.platformUtilsService.isPopupOpen(),t=yield this.getBwTabs();if(e&&t.length>0)for(const e of t)yield hT.executeScriptInTab(e.id,{file:"content/send-popup-open-message.js",runAt:"document_end"})}),100)}}var KN=function(e,t,i,r){return new(i||(i=Promise))(function(n,a){function s(e){try{l(r.next(e))}catch(e){a(e)}}function o(e){try{l(r.throw(e))}catch(e){a(e)}}function l(e){var t;e.done?n(e.value):(t=e.value,t instanceof i?t:new i(function(e){e(t)})).then(s,o)}l((r=r.apply(e,t||[])).next())})};const WN=new r(!1),HN=self.bitwardenMain=new class{constructor(){this.loginToAutoFill=null,this.generatePassword=()=>KN(this,void 0,void 0,function*(){var e,t;const i=null!==(t=null===(e=yield this.passwordGenerationService.getOptions())||void 0===e?void 0:e[0])&&void 0!==t?t:{};return yield this.passwordGenerationService.generatePassword(i)}),this.generatePasswordToClipboard=()=>KN(this,void 0,void 0,function*(){const e=yield this.generatePassword();this.platformUtilsService.copyToClipboard(e),yield this.addPasswordToHistory(e)}),this.addPasswordToHistory=e=>KN(this,void 0,void 0,function*(){yield this.passwordGenerationService.addHistory(e)});const e=(e,t)=>KN(this,void 0,void 0,function*(){return yield this.logout(e,t)});this.logService=new r(!1),this.cryptoFunctionService=new Tg(self),this.keyGenerationService=new Ig(this.cryptoFunctionService),this.storageService=new QO(this.logService),this.intraprocessMessagingSubject=new H,this.messagingService=Kf.combine(new Jf(this.intraprocessMessagingSubject),new _O(this.logService));const t=new Vf(_e(this.intraprocessMessagingSubject.asObservable(),xD(chrome.runtime.onMessage).pipe(X(([e,t])=>(null!=e||(e={}),"webExtSender"in e||(e.webExtSender=t),e)),X(e=>Object.assign(e,{[Hf]:!0})),Gt())));this.offscreenDocumentService=new CO(this.logService),this.platformUtilsService=new uN(this.messagingService,(e,t)=>this.clearClipboard(e,t),self,this.offscreenDocumentService),this.secureStorageService=this.storageService,hT.isManifestVersion(3)?(this.memoryStorageForStateProviders=new JO,this.memoryStorageService=this.memoryStorageForStateProviders):(this.memoryStorageForStateProviders=new EN(this.logService),this.memoryStorageService=this.memoryStorageForStateProviders),this.encryptService=new Pg(this.cryptoFunctionService,this.logService,!0),hT.isManifestVersion(3)?this.largeObjectMemoryStorageForStateProviders=new cN(new JO,this.storageService,this.keyGenerationService,this.encryptService,this.platformUtilsService,this.logService):this.largeObjectMemoryStorageForStateProviders=this.memoryStorageForStateProviders;const i=hT.isManifestVersion(3)?new AN(this.offscreenDocumentService):new Dk(self.localStorage),n=new zN(this.storageService,this.memoryStorageForStateProviders,this.largeObjectMemoryStorageForStateProviders,new Tk(this.storageService,i));this.globalStateProvider=new dc(n,this.logService);const a=new Ic(this.globalStateProvider,n);this.stateEventRunnerService=new Ec(this.globalStateProvider,n),this.singleUserStateProvider=new pc(n,a,this.logService),this.accountService=new ru(this.messagingService,this.logService,this.globalStateProvider,this.singleUserStateProvider);const s=new yp(this.accountService);this.activeUserStateProvider=new rc(s,this.singleUserStateProvider),this.derivedStateProvider=new fc,this.stateProvider=new mc(this.activeUserStateProvider,this.singleUserStateProvider,this.globalStateProvider,this.derivedStateProvider),this.taskSchedulerService=new IN(this.logService,this.stateProvider),this.accountCryptographicStateService=new kg(this.stateProvider),this.backgroundSyncService=new $j(this.taskSchedulerService),this.backgroundSyncService.register(()=>this.fullSync()),this.environmentService=new MO(this.logService,this.stateProvider,this.accountService,{ENV:"production"}.ADDITIONAL_REGIONS),this.biometricStateService=new Mu(this.stateProvider),this.userNotificationSettingsService=new ug(this.stateProvider),this.tokenService=new Gp(this.singleUserStateProvider,this.globalStateProvider,this.platformUtilsService.supportsSecureStorage(),this.secureStorageService,this.keyGenerationService,this.encryptService,this.logService,e),this.securityStateService=new Of(this.accountCryptographicStateService),this.popupViewCacheBackgroundService=new fN(t,this.globalStateProvider,this.taskSchedulerService),this.popupRouterCacheBackgroundService=new yN(this.globalStateProvider),this.migrationRunner=new ik(this.storageService,this.logService,new ek,Ku.Browser),this.stateService=new _c(this.storageService,this.secureStorageService,s),this.masterPasswordService=new xf(this.stateProvider,this.keyGenerationService,this.logService,this.cryptoFunctionService,this.accountService),this.i18nService=new nN(hT.getUILanguage(),this.globalStateProvider),this.kdfConfigService=new Dd(this.stateProvider),this.keyService=new Ed(this.masterPasswordService,this.keyGenerationService,this.cryptoFunctionService,this.encryptService,this.platformUtilsService,this.logService,this.stateService,this.accountService,this.stateProvider,this.kdfConfigService,this.accountCryptographicStateService);const o=new Pf(this.stateProvider);this.appIdService=new pb(this.storageService,this.logService),this.userDecryptionOptionsService=new bh(this.singleUserStateProvider),this.organizationService=new tp(this.stateProvider),this.policyService=new sd(this.stateProvider,this.organizationService,this.accountService);const l=new lO(this.platformUtilsService);this.vaultTimeoutSettingsService=new yd(this.accountService,o,this.userDecryptionOptionsService,this.keyService,this.tokenService,this.policyService,this.biometricStateService,this.stateProvider,this.logService,cd,l),this.apiService=new QS(this.tokenService,this.platformUtilsService,this.environmentService,this.appIdService,()=>{this.messagingService.send("showToast",{type:"error",title:this.i18nService.t("errorRefreshingAccessToken"),message:this.i18nService.t("errorRefreshingAccessTokenDesc")})},this.logService,(e,t)=>this.logout(e,t),this.vaultTimeoutSettingsService,this.accountService,{createRequest:(e,t)=>new Request(e,t)}),this.organizationUserApiService=new Vc(this.apiService),this.organizationUserService=new su(this.keyService,this.encryptService,this.organizationUserApiService,this.accountService,this.i18nService),this.hibpApiService=new fg(this.apiService),this.fileUploadService=new Zw(this.logService,this.apiService),this.cipherFileUploadService=new PC(this.apiService,this.fileUploadService),this.searchService=new WC(this.logService,this.i18nService,this.stateProvider),this.collectionService=new jc(this.keyService,this.encryptService,this.i18nService,this.stateProvider),this.badgeSettingsService=new Ym(this.stateProvider),this.policyApiService=new np(this.policyService,this.apiService,this.accountService),this.authService=new hp(this.accountService,this.messagingService,this.keyService,this.apiService,this.stateService,this.tokenService),this.configApiService=new vb(this.apiService),this.configService=new yf(this.configApiService,this.environmentService,this.logService,this.stateProvider,this.authService),this.autoConfirmService=new Qh(this.configService,this.apiService,this.organizationUserService,this.stateProvider,this.organizationService,this.organizationUserApiService,this.policyService);const c=of("sdk")?new rk:new _k;if(this.sdkLoadService=new kN(this.logService),this.sdkService=new Sk(c,this.environmentService,this.platformUtilsService,this.accountService,this.kdfConfigService,this.keyService,this.securityStateService,this.apiService,this.stateProvider,this.configService),this.registerSdkService=new Ek(c,this.environmentService,this.platformUtilsService,this.accountService,this.apiService,this.stateProvider,this.configService),this.keyConnectorService=new Xg(this.accountService,this.masterPasswordService,this.keyService,this.apiService,this.tokenService,this.logService,this.organizationService,this.keyGenerationService,e,this.stateProvider,this.configService,this.registerSdkService,this.securityStateService,this.accountCryptographicStateService),this.pinService=new Df(this.encryptService,this.logService,this.keyService,this.sdkService,o),this.biometricsService=new sO(()=>this.nativeMessagingBackground,this.logService,this.keyService,this.biometricStateService,this.messagingService,this.vaultTimeoutSettingsService,this.pinService),this.passwordStrengthService=new dx,this.passwordGenerationService=function(e,t,i,r,n){const a=new Mz,s=new Vz(a,Date.now),o=new $z(new Bz(s,n),i),l=new $z(new Lz(s,n),i),c=new Nz(n,i),u=new zz(e,t,n);return new Fz(r,c,o,l,u)}(this.encryptService,this.keyService,this.policyService,this.accountService,this.stateProvider),this.devicesApiService=new Ip(this.apiService),this.deviceTrustService=new qg(this.keyGenerationService,this.cryptoFunctionService,this.keyService,this.encryptService,this.appIdService,this.devicesApiService,this.i18nService,this.platformUtilsService,this.stateProvider,this.secureStorageService,this.userDecryptionOptionsService,this.logService,this.configService,this.accountService),this.devicesService=new bp(this.appIdService,this.devicesApiService,this.i18nService),this.authRequestApiService=new Eh(this.apiService,this.logService),this.authRequestService=new Ch(this.appIdService,this.masterPasswordService,this.keyService,this.encryptService,this.apiService,this.stateProvider,this.authRequestApiService,this.accountService),this.billingAccountProfileStateService=new mg(this.stateProvider),this.restrictedItemTypesService=new LC(this.accountService,this.organizationService,this.policyService),this.autofillSettingsService=new Qm(this.stateProvider,this.policyService,this.accountService,this.restrictedItemTypesService),this.ssoLoginService=new Op(this.stateProvider,this.logService,this.policyService),this.userVerificationApiService=new Jp(this.apiService),this.domainSettingsService=new sg(this.stateProvider,this.policyService,this.accountService),this.themeStateService=new Hk(this.globalStateProvider),this.cipherEncryptionService=new EC(this.sdkService,this.logService),this.cipherSdkService=new rC(this.sdkService,this.logService),this.cipherService=new _C(this.keyService,this.domainSettingsService,this.apiService,this.i18nService,this.searchService,this.autofillSettingsService,this.encryptService,this.cipherFileUploadService,this.configService,this.stateProvider,this.accountService,this.logService,this.cipherEncryptionService,this.messagingService,this.cipherSdkService),this.folderService=new qC(this.keyService,this.encryptService,this.i18nService,this.cipherService,this.stateProvider),this.folderApiService=new TC(this.folderService,this.apiService),this.userVerificationService=new em(this.keyService,this.accountService,this.masterPasswordService,this.i18nService,this.userVerificationApiService,this.userDecryptionOptionsService,this.pinService,this.kdfConfigService,this.biometricsService),this.vaultSettingsService=new ZC(this.stateProvider,this.restrictedItemTypesService),this.containerService=new bb(this.keyService,this.encryptService),this.sendStateProvider=new Mx(this.stateProvider),this.sendService=new Kx(this.accountService,this.keyService,this.i18nService,this.keyGenerationService,this.sendStateProvider,this.encryptService,this.configService),this.sendApiService=new Fx(this.apiService,this.fileUploadService,this.sendService),this.avatarService=new fp(this.apiService,this.stateProvider),this.providerService=new op(this.stateProvider),this.syncService=new $k(this.masterPasswordService,this.accountService,this.apiService,this.domainSettingsService,this.folderService,this.cipherService,this.keyService,this.collectionService,this.messagingService,this.policyService,this.sendService,this.logService,this.keyConnectorService,this.providerService,this.folderApiService,this.organizationService,this.sendApiService,this.userDecryptionOptionsService,this.avatarService,e,this.billingAccountProfileStateService,this.tokenService,this.authService,this.stateProvider,this.securityStateService,this.kdfConfigService,this.accountCryptographicStateService),this.syncServiceListener=new ON(this.syncService,t,this.messagingService,this.logService),this.eventUploadService=new a_(this.apiService,this.stateProvider,this.logService,this.authService,this.taskSchedulerService),this.eventCollectionService=new i_(this.cipherService,this.stateProvider,this.organizationService,this.eventUploadService,this.authService,this.accountService),this.totpService=new HC(this.sdkService),this.scriptInjectorService=new XO(this.domainSettingsService,this.platformUtilsService,this.logService),this.autofillService=new $D(this.cipherService,this.autofillSettingsService,this.totpService,this.eventCollectionService,this.logService,this.domainSettingsService,this.userVerificationService,this.billingAccountProfileStateService,this.scriptInjectorService,this.accountService,this.authService,this.configService,this.userNotificationSettingsService,t),this.auditService=new YS(this.cryptoFunctionService,this.apiService,this.hibpApiService),this.importApiService=new dP(this.apiService),this.importMetadataService=new Vj(function(e,t,i,r,n,a,s){let o;return o=a.isDev()?function(e,t){return t.length&&Cx(e,"enableLogForTypes",{types:t}),function(i){const{type:r}=i;if("string"==typeof r&&t.includes(r)){const n=new Sx(e,i);return Cx(e,"enableLogForTypes",{targetType:r,available:t,loggerContext:i}),n}return xx}}(n,[]):Ix,{policy:i,extension:new kx(r,{encryptor:e,state:t,log:o,now:Date.now}),log:o,configService:s,environment:a}}(new N_(this.encryptService,this.keyService),this.stateProvider,this.policyService,function(){const e=new K_(q_,L_);for(const t of Reflect.ownKeys(B_))e.registerSite(B_[t]);for(const t of ox)e.registerVendor(t);for(const t of lx)e.registerExtension(t);return e}(),this.logService,this.platformUtilsService,this.configService)),this.importService=new Mj(this.cipherService,this.folderService,this.importApiService,this.i18nService,this.collectionService,this.keyService,this.encryptService,this.keyGenerationService,this.accountService,this.restrictedItemTypesService),this.individualVaultExportService=new XP(this.folderService,this.cipherService,this.keyGenerationService,this.keyService,this.encryptService,this.cryptoFunctionService,this.kdfConfigService,this.apiService,this.restrictedItemTypesService),this.exportApiService=new eA(this.apiService),this.organizationVaultExportService=new QP(this.cipherService,this.exportApiService,this.keyGenerationService,this.keyService,this.encryptService,this.cryptoFunctionService,this.collectionService,this.kdfConfigService,this.restrictedItemTypesService),this.exportService=new KP(this.individualVaultExportService,this.organizationVaultExportService,this.accountService),this.browserInitialInstallService=new $O(this.stateProvider),hT.isManifestVersion(3)){const e=null===self||void 0===self?void 0:self.registration;this.webPushConnectionService=null!=e?new wy(this.configService,new db(this.apiService,this.appIdService),e,this.stateProvider):new cb}else this.webPushConnectionService=new cb;this.actionsService=new uO(this.logService,this.platformUtilsService),"notifications"in chrome&&null!=chrome.notifications?this.systemNotificationService=new RN(this.platformUtilsService):this.systemNotificationService=new Kk,this.pendingAuthRequestStateService=new dp(this.stateProvider),this.authRequestAnsweringService=new Qj(this.accountService,this.authService,this.masterPasswordService,this.messagingService,this.pendingAuthRequestStateService,this.actionsService,this.i18nService,this.platformUtilsService,this.systemNotificationService,this.logService),this.serverNotificationsService=new lb(this.logService,this.syncService,this.appIdService,this.environmentService,e,this.messagingService,this.accountService,new ab(this.apiService,this.logService,this.platformUtilsService),this.authService,this.webPushConnectionService,this.authRequestAnsweringService,this.configService,this.policyService,this.autoConfirmService),this.fido2UserInterfaceService=new PD(this.authService),this.fido2AuthenticatorService=new qw(this.cipherService,this.fido2UserInterfaceService,this.syncService,this.accountService,this.logService),this.fido2ActiveRequestManager=new xb,this.fido2ClientService=new Hw(this.fido2AuthenticatorService,this.configService,this.authService,this.vaultSettingsService,this.domainSettingsService,this.taskSchedulerService,this.fido2ActiveRequestManager,this.logService),this.systemService=new Pk(this.platformUtilsService,this.autofillSettingsService,this.taskSchedulerService),this.processReloadService=new Rf(this.pinService,this.messagingService,()=>KN(this,void 0,void 0,function*(){yield this.taskSchedulerService.clearAllScheduledTasks(),yield wT.waitForAllPopupsClose(),hT.reloadExtension()}),this.vaultTimeoutSettingsService,this.biometricStateService,this.accountService,this.logService,this.authService),this.fido2Background=new _D(this.logService,this.fido2ActiveRequestManager,this.fido2ClientService,this.vaultSettingsService,this.scriptInjectorService,this.authService);const u=new jh(this.messagingService);this.lockService=new Zj(this.accountService,this.biometricsService,this.vaultTimeoutSettingsService,u,this.messagingService,this.searchService,this.folderService,this.masterPasswordService,this.stateEventRunnerService,this.cipherService,this.authService,this.systemService,this.processReloadService,this.logService,this.keyService,this),this.vaultTimeoutService=new cO(this.accountService,this.platformUtilsService,this.authService,this.vaultTimeoutSettingsService,this.taskSchedulerService,this.logService,this.lockService,u),this.runtimeBackground=new $N(this,this.autofillService,this.platformUtilsService,this.autofillSettingsService,this.processReloadService,this.environmentService,this.messagingService,this.logService,this.configService,t,this.accountService,this.lockService,this.billingAccountProfileStateService,this.browserInitialInstallService),this.nativeMessagingBackground=new MN(this.keyService,this.encryptService,this.cryptoFunctionService,this.runtimeBackground,this.messagingService,this.appIdService,this.platformUtilsService,this.logService,this.authService,this.biometricStateService,this.accountService),this.commandsBackground=new qN(this,this.platformUtilsService,this.authService,()=>this.generatePasswordToClipboard(),this.accountService,this.lockService),this.taskService=new sI(this.stateProvider,this.apiService,this.organizationService,this.authService,this.serverNotificationsService,t),this.notificationBackground=new RT(this.accountService,this.authService,this.autofillService,this.cipherService,this.collectionService,this.configService,this.domainSettingsService,this.environmentService,this.folderService,this.logService,this.organizationService,this.policyService,this.themeStateService,this.userNotificationSettingsService,this.taskService,this.messagingService,this.fido2Background),this.overlayNotificationsBackground=new KT(this.logService,this.notificationBackground),this.autoSubmitLoginBackground=new mT(this.logService,this.autofillService,this.scriptInjectorService,this.authService,this.platformUtilsService,this.policyService,this.accountService);const d=new gD(e=>this.platformUtilsService.copyToClipboard(e.text),e=>KN(this,void 0,void 0,function*(){var e,t;const i=null!==(t=null===(e=yield this.passwordGenerationService.getOptions())||void 0===e?void 0:e[0])&&void 0!==t?t:{},r=yield this.passwordGenerationService.generatePassword(i);this.platformUtilsService.copyToClipboard(r),this.passwordGenerationService.addHistory(r)}),(e,t)=>KN(this,void 0,void 0,function*(){this.loginToAutoFill=t,null!=e&&hT.tabSendMessage(e,{command:"collectPageDetails",tab:e,sender:"contextMenu"})}),this.authService,this.cipherService,this.totpService,this.eventCollectionService,this.userVerificationService,this.accountService);this.contextMenusBackground=new gT(d),this.idleBackground=new LN(this.vaultTimeoutService,this.serverNotificationsService,this.accountService,this.vaultTimeoutSettingsService,this.lockService,u),this.usernameGenerationService=function(e,t,i,r,n,a,s){const o=new Jz,l=new Wz(e,t),c=new Yz(o),u=new Xz(o),d=new Zz,h=new eP(new rP(c,s),n),p=new eP(new iP(d,u,s),n),m=new eP(new tP(d,u,s),n),g=new eP(new nP(BI.AddyIo,l,t,r,i,s),n),f=new eP(new nP(BI.DuckDuckGo,l,t,r,i,s),n),y=new eP(new nP(BI.Fastmail,l,t,r,i,s),n),v=new eP(new nP(BI.FirefoxRelay,l,t,r,i,s),n),b=new eP(new nP(BI.ForwardEmail,l,t,r,i,s),n),w=new eP(new nP(BI.SimpleLogin,l,t,r,i,s),n),k=new Nz(s,n);return new Qz(a,k,m,h,p,g,f,y,v,b,w)}(this.apiService,this.i18nService,this.keyService,this.encryptService,this.policyService,this.accountService,this.stateProvider),this.mainContextMenuHandler=new dD(this.tokenService,this.autofillSettingsService,this.i18nService,this.logService,this.billingAccountProfileStateService,this.accountService,this.restrictedItemTypesService),this.cipherContextMenuHandler=new pD(this.mainContextMenuHandler,this.authService,this.cipherService,this.accountService),null!=chrome.webRequest&&null!=chrome.webRequest.onAuthRequired&&(this.webRequestBackground=new oD(this.platformUtilsService,this.cipherService,this.authService,this.accountService,chrome.webRequest)),this.userAutoUnlockKeyService=new Ak(this.keyService),this.cipherAuthorizationService=new Xx(this.collectionService,this.organizationService,this.accountService),this.inlineMenuFieldQualificationService=new KD,this.phishingDataService=new eO(this.apiService,this.taskSchedulerService,this.globalStateProvider,this.logService,this.platformUtilsService),this.phishingDetectionSettingsService=new vg(this.accountService,this.billingAccountProfileStateService,this.configService,this.logService,this.organizationService,this.platformUtilsService,this.stateProvider),nO.initialize(this.logService,this.phishingDataService,this.phishingDetectionSettingsService,t),this.ipcContentScriptManagerService=new kO(this.configService);const h=new Bf(this.stateProvider);this.ipcService=new bO(this.platformUtilsService,this.logService,h),this.endUserNotificationService=new Yx(this.stateProvider,this.apiService,this.serverNotificationsService,this.authService,this.logService),this.badgeService=new fO(new pO(this.platformUtilsService),this.logService),this.authStatusBadgeUpdaterService=new Xj(this.badgeService,this.accountService,this.authService),this.webPushConnectionService instanceof wy&&this.webPushConnectionService.start(),this.initNotificationSubscriptions()}bootstrap(){return KN(this,void 0,void 0,function*(){var e,t,i;this.containerService.attachToGlobal(self),yield this.sdkLoadService.loadAndInit(),yield this.migrationRunner.run();const r=yield Ce(this.accountService.accounts$),n=[];for(const e of Object.keys(r))n.push(this.userAutoUnlockKeyService.setUserKeyInMemoryIfAutoUserKeySet(e));yield Promise.all(n),yield this.i18nService.init(),this.eventUploadService.init(!0),this.popupViewCacheBackgroundService.startObservingMessages(),this.popupRouterCacheBackgroundService.init(),yield this.vaultTimeoutService.init(!0),this.fido2Background.init(),yield this.runtimeBackground.init(),yield this.notificationBackground.init(),this.overlayNotificationsBackground.init(),this.commandsBackground.init(),null===(e=this.contextMenusBackground)||void 0===e||e.init(),this.idleBackground.init(),null===(t=this.webRequestBackground)||void 0===t||t.startListening(),null===(i=this.syncServiceListener)||void 0===i||i.listener$().subscribe(),yield this.autoSubmitLoginBackground.init();const a=yield Ce(this.accountService.activeAccount$);if(null!=a&&(yield Ce(this.authService.authStatuses$.pipe(X(e=>e[a.id]))))===cu.LoggedOut){const e=yield Ce(this.accountService.nextUpAccount$);yield this.switchAccount(null==e?void 0:e.id)}return yield this.initOverlayAndTabsBackground(),yield this.ipcService.init(),this.badgeService.startListening(),new Promise(e=>{setTimeout(()=>KN(this,void 0,void 0,function*(){yield this.fullSync(!1),this.backgroundSyncService.init(),this.serverNotificationsService.startListening(),this.taskService.listenForTaskNotifications(),this.endUserNotificationService.listenForEndUserNotifications(),e()}),500)})})}refreshMenu(){return KN(this,arguments,void 0,function*(e=!1){var t,i,r;if(!chrome.windows||!chrome.contextMenus)return;if(yield dD.removeAll(),e)return yield null===(t=this.mainContextMenuHandler)||void 0===t?void 0:t.noAccess(),void(this.onUpdatedRan=this.onReplacedRan=!1);if(!(yield null===(i=this.mainContextMenuHandler)||void 0===i?void 0:i.init()))return void(this.onUpdatedRan=this.onReplacedRan=!1);const n=yield hT.getTabFromCurrentWindow();if(n){const e=yield Ce(this.domainSettingsService.blockedInteractionsUris$.pipe(X(e=>{var t;return!(!e||!(null===(t=null==n?void 0:n.url)||void 0===t?void 0:t.length))&&hg(n.url,e)})));yield null===(r=this.cipherContextMenuHandler)||void 0===r?void 0:r.update(n.url,e),this.onUpdatedRan=this.onReplacedRan=!1}})}updateOverlayCiphers(){return KN(this,void 0,void 0,function*(){this.overlayBackground&&(yield this.overlayBackground.updateOverlayCiphers())})}switchAccount(e){return KN(this,void 0,void 0,function*(){let t;try{const i=Ce(this.accountService.activeAccount$.pipe(Ie(t=>{var i;return(null!==(i=null==t?void 0:t.id)&&void 0!==i?i:null)===(null!=e?e:null)}),Fe({first:1e3,with:()=>{throw new Error("The account switch process did not complete in a reasonable amount of time.")}})));if(yield this.popupViewCacheBackgroundService.clearState(),yield this.accountService.switchAccount(e),yield i,null==e)return yield this.refreshMenu(),yield this.updateOverlayCiphers(),void this.messagingService.send("goHome");t=yield this.authService.getAuthStatus(e),yield this.systemService.clearPendingClipboard(),t===cu.LoggedOut?this.messagingService.send("goHome"):t===cu.Locked?this.messagingService.send("locked",{userId:e}):(this.messagingService.send("unlocked",{userId:e}),yield this.refreshMenu(),yield this.updateOverlayCiphers(),yield this.syncService.fullSync(!1))}finally{this.messagingService.send("switchAccountFinish",{userId:e,status:t})}})}logout(e,t){return KN(this,void 0,void 0,function*(){var i;const r=yield Ce(this.accountService.activeAccount$.pipe(X(e=>null==e?void 0:e.id),Fe({first:2e3,with:()=>{throw new Error("No active account found to logout")}}))),n=null!=t?t:r;yield this.eventUploadService.uploadEvents(n);const a=n===r?yield Ce(this.accountService.nextUpAccount$.pipe(X(e=>null==e?void 0:e.id))):null;yield this.switchAccount(a);const s=Ce(this.authService.authStatusFor$(n).pipe(Ie(e=>e===cu.LoggedOut),Fe({first:5e3,with:()=>{throw new Error("The logout process did not complete in a reasonable amount of time.")}})));yield Promise.all([this.keyService.clearKeys(n),this.cipherService.clear(n),this.folderService.clear(n),this.biometricStateService.logout(n),this.popupViewCacheBackgroundService.clearState(),this.pinService.logout(n)]);const o=yield this.needsStorageReseed(n);yield this.stateService.clean({userId:n}),yield this.tokenService.clearAccessToken(n),yield this.accountService.clean(n),yield this.stateEventRunnerService.handleEvent("logout",n),yield s,this.messagingService.send("doneLoggingOut",{logoutReason:e,userId:n}),o&&(yield this.reseedStorage()),hT.isManifestVersion(3)&&hT.sendMessage("updateBadge"),yield null===(i=this.mainContextMenuHandler)||void 0===i?void 0:i.noAccess(),yield this.systemService.clearPendingClipboard(),yield this.processReloadService.startProcessReload()})}needsStorageReseed(e){return KN(this,void 0,void 0,function*(){return(yield Ce(this.vaultTimeoutSettingsService.getVaultTimeoutByUserId$(e)))!=ld})}collectPageDetailsForContentScript(e,t){return KN(this,arguments,void 0,function*(e,t,i=null){if(null==e||!e.id)return;const r={};null!=i&&(r.frameId=i),hT.tabSendMessage(e,{command:"collectPageDetails",tab:e,sender:t},r)})}openPopup(){return KN(this,void 0,void 0,function*(){const e=hT.getBrowserAction();"openPopup"in e&&"function"==typeof e.openPopup?yield e.openPopup():this.platformUtilsService.isSafari()&&(yield iT.sendMessageToApp("showPopover",null,!0))})}openAtRisksPasswordsPage(){return KN(this,void 0,void 0,function*(){const e=hT.getBrowserAction();try{yield e.setPopup({popup:dm.AtRiskPasswords}),yield this.openPopup()}finally{yield e.setPopup({popup:dm.Index})}})}openTheExtensionToPage(){return KN(this,arguments,void 0,function*(e=dm.Index){if(!Object.values(dm).includes(e))return;const t=hT.getBrowserAction();try{yield t.setPopup({popup:e}),yield this.openPopup()}finally{yield t.setPopup({popup:dm.Index})}})}reseedStorage(){return KN(this,void 0,void 0,function*(){(this.platformUtilsService.isChrome()||this.platformUtilsService.isVivaldi()||this.platformUtilsService.isOpera())&&(yield this.storageService.fillBuffer())})}clearClipboard(e,t){return KN(this,void 0,void 0,function*(){null!=this.systemService&&(yield this.systemService.clearClipboard(e,t))})}fullSync(){return KN(this,arguments,void 0,function*(e=!1){const t=yield this.syncService.getLastSync();let i=21600001;null!=t&&(i=(new Date).getTime()-t.getTime()),(e||i>=216e5)&&(yield this.syncService.fullSync(e))})}initNotificationSubscriptions(){const e=[];var t,i;t=lp.AuthRequest,i=e=>this.authRequestAnsweringService.handleAuthRequestNotificationClicked(e),e.push({startsWith:t,handler:i});const r=e.map(({startsWith:e,handler:t})=>this.systemNotificationService.notificationClicked$.pipe(Ie(t=>t.id.startsWith(e+"_")),Le(e=>Se(Promise.resolve(t(e))))));r.length>0&&_e(...r).subscribe()}initOverlayAndTabsBackground(){return KN(this,void 0,void 0,function*(){this.overlayBackground||this.tabsBackground||(yield Ce(this.authService.activeAccountStatus$))===cu.LoggedOut||(this.overlayBackground=new rD(this.logService,this.cipherService,this.autofillService,this.authService,this.environmentService,this.domainSettingsService,this.autofillSettingsService,this.i18nService,this.platformUtilsService,this.vaultSettingsService,this.fido2ActiveRequestManager,this.inlineMenuFieldQualificationService,this.themeStateService,this.totpService,this.accountService,()=>this.generatePassword(),e=>this.addPasswordToHistory(e)),this.autofillBadgeUpdaterService=new DD(this.badgeService,this.accountService,this.cipherService,this.badgeSettingsService,this.logService),this.atRiskCipherUpdaterService=new UN(this.badgeService,this.accountService,this.cipherService,this.taskService),this.tabsBackground=new aD(this,this.notificationBackground,this.overlayBackground),yield this.overlayBackground.init(),yield this.tabsBackground.init(),yield this.autofillBadgeUpdaterService.init(),yield this.atRiskCipherUpdaterService.init())})}};HN.bootstrap().catch(e=>WN.error(e))})()})();