/******/ (function() { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 641: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var stringify=__webpack_require__(62520);var parse=__webpack_require__(46998);var formats=__webpack_require__(10681);module.exports={formats:formats,parse:parse,stringify:stringify}; /***/ }), /***/ 732: /***/ (function(module) { "use strict"; /** @type {import('./pow')} */module.exports=Math.pow; /***/ }), /***/ 1697: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var call=Function.prototype.call;var $hasOwn=Object.prototype.hasOwnProperty;var bind=__webpack_require__(10539);/** @type {import('.')} */module.exports=bind.call(call,$hasOwn); /***/ }), /***/ 2301: /***/ (function(module) { "use strict"; /* eslint no-invalid-this: 1 */var ERROR_MESSAGE='Function.prototype.bind called on incompatible ';var toStr=Object.prototype.toString;var max=Math.max;var funcType='[object Function]';var concatty=function concatty(a,b){var arr=[];for(var i=0;i','"','`',' ','\r','\n','\t'],// RFC 2396: characters not allowed for various reasons. unwise=['{','}','|','\\','^','`'].concat(delims),// Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape=['\''].concat(unwise),/* * Characters that are never ever allowed in a hostname. * Note that any invalid chars are also handled, but these * are the ones that are *expected* to be seen, so we fast-path * them. */nonHostChars=['%','/','?',';','#'].concat(autoEscape),hostEndingChars=['/','?','#'],hostnameMaxLen=255,hostnamePartPattern=/^[+a-z0-9A-Z_-]{0,63}$/,hostnamePartStart=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,// protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol={javascript:true,'javascript:':true},// protocols that never have a hostname. hostlessProtocol={javascript:true,'javascript:':true},// protocols that always contain a // bit. slashedProtocol={http:true,https:true,ftp:true,gopher:true,file:true,'http:':true,'https:':true,'ftp:':true,'gopher:':true,'file:':true},querystring=__webpack_require__(641);function urlParse(url,parseQueryString,slashesDenoteHost){if(url&&typeof url==='object'&&url instanceof Url){return url;}var u=new Url();u.parse(url,parseQueryString,slashesDenoteHost);return u;}Url.prototype.parse=function(url,parseQueryString,slashesDenoteHost){if(typeof url!=='string'){throw new TypeError("Parameter 'url' must be a string, not "+typeof url);}/* * Copy chrome, IE, opera backslash-handling behavior. * Back slashes before the query string get converted to forward slashes * See: https://code.google.com/p/chromium/issues/detail?id=25916 */var queryIndex=url.indexOf('?'),splitter=queryIndex!==-1&&queryIndex user:a@b host:c * http://a@b?@c => user:a host:c path:/?@c *//* * v0.12 TODO(isaacs): This is not quite how Chrome does things. * Review our test case against browsers more comprehensively. */// find the first instance of any hostEndingChars var hostEnd=-1;for(var i=0;i host:b auth:a path:/c@d */atSign=rest.lastIndexOf('@',hostEnd);}/* * Now we have a portion which is definitely the auth. * Pull that off. */if(atSign!==-1){auth=rest.slice(0,atSign);rest=rest.slice(atSign+1);this.auth=decodeURIComponent(auth);}// the host is the remaining to the left of the first non-host char hostEnd=-1;for(var i=0;i127){/* * we replace non-ASCII char with a temporary placeholder * we need this to make sure size of hostname is not * broken by replacing non-ASCII by nothing */newpart+='x';}else{newpart+=part[j];}}// we test again with ASCII char only if(!newpart.match(hostnamePartPattern)){var validParts=hostparts.slice(0,i);var notHost=hostparts.slice(i+1);var bit=part.match(hostnamePartStart);if(bit){validParts.push(bit[1]);notHost.unshift(bit[2]);}if(notHost.length){rest='/'+notHost.join('.')+rest;}this.hostname=validParts.join('.');break;}}}}if(this.hostname.length>hostnameMaxLen){this.hostname='';}else{// hostnames are always lower case. this.hostname=this.hostname.toLowerCase();}if(!ipv6Hostname){/* * IDNA Support: Returns a punycoded representation of "domain". * It only converts parts of the domain name that * have non-ASCII characters, i.e. it doesn't matter if * you call it with a domain that already is ASCII-only. */this.hostname=punycode.toASCII(this.hostname);}var p=this.port?':'+this.port:'';var h=this.hostname||'';this.host=h+p;this.href+=this.host;/* * strip [ and ] from the hostname * the host field still retains them, though */if(ipv6Hostname){this.hostname=this.hostname.substr(1,this.hostname.length-2);if(rest[0]!=='/'){rest='/'+rest;}}}/* * now rest is set to the post-host stuff. * chop off any delim chars. */if(!unsafeProtocol[lowerProto]){/* * First, make 100% sure that any "autoEscape" chars get * escaped, even if encodeURIComponent doesn't think they * need to be. */for(var i=0,l=autoEscape.length;i0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.hostname=authInHost.shift();result.host=result.hostname;}}result.search=relative.search;result.query=relative.query;// to support http.request if(result.pathname!==null||result.search!==null){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.href=result.format();return result;}if(!srcPath.length){/* * no path at all. easy. * we've already handled the other stuff above. */result.pathname=null;// to support http.request if(result.search){result.path='/'+result.search;}else{result.path=null;}result.href=result.format();return result;}/* * if a url ENDs in . or .., then it must get a trailing slash. * however, if it ends in anything else non-slashy, * then it must NOT get a trailing slash. */var last=srcPath.slice(-1)[0];var hasTrailingSlash=(result.host||relative.host||srcPath.length>1)&&(last==='.'||last==='..')||last==='';/* * strip single dots, resolve double dots to parent dir * if the path tries to go above the root, `up` ends up > 0 */var up=0;for(var i=srcPath.length;i>=0;i--){last=srcPath[i];if(last==='.'){srcPath.splice(i,1);}else if(last==='..'){srcPath.splice(i,1);up++;}else if(up){srcPath.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s if(!mustEndAbs&&!removeAllDots){for(;up--;up){srcPath.unshift('..');}}if(mustEndAbs&&srcPath[0]!==''&&(!srcPath[0]||srcPath[0].charAt(0)!=='/')){srcPath.unshift('');}if(hasTrailingSlash&&srcPath.join('/').substr(-1)!=='/'){srcPath.push('');}var isAbsolute=srcPath[0]===''||srcPath[0]&&srcPath[0].charAt(0)==='/';// put the host back if(psychotic){result.hostname=isAbsolute?'':srcPath.length?srcPath.shift():'';result.host=result.hostname;/* * occationaly the auth can get stuck only in host * this especially happens in cases like * url.resolveObject('mailto:local1@domain1', 'local2@domain2') */var authInHost=result.host&&result.host.indexOf('@')>0?result.host.split('@'):false;if(authInHost){result.auth=authInHost.shift();result.hostname=authInHost.shift();result.host=result.hostname;}}mustEndAbs=mustEndAbs||result.host&&srcPath.length;if(mustEndAbs&&!isAbsolute){srcPath.unshift('');}if(srcPath.length>0){result.pathname=srcPath.join('/');}else{result.pathname=null;result.path=null;}// to support request.http if(result.pathname!==null||result.search!==null){result.path=(result.pathname?result.pathname:'')+(result.search?result.search:'');}result.auth=relative.auth||result.auth;result.slashes=result.slashes||relative.slashes;result.href=result.format();return result;};Url.prototype.parseHost=function(){var host=this.host;var port=portPattern.exec(host);if(port){port=port[0];if(port!==':'){this.port=port.substr(1);}host=host.substr(0,host.length-port.length);}if(host){this.hostname=host;}};exports.parse=urlParse;exports.resolve=urlResolve;exports.resolveObject=urlResolveObject;exports.format=urlFormat;exports.Url=Url; /***/ }), /***/ 12263: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var GetIntrinsic=__webpack_require__(35049);var callBound=__webpack_require__(95736);var inspect=__webpack_require__(73271);var $TypeError=__webpack_require__(93767);var $Map=GetIntrinsic('%Map%',true);/** @type {(thisArg: Map, key: K) => V} */var $mapGet=callBound('Map.prototype.get',true);/** @type {(thisArg: Map, key: K, value: V) => void} */var $mapSet=callBound('Map.prototype.set',true);/** @type {(thisArg: Map, key: K) => boolean} */var $mapHas=callBound('Map.prototype.has',true);/** @type {(thisArg: Map, key: K) => boolean} */var $mapDelete=callBound('Map.prototype.delete',true);/** @type {(thisArg: Map) => number} */var $mapSize=callBound('Map.prototype.size',true);/** @type {import('.')} */module.exports=!!$Map&&/** @type {Exclude} */function getSideChannelMap(){/** @typedef {ReturnType} Channel *//** @typedef {Parameters[0]} K *//** @typedef {Parameters[1]} V *//** @type {Map | undefined} */var $m;/** @type {Channel} */var channel={assert:function(key){if(!channel.has(key)){throw new $TypeError('Side channel does not contain '+inspect(key));}},'delete':function(key){if($m){var result=$mapDelete($m,key);if($mapSize($m)===0){$m=void undefined;}return result;}return false;},get:function(key){// eslint-disable-line consistent-return if($m){return $mapGet($m,key);}},has:function(key){if($m){return $mapHas($m,key);}return false;},set:function(key,value){if(!$m){// @ts-expect-error TS can't handle narrowing a variable inside a closure $m=new $Map();}$mapSet($m,key,value);}};// @ts-expect-error TODO: figure out why TS is erroring here return channel;}; /***/ }), /***/ 16019: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var origSymbol=typeof Symbol!=='undefined'&&Symbol;var hasSymbolSham=__webpack_require__(75985);/** @type {import('.')} */module.exports=function hasNativeSymbols(){if(typeof origSymbol!=='function'){return false;}if(typeof Symbol!=='function'){return false;}if(typeof origSymbol('foo')!=='symbol'){return false;}if(typeof Symbol('bar')!=='symbol'){return false;}return hasSymbolSham();}; /***/ }), /***/ 22060: /***/ (function(module) { "use strict"; /** @type {import('./Reflect.getPrototypeOf')} */module.exports=typeof Reflect!=='undefined'&&Reflect.getPrototypeOf||null; /***/ }), /***/ 29382: /***/ (function(module) { "use strict"; /** @type {import('./range')} */module.exports=RangeError; /***/ }), /***/ 29499: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var GetIntrinsic=__webpack_require__(35049);var callBound=__webpack_require__(95736);var inspect=__webpack_require__(73271);var getSideChannelMap=__webpack_require__(12263);var $TypeError=__webpack_require__(93767);var $WeakMap=GetIntrinsic('%WeakMap%',true);/** @type {(thisArg: WeakMap, key: K) => V} */var $weakMapGet=callBound('WeakMap.prototype.get',true);/** @type {(thisArg: WeakMap, key: K, value: V) => void} */var $weakMapSet=callBound('WeakMap.prototype.set',true);/** @type {(thisArg: WeakMap, key: K) => boolean} */var $weakMapHas=callBound('WeakMap.prototype.has',true);/** @type {(thisArg: WeakMap, key: K) => boolean} */var $weakMapDelete=callBound('WeakMap.prototype.delete',true);/** @type {import('.')} */module.exports=$WeakMap?/** @type {Exclude} */function getSideChannelWeakMap(){/** @typedef {ReturnType} Channel *//** @typedef {Parameters[0]} K *//** @typedef {Parameters[1]} V *//** @type {WeakMap | undefined} */var $wm;/** @type {Channel | undefined} */var $m;/** @type {Channel} */var channel={assert:function(key){if(!channel.has(key)){throw new $TypeError('Side channel does not contain '+inspect(key));}},'delete':function(key){if($WeakMap&&key&&(typeof key==='object'||typeof key==='function')){if($wm){return $weakMapDelete($wm,key);}}else if(getSideChannelMap){if($m){return $m['delete'](key);}}return false;},get:function(key){if($WeakMap&&key&&(typeof key==='object'||typeof key==='function')){if($wm){return $weakMapGet($wm,key);}}return $m&&$m.get(key);},has:function(key){if($WeakMap&&key&&(typeof key==='object'||typeof key==='function')){if($wm){return $weakMapHas($wm,key);}}return!!$m&&$m.has(key);},set:function(key,value){if($WeakMap&&key&&(typeof key==='object'||typeof key==='function')){if(!$wm){$wm=new $WeakMap();}$weakMapSet($wm,key,value);}else if(getSideChannelMap){if(!$m){$m=getSideChannelMap();}// eslint-disable-next-line no-extra-parens /** @type {NonNullable} */$m.set(key,value);}}};// @ts-expect-error TODO: figure out why this is erroring return channel;}:getSideChannelMap; /***/ }), /***/ 30708: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var callBind=__webpack_require__(77434);var gOPD=__webpack_require__(37391);var hasProtoAccessor;try{// eslint-disable-next-line no-extra-parens, no-proto hasProtoAccessor=/** @type {{ __proto__?: typeof Array.prototype }} */[].__proto__===Array.prototype;}catch(e){if(!e||typeof e!=='object'||!('code'in e)||e.code!=='ERR_PROTO_ACCESS'){throw e;}}// eslint-disable-next-line no-extra-parens var desc=!!hasProtoAccessor&&gOPD&&gOPD(Object.prototype,/** @type {keyof typeof Object.prototype} */'__proto__');var $Object=Object;var $getPrototypeOf=$Object.getPrototypeOf;/** @type {import('./get')} */module.exports=desc&&typeof desc.get==='function'?callBind([desc.get]):typeof $getPrototypeOf==='function'?/** @type {import('./get')} */function getDunder(value){// eslint-disable-next-line eqeqeq return $getPrototypeOf(value==null?value:$Object(value));}:false; /***/ }), /***/ 30816: /***/ (function(module) { "use strict"; /** @type {import('./syntax')} */module.exports=SyntaxError; /***/ }), /***/ 31506: /***/ (function(__unused_webpack_module, exports) { "use strict"; exports.byteLength=byteLength;exports.toByteArray=toByteArray;exports.fromByteArray=fromByteArray;var lookup=[];var revLookup=[];var Arr=typeof Uint8Array!=='undefined'?Uint8Array:Array;var code='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';for(var i=0,len=code.length;i0){throw new Error('Invalid string. Length must be a multiple of 4');}// Trim off extra bytes after placeholder bytes are found // See: https://github.com/beatgammit/base64-js/issues/42 var validLen=b64.indexOf('=');if(validLen===-1)validLen=len;var placeHoldersLen=validLen===len?0:4-validLen%4;return[validLen,placeHoldersLen];}// base64 is 4/3 + up to two characters of the original data function byteLength(b64){var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function _byteLength(b64,validLen,placeHoldersLen){return(validLen+placeHoldersLen)*3/4-placeHoldersLen;}function toByteArray(b64){var tmp;var lens=getLens(b64);var validLen=lens[0];var placeHoldersLen=lens[1];var arr=new Arr(_byteLength(b64,validLen,placeHoldersLen));var curByte=0;// if there are placeholders, only get up to the last complete 4 chars var len=placeHoldersLen>0?validLen-4:validLen;var i;for(i=0;i>16&0xFF;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===2){tmp=revLookup[b64.charCodeAt(i)]<<2|revLookup[b64.charCodeAt(i+1)]>>4;arr[curByte++]=tmp&0xFF;}if(placeHoldersLen===1){tmp=revLookup[b64.charCodeAt(i)]<<10|revLookup[b64.charCodeAt(i+1)]<<4|revLookup[b64.charCodeAt(i+2)]>>2;arr[curByte++]=tmp>>8&0xFF;arr[curByte++]=tmp&0xFF;}return arr;}function tripletToBase64(num){return lookup[num>>18&0x3F]+lookup[num>>12&0x3F]+lookup[num>>6&0x3F]+lookup[num&0x3F];}function encodeChunk(uint8,start,end){var tmp;var output=[];for(var i=start;ilen2?len2:i+maxChunkLength));}// pad the end with zeros, but make sure to not forget the extra bytes if(extraBytes===1){tmp=uint8[len-1];parts.push(lookup[tmp>>2]+lookup[tmp<<4&0x3F]+'==');}else if(extraBytes===2){tmp=(uint8[len-2]<<8)+uint8[len-1];parts.push(lookup[tmp>>10]+lookup[tmp>>4&0x3F]+lookup[tmp<<2&0x3F]+'=');}return parts.join('');} /***/ }), /***/ 32429: /***/ (function(module) { "use strict"; /** @type {import('./uri')} */module.exports=URIError; /***/ }), /***/ 33556: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var $Object=__webpack_require__(85344);/** @type {import('./Object.getPrototypeOf')} */module.exports=$Object.getPrototypeOf||null; /***/ }), /***/ 33968: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var reflectGetProto=__webpack_require__(22060);var originalGetProto=__webpack_require__(33556);var getDunderProto=__webpack_require__(30708);/** @type {import('.')} */module.exports=reflectGetProto?function getProto(O){// @ts-expect-error TS can't narrow inside a closure, for some reason return reflectGetProto(O);}:originalGetProto?function getProto(O){if(!O||typeof O!=='object'&&typeof O!=='function'){throw new TypeError('getProto: not an object');}// @ts-expect-error TS can't narrow inside a closure, for some reason return originalGetProto(O);}:getDunderProto?function getProto(O){// @ts-expect-error TS can't narrow inside a closure, for some reason return getDunderProto(O);}:null; /***/ }), /***/ 35049: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var undefined;var $Object=__webpack_require__(85344);var $Error=__webpack_require__(94067);var $EvalError=__webpack_require__(58809);var $RangeError=__webpack_require__(29382);var $ReferenceError=__webpack_require__(52166);var $SyntaxError=__webpack_require__(30816);var $TypeError=__webpack_require__(93767);var $URIError=__webpack_require__(32429);var abs=__webpack_require__(52126);var floor=__webpack_require__(5820);var max=__webpack_require__(73368);var min=__webpack_require__(60966);var pow=__webpack_require__(732);var round=__webpack_require__(10818);var sign=__webpack_require__(93425);var $Function=Function;// eslint-disable-next-line consistent-return var getEvalledConstructor=function(expressionSyntax){try{return $Function('"use strict"; return ('+expressionSyntax+').constructor;')();}catch(e){}};var $gOPD=__webpack_require__(37391);var $defineProperty=__webpack_require__(85835);var throwTypeError=function(){throw new $TypeError();};var ThrowTypeError=$gOPD?function(){try{// eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee;// IE 8 does not throw here return throwTypeError;}catch(calleeThrows){try{// IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments,'callee').get;}catch(gOPDthrows){return throwTypeError;}}}():throwTypeError;var hasSymbols=__webpack_require__(16019)();var getProto=__webpack_require__(33968);var $ObjectGPO=__webpack_require__(33556);var $ReflectGPO=__webpack_require__(22060);var $apply=__webpack_require__(84750);var $call=__webpack_require__(51008);var needsEval={};var TypedArray=typeof Uint8Array==='undefined'||!getProto?undefined:getProto(Uint8Array);var INTRINSICS={__proto__:null,'%AggregateError%':typeof AggregateError==='undefined'?undefined:AggregateError,'%Array%':Array,'%ArrayBuffer%':typeof ArrayBuffer==='undefined'?undefined:ArrayBuffer,'%ArrayIteratorPrototype%':hasSymbols&&getProto?getProto([][Symbol.iterator]()):undefined,'%AsyncFromSyncIteratorPrototype%':undefined,'%AsyncFunction%':needsEval,'%AsyncGenerator%':needsEval,'%AsyncGeneratorFunction%':needsEval,'%AsyncIteratorPrototype%':needsEval,'%Atomics%':typeof Atomics==='undefined'?undefined:Atomics,'%BigInt%':typeof BigInt==='undefined'?undefined:BigInt,'%BigInt64Array%':typeof BigInt64Array==='undefined'?undefined:BigInt64Array,'%BigUint64Array%':typeof BigUint64Array==='undefined'?undefined:BigUint64Array,'%Boolean%':Boolean,'%DataView%':typeof DataView==='undefined'?undefined:DataView,'%Date%':Date,'%decodeURI%':decodeURI,'%decodeURIComponent%':decodeURIComponent,'%encodeURI%':encodeURI,'%encodeURIComponent%':encodeURIComponent,'%Error%':$Error,'%eval%':eval,// eslint-disable-line no-eval '%EvalError%':$EvalError,'%Float16Array%':typeof Float16Array==='undefined'?undefined:Float16Array,'%Float32Array%':typeof Float32Array==='undefined'?undefined:Float32Array,'%Float64Array%':typeof Float64Array==='undefined'?undefined:Float64Array,'%FinalizationRegistry%':typeof FinalizationRegistry==='undefined'?undefined:FinalizationRegistry,'%Function%':$Function,'%GeneratorFunction%':needsEval,'%Int8Array%':typeof Int8Array==='undefined'?undefined:Int8Array,'%Int16Array%':typeof Int16Array==='undefined'?undefined:Int16Array,'%Int32Array%':typeof Int32Array==='undefined'?undefined:Int32Array,'%isFinite%':isFinite,'%isNaN%':isNaN,'%IteratorPrototype%':hasSymbols&&getProto?getProto(getProto([][Symbol.iterator]())):undefined,'%JSON%':typeof JSON==='object'?JSON:undefined,'%Map%':typeof Map==='undefined'?undefined:Map,'%MapIteratorPrototype%':typeof Map==='undefined'||!hasSymbols||!getProto?undefined:getProto(new Map()[Symbol.iterator]()),'%Math%':Math,'%Number%':Number,'%Object%':$Object,'%Object.getOwnPropertyDescriptor%':$gOPD,'%parseFloat%':parseFloat,'%parseInt%':parseInt,'%Promise%':typeof Promise==='undefined'?undefined:Promise,'%Proxy%':typeof Proxy==='undefined'?undefined:Proxy,'%RangeError%':$RangeError,'%ReferenceError%':$ReferenceError,'%Reflect%':typeof Reflect==='undefined'?undefined:Reflect,'%RegExp%':RegExp,'%Set%':typeof Set==='undefined'?undefined:Set,'%SetIteratorPrototype%':typeof Set==='undefined'||!hasSymbols||!getProto?undefined:getProto(new Set()[Symbol.iterator]()),'%SharedArrayBuffer%':typeof SharedArrayBuffer==='undefined'?undefined:SharedArrayBuffer,'%String%':String,'%StringIteratorPrototype%':hasSymbols&&getProto?getProto(''[Symbol.iterator]()):undefined,'%Symbol%':hasSymbols?Symbol:undefined,'%SyntaxError%':$SyntaxError,'%ThrowTypeError%':ThrowTypeError,'%TypedArray%':TypedArray,'%TypeError%':$TypeError,'%Uint8Array%':typeof Uint8Array==='undefined'?undefined:Uint8Array,'%Uint8ClampedArray%':typeof Uint8ClampedArray==='undefined'?undefined:Uint8ClampedArray,'%Uint16Array%':typeof Uint16Array==='undefined'?undefined:Uint16Array,'%Uint32Array%':typeof Uint32Array==='undefined'?undefined:Uint32Array,'%URIError%':$URIError,'%WeakMap%':typeof WeakMap==='undefined'?undefined:WeakMap,'%WeakRef%':typeof WeakRef==='undefined'?undefined:WeakRef,'%WeakSet%':typeof WeakSet==='undefined'?undefined:WeakSet,'%Function.prototype.call%':$call,'%Function.prototype.apply%':$apply,'%Object.defineProperty%':$defineProperty,'%Object.getPrototypeOf%':$ObjectGPO,'%Math.abs%':abs,'%Math.floor%':floor,'%Math.max%':max,'%Math.min%':min,'%Math.pow%':pow,'%Math.round%':round,'%Math.sign%':sign,'%Reflect.getPrototypeOf%':$ReflectGPO};if(getProto){try{null.error;// eslint-disable-line no-unused-expressions }catch(e){// https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 var errorProto=getProto(getProto(e));INTRINSICS['%Error.prototype%']=errorProto;}}var doEval=function doEval(name){var value;if(name==='%AsyncFunction%'){value=getEvalledConstructor('async function () {}');}else if(name==='%GeneratorFunction%'){value=getEvalledConstructor('function* () {}');}else if(name==='%AsyncGeneratorFunction%'){value=getEvalledConstructor('async function* () {}');}else if(name==='%AsyncGenerator%'){var fn=doEval('%AsyncGeneratorFunction%');if(fn){value=fn.prototype;}}else if(name==='%AsyncIteratorPrototype%'){var gen=doEval('%AsyncGenerator%');if(gen&&getProto){value=getProto(gen.prototype);}}INTRINSICS[name]=value;return value;};var LEGACY_ALIASES={__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']};var bind=__webpack_require__(10539);var hasOwn=__webpack_require__(1697);var $concat=bind.call($call,Array.prototype.concat);var $spliceApply=bind.call($apply,Array.prototype.splice);var $replace=bind.call($call,String.prototype.replace);var $strSlice=bind.call($call,String.prototype.slice);var $exec=bind.call($call,RegExp.prototype.exec);/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */var rePropName=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;var reEscapeChar=/\\(\\)?/g;/** Used to match backslashes in property paths. */var stringToPath=function stringToPath(string){var first=$strSlice(string,0,1);var last=$strSlice(string,-1);if(first==='%'&&last!=='%'){throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');}else if(last==='%'&&first!=='%'){throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');}var result=[];$replace(string,rePropName,function(match,number,quote,subString){result[result.length]=quote?$replace(subString,reEscapeChar,'$1'):number||match;});return result;};/* end adaptation */var getBaseIntrinsic=function getBaseIntrinsic(name,allowMissing){var intrinsicName=name;var alias;if(hasOwn(LEGACY_ALIASES,intrinsicName)){alias=LEGACY_ALIASES[intrinsicName];intrinsicName='%'+alias[0]+'%';}if(hasOwn(INTRINSICS,intrinsicName)){var value=INTRINSICS[intrinsicName];if(value===needsEval){value=doEval(intrinsicName);}if(typeof value==='undefined'&&!allowMissing){throw new $TypeError('intrinsic '+name+' exists, but is not available. Please file an issue!');}return{alias:alias,name:intrinsicName,value:value};}throw new $SyntaxError('intrinsic '+name+' does not exist!');};module.exports=function GetIntrinsic(name,allowMissing){if(typeof name!=='string'||name.length===0){throw new $TypeError('intrinsic name must be a non-empty string');}if(arguments.length>1&&typeof allowMissing!=='boolean'){throw new $TypeError('"allowMissing" argument must be a boolean');}if($exec(/^%?[^%]*%?$/,name)===null){throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name');}var parts=stringToPath(name);var intrinsicBaseName=parts.length>0?parts[0]:'';var intrinsic=getBaseIntrinsic('%'+intrinsicBaseName+'%',allowMissing);var intrinsicRealName=intrinsic.name;var value=intrinsic.value;var skipFurtherCaching=false;var alias=intrinsic.alias;if(alias){intrinsicBaseName=alias[0];$spliceApply(parts,$concat([0,1],alias));}for(var i=1,isOwn=true;i=parts.length){var desc=$gOPD(value,part);isOwn=!!desc;// By convention, when a data property is converted to an accessor // property to emulate a data property that does not suffer from // the override mistake, that accessor's getter is marked with // an `originalValue` property. Here, when we detect this, we // uphold the illusion by pretending to see that original data // property, i.e., returning the value rather than the getter // itself. if(isOwn&&'get'in desc&&!('originalValue'in desc.get)){value=desc.get;}else{value=value[part];}}else{isOwn=hasOwn(value,part);value=value[part];}if(isOwn&&!skipFurtherCaching){INTRINSICS[intrinsicRealName]=value;}}}return value;}; /***/ }), /***/ 37391: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; /** @type {import('.')} */var $gOPD=__webpack_require__(4089);if($gOPD){try{$gOPD([],'length');}catch(e){// IE 8 has a broken gOPD $gOPD=null;}}module.exports=$gOPD; /***/ }), /***/ 45202: /***/ (function(module) { // shim for using process in browser var process=module.exports={};// cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout;var cachedClearTimeout;function defaultSetTimout(){throw new Error('setTimeout has not been defined');}function defaultClearTimeout(){throw new Error('clearTimeout has not been defined');}(function(){try{if(typeof setTimeout==='function'){cachedSetTimeout=setTimeout;}else{cachedSetTimeout=defaultSetTimout;}}catch(e){cachedSetTimeout=defaultSetTimout;}try{if(typeof clearTimeout==='function'){cachedClearTimeout=clearTimeout;}else{cachedClearTimeout=defaultClearTimeout;}}catch(e){cachedClearTimeout=defaultClearTimeout;}})();function runTimeout(fun){if(cachedSetTimeout===setTimeout){//normal enviroments in sane situations return setTimeout(fun,0);}// if setTimeout wasn't available but was latter defined if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout){cachedSetTimeout=setTimeout;return setTimeout(fun,0);}try{// when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun,0);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null,fun,0);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this,fun,0);}}}function runClearTimeout(marker){if(cachedClearTimeout===clearTimeout){//normal enviroments in sane situations return clearTimeout(marker);}// if clearTimeout wasn't available but was latter defined if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout){cachedClearTimeout=clearTimeout;return clearTimeout(marker);}try{// when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker);}catch(e){try{// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null,marker);}catch(e){// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this,marker);}}}var queue=[];var draining=false;var currentQueue;var queueIndex=-1;function cleanUpNextTick(){if(!draining||!currentQueue){return;}draining=false;if(currentQueue.length){queue=currentQueue.concat(queue);}else{queueIndex=-1;}if(queue.length){drainQueue();}}function drainQueue(){if(draining){return;}var timeout=runTimeout(cleanUpNextTick);draining=true;var len=queue.length;while(len){currentQueue=queue;queue=[];while(++queueIndex1){for(var i=1;i-1){return val.split(',');}if(options.throwOnLimitExceeded&¤tArrayLength>=options.arrayLimit){throw new RangeError('Array limit exceeded. Only '+options.arrayLimit+' element'+(options.arrayLimit===1?'':'s')+' allowed in an array.');}return val;};// This is what browsers will submit when the ✓ character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the ✓ character, such as us-ascii. var isoSentinel='utf8=%26%2310003%3B';// encodeURIComponent('✓') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel='utf8=%E2%9C%93';// encodeURIComponent('✓') var parseValues=function parseQueryStringValues(str,options){var obj={__proto__:null};var cleanStr=options.ignoreQueryPrefix?str.replace(/^\?/,''):str;cleanStr=cleanStr.replace(/%5B/gi,'[').replace(/%5D/gi,']');var limit=options.parameterLimit===Infinity?undefined:options.parameterLimit;var parts=cleanStr.split(options.delimiter,options.throwOnLimitExceeded?limit+1:limit);if(options.throwOnLimitExceeded&&parts.length>limit){throw new RangeError('Parameter limit exceeded. Only '+limit+' parameter'+(limit===1?'':'s')+' allowed.');}var skipIndex=-1;// Keep track of where the utf8 sentinel was found var i;var charset=options.charset;if(options.charsetSentinel){for(i=0;i-1){val=isArray(val)?[val]:val;}var existing=has.call(obj,key);if(existing&&options.duplicates==='combine'){obj[key]=utils.combine(obj[key],val);}else if(!existing||options.duplicates==='last'){obj[key]=val;}}return obj;};var parseObject=function(chain,val,options,valuesParsed){var currentArrayLength=0;if(chain.length>0&&chain[chain.length-1]==='[]'){var parentKey=chain.slice(0,-1).join('');currentArrayLength=Array.isArray(val)&&val[parentKey]?val[parentKey].length:0;}var leaf=valuesParsed?val:parseArrayValue(val,options,currentArrayLength);for(var i=chain.length-1;i>=0;--i){var obj;var root=chain[i];if(root==='[]'&&options.parseArrays){obj=options.allowEmptyArrays&&(leaf===''||options.strictNullHandling&&leaf===null)?[]:utils.combine([],leaf);}else{obj=options.plainObjects?{__proto__:null}:{};var cleanRoot=root.charAt(0)==='['&&root.charAt(root.length-1)===']'?root.slice(1,-1):root;var decodedRoot=options.decodeDotInKeys?cleanRoot.replace(/%2E/g,'.'):cleanRoot;var index=parseInt(decodedRoot,10);if(!options.parseArrays&&decodedRoot===''){obj={0:leaf};}else if(!isNaN(index)&&root!==decodedRoot&&String(index)===decodedRoot&&index>=0&&options.parseArrays&&index<=options.arrayLimit){obj=[];obj[index]=leaf;}else if(decodedRoot!=='__proto__'){obj[decodedRoot]=leaf;}}leaf=obj;}return leaf;};var parseKeys=function parseQueryStringKeys(givenKey,val,options,valuesParsed){if(!givenKey){return;}// Transform dot notation to bracket notation var key=options.allowDots?givenKey.replace(/\.([^.[]+)/g,'[$1]'):givenKey;// The regex chunks var brackets=/(\[[^[\]]*])/;var child=/(\[[^[\]]*])/g;// Get the parent var segment=options.depth>0&&brackets.exec(key);var parent=segment?key.slice(0,segment.index):key;// Stash the parent if it exists var keys=[];if(parent){// If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if(!options.plainObjects&&has.call(Object.prototype,parent)){if(!options.allowPrototypes){return;}}keys.push(parent);}// Loop through children appending to the array until we hit depth var i=0;while(options.depth>0&&(segment=child.exec(key))!==null&&i2){var lastSlashIndex=res.lastIndexOf('/');if(lastSlashIndex!==res.length-1){if(lastSlashIndex===-1){res='';lastSegmentLength=0;}else{res=res.slice(0,lastSlashIndex);lastSegmentLength=res.length-1-res.lastIndexOf('/');}lastSlash=i;dots=0;continue;}}else if(res.length===2||res.length===1){res='';lastSegmentLength=0;lastSlash=i;dots=0;continue;}}if(allowAboveRoot){if(res.length>0)res+='/..';else res='..';lastSegmentLength=2;}}else{if(res.length>0)res+='/'+path.slice(lastSlash+1,i);else res=path.slice(lastSlash+1,i);lastSegmentLength=i-lastSlash-1;}lastSlash=i;dots=0;}else if(code===46/*.*/&&dots!==-1){++dots;}else{dots=-1;}}return res;}function _format(sep,pathObject){var dir=pathObject.dir||pathObject.root;var base=pathObject.base||(pathObject.name||'')+(pathObject.ext||'');if(!dir){return base;}if(dir===pathObject.root){return dir+base;}return dir+sep+base;}var posix={// path.resolve([from ...], to) resolve:function resolve(){var resolvedPath='';var resolvedAbsolute=false;var cwd;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path;if(i>=0)path=arguments[i];else{if(cwd===undefined)cwd=process.cwd();path=cwd;}assertPath(path);// Skip empty entries if(path.length===0){continue;}resolvedPath=path+'/'+resolvedPath;resolvedAbsolute=path.charCodeAt(0)===47/*/*/;}// At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath=normalizeStringPosix(resolvedPath,!resolvedAbsolute);if(resolvedAbsolute){if(resolvedPath.length>0)return'/'+resolvedPath;else return'/';}else if(resolvedPath.length>0){return resolvedPath;}else{return'.';}},normalize:function normalize(path){assertPath(path);if(path.length===0)return'.';var isAbsolute=path.charCodeAt(0)===47/*/*/;var trailingSeparator=path.charCodeAt(path.length-1)===47/*/*/;// Normalize the path path=normalizeStringPosix(path,!isAbsolute);if(path.length===0&&!isAbsolute)path='.';if(path.length>0&&trailingSeparator)path+='/';if(isAbsolute)return'/'+path;return path;},isAbsolute:function isAbsolute(path){assertPath(path);return path.length>0&&path.charCodeAt(0)===47/*/*/;},join:function join(){if(arguments.length===0)return'.';var joined;for(var i=0;i0){if(joined===undefined)joined=arg;else joined+='/'+arg;}}if(joined===undefined)return'.';return posix.normalize(joined);},relative:function relative(from,to){assertPath(from);assertPath(to);if(from===to)return'';from=posix.resolve(from);to=posix.resolve(to);if(from===to)return'';// Trim any leading backslashes var fromStart=1;for(;fromStartlength){if(to.charCodeAt(toStart+i)===47/*/*/){// We get here if `from` is the exact base path for `to`. // For example: from='/foo/bar'; to='/foo/bar/baz' return to.slice(toStart+i+1);}else if(i===0){// We get here if `from` is the root // For example: from='/'; to='/foo' return to.slice(toStart+i);}}else if(fromLen>length){if(from.charCodeAt(fromStart+i)===47/*/*/){// We get here if `to` is the exact base path for `from`. // For example: from='/foo/bar/baz'; to='/foo/bar' lastCommonSep=i;}else if(i===0){// We get here if `to` is the root. // For example: from='/foo'; to='/' lastCommonSep=0;}}break;}var fromCode=from.charCodeAt(fromStart+i);var toCode=to.charCodeAt(toStart+i);if(fromCode!==toCode)break;else if(fromCode===47/*/*/)lastCommonSep=i;}var out='';// Generate the relative path based on the path difference between `to` // and `from` for(i=fromStart+lastCommonSep+1;i<=fromEnd;++i){if(i===fromEnd||from.charCodeAt(i)===47/*/*/){if(out.length===0)out+='..';else out+='/..';}}// Lastly, append the rest of the destination (`to`) path that comes after // the common path parts if(out.length>0)return out+to.slice(toStart+lastCommonSep);else{toStart+=lastCommonSep;if(to.charCodeAt(toStart)===47/*/*/)++toStart;return to.slice(toStart);}},_makeLong:function _makeLong(path){return path;},dirname:function dirname(path){assertPath(path);if(path.length===0)return'.';var code=path.charCodeAt(0);var hasRoot=code===47/*/*/;var end=-1;var matchedSlash=true;for(var i=path.length-1;i>=1;--i){code=path.charCodeAt(i);if(code===47/*/*/){if(!matchedSlash){end=i;break;}}else{// We saw the first non-path separator matchedSlash=false;}}if(end===-1)return hasRoot?'/':'.';if(hasRoot&&end===1)return'//';return path.slice(0,end);},basename:function basename(path,ext){if(ext!==undefined&&typeof ext!=='string')throw new TypeError('"ext" argument must be a string');assertPath(path);var start=0;var end=-1;var matchedSlash=true;var i;if(ext!==undefined&&ext.length>0&&ext.length<=path.length){if(ext.length===path.length&&ext===path)return'';var extIdx=ext.length-1;var firstNonSlashEnd=-1;for(i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47/*/*/){// If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if(!matchedSlash){start=i+1;break;}}else{if(firstNonSlashEnd===-1){// We saw the first non-path separator, remember this index in case // we need it if the extension ends up not matching matchedSlash=false;firstNonSlashEnd=i+1;}if(extIdx>=0){// Try to match the explicit extension if(code===ext.charCodeAt(extIdx)){if(--extIdx===-1){// We matched the extension, so mark this as the end of our path // component end=i;}}else{// Extension does not match, so our result is the entire path // component extIdx=-1;end=firstNonSlashEnd;}}}}if(start===end)end=firstNonSlashEnd;else if(end===-1)end=path.length;return path.slice(start,end);}else{for(i=path.length-1;i>=0;--i){if(path.charCodeAt(i)===47/*/*/){// If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if(!matchedSlash){start=i+1;break;}}else if(end===-1){// We saw the first non-path separator, mark this as the end of our // path component matchedSlash=false;end=i+1;}}if(end===-1)return'';return path.slice(start,end);}},extname:function extname(path){assertPath(path);var startDot=-1;var startPart=0;var end=-1;var matchedSlash=true;// Track the state of characters (if any) we see before our first dot and // after any path separator we find var preDotState=0;for(var i=path.length-1;i>=0;--i){var code=path.charCodeAt(i);if(code===47/*/*/){// If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if(!matchedSlash){startPart=i+1;break;}continue;}if(end===-1){// We saw the first non-path separator, mark this as the end of our // extension matchedSlash=false;end=i+1;}if(code===46/*.*/){// If this is our first dot, mark it as the start of our extension if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1;}else if(startDot!==-1){// We saw a non-dot and non-path separator before our dot, so we should // have a good chance at having a non-empty extension preDotState=-1;}}if(startDot===-1||end===-1||// We saw a non-dot character immediately before the dot preDotState===0||// The (right-most) trimmed path component is exactly '..' preDotState===1&&startDot===end-1&&startDot===startPart+1){return'';}return path.slice(startDot,end);},format:function format(pathObject){if(pathObject===null||typeof pathObject!=='object'){throw new TypeError('The "pathObject" argument must be of type Object. Received type '+typeof pathObject);}return _format('/',pathObject);},parse:function parse(path){assertPath(path);var ret={root:'',dir:'',base:'',ext:'',name:''};if(path.length===0)return ret;var code=path.charCodeAt(0);var isAbsolute=code===47/*/*/;var start;if(isAbsolute){ret.root='/';start=1;}else{start=0;}var startDot=-1;var startPart=0;var end=-1;var matchedSlash=true;var i=path.length-1;// Track the state of characters (if any) we see before our first dot and // after any path separator we find var preDotState=0;// Get non-dir info for(;i>=start;--i){code=path.charCodeAt(i);if(code===47/*/*/){// If we reached a path separator that was not part of a set of path // separators at the end of the string, stop now if(!matchedSlash){startPart=i+1;break;}continue;}if(end===-1){// We saw the first non-path separator, mark this as the end of our // extension matchedSlash=false;end=i+1;}if(code===46/*.*/){// If this is our first dot, mark it as the start of our extension if(startDot===-1)startDot=i;else if(preDotState!==1)preDotState=1;}else if(startDot!==-1){// We saw a non-dot and non-path separator before our dot, so we should // have a good chance at having a non-empty extension preDotState=-1;}}if(startDot===-1||end===-1||// We saw a non-dot character immediately before the dot preDotState===0||// The (right-most) trimmed path component is exactly '..' preDotState===1&&startDot===end-1&&startDot===startPart+1){if(end!==-1){if(startPart===0&&isAbsolute)ret.base=ret.name=path.slice(1,end);else ret.base=ret.name=path.slice(startPart,end);}}else{if(startPart===0&&isAbsolute){ret.name=path.slice(1,startDot);ret.base=path.slice(1,end);}else{ret.name=path.slice(startPart,startDot);ret.base=path.slice(startPart,end);}ret.ext=path.slice(startDot,end);}if(startPart>0)ret.dir=path.slice(0,startPart-1);else if(isAbsolute)ret.dir='/';return ret;},sep:'/',delimiter:':',win32:null,posix:null};posix.posix=posix;module.exports=posix; /***/ }), /***/ 58809: /***/ (function(module) { "use strict"; /** @type {import('./eval')} */module.exports=EvalError; /***/ }), /***/ 60271: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var inspect=__webpack_require__(73271);var $TypeError=__webpack_require__(93767);/* * This function traverses the list returning the node corresponding to the given key. * * That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. * By doing so, all the recently used nodes can be accessed relatively quickly. *//** @type {import('./list.d.ts').listGetNode} */// eslint-disable-next-line consistent-return var listGetNode=function(list,key,isDelete){/** @type {typeof list | NonNullable<(typeof list)['next']>} */var prev=list;/** @type {(typeof list)['next']} */var curr;// eslint-disable-next-line eqeqeq for(;(curr=prev.next)!=null;prev=curr){if(curr.key===key){prev.next=curr.next;if(!isDelete){// eslint-disable-next-line no-extra-parens curr.next=/** @type {NonNullable} */list.next;list.next=curr;// eslint-disable-line no-param-reassign }return curr;}}};/** @type {import('./list.d.ts').listGet} */var listGet=function(objects,key){if(!objects){return void undefined;}var node=listGetNode(objects,key);return node&&node.value;};/** @type {import('./list.d.ts').listSet} */var listSet=function(objects,key,value){var node=listGetNode(objects,key);if(node){node.value=value;}else{// Prepend the new node to the beginning of the list objects.next=/** @type {import('./list.d.ts').ListNode} */{// eslint-disable-line no-param-reassign, no-extra-parens key:key,next:objects.next,value:value};}};/** @type {import('./list.d.ts').listHas} */var listHas=function(objects,key){if(!objects){return false;}return!!listGetNode(objects,key);};/** @type {import('./list.d.ts').listDelete} */// eslint-disable-next-line consistent-return var listDelete=function(objects,key){if(objects){return listGetNode(objects,key,true);}};/** @type {import('.')} */module.exports=function getSideChannelList(){/** @typedef {ReturnType} Channel *//** @typedef {Parameters[0]} K *//** @typedef {Parameters[1]} V *//** @type {import('./list.d.ts').RootNode | undefined} */var $o;/** @type {Channel} */var channel={assert:function(key){if(!channel.has(key)){throw new $TypeError('Side channel does not contain '+inspect(key));}},'delete':function(key){var root=$o&&$o.next;var deletedNode=listDelete($o,key);if(deletedNode&&root&&root===deletedNode){$o=void undefined;}return!!deletedNode;},get:function(key){return listGet($o,key);},has:function(key){return listHas($o,key);},set:function(key,value){if(!$o){// Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head $o={next:void undefined};}// eslint-disable-next-line no-extra-parens listSet(/** @type {NonNullable} */$o,key,value);}};// @ts-expect-error TODO: figure out why this is erroring return channel;}; /***/ }), /***/ 60966: /***/ (function(module) { "use strict"; /** @type {import('./min')} */module.exports=Math.min; /***/ }), /***/ 62520: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var getSideChannel=__webpack_require__(67124);var utils=__webpack_require__(92972);var formats=__webpack_require__(10681);var has=Object.prototype.hasOwnProperty;var arrayPrefixGenerators={brackets:function brackets(prefix){return prefix+'[]';},comma:'comma',indices:function indices(prefix,key){return prefix+'['+key+']';},repeat:function repeat(prefix){return prefix;}};var isArray=Array.isArray;var push=Array.prototype.push;var pushToArray=function(arr,valueOrArray){push.apply(arr,isArray(valueOrArray)?valueOrArray:[valueOrArray]);};var toISO=Date.prototype.toISOString;var defaultFormat=formats['default'];var defaults={addQueryPrefix:false,allowDots:false,allowEmptyArrays:false,arrayFormat:'indices',charset:'utf-8',charsetSentinel:false,commaRoundTrip:false,delimiter:'&',encode:true,encodeDotInKeys:false,encoder:utils.encode,encodeValuesOnly:false,filter:void undefined,format:defaultFormat,formatter:formats.formatters[defaultFormat],// deprecated indices:false,serializeDate:function serializeDate(date){return toISO.call(date);},skipNulls:false,strictNullHandling:false};var isNonNullishPrimitive=function isNonNullishPrimitive(v){return typeof v==='string'||typeof v==='number'||typeof v==='boolean'||typeof v==='symbol'||typeof v==='bigint';};var sentinel={};var stringify=function stringify(object,prefix,generateArrayPrefix,commaRoundTrip,allowEmptyArrays,strictNullHandling,skipNulls,encodeDotInKeys,encoder,filter,sort,allowDots,serializeDate,format,formatter,encodeValuesOnly,charset,sideChannel){var obj=object;var tmpSc=sideChannel;var step=0;var findFlag=false;while((tmpSc=tmpSc.get(sentinel))!==void undefined&&!findFlag){// Where object last appeared in the ref tree var pos=tmpSc.get(object);step+=1;if(typeof pos!=='undefined'){if(pos===step){throw new RangeError('Cyclic object value');}else{findFlag=true;// Break while }}if(typeof tmpSc.get(sentinel)==='undefined'){step=0;}}if(typeof filter==='function'){obj=filter(prefix,obj);}else if(obj instanceof Date){obj=serializeDate(obj);}else if(generateArrayPrefix==='comma'&&isArray(obj)){obj=utils.maybeMap(obj,function(value){if(value instanceof Date){return serializeDate(value);}return value;});}if(obj===null){if(strictNullHandling){return encoder&&!encodeValuesOnly?encoder(prefix,defaults.encoder,charset,'key',format):prefix;}obj='';}if(isNonNullishPrimitive(obj)||utils.isBuffer(obj)){if(encoder){var keyValue=encodeValuesOnly?prefix:encoder(prefix,defaults.encoder,charset,'key',format);return[formatter(keyValue)+'='+formatter(encoder(obj,defaults.encoder,charset,'value',format))];}return[formatter(prefix)+'='+formatter(String(obj))];}var values=[];if(typeof obj==='undefined'){return values;}var objKeys;if(generateArrayPrefix==='comma'&&isArray(obj)){// we need to join elements in if(encodeValuesOnly&&encoder){obj=utils.maybeMap(obj,encoder);}objKeys=[{value:obj.length>0?obj.join(',')||null:void undefined}];}else if(isArray(filter)){objKeys=filter;}else{var keys=Object.keys(obj);objKeys=sort?keys.sort(sort):keys;}var encodedPrefix=encodeDotInKeys?String(prefix).replace(/\./g,'%2E'):String(prefix);var adjustedPrefix=commaRoundTrip&&isArray(obj)&&obj.length===1?encodedPrefix+'[]':encodedPrefix;if(allowEmptyArrays&&isArray(obj)&&obj.length===0){return adjustedPrefix+'[]';}for(var j=0;j0?prefix+joined:'';}; /***/ }), /***/ 67124: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var $TypeError=__webpack_require__(93767);var inspect=__webpack_require__(73271);var getSideChannelList=__webpack_require__(60271);var getSideChannelMap=__webpack_require__(12263);var getSideChannelWeakMap=__webpack_require__(29499);var makeChannel=getSideChannelWeakMap||getSideChannelMap||getSideChannelList;/** @type {import('.')} */module.exports=function getSideChannel(){/** @typedef {ReturnType} Channel *//** @type {Channel | undefined} */var $channelData;/** @type {Channel} */var channel={assert:function(key){if(!channel.has(key)){throw new $TypeError('Side channel does not contain '+inspect(key));}},'delete':function(key){return!!$channelData&&$channelData['delete'](key);},get:function(key){return $channelData&&$channelData.get(key);},has:function(key){return!!$channelData&&$channelData.has(key);},set:function(key,value){if(!$channelData){$channelData=makeChannel();}$channelData.set(key,value);}};// @ts-expect-error TODO: figure out why this is erroring return channel;}; /***/ }), /***/ 70526: /***/ (function() { (function(){/* Copyright (c) 2016 The Polymer Project Authors. All rights reserved. This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt Code distributed by Google as part of the polymer project is also subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */'use strict';var n=window.Document.prototype.createElement,p=window.Document.prototype.createElementNS,aa=window.Document.prototype.importNode,ba=window.Document.prototype.prepend,ca=window.Document.prototype.append,da=window.DocumentFragment.prototype.prepend,ea=window.DocumentFragment.prototype.append,q=window.Node.prototype.cloneNode,r=window.Node.prototype.appendChild,t=window.Node.prototype.insertBefore,u=window.Node.prototype.removeChild,v=window.Node.prototype.replaceChild,w=Object.getOwnPropertyDescriptor(window.Node.prototype,"textContent"),y=window.Element.prototype.attachShadow,z=Object.getOwnPropertyDescriptor(window.Element.prototype,"innerHTML"),A=window.Element.prototype.getAttribute,B=window.Element.prototype.setAttribute,C=window.Element.prototype.removeAttribute,D=window.Element.prototype.toggleAttribute,E=window.Element.prototype.getAttributeNS,F=window.Element.prototype.setAttributeNS,G=window.Element.prototype.removeAttributeNS,H=window.Element.prototype.insertAdjacentElement,fa=window.Element.prototype.insertAdjacentHTML,ha=window.Element.prototype.prepend,ia=window.Element.prototype.append,ja=window.Element.prototype.before,ka=window.Element.prototype.after,la=window.Element.prototype.replaceWith,ma=window.Element.prototype.remove,na=window.HTMLElement,I=Object.getOwnPropertyDescriptor(window.HTMLElement.prototype,"innerHTML"),oa=window.HTMLElement.prototype.insertAdjacentElement,pa=window.HTMLElement.prototype.insertAdjacentHTML;var qa=new Set();"annotation-xml color-profile font-face font-face-src font-face-uri font-face-format font-face-name missing-glyph".split(" ").forEach(function(a){return qa.add(a);});function ra(a){var b=qa.has(a);a=/^[a-z][.0-9_a-z]*-[-.0-9_a-z]*$/.test(a);return!b&&a;}var sa=document.contains?document.contains.bind(document):document.documentElement.contains.bind(document.documentElement);function J(a){var b=a.isConnected;if(void 0!==b)return b;if(sa(a))return!0;for(;a&&!(a.__CE_isImportDocument||a instanceof Document);)a=a.parentNode||(window.ShadowRoot&&a instanceof ShadowRoot?a.host:void 0);return!(!a||!(a.__CE_isImportDocument||a instanceof Document));}function K(a){var b=a.children;if(b)return Array.prototype.slice.call(b);b=[];for(a=a.firstChild;a;a=a.nextSibling)a.nodeType===Node.ELEMENT_NODE&&b.push(a);return b;}function L(a,b){for(;b&&b!==a&&!b.nextSibling;)b=b.parentNode;return b&&b!==a?b.nextSibling:null;}function M(a,b,d){for(var f=a;f;){if(f.nodeType===Node.ELEMENT_NODE){var c=f;b(c);var e=c.localName;if("link"===e&&"import"===c.getAttribute("rel")){f=c.import;void 0===d&&(d=new Set());if(f instanceof Node&&!d.has(f))for(d.add(f),f=f.firstChild;f;f=f.nextSibling)M(f,b,d);f=L(a,c);continue;}else if("template"===e){f=L(a,c);continue;}if(c=c.__CE_shadowRoot)for(c=c.firstChild;c;c=c.nextSibling)M(c,b,d);}f=f.firstChild?f.firstChild:L(a,f);}};function N(){var a=!(null===O||void 0===O||!O.noDocumentConstructionObserver),b=!(null===O||void 0===O||!O.shadyDomFastWalk);this.m=[];this.g=[];this.j=!1;this.shadyDomFastWalk=b;this.I=!a;}function P(a,b,d,f){var c=window.ShadyDOM;if(a.shadyDomFastWalk&&c&&c.inUse){if(b.nodeType===Node.ELEMENT_NODE&&d(b),b.querySelectorAll)for(a=c.nativeMethods.querySelectorAll.call(b,"*"),b=0;b-1000&&num<1000||$test.call(/e/,str)){return str;}var sepRegex=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof num==='number'){var int=num<0?-$floor(-num):$floor(num);// trunc(num) if(int!==num){var intStr=String(int);var dec=$slice.call(str,intStr.length+1);return $replace.call(intStr,sepRegex,'$&_')+'.'+$replace.call($replace.call(dec,/([0-9]{3})/g,'$&_'),/_$/,'');}}return $replace.call(str,sepRegex,'$&_');}var utilInspect=__webpack_require__(86973);var inspectCustom=utilInspect.custom;var inspectSymbol=isSymbol(inspectCustom)?inspectCustom:null;var quotes={__proto__:null,'double':'"',single:"'"};var quoteREs={__proto__:null,'double':/(["\\])/g,single:/(['\\])/g};module.exports=function inspect_(obj,options,depth,seen){var opts=options||{};if(has(opts,'quoteStyle')&&!has(quotes,opts.quoteStyle)){throw new TypeError('option "quoteStyle" must be "single" or "double"');}if(has(opts,'maxStringLength')&&(typeof opts.maxStringLength==='number'?opts.maxStringLength<0&&opts.maxStringLength!==Infinity:opts.maxStringLength!==null)){throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');}var customInspect=has(opts,'customInspect')?opts.customInspect:true;if(typeof customInspect!=='boolean'&&customInspect!=='symbol'){throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`');}if(has(opts,'indent')&&opts.indent!==null&&opts.indent!=='\t'&&!(parseInt(opts.indent,10)===opts.indent&&opts.indent>0)){throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');}if(has(opts,'numericSeparator')&&typeof opts.numericSeparator!=='boolean'){throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');}var numericSeparator=opts.numericSeparator;if(typeof obj==='undefined'){return'undefined';}if(obj===null){return'null';}if(typeof obj==='boolean'){return obj?'true':'false';}if(typeof obj==='string'){return inspectString(obj,opts);}if(typeof obj==='number'){if(obj===0){return Infinity/obj>0?'0':'-0';}var str=String(obj);return numericSeparator?addNumericSeparator(obj,str):str;}if(typeof obj==='bigint'){var bigIntStr=String(obj)+'n';return numericSeparator?addNumericSeparator(obj,bigIntStr):bigIntStr;}var maxDepth=typeof opts.depth==='undefined'?5:opts.depth;if(typeof depth==='undefined'){depth=0;}if(depth>=maxDepth&&maxDepth>0&&typeof obj==='object'){return isArray(obj)?'[Array]':'[Object]';}var indent=getIndent(opts,depth);if(typeof seen==='undefined'){seen=[];}else if(indexOf(seen,obj)>=0){return'[Circular]';}function inspect(value,from,noIndent){if(from){seen=$arrSlice.call(seen);seen.push(from);}if(noIndent){var newOpts={depth:opts.depth};if(has(opts,'quoteStyle')){newOpts.quoteStyle=opts.quoteStyle;}return inspect_(value,newOpts,depth+1,seen);}return inspect_(value,opts,depth+1,seen);}if(typeof obj==='function'&&!isRegExp(obj)){// in older engines, regexes are callable var name=nameOf(obj);var keys=arrObjKeys(obj,inspect);return'[Function'+(name?': '+name:' (anonymous)')+']'+(keys.length>0?' { '+$join.call(keys,', ')+' }':'');}if(isSymbol(obj)){var symString=hasShammedSymbols?$replace.call(String(obj),/^(Symbol\(.*\))_[^)]*$/,'$1'):symToString.call(obj);return typeof obj==='object'&&!hasShammedSymbols?markBoxed(symString):symString;}if(isElement(obj)){var s='<'+$toLowerCase.call(String(obj.nodeName));var attrs=obj.attributes||[];for(var i=0;i';return s;}if(isArray(obj)){if(obj.length===0){return'[]';}var xs=arrObjKeys(obj,inspect);if(indent&&!singleLineValues(xs)){return'['+indentedJoin(xs,indent)+']';}return'[ '+$join.call(xs,', ')+' ]';}if(isError(obj)){var parts=arrObjKeys(obj,inspect);if(!('cause'in Error.prototype)&&'cause'in obj&&!isEnumerable.call(obj,'cause')){return'{ ['+String(obj)+'] '+$join.call($concat.call('[cause]: '+inspect(obj.cause),parts),', ')+' }';}if(parts.length===0){return'['+String(obj)+']';}return'{ ['+String(obj)+'] '+$join.call(parts,', ')+' }';}if(typeof obj==='object'&&customInspect){if(inspectSymbol&&typeof obj[inspectSymbol]==='function'&&utilInspect){return utilInspect(obj,{depth:maxDepth-depth});}else if(customInspect!=='symbol'&&typeof obj.inspect==='function'){return obj.inspect();}}if(isMap(obj)){var mapParts=[];if(mapForEach){mapForEach.call(obj,function(value,key){mapParts.push(inspect(key,obj,true)+' => '+inspect(value,obj));});}return collectionOf('Map',mapSize.call(obj),mapParts,indent);}if(isSet(obj)){var setParts=[];if(setForEach){setForEach.call(obj,function(value){setParts.push(inspect(value,obj));});}return collectionOf('Set',setSize.call(obj),setParts,indent);}if(isWeakMap(obj)){return weakCollectionOf('WeakMap');}if(isWeakSet(obj)){return weakCollectionOf('WeakSet');}if(isWeakRef(obj)){return weakCollectionOf('WeakRef');}if(isNumber(obj)){return markBoxed(inspect(Number(obj)));}if(isBigInt(obj)){return markBoxed(inspect(bigIntValueOf.call(obj)));}if(isBoolean(obj)){return markBoxed(booleanValueOf.call(obj));}if(isString(obj)){return markBoxed(inspect(String(obj)));}// note: in IE 8, sometimes `global !== window` but both are the prototypes of each other /* eslint-env browser */if(typeof window!=='undefined'&&obj===window){return'{ [object Window] }';}if(typeof globalThis!=='undefined'&&obj===globalThis||typeof __webpack_require__.g!=='undefined'&&obj===__webpack_require__.g){return'{ [object globalThis] }';}if(!isDate(obj)&&!isRegExp(obj)){var ys=arrObjKeys(obj,inspect);var isPlainObject=gPO?gPO(obj)===Object.prototype:obj instanceof Object||obj.constructor===Object;var protoTag=obj instanceof Object?'':'null prototype';var stringTag=!isPlainObject&&toStringTag&&Object(obj)===obj&&toStringTag in obj?$slice.call(toStr(obj),8,-1):protoTag?'Object':'';var constructorTag=isPlainObject||typeof obj.constructor!=='function'?'':obj.constructor.name?obj.constructor.name+' ':'';var tag=constructorTag+(stringTag||protoTag?'['+$join.call($concat.call([],stringTag||[],protoTag||[]),': ')+'] ':'');if(ys.length===0){return tag+'{}';}if(indent){return tag+'{'+indentedJoin(ys,indent)+'}';}return tag+'{ '+$join.call(ys,', ')+' }';}return String(obj);};function wrapQuotes(s,defaultStyle,opts){var style=opts.quoteStyle||defaultStyle;var quoteChar=quotes[style];return quoteChar+s+quoteChar;}function quote(s){return $replace.call(String(s),/"/g,'"');}function canTrustToString(obj){return!toStringTag||!(typeof obj==='object'&&(toStringTag in obj||typeof obj[toStringTag]!=='undefined'));}function isArray(obj){return toStr(obj)==='[object Array]'&&canTrustToString(obj);}function isDate(obj){return toStr(obj)==='[object Date]'&&canTrustToString(obj);}function isRegExp(obj){return toStr(obj)==='[object RegExp]'&&canTrustToString(obj);}function isError(obj){return toStr(obj)==='[object Error]'&&canTrustToString(obj);}function isString(obj){return toStr(obj)==='[object String]'&&canTrustToString(obj);}function isNumber(obj){return toStr(obj)==='[object Number]'&&canTrustToString(obj);}function isBoolean(obj){return toStr(obj)==='[object Boolean]'&&canTrustToString(obj);}// Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives function isSymbol(obj){if(hasShammedSymbols){return obj&&typeof obj==='object'&&obj instanceof Symbol;}if(typeof obj==='symbol'){return true;}if(!obj||typeof obj!=='object'||!symToString){return false;}try{symToString.call(obj);return true;}catch(e){}return false;}function isBigInt(obj){if(!obj||typeof obj!=='object'||!bigIntValueOf){return false;}try{bigIntValueOf.call(obj);return true;}catch(e){}return false;}var hasOwn=Object.prototype.hasOwnProperty||function(key){return key in this;};function has(obj,key){return hasOwn.call(obj,key);}function toStr(obj){return objectToString.call(obj);}function nameOf(f){if(f.name){return f.name;}var m=$match.call(functionToString.call(f),/^function\s*([\w$]+)/);if(m){return m[1];}return null;}function indexOf(xs,x){if(xs.indexOf){return xs.indexOf(x);}for(var i=0,l=xs.length;iopts.maxStringLength){var remaining=str.length-opts.maxStringLength;var trailer='... '+remaining+' more character'+(remaining>1?'s':'');return inspectString($slice.call(str,0,opts.maxStringLength),opts)+trailer;}var quoteRE=quoteREs[opts.quoteStyle||'single'];quoteRE.lastIndex=0;// eslint-disable-next-line no-control-regex var s=$replace.call($replace.call(str,quoteRE,'\\$1'),/[\x00-\x1f]/g,lowbyte);return wrapQuotes(s,'single',opts);}function lowbyte(c){var n=c.charCodeAt(0);var x={8:'b',9:'t',10:'n',12:'f',13:'r'}[n];if(x){return'\\'+x;}return'\\x'+(n<0x10?'0':'')+$toUpperCase.call(n.toString(16));}function markBoxed(str){return'Object('+str+')';}function weakCollectionOf(type){return type+' { ? }';}function collectionOf(type,size,entries,indent){var joinedEntries=indent?indentedJoin(entries,indent):$join.call(entries,', ');return type+' ('+size+') {'+joinedEntries+'}';}function singleLineValues(xs){for(var i=0;i=0){return false;}}return true;}function getIndent(opts,depth){var baseIndent;if(opts.indent==='\t'){baseIndent='\t';}else if(typeof opts.indent==='number'&&opts.indent>0){baseIndent=$join.call(Array(opts.indent+1),' ');}else{return null;}return{base:baseIndent,prev:$join.call(Array(depth+1),baseIndent)};}function indentedJoin(xs,indent){if(xs.length===0){return'';}var lineJoiner='\n'+indent.prev+indent.base;return lineJoiner+$join.call(xs,','+lineJoiner)+'\n'+indent.prev;}function arrObjKeys(obj,inspect){var isArr=isArray(obj);var xs=[];if(isArr){xs.length=obj.length;for(var i=0;i Function} TODO FIXME, find a way to use import('.') */module.exports=function callBindBasic(args){if(args.length<1||typeof args[0]!=='function'){throw new $TypeError('a function is required');}return $actualApply(bind,$call,args);}; /***/ }), /***/ 84323: /***/ (function(module) { "use strict"; /** @type {import('./reflectApply')} */module.exports=typeof Reflect!=='undefined'&&Reflect&&Reflect.apply; /***/ }), /***/ 84750: /***/ (function(module) { "use strict"; /** @type {import('./functionApply')} */module.exports=Function.prototype.apply; /***/ }), /***/ 85344: /***/ (function(module) { "use strict"; /** @type {import('.')} */module.exports=Object; /***/ }), /***/ 85835: /***/ (function(module) { "use strict"; /** @type {import('.')} */var $defineProperty=Object.defineProperty||false;if($defineProperty){try{$defineProperty({},'a',{value:1});}catch(e){// IE 8 has a broken defineProperty $defineProperty=false;}}module.exports=$defineProperty; /***/ }), /***/ 86973: /***/ (function() { /* (ignored) */ /***/ }), /***/ 90791: /***/ (function(__unused_webpack_module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ decode: function() { return /* binding */ decode; }, /* harmony export */ encode: function() { return /* binding */ encode; }, /* harmony export */ toASCII: function() { return /* binding */ toASCII; }, /* harmony export */ toUnicode: function() { return /* binding */ toUnicode; }, /* harmony export */ ucs2decode: function() { return /* binding */ ucs2decode; }, /* harmony export */ ucs2encode: function() { return /* binding */ ucs2encode; } /* harmony export */ }); /** Highest positive signed 32-bit float value */const maxInt=2147483647;// aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */const base=36;const tMin=1;const tMax=26;const skew=38;const damp=700;const initialBias=72;const initialN=128;// 0x80 const delimiter='-';// '\x2D' /** Regular expressions */const regexPunycode=/^xn--/;const regexNonASCII=/[^\0-\x7F]/;// Note: U+007F DEL is excluded too. const regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g;// RFC 3490 separators /** Error messages */const errors={'overflow':'Overflow: input needs wider integers to process','not-basic':'Illegal input >= 0x80 (not a basic code point)','invalid-input':'Invalid input'};/** Convenience shortcuts */const baseMinusTMin=base-tMin;const floor=Math.floor;const stringFromCharCode=String.fromCharCode;/*--------------------------------------------------------------------------*//** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */function error(type){throw new RangeError(errors[type]);}/** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */function map(array,callback){const result=[];let length=array.length;while(length--){result[length]=callback(array[length]);}return result;}/** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {String} A new string of characters returned by the callback * function. */function mapDomain(domain,callback){const parts=domain.split('@');let result='';if(parts.length>1){// In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result=parts[0]+'@';domain=parts[1];}// Avoid `split(regex)` for IE8 compatibility. See #17. domain=domain.replace(regexSeparators,'\x2E');const labels=domain.split('.');const encoded=map(labels,callback).join('.');return result+encoded;}/** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */function ucs2decode(string){const output=[];let counter=0;const length=string.length;while(counter=0xD800&&value<=0xDBFF&&counterString.fromCodePoint(...codePoints);/** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */const basicToDigit=function(codePoint){if(codePoint>=0x30&&codePoint<0x3A){return 26+(codePoint-0x30);}if(codePoint>=0x41&&codePoint<0x5B){return codePoint-0x41;}if(codePoint>=0x61&&codePoint<0x7B){return codePoint-0x61;}return base;};/** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */const digitToBasic=function(digit,flag){// 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit+22+75*(digit<26)-((flag!=0)<<5);};/** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */const adapt=function(delta,numPoints,firstTime){let k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for/* no initialization */(;delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));};/** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */const decode=function(input){// Don't use UCS-2. const output=[];const inputLength=input.length;let i=0;let n=initialN;let bias=initialBias;// Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. let basic=input.lastIndexOf(delimiter);if(basic<0){basic=0;}for(let j=0;j=0x80){error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for/* no final expression */(let index=basic>0?basic+1:0;index=inputLength){error('invalid-input');}const digit=basicToDigit(input.charCodeAt(index++));if(digit>=base){error('invalid-input');}if(digit>floor((maxInt-i)/w)){error('overflow');}i+=digit*w;const t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error('overflow');}w*=baseMinusT;}const out=output.length+1;bias=adapt(i-oldi,out,oldi==0);// `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if(floor(i/out)>maxInt-n){error('overflow');}n+=floor(i/out);i%=out;// Insert `n` at position `i` of the output. output.splice(i++,0,n);}return String.fromCodePoint(...output);};/** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */const encode=function(input){const output=[];// Convert the input in UCS-2 to an array of Unicode code points. input=ucs2decode(input);// Cache the length. const inputLength=input.length;// Initialize the state. let n=initialN;let delta=0;let bias=initialBias;// Handle the basic code points. for(const currentValue of input){if(currentValue<0x80){output.push(stringFromCharCode(currentValue));}}const basicLength=output.length;let handledCPCount=basicLength;// `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string with a delimiter unless it's empty. if(basicLength){output.push(delimiter);}// Main encoding loop: while(handledCPCount=n&¤tValue state to , // but guard against overflow. const handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error('overflow');}delta+=(m-n)*handledCPCountPlusOne;n=m;for(const currentValue of input){if(currentValuemaxInt){error('overflow');}if(currentValue===n){// Represent delta as a generalized variable-length integer. let q=delta;for/* no condition */(let k=base;;k+=base){const t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q * @memberOf punycode * @type Object */'ucs2':{'decode':ucs2decode,'encode':ucs2encode},'decode':decode,'encode':encode,'toASCII':toASCII,'toUnicode':toUnicode};/* harmony default export */ __webpack_exports__["default"] = (punycode); /***/ }), /***/ 92972: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var formats=__webpack_require__(10681);var has=Object.prototype.hasOwnProperty;var isArray=Array.isArray;var hexTable=function(){var array=[];for(var i=0;i<256;++i){array.push('%'+((i<16?'0':'')+i.toString(16)).toUpperCase());}return array;}();var compactQueue=function compactQueue(queue){while(queue.length>1){var item=queue.pop();var obj=item.obj[item.prop];if(isArray(obj)){var compacted=[];for(var j=0;j=limit?string.slice(j,j+limit):string;var arr=[];for(var i=0;i=0x30&&c<=0x39// 0-9 ||c>=0x41&&c<=0x5A// a-z ||c>=0x61&&c<=0x7A// A-Z ||format===formats.RFC1738&&(c===0x28||c===0x29)// ( ) ){arr[arr.length]=segment.charAt(i);continue;}if(c<0x80){arr[arr.length]=hexTable[c];continue;}if(c<0x800){arr[arr.length]=hexTable[0xC0|c>>6]+hexTable[0x80|c&0x3F];continue;}if(c<0xD800||c>=0xE000){arr[arr.length]=hexTable[0xE0|c>>12]+hexTable[0x80|c>>6&0x3F]+hexTable[0x80|c&0x3F];continue;}i+=1;c=0x10000+((c&0x3FF)<<10|segment.charCodeAt(i)&0x3FF);arr[arr.length]=hexTable[0xF0|c>>18]+hexTable[0x80|c>>12&0x3F]+hexTable[0x80|c>>6&0x3F]+hexTable[0x80|c&0x3F];}out+=arr.join('');}return out;};var compact=function compact(value){var queue=[{obj:{o:value},prop:'o'}];var refs=[];for(var i=0;i */exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var nBits=-7;var i=isLE?nBytes-1:0;var d=isLE?-1:1;var s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8){}m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8){}if(e===0){e=1-eBias;}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity;}else{m=m+Math.pow(2,mLen);e=e-eBias;}return(s?-1:1)*m*Math.pow(2,e-mLen);};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c;var eLen=nBytes*8-mLen-1;var eMax=(1<>1;var rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0;var i=isLE?0:nBytes-1;var d=isLE?1:-1;var s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax;}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2;}if(e+eBias>=1){value+=rt/c;}else{value+=rt*Math.pow(2,1-eBias);}if(value*c>=2){e++;c/=2;}if(e+eBias>=eMax){m=0;e=eMax;}else if(e+eBias>=1){m=(value*c-1)*Math.pow(2,mLen);e=e+eBias;}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0;}}for(;mLen>=8;buffer[offset+i]=m&0xff,i+=d,m/=256,mLen-=8){}e=e<0;buffer[offset+i]=e&0xff,i+=d,e/=256,eLen-=8){}buffer[offset+i-d]|=s*128;}; /***/ }), /***/ 95736: /***/ (function(module, __unused_webpack_exports, __webpack_require__) { "use strict"; var GetIntrinsic=__webpack_require__(35049);var callBindBasic=__webpack_require__(77434);/** @type {(thisArg: string, searchString: string, position?: number) => number} */var $indexOf=callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]);/** @type {import('.')} */module.exports=function callBoundIntrinsic(name,allowMissing){/* eslint no-extra-parens: 0 */var intrinsic=/** @type {(this: unknown, ...args: unknown[]) => unknown} */GetIntrinsic(name,!!allowMissing);if(typeof intrinsic==='function'&&$indexOf(name,'.prototype.')>-1){return callBindBasic(/** @type {const} */[intrinsic]);}return intrinsic;}; /***/ }), /***/ 97763: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __webpack_unused_export__; /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT *//* eslint-disable no-proto */const base64=__webpack_require__(31506);const ieee754=__webpack_require__(94087);const customInspectSymbol=typeof Symbol==='function'&&typeof Symbol['for']==='function'// eslint-disable-line dot-notation ?Symbol['for']('nodejs.util.inspect.custom')// eslint-disable-line dot-notation :null;exports.hp=Buffer;__webpack_unused_export__=SlowBuffer;exports.IS=50;const K_MAX_LENGTH=0x7fffffff;__webpack_unused_export__=K_MAX_LENGTH;/** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Print warning and recommend using `buffer` v4.x which has an Object * implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * We report that the browser does not support typed arrays if the are not subclassable * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support * for __proto__ and has a buggy typed array implementation. */Buffer.TYPED_ARRAY_SUPPORT=typedArraySupport();if(!Buffer.TYPED_ARRAY_SUPPORT&&typeof console!=='undefined'&&typeof console.error==='function'){console.error('This browser lacks typed array (Uint8Array) support which is required by '+'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.');}function typedArraySupport(){// Can typed array instances can be augmented? try{const arr=new Uint8Array(1);const proto={foo:function(){return 42;}};Object.setPrototypeOf(proto,Uint8Array.prototype);Object.setPrototypeOf(arr,proto);return arr.foo()===42;}catch(e){return false;}}Object.defineProperty(Buffer.prototype,'parent',{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.buffer;}});Object.defineProperty(Buffer.prototype,'offset',{enumerable:true,get:function(){if(!Buffer.isBuffer(this))return undefined;return this.byteOffset;}});function createBuffer(length){if(length>K_MAX_LENGTH){throw new RangeError('The value "'+length+'" is invalid for option "size"');}// Return an augmented `Uint8Array` instance const buf=new Uint8Array(length);Object.setPrototypeOf(buf,Buffer.prototype);return buf;}/** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */function Buffer(arg,encodingOrOffset,length){// Common case. if(typeof arg==='number'){if(typeof encodingOrOffset==='string'){throw new TypeError('The "string" argument must be of type string. Received type number');}return allocUnsafe(arg);}return from(arg,encodingOrOffset,length);}Buffer.poolSize=8192;// not used by this implementation function from(value,encodingOrOffset,length){if(typeof value==='string'){return fromString(value,encodingOrOffset);}if(ArrayBuffer.isView(value)){return fromArrayView(value);}if(value==null){throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, '+'or Array-like Object. Received type '+typeof value);}if(isInstance(value,ArrayBuffer)||value&&isInstance(value.buffer,ArrayBuffer)){return fromArrayBuffer(value,encodingOrOffset,length);}if(typeof SharedArrayBuffer!=='undefined'&&(isInstance(value,SharedArrayBuffer)||value&&isInstance(value.buffer,SharedArrayBuffer))){return fromArrayBuffer(value,encodingOrOffset,length);}if(typeof value==='number'){throw new TypeError('The "value" argument must not be of type number. Received type number');}const valueOf=value.valueOf&&value.valueOf();if(valueOf!=null&&valueOf!==value){return Buffer.from(valueOf,encodingOrOffset,length);}const b=fromObject(value);if(b)return b;if(typeof Symbol!=='undefined'&&Symbol.toPrimitive!=null&&typeof value[Symbol.toPrimitive]==='function'){return Buffer.from(value[Symbol.toPrimitive]('string'),encodingOrOffset,length);}throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, '+'or Array-like Object. Received type '+typeof value);}/** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/Buffer.from=function(value,encodingOrOffset,length){return from(value,encodingOrOffset,length);};// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: // https://github.com/feross/buffer/pull/148 Object.setPrototypeOf(Buffer.prototype,Uint8Array.prototype);Object.setPrototypeOf(Buffer,Uint8Array);function assertSize(size){if(typeof size!=='number'){throw new TypeError('"size" argument must be of type number');}else if(size<0){throw new RangeError('The value "'+size+'" is invalid for option "size"');}}function alloc(size,fill,encoding){assertSize(size);if(size<=0){return createBuffer(size);}if(fill!==undefined){// Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpreted as a start offset. return typeof encoding==='string'?createBuffer(size).fill(fill,encoding):createBuffer(size).fill(fill);}return createBuffer(size);}/** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/Buffer.alloc=function(size,fill,encoding){return alloc(size,fill,encoding);};function allocUnsafe(size){assertSize(size);return createBuffer(size<0?0:checked(size)|0);}/** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */Buffer.allocUnsafe=function(size){return allocUnsafe(size);};/** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */Buffer.allocUnsafeSlow=function(size){return allocUnsafe(size);};function fromString(string,encoding){if(typeof encoding!=='string'||encoding===''){encoding='utf8';}if(!Buffer.isEncoding(encoding)){throw new TypeError('Unknown encoding: '+encoding);}const length=byteLength(string,encoding)|0;let buf=createBuffer(length);const actual=buf.write(string,encoding);if(actual!==length){// Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') buf=buf.slice(0,actual);}return buf;}function fromArrayLike(array){const length=array.length<0?0:checked(array.length)|0;const buf=createBuffer(length);for(let i=0;i=K_MAX_LENGTH){throw new RangeError('Attempt to allocate Buffer larger than maximum '+'size: 0x'+K_MAX_LENGTH.toString(16)+' bytes');}return length|0;}function SlowBuffer(length){if(+length!=length){// eslint-disable-line eqeqeq length=0;}return Buffer.alloc(+length);}Buffer.isBuffer=function isBuffer(b){return b!=null&&b._isBuffer===true&&b!==Buffer.prototype;// so Buffer.isBuffer(Buffer.prototype) will be false };Buffer.compare=function compare(a,b){if(isInstance(a,Uint8Array))a=Buffer.from(a,a.offset,a.byteLength);if(isInstance(b,Uint8Array))b=Buffer.from(b,b.offset,b.byteLength);if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b)){throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');}if(a===b)return 0;let x=a.length;let y=b.length;for(let i=0,len=Math.min(x,y);ibuffer.length){if(!Buffer.isBuffer(buf))buf=Buffer.from(buf);buf.copy(buffer,pos);}else{Uint8Array.prototype.set.call(buffer,buf,pos);}}else if(!Buffer.isBuffer(buf)){throw new TypeError('"list" argument must be an Array of Buffers');}else{buf.copy(buffer,pos);}pos+=buf.length;}return buffer;};function byteLength(string,encoding){if(Buffer.isBuffer(string)){return string.length;}if(ArrayBuffer.isView(string)||isInstance(string,ArrayBuffer)){return string.byteLength;}if(typeof string!=='string'){throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. '+'Received type '+typeof string);}const len=string.length;const mustMatch=arguments.length>2&&arguments[2]===true;if(!mustMatch&&len===0)return 0;// Use a for loop to avoid recursion let loweredCase=false;for(;;){switch(encoding){case'ascii':case'latin1':case'binary':return len;case'utf8':case'utf-8':return utf8ToBytes(string).length;case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return len*2;case'hex':return len>>>1;case'base64':return base64ToBytes(string).length;default:if(loweredCase){return mustMatch?-1:utf8ToBytes(string).length;// assume utf8 }encoding=(''+encoding).toLowerCase();loweredCase=true;}}}Buffer.byteLength=byteLength;function slowToString(encoding,start,end){let loweredCase=false;// No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if(start===undefined||start<0){start=0;}// Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if(start>this.length){return'';}if(end===undefined||end>this.length){end=this.length;}if(end<=0){return'';}// Force coercion to uint32. This will also coerce falsey/NaN values to 0. end>>>=0;start>>>=0;if(end<=start){return'';}if(!encoding)encoding='utf8';while(true){switch(encoding){case'hex':return hexSlice(this,start,end);case'utf8':case'utf-8':return utf8Slice(this,start,end);case'ascii':return asciiSlice(this,start,end);case'latin1':case'binary':return latin1Slice(this,start,end);case'base64':return base64Slice(this,start,end);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(encoding+'').toLowerCase();loweredCase=true;}}}// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) // to detect a Buffer instance. It's not possible to use `instanceof Buffer` // reliably in a browserify context because there could be multiple different // copies of the 'buffer' package in use. This method works even for Buffer // instances that were created from another copy of the `buffer` package. // See: https://github.com/feross/buffer/issues/154 Buffer.prototype._isBuffer=true;function swap(b,n,m){const i=b[n];b[n]=b[m];b[m]=i;}Buffer.prototype.swap16=function swap16(){const len=this.length;if(len%2!==0){throw new RangeError('Buffer size must be a multiple of 16-bits');}for(let i=0;imax)str+=' ... ';return'';};if(customInspectSymbol){Buffer.prototype[customInspectSymbol]=Buffer.prototype.inspect;}Buffer.prototype.compare=function compare(target,start,end,thisStart,thisEnd){if(isInstance(target,Uint8Array)){target=Buffer.from(target,target.offset,target.byteLength);}if(!Buffer.isBuffer(target)){throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. '+'Received type '+typeof target);}if(start===undefined){start=0;}if(end===undefined){end=target?target.length:0;}if(thisStart===undefined){thisStart=0;}if(thisEnd===undefined){thisEnd=this.length;}if(start<0||end>target.length||thisStart<0||thisEnd>this.length){throw new RangeError('out of range index');}if(thisStart>=thisEnd&&start>=end){return 0;}if(thisStart>=thisEnd){return-1;}if(start>=end){return 1;}start>>>=0;end>>>=0;thisStart>>>=0;thisEnd>>>=0;if(this===target)return 0;let x=thisEnd-thisStart;let y=end-start;const len=Math.min(x,y);const thisCopy=this.slice(thisStart,thisEnd);const targetCopy=target.slice(start,end);for(let i=0;i= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf(buffer,val,byteOffset,encoding,dir){// Empty buffer means no match if(buffer.length===0)return-1;// Normalize byteOffset if(typeof byteOffset==='string'){encoding=byteOffset;byteOffset=0;}else if(byteOffset>0x7fffffff){byteOffset=0x7fffffff;}else if(byteOffset<-0x80000000){byteOffset=-0x80000000;}byteOffset=+byteOffset;// Coerce to Number. if(numberIsNaN(byteOffset)){// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset=dir?0:buffer.length-1;}// Normalize byteOffset: negative offsets start from the end of the buffer if(byteOffset<0)byteOffset=buffer.length+byteOffset;if(byteOffset>=buffer.length){if(dir)return-1;else byteOffset=buffer.length-1;}else if(byteOffset<0){if(dir)byteOffset=0;else return-1;}// Normalize val if(typeof val==='string'){val=Buffer.from(val,encoding);}// Finally, search either indexOf (if dir is true) or lastIndexOf if(Buffer.isBuffer(val)){// Special case: looking for empty string/buffer always fails if(val.length===0){return-1;}return arrayIndexOf(buffer,val,byteOffset,encoding,dir);}else if(typeof val==='number'){val=val&0xFF;// Search for a byte value [0-255] if(typeof Uint8Array.prototype.indexOf==='function'){if(dir){return Uint8Array.prototype.indexOf.call(buffer,val,byteOffset);}else{return Uint8Array.prototype.lastIndexOf.call(buffer,val,byteOffset);}}return arrayIndexOf(buffer,[val],byteOffset,encoding,dir);}throw new TypeError('val must be string, number or Buffer');}function arrayIndexOf(arr,val,byteOffset,encoding,dir){let indexSize=1;let arrLength=arr.length;let valLength=val.length;if(encoding!==undefined){encoding=String(encoding).toLowerCase();if(encoding==='ucs2'||encoding==='ucs-2'||encoding==='utf16le'||encoding==='utf-16le'){if(arr.length<2||val.length<2){return-1;}indexSize=2;arrLength/=2;valLength/=2;byteOffset/=2;}}function read(buf,i){if(indexSize===1){return buf[i];}else{return buf.readUInt16BE(i*indexSize);}}let i;if(dir){let foundIndex=-1;for(i=byteOffset;iarrLength)byteOffset=arrLength-valLength;for(i=byteOffset;i>=0;i--){let found=true;for(let j=0;jremaining){length=remaining;}}const strLen=string.length;if(length>strLen/2){length=strLen/2;}let i;for(i=0;i>>0;if(isFinite(length)){length=length>>>0;if(encoding===undefined)encoding='utf8';}else{encoding=length;length=undefined;}}else{throw new Error('Buffer.write(string, encoding, offset[, length]) is no longer supported');}const remaining=this.length-offset;if(length===undefined||length>remaining)length=remaining;if(string.length>0&&(length<0||offset<0)||offset>this.length){throw new RangeError('Attempt to write outside buffer bounds');}if(!encoding)encoding='utf8';let loweredCase=false;for(;;){switch(encoding){case'hex':return hexWrite(this,string,offset,length);case'utf8':case'utf-8':return utf8Write(this,string,offset,length);case'ascii':case'latin1':case'binary':return asciiWrite(this,string,offset,length);case'base64':// Warning: maxLength not taken into account in base64Write return base64Write(this,string,offset,length);case'ucs2':case'ucs-2':case'utf16le':case'utf-16le':return ucs2Write(this,string,offset,length);default:if(loweredCase)throw new TypeError('Unknown encoding: '+encoding);encoding=(''+encoding).toLowerCase();loweredCase=true;}}};Buffer.prototype.toJSON=function toJSON(){return{type:'Buffer',data:Array.prototype.slice.call(this._arr||this,0)};};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf);}else{return base64.fromByteArray(buf.slice(start,end));}}function utf8Slice(buf,start,end){end=Math.min(buf.length,end);const res=[];let i=start;while(i0xEF?4:firstByte>0xDF?3:firstByte>0xBF?2:1;if(i+bytesPerSequence<=end){let secondByte,thirdByte,fourthByte,tempCodePoint;switch(bytesPerSequence){case 1:if(firstByte<0x80){codePoint=firstByte;}break;case 2:secondByte=buf[i+1];if((secondByte&0xC0)===0x80){tempCodePoint=(firstByte&0x1F)<<0x6|secondByte&0x3F;if(tempCodePoint>0x7F){codePoint=tempCodePoint;}}break;case 3:secondByte=buf[i+1];thirdByte=buf[i+2];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0xC|(secondByte&0x3F)<<0x6|thirdByte&0x3F;if(tempCodePoint>0x7FF&&(tempCodePoint<0xD800||tempCodePoint>0xDFFF)){codePoint=tempCodePoint;}}break;case 4:secondByte=buf[i+1];thirdByte=buf[i+2];fourthByte=buf[i+3];if((secondByte&0xC0)===0x80&&(thirdByte&0xC0)===0x80&&(fourthByte&0xC0)===0x80){tempCodePoint=(firstByte&0xF)<<0x12|(secondByte&0x3F)<<0xC|(thirdByte&0x3F)<<0x6|fourthByte&0x3F;if(tempCodePoint>0xFFFF&&tempCodePoint<0x110000){codePoint=tempCodePoint;}}}}if(codePoint===null){// we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint=0xFFFD;bytesPerSequence=1;}else if(codePoint>0xFFFF){// encode to utf16 (surrogate pair dance) codePoint-=0x10000;res.push(codePoint>>>10&0x3FF|0xD800);codePoint=0xDC00|codePoint&0x3FF;}res.push(codePoint);i+=bytesPerSequence;}return decodeCodePointsArray(res);}// Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety const MAX_ARGUMENTS_LENGTH=0x1000;function decodeCodePointsArray(codePoints){const len=codePoints.length;if(len<=MAX_ARGUMENTS_LENGTH){return String.fromCharCode.apply(String,codePoints);// avoid extra slice() }// Decode in chunks to avoid "call stack size exceeded". let res='';let i=0;while(ilen)end=len;let out='';for(let i=start;ilen){start=len;}if(end<0){end+=len;if(end<0)end=0;}else if(end>len){end=len;}if(endlength)throw new RangeError('Trying to access beyond buffer length');}Buffer.prototype.readUintLE=Buffer.prototype.readUIntLE=function readUIntLE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);let val=this[offset];let mul=1;let i=0;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){checkOffset(offset,byteLength,this.length);}let val=this[offset+--byteLength];let mul=1;while(byteLength>0&&(mul*=0x100)){val+=this[offset+--byteLength]*mul;}return val;};Buffer.prototype.readUint8=Buffer.prototype.readUInt8=function readUInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);return this[offset];};Buffer.prototype.readUint16LE=Buffer.prototype.readUInt16LE=function readUInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8;};Buffer.prototype.readUint16BE=Buffer.prototype.readUInt16BE=function readUInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1];};Buffer.prototype.readUint32LE=Buffer.prototype.readUInt32LE=function readUInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*0x1000000;};Buffer.prototype.readUint32BE=Buffer.prototype.readUInt32BE=function readUInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*0x1000000+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3]);};Buffer.prototype.readBigUInt64LE=defineBigIntMethod(function readBigUInt64LE(offset){offset=offset>>>0;validateNumber(offset,'offset');const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8);}const lo=first+this[++offset]*2**8+this[++offset]*2**16+this[++offset]*2**24;const hi=this[++offset]+this[++offset]*2**8+this[++offset]*2**16+last*2**24;return BigInt(lo)+(BigInt(hi)<>>0;validateNumber(offset,'offset');const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8);}const hi=first*2**24+this[++offset]*2**16+this[++offset]*2**8+this[++offset];const lo=this[++offset]*2**24+this[++offset]*2**16+this[++offset]*2**8+last;return(BigInt(hi)<>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);let val=this[offset];let mul=1;let i=0;while(++i=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readIntBE=function readIntBE(offset,byteLength,noAssert){offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert)checkOffset(offset,byteLength,this.length);let i=byteLength;let mul=1;let val=this[offset+--i];while(i>0&&(mul*=0x100)){val+=this[offset+--i]*mul;}mul*=0x80;if(val>=mul)val-=Math.pow(2,8*byteLength);return val;};Buffer.prototype.readInt8=function readInt8(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&0x80))return this[offset];return(0xff-this[offset]+1)*-1;};Buffer.prototype.readInt16LE=function readInt16LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);const val=this[offset]|this[offset+1]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt16BE=function readInt16BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,2,this.length);const val=this[offset+1]|this[offset]<<8;return val&0x8000?val|0xFFFF0000:val;};Buffer.prototype.readInt32LE=function readInt32LE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24;};Buffer.prototype.readInt32BE=function readInt32BE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3];};Buffer.prototype.readBigInt64LE=defineBigIntMethod(function readBigInt64LE(offset){offset=offset>>>0;validateNumber(offset,'offset');const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8);}const val=this[offset+4]+this[offset+5]*2**8+this[offset+6]*2**16+(last<<24);// Overflow return(BigInt(val)<>>0;validateNumber(offset,'offset');const first=this[offset];const last=this[offset+7];if(first===undefined||last===undefined){boundsError(offset,this.length-8);}const val=(first<<24)+// Overflow this[++offset]*2**16+this[++offset]*2**8+this[++offset];return(BigInt(val)<>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4);};Buffer.prototype.readFloatBE=function readFloatBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4);};Buffer.prototype.readDoubleLE=function readDoubleLE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8);};Buffer.prototype.readDoubleBE=function readDoubleBE(offset,noAssert){offset=offset>>>0;if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8);};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError('"buffer" argument must be a Buffer instance');if(value>max||valuebuf.length)throw new RangeError('Index out of range');}Buffer.prototype.writeUintLE=Buffer.prototype.writeUIntLE=function writeUIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;byteLength=byteLength>>>0;if(!noAssert){const maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0);}let mul=1;let i=0;this[offset]=value&0xFF;while(++i>>0;byteLength=byteLength>>>0;if(!noAssert){const maxBytes=Math.pow(2,8*byteLength)-1;checkInt(this,value,offset,byteLength,maxBytes,0);}let i=byteLength-1;let mul=1;this[offset+i]=value&0xFF;while(--i>=0&&(mul*=0x100)){this[offset+i]=value/mul&0xFF;}return offset+byteLength;};Buffer.prototype.writeUint8=Buffer.prototype.writeUInt8=function writeUInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,0xff,0);this[offset]=value&0xff;return offset+1;};Buffer.prototype.writeUint16LE=Buffer.prototype.writeUInt16LE=function writeUInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);this[offset]=value&0xff;this[offset+1]=value>>>8;return offset+2;};Buffer.prototype.writeUint16BE=Buffer.prototype.writeUInt16BE=function writeUInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,0xffff,0);this[offset]=value>>>8;this[offset+1]=value&0xff;return offset+2;};Buffer.prototype.writeUint32LE=Buffer.prototype.writeUInt32LE=function writeUInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value&0xff;return offset+4;};Buffer.prototype.writeUint32BE=Buffer.prototype.writeUInt32BE=function writeUInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,0xffffffff,0);this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;return offset+4;};function wrtBigUInt64LE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(0xffffffff));buf[offset++]=lo;lo=lo>>8;buf[offset++]=lo;lo=lo>>8;buf[offset++]=lo;lo=lo>>8;buf[offset++]=lo;let hi=Number(value>>BigInt(32)&BigInt(0xffffffff));buf[offset++]=hi;hi=hi>>8;buf[offset++]=hi;hi=hi>>8;buf[offset++]=hi;hi=hi>>8;buf[offset++]=hi;return offset;}function wrtBigUInt64BE(buf,value,offset,min,max){checkIntBI(value,min,max,buf,offset,7);let lo=Number(value&BigInt(0xffffffff));buf[offset+7]=lo;lo=lo>>8;buf[offset+6]=lo;lo=lo>>8;buf[offset+5]=lo;lo=lo>>8;buf[offset+4]=lo;let hi=Number(value>>BigInt(32)&BigInt(0xffffffff));buf[offset+3]=hi;hi=hi>>8;buf[offset+2]=hi;hi=hi>>8;buf[offset+1]=hi;hi=hi>>8;buf[offset]=hi;return offset+8;}Buffer.prototype.writeBigUInt64LE=defineBigIntMethod(function writeBigUInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,BigInt(0),BigInt('0xffffffffffffffff'));});Buffer.prototype.writeBigUInt64BE=defineBigIntMethod(function writeBigUInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,BigInt(0),BigInt('0xffffffffffffffff'));});Buffer.prototype.writeIntLE=function writeIntLE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}let i=0;let mul=1;let sub=0;this[offset]=value&0xFF;while(++i>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeIntBE=function writeIntBE(value,offset,byteLength,noAssert){value=+value;offset=offset>>>0;if(!noAssert){const limit=Math.pow(2,8*byteLength-1);checkInt(this,value,offset,byteLength,limit-1,-limit);}let i=byteLength-1;let mul=1;let sub=0;this[offset+i]=value&0xFF;while(--i>=0&&(mul*=0x100)){if(value<0&&sub===0&&this[offset+i+1]!==0){sub=1;}this[offset+i]=(value/mul>>0)-sub&0xFF;}return offset+byteLength;};Buffer.prototype.writeInt8=function writeInt8(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,0x7f,-0x80);if(value<0)value=0xff+value+1;this[offset]=value&0xff;return offset+1;};Buffer.prototype.writeInt16LE=function writeInt16LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);this[offset]=value&0xff;this[offset+1]=value>>>8;return offset+2;};Buffer.prototype.writeInt16BE=function writeInt16BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,0x7fff,-0x8000);this[offset]=value>>>8;this[offset+1]=value&0xff;return offset+2;};Buffer.prototype.writeInt32LE=function writeInt32LE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);this[offset]=value&0xff;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24;return offset+4;};Buffer.prototype.writeInt32BE=function writeInt32BE(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,0x7fffffff,-0x80000000);if(value<0)value=0xffffffff+value+1;this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value&0xff;return offset+4;};Buffer.prototype.writeBigInt64LE=defineBigIntMethod(function writeBigInt64LE(value,offset=0){return wrtBigUInt64LE(this,value,offset,-BigInt('0x8000000000000000'),BigInt('0x7fffffffffffffff'));});Buffer.prototype.writeBigInt64BE=defineBigIntMethod(function writeBigInt64BE(value,offset=0){return wrtBigUInt64BE(this,value,offset,-BigInt('0x8000000000000000'),BigInt('0x7fffffffffffffff'));});function checkIEEE754(buf,value,offset,ext,max,min){if(offset+ext>buf.length)throw new RangeError('Index out of range');if(offset<0)throw new RangeError('Index out of range');}function writeFloat(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,4,3.4028234663852886e+38,-3.4028234663852886e+38);}ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4;}Buffer.prototype.writeFloatLE=function writeFloatLE(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert);};Buffer.prototype.writeFloatBE=function writeFloatBE(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert);};function writeDouble(buf,value,offset,littleEndian,noAssert){value=+value;offset=offset>>>0;if(!noAssert){checkIEEE754(buf,value,offset,8,1.7976931348623157E+308,-1.7976931348623157E+308);}ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8;}Buffer.prototype.writeDoubleLE=function writeDoubleLE(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert);};Buffer.prototype.writeDoubleBE=function writeDoubleBE(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert);};// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy=function copy(target,targetStart,start,end){if(!Buffer.isBuffer(target))throw new TypeError('argument should be a Buffer');if(!start)start=0;if(!end&&end!==0)end=this.length;if(targetStart>=target.length)targetStart=target.length;if(!targetStart)targetStart=0;if(end>0&&end=this.length)throw new RangeError('Index out of range');if(end<0)throw new RangeError('sourceEnd out of bounds');// Are we oob? if(end>this.length)end=this.length;if(target.length-targetStart>>0;end=end===undefined?this.length:end>>>0;if(!val)val=0;let i;if(typeof val==='number'){for(i=start;i2**32){received=addNumericalSeparator(String(input));}else if(typeof input==='bigint'){received=String(input);if(input>BigInt(2)**BigInt(32)||input<-(BigInt(2)**BigInt(32))){received=addNumericalSeparator(received);}received+='n';}msg+=` It must be ${range}. Received ${received}`;return msg;},RangeError);function addNumericalSeparator(val){let res='';let i=val.length;const start=val[0]==='-'?1:0;for(;i>=start+4;i-=3){res=`_${val.slice(i-3,i)}${res}`;}return`${val.slice(0,i)}${res}`;}// CHECK FUNCTIONS // =============== function checkBounds(buf,offset,byteLength){validateNumber(offset,'offset');if(buf[offset]===undefined||buf[offset+byteLength]===undefined){boundsError(offset,buf.length-(byteLength+1));}}function checkIntBI(value,min,max,buf,offset,byteLength){if(value>max||value3){if(min===0||min===BigInt(0)){range=`>= 0${n} and < 2${n} ** ${(byteLength+1)*8}${n}`;}else{range=`>= -(2${n} ** ${(byteLength+1)*8-1}${n}) and < 2 ** `+`${(byteLength+1)*8-1}${n}`;}}else{range=`>= ${min}${n} and <= ${max}${n}`;}throw new errors.ERR_OUT_OF_RANGE('value',range,value);}checkBounds(buf,offset,byteLength);}function validateNumber(value,name){if(typeof value!=='number'){throw new errors.ERR_INVALID_ARG_TYPE(name,'number',value);}}function boundsError(value,length,type){if(Math.floor(value)!==value){validateNumber(value,type);throw new errors.ERR_OUT_OF_RANGE(type||'offset','an integer',value);}if(length<0){throw new errors.ERR_BUFFER_OUT_OF_BOUNDS();}throw new errors.ERR_OUT_OF_RANGE(type||'offset',`>= ${type?1:0} and <= ${length}`,value);}// HELPER FUNCTIONS // ================ const INVALID_BASE64_RE=/[^+/0-9A-Za-z-_]/g;function base64clean(str){// Node takes equal signs as end of the Base64 encoding str=str.split('=')[0];// Node strips out invalid characters like \n and \t from the string, base64-js does not str=str.trim().replace(INVALID_BASE64_RE,'');// Node converts strings with length < 2 to '' if(str.length<2)return'';// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while(str.length%4!==0){str=str+'=';}return str;}function utf8ToBytes(string,units){units=units||Infinity;let codePoint;const length=string.length;let leadSurrogate=null;const bytes=[];for(let i=0;i0xD7FF&&codePoint<0xE000){// last char was a lead if(!leadSurrogate){// no lead yet if(codePoint>0xDBFF){// unexpected trail if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}else if(i+1===length){// unpaired lead if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);continue;}// valid lead leadSurrogate=codePoint;continue;}// 2 leads in a row if(codePoint<0xDC00){if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);leadSurrogate=codePoint;continue;}// valid surrogate pair codePoint=(leadSurrogate-0xD800<<10|codePoint-0xDC00)+0x10000;}else if(leadSurrogate){// valid bmp char, but last char was a lead if((units-=3)>-1)bytes.push(0xEF,0xBF,0xBD);}leadSurrogate=null;// encode utf8 if(codePoint<0x80){if((units-=1)<0)break;bytes.push(codePoint);}else if(codePoint<0x800){if((units-=2)<0)break;bytes.push(codePoint>>0x6|0xC0,codePoint&0x3F|0x80);}else if(codePoint<0x10000){if((units-=3)<0)break;bytes.push(codePoint>>0xC|0xE0,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else if(codePoint<0x110000){if((units-=4)<0)break;bytes.push(codePoint>>0x12|0xF0,codePoint>>0xC&0x3F|0x80,codePoint>>0x6&0x3F|0x80,codePoint&0x3F|0x80);}else{throw new Error('Invalid code point');}}return bytes;}function asciiToBytes(str){const byteArray=[];for(let i=0;i>8;lo=c%256;byteArray.push(lo);byteArray.push(hi);}return byteArray;}function base64ToBytes(str){return base64.toByteArray(base64clean(str));}function blitBuffer(src,dst,offset,length){let i;for(i=0;i=dst.length||i>=src.length)break;dst[i+offset]=src[i];}return i;}// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass // the `instanceof` check but they should be treated as of that type. // See: https://github.com/feross/buffer/issues/166 function isInstance(obj,type){return obj instanceof type||obj!=null&&obj.constructor!=null&&obj.constructor.name!=null&&obj.constructor.name===type.name;}function numberIsNaN(obj){// For IE11 support return obj!==obj;// eslint-disable-line no-self-compare }// Create lookup table for `toString('hex')` // See: https://github.com/feross/buffer/issues/219 const hexSliceLookupTable=function(){const alphabet='0123456789abcdef';const table=new Array(256);for(let i=0;i<16;++i){const i16=i*16;for(let j=0;j<16;++j){table[i16+j]=alphabet[i]+alphabet[j];}}return table;}();// Return not function with Error if BigInt not supported function defineBigIntMethod(fn){return typeof BigInt==='undefined'?BufferBigIntNotDefined:fn;}function BufferBigIntNotDefined(){throw new Error('BigInt not supported');} /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ var cachedModule = __webpack_module_cache__[moduleId]; /******/ if (cachedModule !== undefined) { /******/ return cachedModule.exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ !function() { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = function(exports, definition) { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ }(); /******/ /******/ /* webpack/runtime/global */ /******/ !function() { /******/ __webpack_require__.g = (function() { /******/ if (typeof globalThis === 'object') return globalThis; /******/ try { /******/ return this || new Function('return this')(); /******/ } catch (e) { /******/ if (typeof window === 'object') return window; /******/ } /******/ })(); /******/ }(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ !function() { /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /******/ }(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ !function() { /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ }(); /******/ /************************************************************************/ var __webpack_exports__ = {}; // This entry needs to be wrapped in an IIFE because it needs to be in strict mode. !function() { "use strict"; ;// ./src/autofill/enums/autofill-overlay.enum.ts const AutofillOverlayElement = { Button: "autofill-inline-menu-button", List: "autofill-inline-menu-list", }; const AutofillOverlayPort = { Button: "autofill-inline-menu-button-port", ButtonMessageConnector: "autofill-inline-menu-button-message-connector", List: "autofill-inline-menu-list-port", ListMessageConnector: "autofill-inline-menu-list-message-connector", }; const RedirectFocusDirection = { Current: "current", Previous: "previous", Next: "next", }; const InlineMenuFillTypes = { AccountCreationUsername: 5, PasswordGeneration: 6, CurrentPasswordUpdate: 7, }; const InlineMenuAccountCreationFieldType = { Text: "text", Email: "email", Password: "password", Totp: "totp", }; const MAX_SUB_FRAME_DEPTH = 8; ;// ./src/autofill/enums/autofill-port.enum.ts const AutofillPort = { InjectedScript: "autofill-injected-script-port", }; ;// ./src/autofill/utils/index.ts var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; /** * Generates a random string of characters. * * @param length - The length of the random string to generate. */ function generateRandomChars(length) { const chars = "abcdefghijklmnopqrstuvwxyz"; const randomChars = []; const randomBytes = new Uint8Array(length); globalThis.crypto.getRandomValues(randomBytes); for (let byteIndex = 0; byteIndex < randomBytes.length; byteIndex++) { const byte = randomBytes[byteIndex]; randomChars.push(chars[byte % chars.length]); } return randomChars.join(""); } /** * Polyfills the requestIdleCallback API with a setTimeout fallback. * * @param callback - The callback function to run when the browser is idle. * @param options - The options to pass to the requestIdleCallback function. */ function requestIdleCallbackPolyfill(callback, options) { if ("requestIdleCallback" in globalThis) { return globalThis.requestIdleCallback(() => callback(), options); } return globalThis.setTimeout(() => callback(), 1); } /** * Polyfills the cancelIdleCallback API with a clearTimeout fallback. * * @param id - The ID of the idle callback to cancel. */ function cancelIdleCallbackPolyfill(id) { if ("cancelIdleCallback" in globalThis) { return globalThis.cancelIdleCallback(id); } return globalThis.clearTimeout(id); } /** * Generates a random string of characters that formatted as a custom element name. */ function generateRandomCustomElementName() { const length = Math.floor(Math.random() * 5) + 8; // Between 8 and 12 characters const numHyphens = Math.min(Math.max(Math.floor(Math.random() * 4), 1), length - 1); // At least 1, maximum of 3 hyphens const hyphenIndices = []; while (hyphenIndices.length < numHyphens) { const index = Math.floor(Math.random() * (length - 1)) + 1; if (!hyphenIndices.includes(index)) { hyphenIndices.push(index); } } hyphenIndices.sort((a, b) => a - b); let randomString = ""; let prevIndex = 0; for (let index = 0; index < hyphenIndices.length; index++) { const hyphenIndex = hyphenIndices[index]; randomString = randomString + generateRandomChars(hyphenIndex - prevIndex) + "-"; prevIndex = hyphenIndex; } randomString += generateRandomChars(length - prevIndex); return randomString; } /** * Builds a DOM element from an SVG string. * * @param svgString - The SVG string to build the DOM element from. * @param ariaHidden - Determines whether the SVG should be hidden from screen readers. */ function buildSvgDomElement(svgString, ariaHidden = true) { const domParser = new DOMParser(); const svgDom = domParser.parseFromString(svgString, "image/svg+xml"); const domElement = svgDom.documentElement; domElement.setAttribute("aria-hidden", `${ariaHidden}`); return domElement; } /** * Sends a message to the extension. * * @param command - The command to send. * @param options - The options to send with the command. */ function sendExtensionMessage(command_1) { return __awaiter(this, arguments, void 0, function* (command, options = {}) { if (typeof browser !== "undefined" && typeof browser.runtime !== "undefined" && typeof browser.runtime.sendMessage !== "undefined") { return browser.runtime.sendMessage(Object.assign({ command }, options)); } return new Promise((resolve) => chrome.runtime.sendMessage(Object.assign({ command }, options), (response) => { if (chrome.runtime.lastError) { resolve(null); } resolve(response); })); }); } /** * Sets CSS styles on an element. * * @param element - The element to set the styles on. * @param styles - The styles to set on the element. * @param priority - Determines whether the styles should be set as important. */ function setElementStyles(element, styles, priority) { if (!element || !styles || !Object.keys(styles).length) { return; } for (const styleProperty in styles) { element.style.setProperty(styleProperty.replace(/([a-z])([A-Z])/g, "$1-$2"), // Convert camelCase to kebab-case styles[styleProperty], priority ? "important" : undefined); } } /** * Sets up a long-lived connection with the extension background * and triggers an onDisconnect event if the extension context * is invalidated. * * @param callback - Callback export function to run when the extension disconnects */ function setupExtensionDisconnectAction(callback) { const port = chrome.runtime.connect({ name: AutofillPort.InjectedScript }); const onDisconnectCallback = (disconnectedPort) => { callback(disconnectedPort); port.onDisconnect.removeListener(onDisconnectCallback); }; port.onDisconnect.addListener(onDisconnectCallback); } /** * Handles setup of the extension disconnect action for the autofill init class * in both instances where the overlay might or might not be initialized. * * @param windowContext - The global window context */ function setupAutofillInitDisconnectAction(windowContext) { if (!windowContext.bitwardenAutofillInit) { return; } const onDisconnectCallback = () => { windowContext.bitwardenAutofillInit.destroy(); delete windowContext.bitwardenAutofillInit; }; setupExtensionDisconnectAction(onDisconnectCallback); } /** * Identifies whether an element is a fillable form field. * This is determined by whether the element is a form field and not a span. * * @param formFieldElement - The form field element to check. */ function elementIsFillableFormField(formFieldElement) { return !elementIsSpanElement(formFieldElement); } /** * Identifies whether an element is an instance of a specific tag name. * * @param element - The element to check. * @param tagName - The tag name to check against. */ function elementIsInstanceOf(element, tagName) { return nodeIsElement(element) && element.tagName.toLowerCase() === tagName; } /** * Identifies whether an element is a span element. * * @param element - The element to check. */ function elementIsSpanElement(element) { return elementIsInstanceOf(element, "span"); } /** * Identifies whether an element is an input field. * * @param element - The element to check. */ function elementIsInputElement(element) { return elementIsInstanceOf(element, "input"); } /** * Identifies whether an element is a select field. * * @param element - The element to check. */ function elementIsSelectElement(element) { return elementIsInstanceOf(element, "select"); } /** * Identifies whether an element is a textarea field. * * @param element - The element to check. */ function elementIsTextAreaElement(element) { return elementIsInstanceOf(element, "textarea"); } /** * Identifies whether an element is a form element. * * @param element - The element to check. */ function elementIsFormElement(element) { return elementIsInstanceOf(element, "form"); } /** * Identifies whether an element is a label element. * * @param element - The element to check. */ function elementIsLabelElement(element) { return elementIsInstanceOf(element, "label"); } /** * Identifies whether an element is a description details `dd` element. * * @param element - The element to check. */ function elementIsDescriptionDetailsElement(element) { return elementIsInstanceOf(element, "dd"); } /** * Identifies whether an element is a description term `dt` element. * * @param element - The element to check. */ function elementIsDescriptionTermElement(element) { return elementIsInstanceOf(element, "dt"); } /** * Identifies whether a node is an HTML element. * * @param node - The node to check. */ function nodeIsElement(node) { if (!node) { return false; } return (node === null || node === void 0 ? void 0 : node.nodeType) === Node.ELEMENT_NODE; } /** * Identifies whether a node is an input element. * * @param node - The node to check. */ function nodeIsInputElement(node) { return nodeIsElement(node) && elementIsInputElement(node); } /** * Identifies whether a node is a form element. * * @param node - The node to check. */ function nodeIsFormElement(node) { return nodeIsElement(node) && elementIsFormElement(node); } function nodeIsTypeSubmitElement(node) { return nodeIsElement(node) && getPropertyOrAttribute(node, "type") === "submit"; } function nodeIsButtonElement(node) { return (nodeIsElement(node) && (elementIsInstanceOf(node, "button") || getPropertyOrAttribute(node, "type") === "button")); } function nodeIsAnchorElement(node) { return nodeIsElement(node) && elementIsInstanceOf(node, "a"); } /** * Returns a boolean representing the attribute value of an element. * * @param element * @param attributeName * @param checkString */ function getAttributeBoolean(element, attributeName, checkString = false) { if (checkString) { return getPropertyOrAttribute(element, attributeName) === "true"; } return Boolean(getPropertyOrAttribute(element, attributeName)); } /** * Get the value of a property or attribute from a FormFieldElement. * * @param element * @param attributeName */ function getPropertyOrAttribute(element, attributeName) { if (attributeName in element) { return element[attributeName]; } return element.getAttribute(attributeName); } /** * Throttles a callback function to run at most once every `limit` milliseconds. * * @param callback - The callback function to throttle. * @param limit - The time in milliseconds to throttle the callback. */ function throttle(callback, limit) { let waitingDelay = false; return function (...args) { if (!waitingDelay) { callback.apply(this, args); waitingDelay = true; globalThis.setTimeout(() => (waitingDelay = false), limit); } }; } /** * Debounces a callback function to run after a delay of `delay` milliseconds. * * @param callback - The callback function to debounce. * @param delay - The time in milliseconds to debounce the callback. * @param immediate - Determines whether the callback should run immediately. */ function debounce(callback, delay, immediate) { let timeout; return function (...args) { const callImmediately = !!immediate && !timeout; if (timeout) { globalThis.clearTimeout(timeout); } timeout = globalThis.setTimeout(() => { timeout = null; if (!callImmediately) { callback.apply(this, args); } }, delay); if (callImmediately) { callback.apply(this, args); } }; } /** * Gathers and normalizes keywords from a potential submit button element. Used * to verify if the element submits a login or change password form. * * @param element - The element to gather keywords from. */ function getSubmitButtonKeywordsSet(element) { const keywords = [ element.textContent, element.getAttribute("type"), element.getAttribute("value"), element.getAttribute("aria-label"), element.getAttribute("aria-labelledby"), element.getAttribute("aria-describedby"), element.getAttribute("title"), element.getAttribute("id"), element.getAttribute("name"), element.getAttribute("class"), ]; const keywordsSet = new Set(); for (let i = 0; i < keywords.length; i++) { if (typeof keywords[i] === "string") { // Iterate over all keywords metadata and split them by non-letter characters. // This ensures we check against individual words and not the entire string. keywords[i] .toLowerCase() .replace(/[-\s]/g, "") .split(/[^\p{L}]+/gu) .forEach((keyword) => { if (keyword) { keywordsSet.add(keyword); } }); } } return keywordsSet; } /** * Generates the origin and subdomain match patterns for the URL. * * @param url - The URL of the tab */ function generateDomainMatchPatterns(url) { try { const extensionUrlPattern = /^(chrome|chrome-extension|moz-extension|safari-web-extension):\/\/\/?/; if (extensionUrlPattern.test(url)) { return []; } // Add protocol to URL if it is missing to allow for parsing the hostname correctly const urlPattern = /^(https?|file):\/\/\/?/; if (!urlPattern.test(url)) { url = `https://${url}`; } let protocolGlob = "*://"; if (url.startsWith("file:///")) { protocolGlob = "*:///"; // File URLs require three slashes to be a valid match pattern } const parsedUrl = new URL(url); const originMatchPattern = `${protocolGlob}${parsedUrl.hostname}/*`; const splitHost = parsedUrl.hostname.split("."); const domain = splitHost.slice(-2).join("."); const subDomainMatchPattern = `${protocolGlob}*.${domain}/*`; return [originMatchPattern, subDomainMatchPattern]; } catch (_a) { return []; } } /** * Determines if the status code of the web response is invalid. An invalid status code is * any status code that is not in the 200-299 range. * * @param statusCode - The status code of the web response */ function isInvalidResponseStatusCode(statusCode) { return statusCode < 200 || statusCode >= 300; } /** * Determines if the current context is within a sandboxed iframe. */ function currentlyInSandboxedIframe() { var _a, _b; if (String(self.origin).toLowerCase() === "null" || globalThis.location.hostname === "") { return true; } const sandbox = (_b = (_a = globalThis.frameElement) === null || _a === void 0 ? void 0 : _a.getAttribute) === null || _b === void 0 ? void 0 : _b.call(_a, "sandbox"); // No frameElement or sandbox attribute means not sandboxed if (sandbox === null || sandbox === undefined) { return false; } // An empty string means fully sandboxed if (sandbox === "") { return true; } const tokens = new Set(sandbox.toLowerCase().split(" ")); return !["allow-scripts", "allow-same-origin"].every((token) => tokens.has(token)); } /** * This object allows us to map a special character to a key name. The key name is used * in gathering the i18n translation of the written version of the special character. */ const specialCharacterToKeyMap = { " ": "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", }; /** * Determines if the current rect values are not all 0. */ function rectHasSize(rect) { if (rect.right > 0 && rect.left > 0 && rect.top > 0 && rect.bottom > 0) { return true; } return false; } /** * Checks if all the values corresponding to the specified keys in an object are null. * If no keys are specified, checks all keys in the object. * * @param obj - The object to check. * @param keys - An optional array of keys to check in the object. Defaults to all keys. * @returns Returns true if all values for the specified keys (or all keys if none are provided) are null; otherwise, false. */ function areKeyValuesNull(obj, keys) { const keysToCheck = keys && keys.length > 0 ? keys : Object.keys(obj); return keysToCheck.every((key) => obj[key] == null); } ;// ../../libs/common/src/autofill/constants/match-patterns.ts const CardExpiryDateDelimiters = ["/", "-", ".", " "]; // `CardExpiryDateDelimiters` is not intended solely for regex consumption, // so we need to format it here const ExpiryDateDelimitersPattern = "\\" + CardExpiryDateDelimiters.join("\\") // replace space character with the regex whitespace character class .replace(" ", "s"); const MonthPattern = "(([1]{1}[0-2]{1})|(0?[1-9]{1}))"; // Because we're dealing with expiry dates, we assume the year will be in current or next century (as of 2024) const match_patterns_ExpiryFullYearPattern = "2[0-1]{1}\\d{2}"; const match_patterns_DelimiterPatternExpression = new RegExp(`[${ExpiryDateDelimitersPattern}]`, "g"); const match_patterns_IrrelevantExpiryCharactersPatternExpression = new RegExp( // "nor digits" to ensure numbers are removed from guidance pattern, which aren't covered by ^\w `[^\\d${ExpiryDateDelimitersPattern}]`, "g"); const match_patterns_MonthPatternExpression = new RegExp(`^${MonthPattern}$`); const match_patterns_ExpiryFullYearPatternExpression = new RegExp(`^${match_patterns_ExpiryFullYearPattern}$`); ;// ../../libs/common/src/autofill/constants/index.ts const TYPE_CHECK = { FUNCTION: "function", NUMBER: "number", STRING: "string", }; const EVENTS = { CHANGE: "change", INPUT: "input", KEYDOWN: "keydown", KEYPRESS: "keypress", KEYUP: "keyup", BLUR: "blur", CLICK: "click", FOCUS: "focus", FOCUSIN: "focusin", FOCUSOUT: "focusout", SCROLL: "scroll", RESIZE: "resize", DOMCONTENTLOADED: "DOMContentLoaded", LOAD: "load", MESSAGE: "message", VISIBILITYCHANGE: "visibilitychange", MOUSEENTER: "mouseenter", MOUSELEAVE: "mouseleave", MOUSEUP: "mouseup", MOUSEOUT: "mouseout", SUBMIT: "submit", }; const ClearClipboardDelay = { Never: null, TenSeconds: 10, TwentySeconds: 20, ThirtySeconds: 30, OneMinute: 60, TwoMinutes: 120, FiveMinutes: 300, }; /* Ids for context menu items and messaging events */ const AUTOFILL_CARD_ID = "autofill-card"; const AUTOFILL_ID = "autofill"; const SHOW_AUTOFILL_BUTTON = "show-autofill-button"; const AUTOFILL_IDENTITY_ID = "autofill-identity"; const COPY_IDENTIFIER_ID = "copy-identifier"; const COPY_PASSWORD_ID = "copy-password"; const COPY_USERNAME_ID = "copy-username"; const COPY_VERIFICATION_CODE_ID = "copy-totp"; const CREATE_CARD_ID = "create-card"; const CREATE_IDENTITY_ID = "create-identity"; const CREATE_LOGIN_ID = "create-login"; const GENERATE_PASSWORD_ID = "generate-password"; const NOOP_COMMAND_SUFFIX = "noop"; const ROOT_ID = "root"; const SEPARATOR_ID = "separator"; const UPDATE_PASSWORD = "update-password"; const NOTIFICATION_BAR_LIFESPAN_MS = 150000; // 150 seconds const AUTOFILL_OVERLAY_HANDLE_REPOSITION = "autofill-overlay-handle-reposition-event"; const AUTOFILL_OVERLAY_HANDLE_SCROLL = "autofill-overlay-handle-scroll-event"; const UPDATE_PASSKEYS_HEADINGS_ON_SCROLL = "update-passkeys-headings-on-scroll"; const AUTOFILL_TRIGGER_FORM_FIELD_SUBMIT = "autofill-trigger-form-field-submit"; const AutofillOverlayVisibility = { Off: 0, OnButtonClick: 1, OnFieldFocus: 2, }; const BrowserClientVendors = { Chrome: "Chrome", Opera: "Opera", Edge: "Edge", Vivaldi: "Vivaldi", Unknown: "Unknown", }; const BrowserShortcutsUris = { Chrome: "chrome://extensions/shortcuts", Opera: "opera://extensions/shortcuts", Edge: "edge://extensions/shortcuts", Vivaldi: "vivaldi://extensions/shortcuts", Unknown: "https://bitwarden.com/help/keyboard-shortcuts", }; const DisablePasswordManagerUris = { Chrome: "chrome://settings/autofill", Opera: "opera://settings/autofill", Edge: "edge://settings/passwords", Vivaldi: "vivaldi://settings/autofill", Unknown: "https://bitwarden.com/help/disable-browser-autofill/", }; const ExtensionCommand = { AutofillCommand: "autofill_cmd", AutofillCard: "autofill_card", AutofillIdentity: "autofill_identity", AutofillLogin: "autofill_login", OpenAutofillOverlay: "open_autofill_overlay", GeneratePassword: "generate_password", OpenPopup: "open_popup", LockVault: "lock_vault", NoopCommand: "noop", }; const CLEAR_NOTIFICATION_LOGIN_DATA_DURATION = (/* unused pure expression or super */ null && (60 * 1000)); // 1 minute const MAX_DEEP_QUERY_RECURSION_DEPTH = 4; ;// ../../libs/common/src/platform/enums/encryption-type.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var EncryptionType; (function (EncryptionType) { // Symmetric encryption types EncryptionType[EncryptionType["AesCbc256_B64"] = 0] = "AesCbc256_B64"; // Type 1 was the unused and removed AesCbc128_HmacSha256_B64 EncryptionType[EncryptionType["AesCbc256_HmacSha256_B64"] = 2] = "AesCbc256_HmacSha256_B64"; // Cose is the encoding for the key used, but contained can be: // - XChaCha20Poly1305 EncryptionType[EncryptionType["CoseEncrypt0"] = 7] = "CoseEncrypt0"; // Asymmetric encryption types. These never occur in the same places that the symmetric ones would // and can be split out into a separate enum. EncryptionType[EncryptionType["Rsa2048_OaepSha256_B64"] = 3] = "Rsa2048_OaepSha256_B64"; EncryptionType[EncryptionType["Rsa2048_OaepSha1_B64"] = 4] = "Rsa2048_OaepSha1_B64"; EncryptionType[EncryptionType["Rsa2048_OaepSha256_HmacSha256_B64"] = 5] = "Rsa2048_OaepSha256_HmacSha256_B64"; EncryptionType[EncryptionType["Rsa2048_OaepSha1_HmacSha256_B64"] = 6] = "Rsa2048_OaepSha1_HmacSha256_B64"; })(EncryptionType || (EncryptionType = {})); function encryptionTypeToString(encryptionType) { if (encryptionType in EncryptionType) { return EncryptionType[encryptionType]; } else { return "Unknown encryption type " + encryptionType; } } /** The expected number of parts to a serialized EncString of the given encryption type. * For example, an EncString of type AesCbc256_B64 will have 2 parts * * Example of annotated serialized EncStrings: * 0.iv|data * 2.iv|data|mac * 3.data * 4.data * * @see EncString * @see EncryptionType * @see EncString.parseEncryptedString */ const EXPECTED_NUM_PARTS_BY_ENCRYPTION_TYPE = { [EncryptionType.AesCbc256_B64]: 2, [EncryptionType.AesCbc256_HmacSha256_B64]: 3, [EncryptionType.Rsa2048_OaepSha256_B64]: 1, [EncryptionType.Rsa2048_OaepSha1_B64]: 1, [EncryptionType.Rsa2048_OaepSha256_HmacSha256_B64]: 2, [EncryptionType.Rsa2048_OaepSha1_HmacSha256_B64]: 2, [EncryptionType.CoseEncrypt0]: 1, }; ;// ../../libs/common/src/platform/enums/file-upload-type.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var FileUploadType; (function (FileUploadType) { FileUploadType[FileUploadType["Direct"] = 0] = "Direct"; FileUploadType[FileUploadType["Azure"] = 1] = "Azure"; })(FileUploadType || (FileUploadType = {})); ;// ../../libs/common/src/platform/enums/hash-purpose.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var HashPurpose; (function (HashPurpose) { HashPurpose[HashPurpose["ServerAuthorization"] = 1] = "ServerAuthorization"; HashPurpose[HashPurpose["LocalAuthorization"] = 2] = "LocalAuthorization"; })(HashPurpose || (HashPurpose = {})); ;// ../../libs/storage-core/src/html-storage-location.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var HtmlStorageLocation; (function (HtmlStorageLocation) { HtmlStorageLocation["Local"] = "local"; HtmlStorageLocation["Memory"] = "memory"; HtmlStorageLocation["Session"] = "session"; })(HtmlStorageLocation || (HtmlStorageLocation = {})); ;// ../../node_modules/tslib/tslib.es6.mjs /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** *//* global Reflect, Promise, SuppressedError, Symbol, Iterator */var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b;}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p];};return extendStatics(d,b);};function __extends(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d;}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __());}var __assign=function(){__assign=Object.assign||function __assign(t){for(var s,i=1,n=arguments.length;i=0;i--)if(d=decorators[i])r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r;return c>3&&r&&Object.defineProperty(target,key,r),r;}function __param(paramIndex,decorator){return function(target,key){decorator(target,key,paramIndex);};}function __esDecorate(ctor,descriptorIn,decorators,contextIn,initializers,extraInitializers){function accept(f){if(f!==void 0&&typeof f!=="function")throw new TypeError("Function expected");return f;}var kind=contextIn.kind,key=kind==="getter"?"get":kind==="setter"?"set":"value";var target=!descriptorIn&&ctor?contextIn["static"]?ctor:ctor.prototype:null;var descriptor=descriptorIn||(target?Object.getOwnPropertyDescriptor(target,contextIn.name):{});var _,done=false;for(var i=decorators.length-1;i>=0;i--){var context={};for(var p in contextIn)context[p]=p==="access"?{}:contextIn[p];for(var p in contextIn.access)context.access[p]=contextIn.access[p];context.addInitializer=function(f){if(done)throw new TypeError("Cannot add initializers after decoration has completed");extraInitializers.push(accept(f||null));};var result=(0,decorators[i])(kind==="accessor"?{get:descriptor.get,set:descriptor.set}:descriptor[key],context);if(kind==="accessor"){if(result===void 0)continue;if(result===null||typeof result!=="object")throw new TypeError("Object expected");if(_=accept(result.get))descriptor.get=_;if(_=accept(result.set))descriptor.set=_;if(_=accept(result.init))initializers.unshift(_);}else if(_=accept(result)){if(kind==="field")initializers.unshift(_);else descriptor[key]=_;}}if(target)Object.defineProperty(target,contextIn.name,descriptor);done=true;};function __runInitializers(thisArg,initializers,value){var useValue=arguments.length>2;for(var i=0;i0&&t[t.length-1])&&(op[0]===6||op[0]===2)){_=0;continue;}if(op[0]===3&&(!t||op[1]>t[0]&&op[1]=o.length)o=void 0;return{value:o&&o[i++],done:!o};}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.");}function __read(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-->0)&&!(r=i.next()).done)ar.push(r.value);}catch(error){e={error:error};}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i);}finally{if(e)throw e.error;}}return ar;}/** @deprecated */function __spread(){for(var ar=[],i=0;i1||resume(n,v);});};if(f)i[n]=f(i[n]);}}function resume(n,v){try{step(g[n](v));}catch(e){settle(q[0][3],e);}}function step(r){r.value instanceof __await?Promise.resolve(r.value.v).then(fulfill,reject):settle(q[0][2],r);}function fulfill(value){resume("next",value);}function reject(value){resume("throw",value);}function settle(f,v){if(f(v),q.shift(),q.length)resume(q[0][0],q[0][1]);}}function __asyncDelegator(o){var i,p;return i={},verb("next"),verb("throw",function(e){throw e;}),verb("return"),i[Symbol.iterator]=function(){return this;},i;function verb(n,f){i[n]=o[n]?function(v){return(p=!p)?{value:__await(o[n](v)),done:false}:f?f(v):v;}:f;}}function __asyncValues(o){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var m=o[Symbol.asyncIterator],i;return m?m.call(o):(o=typeof __values==="function"?__values(o):o[Symbol.iterator](),i={},verb("next"),verb("throw"),verb("return"),i[Symbol.asyncIterator]=function(){return this;},i);function verb(n){i[n]=o[n]&&function(v){return new Promise(function(resolve,reject){v=o[n](v),settle(resolve,reject,v.done,v.value);});};}function settle(resolve,reject,d,v){Promise.resolve(v).then(function(v){resolve({value:v,done:d});},reject);}}function __makeTemplateObject(cooked,raw){if(Object.defineProperty){Object.defineProperty(cooked,"raw",{value:raw});}else{cooked.raw=raw;}return cooked;};var __setModuleDefault=Object.create?function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v});}:function(o,v){o["default"]=v;};var ownKeys=function(o){ownKeys=Object.getOwnPropertyNames||function(o){var ar=[];for(var k in o)if(Object.prototype.hasOwnProperty.call(o,k))ar[ar.length]=k;return ar;};return ownKeys(o);};function __importStar(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null)for(var k=ownKeys(mod),i=0;i0;},enumerable:false,configurable:true});Subject.prototype._trySubscribe=function(subscriber){this._throwIfClosed();return _super.prototype._trySubscribe.call(this,subscriber);};Subject.prototype._subscribe=function(subscriber){this._throwIfClosed();this._checkFinalizedStatuses(subscriber);return this._innerSubscribe(subscriber);};Subject.prototype._innerSubscribe=function(subscriber){var _this=this;var _a=this,hasError=_a.hasError,isStopped=_a.isStopped,observers=_a.observers;if(hasError||isStopped){return EMPTY_SUBSCRIPTION;}this.currentObservers=null;observers.push(subscriber);return new Subscription(function(){_this.currentObservers=null;arrRemove(observers,subscriber);});};Subject.prototype._checkFinalizedStatuses=function(subscriber){var _a=this,hasError=_a.hasError,thrownError=_a.thrownError,isStopped=_a.isStopped;if(hasError){subscriber.error(thrownError);}else if(isStopped){subscriber.complete();}};Subject.prototype.asObservable=function(){var observable=new Observable_Observable();observable.source=this;return observable;};Subject.create=function(destination,source){return new AnonymousSubject(destination,source);};return Subject;}(Observable_Observable);var AnonymousSubject=function(_super){__extends(AnonymousSubject,_super);function AnonymousSubject(destination,source){var _this=_super.call(this)||this;_this.destination=destination;_this.source=source;return _this;}AnonymousSubject.prototype.next=function(value){var _a,_b;(_b=(_a=this.destination)===null||_a===void 0?void 0:_a.next)===null||_b===void 0?void 0:_b.call(_a,value);};AnonymousSubject.prototype.error=function(err){var _a,_b;(_b=(_a=this.destination)===null||_a===void 0?void 0:_a.error)===null||_b===void 0?void 0:_b.call(_a,err);};AnonymousSubject.prototype.complete=function(){var _a,_b;(_b=(_a=this.destination)===null||_a===void 0?void 0:_a.complete)===null||_b===void 0?void 0:_b.call(_a);};AnonymousSubject.prototype._subscribe=function(subscriber){var _a,_b;return(_b=(_a=this.source)===null||_a===void 0?void 0:_a.subscribe(subscriber))!==null&&_b!==void 0?_b:EMPTY_SUBSCRIPTION;};return AnonymousSubject;}(Subject_Subject); ;// ../../libs/storage-core/src/storage.service.ts class StorageService { } ;// ../../libs/storage-core/src/memory-storage.service.ts var memory_storage_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore class MemoryStorageService extends StorageService { constructor() { super(...arguments); this.store = new Map(); this.updatesSubject = new Subject_Subject(); } get valuesRequireDeserialization() { return false; } get updates$() { return this.updatesSubject.asObservable(); } get(key) { if (this.store.has(key)) { const obj = this.store.get(key); return Promise.resolve(obj); } return Promise.resolve(null); } has(key) { return memory_storage_service_awaiter(this, void 0, void 0, function* () { return (yield this.get(key)) != null; }); } save(key, obj) { if (obj == null) { return this.remove(key); } // TODO: Remove once foreground/background contexts are separated in browser // Needed to ensure ownership of all memory by the context running the storage service const toStore = structuredClone(obj); this.store.set(key, toStore); this.updatesSubject.next({ key, updateType: "save" }); return Promise.resolve(); } remove(key) { this.store.delete(key); this.updatesSubject.next({ key, updateType: "remove" }); return Promise.resolve(); } } ;// ../../libs/storage-core/src/serialized-memory-storage.service.ts var serialized_memory_storage_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore class SerializedMemoryStorageService extends StorageService { constructor() { super(...arguments); this.store = {}; this.updatesSubject = new Subject_Subject(); } get valuesRequireDeserialization() { return true; } get updates$() { return this.updatesSubject.asObservable(); } get(key) { const json = this.store[key]; if (json) { const obj = JSON.parse(json); return Promise.resolve(obj); } return Promise.resolve(null); } has(key) { return serialized_memory_storage_service_awaiter(this, void 0, void 0, function* () { return (yield this.get(key)) != null; }); } save(key, obj) { if (obj == null) { return this.remove(key); } // TODO: Remove once foreground/background contexts are separated in browser // Needed to ensure ownership of all memory by the context running the storage service this.store[key] = JSON.stringify(obj); this.updatesSubject.next({ key, updateType: "save" }); return Promise.resolve(); } remove(key) { delete this.store[key]; this.updatesSubject.next({ key, updateType: "remove" }); return Promise.resolve(); } } ;// ../../libs/storage-core/src/storage-location.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var StorageLocationEnum; (function (StorageLocationEnum) { StorageLocationEnum["Both"] = "both"; StorageLocationEnum["Disk"] = "disk"; StorageLocationEnum["Memory"] = "memory"; })(StorageLocationEnum || (StorageLocationEnum = {})); ;// ../../libs/storage-core/src/index.ts // Renamed to just "StorageService", to be removed when references are updated ;// ../../libs/common/src/platform/enums/html-storage-location.enum.ts ;// ../../libs/common/src/platform/enums/key-suffix-options.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var KeySuffixOptions; (function (KeySuffixOptions) { KeySuffixOptions["Auto"] = "auto"; KeySuffixOptions["Pin"] = "pin"; })(KeySuffixOptions || (KeySuffixOptions = {})); ;// ../../libs/logging/src/log-level.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var LogLevel; (function (LogLevel) { LogLevel[LogLevel["Debug"] = 0] = "Debug"; LogLevel[LogLevel["Info"] = 1] = "Info"; LogLevel[LogLevel["Warning"] = 2] = "Warning"; LogLevel[LogLevel["Error"] = 3] = "Error"; })(LogLevel || (LogLevel = {})); ;// ../../libs/logging/src/console-log.service.ts class ConsoleLogService { constructor(isDev, filter = null) { this.isDev = isDev; this.filter = filter; this.timersMap = new Map(); } debug(message, ...optionalParams) { if (!this.isDev) { return; } this.write(LogLevel.Debug, message, ...optionalParams); } info(message, ...optionalParams) { this.write(LogLevel.Info, message, ...optionalParams); } warning(message, ...optionalParams) { this.write(LogLevel.Warning, message, ...optionalParams); } error(message, ...optionalParams) { this.write(LogLevel.Error, message, ...optionalParams); } write(level, message, ...optionalParams) { if (this.filter != null && this.filter(level)) { return; } switch (level) { case LogLevel.Debug: // eslint-disable-next-line console.log(message, ...optionalParams); break; case LogLevel.Info: // eslint-disable-next-line console.log(message, ...optionalParams); break; case LogLevel.Warning: // eslint-disable-next-line console.warn(message, ...optionalParams); break; case LogLevel.Error: // eslint-disable-next-line console.error(message, ...optionalParams); break; default: break; } } measure(start, trackGroup, track, name, properties) { const measureName = `[${track}]: ${name}`; const measure = performance.measure(measureName, { start: start, detail: { devtools: { dataType: "track-entry", track, trackGroup, properties, }, }, }); this.info(`${measureName} took ${measure.duration}`, properties); return measure; } mark(name) { const mark = performance.mark(name, { detail: { devtools: { dataType: "marker", }, }, }); this.info(mark.name, new Date().toISOString()); return mark; } } ;// ../../libs/logging/src/index.ts ;// ../../libs/common/src/platform/enums/log-level-type.enum.ts ;// ../../libs/common/src/platform/enums/storage-location.enum.ts ;// ../../libs/common/src/platform/enums/theme-type.enum.ts /** * @deprecated prefer the `ThemeTypes` constants and `Theme` type over unsafe enum types **/ // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var ThemeType; (function (ThemeType) { ThemeType["System"] = "system"; ThemeType["Light"] = "light"; ThemeType["Dark"] = "dark"; })(ThemeType || (ThemeType = {})); const ThemeTypes = { System: "system", Light: "light", Dark: "dark", }; ;// ../../libs/common/src/platform/enums/index.ts ;// ../../libs/client-type/src/index.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var ClientType; (function (ClientType) { ClientType["Web"] = "web"; ClientType["Browser"] = "browser"; ClientType["Desktop"] = "desktop"; // Mobile = "mobile", ClientType["Cli"] = "cli"; // DirectoryConnector = "connector", })(ClientType || (ClientType = {})); ;// ../../libs/common/src/enums/client-type.enum.ts ;// ../../libs/common/src/enums/device-type.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var DeviceType; (function (DeviceType) { DeviceType[DeviceType["Android"] = 0] = "Android"; DeviceType[DeviceType["iOS"] = 1] = "iOS"; DeviceType[DeviceType["ChromeExtension"] = 2] = "ChromeExtension"; DeviceType[DeviceType["FirefoxExtension"] = 3] = "FirefoxExtension"; DeviceType[DeviceType["OperaExtension"] = 4] = "OperaExtension"; DeviceType[DeviceType["EdgeExtension"] = 5] = "EdgeExtension"; DeviceType[DeviceType["WindowsDesktop"] = 6] = "WindowsDesktop"; DeviceType[DeviceType["MacOsDesktop"] = 7] = "MacOsDesktop"; DeviceType[DeviceType["LinuxDesktop"] = 8] = "LinuxDesktop"; DeviceType[DeviceType["ChromeBrowser"] = 9] = "ChromeBrowser"; DeviceType[DeviceType["FirefoxBrowser"] = 10] = "FirefoxBrowser"; DeviceType[DeviceType["OperaBrowser"] = 11] = "OperaBrowser"; DeviceType[DeviceType["EdgeBrowser"] = 12] = "EdgeBrowser"; DeviceType[DeviceType["IEBrowser"] = 13] = "IEBrowser"; DeviceType[DeviceType["UnknownBrowser"] = 14] = "UnknownBrowser"; DeviceType[DeviceType["AndroidAmazon"] = 15] = "AndroidAmazon"; DeviceType[DeviceType["UWP"] = 16] = "UWP"; DeviceType[DeviceType["SafariBrowser"] = 17] = "SafariBrowser"; DeviceType[DeviceType["VivaldiBrowser"] = 18] = "VivaldiBrowser"; DeviceType[DeviceType["VivaldiExtension"] = 19] = "VivaldiExtension"; DeviceType[DeviceType["SafariExtension"] = 20] = "SafariExtension"; DeviceType[DeviceType["SDK"] = 21] = "SDK"; DeviceType[DeviceType["Server"] = 22] = "Server"; DeviceType[DeviceType["WindowsCLI"] = 23] = "WindowsCLI"; DeviceType[DeviceType["MacOsCLI"] = 24] = "MacOsCLI"; DeviceType[DeviceType["LinuxCLI"] = 25] = "LinuxCLI"; DeviceType[DeviceType["DuckDuckGoBrowser"] = 26] = "DuckDuckGoBrowser"; })(DeviceType || (DeviceType = {})); const DeviceTypeMetadata = { [DeviceType.Android]: { category: "mobile", platform: "Android" }, [DeviceType.iOS]: { category: "mobile", platform: "iOS" }, [DeviceType.AndroidAmazon]: { category: "mobile", platform: "Amazon" }, [DeviceType.ChromeExtension]: { category: "extension", platform: "Chrome" }, [DeviceType.FirefoxExtension]: { category: "extension", platform: "Firefox" }, [DeviceType.OperaExtension]: { category: "extension", platform: "Opera" }, [DeviceType.EdgeExtension]: { category: "extension", platform: "Edge" }, [DeviceType.VivaldiExtension]: { category: "extension", platform: "Vivaldi" }, [DeviceType.SafariExtension]: { category: "extension", platform: "Safari" }, [DeviceType.ChromeBrowser]: { category: "webApp", platform: "Chrome" }, [DeviceType.FirefoxBrowser]: { category: "webApp", platform: "Firefox" }, [DeviceType.OperaBrowser]: { category: "webApp", platform: "Opera" }, [DeviceType.EdgeBrowser]: { category: "webApp", platform: "Edge" }, [DeviceType.IEBrowser]: { category: "webApp", platform: "IE" }, [DeviceType.SafariBrowser]: { category: "webApp", platform: "Safari" }, [DeviceType.VivaldiBrowser]: { category: "webApp", platform: "Vivaldi" }, [DeviceType.DuckDuckGoBrowser]: { category: "webApp", platform: "DuckDuckGo" }, [DeviceType.UnknownBrowser]: { category: "webApp", platform: "Unknown" }, [DeviceType.WindowsDesktop]: { category: "desktop", platform: "Windows" }, [DeviceType.MacOsDesktop]: { category: "desktop", platform: "macOS" }, [DeviceType.LinuxDesktop]: { category: "desktop", platform: "Linux" }, [DeviceType.UWP]: { category: "desktop", platform: "Windows UWP" }, [DeviceType.WindowsCLI]: { category: "cli", platform: "Windows" }, [DeviceType.MacOsCLI]: { category: "cli", platform: "macOS" }, [DeviceType.LinuxCLI]: { category: "cli", platform: "Linux" }, [DeviceType.SDK]: { category: "sdk", platform: "" }, [DeviceType.Server]: { category: "server", platform: "" }, }; ;// ../../libs/common/src/enums/event-system-user.enum.ts // Note: the enum key is used to describe the EventSystemUser in the UI. Be careful about changing it. // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var EventSystemUser; (function (EventSystemUser) { EventSystemUser[EventSystemUser["SCIM"] = 1] = "SCIM"; EventSystemUser[EventSystemUser["DomainVerification"] = 2] = "DomainVerification"; EventSystemUser[EventSystemUser["PublicApi"] = 3] = "PublicApi"; })(EventSystemUser || (EventSystemUser = {})); ;// ../../libs/common/src/enums/event-type.enum.ts // Increment by 100 for each new set of events // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var EventType; (function (EventType) { EventType[EventType["User_LoggedIn"] = 1000] = "User_LoggedIn"; EventType[EventType["User_ChangedPassword"] = 1001] = "User_ChangedPassword"; EventType[EventType["User_Updated2fa"] = 1002] = "User_Updated2fa"; EventType[EventType["User_Disabled2fa"] = 1003] = "User_Disabled2fa"; EventType[EventType["User_Recovered2fa"] = 1004] = "User_Recovered2fa"; EventType[EventType["User_FailedLogIn"] = 1005] = "User_FailedLogIn"; EventType[EventType["User_FailedLogIn2fa"] = 1006] = "User_FailedLogIn2fa"; EventType[EventType["User_ClientExportedVault"] = 1007] = "User_ClientExportedVault"; EventType[EventType["User_UpdatedTempPassword"] = 1008] = "User_UpdatedTempPassword"; EventType[EventType["User_MigratedKeyToKeyConnector"] = 1009] = "User_MigratedKeyToKeyConnector"; EventType[EventType["User_RequestedDeviceApproval"] = 1010] = "User_RequestedDeviceApproval"; EventType[EventType["User_TdeOffboardingPasswordSet"] = 1011] = "User_TdeOffboardingPasswordSet"; EventType[EventType["Cipher_Created"] = 1100] = "Cipher_Created"; EventType[EventType["Cipher_Updated"] = 1101] = "Cipher_Updated"; EventType[EventType["Cipher_Deleted"] = 1102] = "Cipher_Deleted"; EventType[EventType["Cipher_AttachmentCreated"] = 1103] = "Cipher_AttachmentCreated"; EventType[EventType["Cipher_AttachmentDeleted"] = 1104] = "Cipher_AttachmentDeleted"; EventType[EventType["Cipher_Shared"] = 1105] = "Cipher_Shared"; EventType[EventType["Cipher_UpdatedCollections"] = 1106] = "Cipher_UpdatedCollections"; EventType[EventType["Cipher_ClientViewed"] = 1107] = "Cipher_ClientViewed"; EventType[EventType["Cipher_ClientToggledPasswordVisible"] = 1108] = "Cipher_ClientToggledPasswordVisible"; EventType[EventType["Cipher_ClientToggledHiddenFieldVisible"] = 1109] = "Cipher_ClientToggledHiddenFieldVisible"; EventType[EventType["Cipher_ClientToggledCardCodeVisible"] = 1110] = "Cipher_ClientToggledCardCodeVisible"; EventType[EventType["Cipher_ClientCopiedPassword"] = 1111] = "Cipher_ClientCopiedPassword"; EventType[EventType["Cipher_ClientCopiedHiddenField"] = 1112] = "Cipher_ClientCopiedHiddenField"; EventType[EventType["Cipher_ClientCopiedCardCode"] = 1113] = "Cipher_ClientCopiedCardCode"; EventType[EventType["Cipher_ClientAutofilled"] = 1114] = "Cipher_ClientAutofilled"; EventType[EventType["Cipher_SoftDeleted"] = 1115] = "Cipher_SoftDeleted"; EventType[EventType["Cipher_Restored"] = 1116] = "Cipher_Restored"; EventType[EventType["Cipher_ClientToggledCardNumberVisible"] = 1117] = "Cipher_ClientToggledCardNumberVisible"; EventType[EventType["Cipher_ClientToggledTOTPSeedVisible"] = 1118] = "Cipher_ClientToggledTOTPSeedVisible"; EventType[EventType["Collection_Created"] = 1300] = "Collection_Created"; EventType[EventType["Collection_Updated"] = 1301] = "Collection_Updated"; EventType[EventType["Collection_Deleted"] = 1302] = "Collection_Deleted"; EventType[EventType["Group_Created"] = 1400] = "Group_Created"; EventType[EventType["Group_Updated"] = 1401] = "Group_Updated"; EventType[EventType["Group_Deleted"] = 1402] = "Group_Deleted"; EventType[EventType["OrganizationUser_Invited"] = 1500] = "OrganizationUser_Invited"; EventType[EventType["OrganizationUser_Confirmed"] = 1501] = "OrganizationUser_Confirmed"; EventType[EventType["OrganizationUser_Updated"] = 1502] = "OrganizationUser_Updated"; EventType[EventType["OrganizationUser_Removed"] = 1503] = "OrganizationUser_Removed"; EventType[EventType["OrganizationUser_UpdatedGroups"] = 1504] = "OrganizationUser_UpdatedGroups"; EventType[EventType["OrganizationUser_UnlinkedSso"] = 1505] = "OrganizationUser_UnlinkedSso"; EventType[EventType["OrganizationUser_ResetPassword_Enroll"] = 1506] = "OrganizationUser_ResetPassword_Enroll"; EventType[EventType["OrganizationUser_ResetPassword_Withdraw"] = 1507] = "OrganizationUser_ResetPassword_Withdraw"; EventType[EventType["OrganizationUser_AdminResetPassword"] = 1508] = "OrganizationUser_AdminResetPassword"; EventType[EventType["OrganizationUser_ResetSsoLink"] = 1509] = "OrganizationUser_ResetSsoLink"; EventType[EventType["OrganizationUser_FirstSsoLogin"] = 1510] = "OrganizationUser_FirstSsoLogin"; EventType[EventType["OrganizationUser_Revoked"] = 1511] = "OrganizationUser_Revoked"; EventType[EventType["OrganizationUser_Restored"] = 1512] = "OrganizationUser_Restored"; EventType[EventType["OrganizationUser_ApprovedAuthRequest"] = 1513] = "OrganizationUser_ApprovedAuthRequest"; EventType[EventType["OrganizationUser_RejectedAuthRequest"] = 1514] = "OrganizationUser_RejectedAuthRequest"; EventType[EventType["OrganizationUser_Deleted"] = 1515] = "OrganizationUser_Deleted"; EventType[EventType["OrganizationUser_Left"] = 1516] = "OrganizationUser_Left"; EventType[EventType["Organization_Updated"] = 1600] = "Organization_Updated"; EventType[EventType["Organization_PurgedVault"] = 1601] = "Organization_PurgedVault"; EventType[EventType["Organization_ClientExportedVault"] = 1602] = "Organization_ClientExportedVault"; EventType[EventType["Organization_VaultAccessed"] = 1603] = "Organization_VaultAccessed"; EventType[EventType["Organization_EnabledSso"] = 1604] = "Organization_EnabledSso"; EventType[EventType["Organization_DisabledSso"] = 1605] = "Organization_DisabledSso"; EventType[EventType["Organization_EnabledKeyConnector"] = 1606] = "Organization_EnabledKeyConnector"; EventType[EventType["Organization_DisabledKeyConnector"] = 1607] = "Organization_DisabledKeyConnector"; EventType[EventType["Organization_SponsorshipsSynced"] = 1608] = "Organization_SponsorshipsSynced"; EventType[EventType["Organization_CollectionManagementUpdated"] = 1609] = "Organization_CollectionManagementUpdated"; EventType[EventType["Organization_CollectionManagement_LimitCollectionCreationEnabled"] = 1610] = "Organization_CollectionManagement_LimitCollectionCreationEnabled"; EventType[EventType["Organization_CollectionManagement_LimitCollectionCreationDisabled"] = 1611] = "Organization_CollectionManagement_LimitCollectionCreationDisabled"; EventType[EventType["Organization_CollectionManagement_LimitCollectionDeletionEnabled"] = 1612] = "Organization_CollectionManagement_LimitCollectionDeletionEnabled"; EventType[EventType["Organization_CollectionManagement_LimitCollectionDeletionDisabled"] = 1613] = "Organization_CollectionManagement_LimitCollectionDeletionDisabled"; EventType[EventType["Organization_CollectionManagement_LimitItemDeletionEnabled"] = 1614] = "Organization_CollectionManagement_LimitItemDeletionEnabled"; EventType[EventType["Organization_CollectionManagement_LimitItemDeletionDisabled"] = 1615] = "Organization_CollectionManagement_LimitItemDeletionDisabled"; EventType[EventType["Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsEnabled"] = 1616] = "Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsEnabled"; EventType[EventType["Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsDisabled"] = 1617] = "Organization_CollectionManagement_AllowAdminAccessToAllCollectionItemsDisabled"; EventType[EventType["Organization_ItemOrganization_Accepted"] = 1618] = "Organization_ItemOrganization_Accepted"; EventType[EventType["Organization_ItemOrganization_Declined"] = 1619] = "Organization_ItemOrganization_Declined"; EventType[EventType["Policy_Updated"] = 1700] = "Policy_Updated"; EventType[EventType["ProviderUser_Invited"] = 1800] = "ProviderUser_Invited"; EventType[EventType["ProviderUser_Confirmed"] = 1801] = "ProviderUser_Confirmed"; EventType[EventType["ProviderUser_Updated"] = 1802] = "ProviderUser_Updated"; EventType[EventType["ProviderUser_Removed"] = 1803] = "ProviderUser_Removed"; EventType[EventType["ProviderOrganization_Created"] = 1900] = "ProviderOrganization_Created"; EventType[EventType["ProviderOrganization_Added"] = 1901] = "ProviderOrganization_Added"; EventType[EventType["ProviderOrganization_Removed"] = 1902] = "ProviderOrganization_Removed"; EventType[EventType["ProviderOrganization_VaultAccessed"] = 1903] = "ProviderOrganization_VaultAccessed"; EventType[EventType["OrganizationDomain_Added"] = 2000] = "OrganizationDomain_Added"; EventType[EventType["OrganizationDomain_Removed"] = 2001] = "OrganizationDomain_Removed"; EventType[EventType["OrganizationDomain_Verified"] = 2002] = "OrganizationDomain_Verified"; EventType[EventType["OrganizationDomain_NotVerified"] = 2003] = "OrganizationDomain_NotVerified"; EventType[EventType["Secret_Retrieved"] = 2100] = "Secret_Retrieved"; EventType[EventType["Secret_Created"] = 2101] = "Secret_Created"; EventType[EventType["Secret_Edited"] = 2102] = "Secret_Edited"; EventType[EventType["Secret_Deleted"] = 2103] = "Secret_Deleted"; EventType[EventType["Secret_Permanently_Deleted"] = 2104] = "Secret_Permanently_Deleted"; EventType[EventType["Secret_Restored"] = 2105] = "Secret_Restored"; EventType[EventType["Project_Retrieved"] = 2200] = "Project_Retrieved"; EventType[EventType["Project_Created"] = 2201] = "Project_Created"; EventType[EventType["Project_Edited"] = 2202] = "Project_Edited"; EventType[EventType["Project_Deleted"] = 2203] = "Project_Deleted"; EventType[EventType["ServiceAccount_UserAdded"] = 2300] = "ServiceAccount_UserAdded"; EventType[EventType["ServiceAccount_UserRemoved"] = 2301] = "ServiceAccount_UserRemoved"; EventType[EventType["ServiceAccount_GroupAdded"] = 2302] = "ServiceAccount_GroupAdded"; EventType[EventType["ServiceAccount_GroupRemoved"] = 2303] = "ServiceAccount_GroupRemoved"; EventType[EventType["ServiceAccount_Created"] = 2304] = "ServiceAccount_Created"; EventType[EventType["ServiceAccount_Deleted"] = 2305] = "ServiceAccount_Deleted"; })(EventType || (EventType = {})); ;// ../../libs/common/src/enums/http-status-code.enum.ts /** * Hypertext Transfer Protocol (HTTP) response status codes. * * @see {@link https://en.wikipedia.org/wiki/List_of_HTTP_status_codes} * src: https://gist.github.com/RWOverdijk/6cef816cfdf5722228e01cc05fd4b094 */ // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var HttpStatusCode; (function (HttpStatusCode) { /** * The server has received the request headers and the client should proceed to send the request body * (in the case of a request for which a body needs to be sent; for example, a POST request). * Sending a large request body to a server after a request has been rejected for inappropriate headers would be inefficient. * To have a server check the request's headers, a client must send Expect: 100-continue as a header in its initial request * and receive a 100 Continue status code in response before sending the body. The response 417 Expectation Failed indicates the request should not be continued. */ HttpStatusCode[HttpStatusCode["Continue"] = 100] = "Continue"; /** * The requester has asked the server to switch protocols and the server has agreed to do so. */ HttpStatusCode[HttpStatusCode["SwitchingProtocols"] = 101] = "SwitchingProtocols"; /** * A WebDAV request may contain many sub-requests involving file operations, requiring a long time to complete the request. * This code indicates that the server has received and is processing the request, but no response is available yet. * This prevents the client from timing out and assuming the request was lost. */ HttpStatusCode[HttpStatusCode["Processing"] = 102] = "Processing"; // ********************************************************************************************************** // 200s - SUCCESS // ********************************************************************************************************** /** * Standard response for successful HTTP requests. * The actual response will depend on the request method used. * In a GET request, the response will contain an entity corresponding to the requested resource. * In a POST request, the response will contain an entity describing or containing the result of the action. */ HttpStatusCode[HttpStatusCode["Ok"] = 200] = "Ok"; /** * The request has been fulfilled, resulting in the creation of a new resource. */ HttpStatusCode[HttpStatusCode["Created"] = 201] = "Created"; /** * The request has been accepted for processing, but the processing has not been completed. * The request might or might not be eventually acted upon, and may be disallowed when processing occurs. */ HttpStatusCode[HttpStatusCode["Accepted"] = 202] = "Accepted"; /** * SINCE HTTP/1.1 * The server is a transforming proxy that received a 200 OK from its origin, * but is returning a modified version of the origin's response. */ HttpStatusCode[HttpStatusCode["NonAuthoritativeInformation"] = 203] = "NonAuthoritativeInformation"; /** * The server successfully processed the request and is not returning any content. */ HttpStatusCode[HttpStatusCode["NoContent"] = 204] = "NoContent"; /** * The server successfully processed the request, but is not returning any content. * Unlike a 204 response, this response requires that the requester reset the document view. */ HttpStatusCode[HttpStatusCode["ResetContent"] = 205] = "ResetContent"; /** * The server is delivering only part of the resource (byte serving) due to a range header sent by the client. * The range header is used by HTTP clients to enable resuming of interrupted downloads, * or split a download into multiple simultaneous streams. */ HttpStatusCode[HttpStatusCode["PartialContent"] = 206] = "PartialContent"; /** * The message body that follows is an XML message and can contain a number of separate response codes, * depending on how many sub-requests were made. */ HttpStatusCode[HttpStatusCode["MultiStatus"] = 207] = "MultiStatus"; /** * The members of a DAV binding have already been enumerated in a preceding part of the (multistatus) response, * and are not being included again. */ HttpStatusCode[HttpStatusCode["AlreadyReported"] = 208] = "AlreadyReported"; /** * The server has fulfilled a request for the resource, * and the response is a representation of the result of one or more instance-manipulations applied to the current instance. */ HttpStatusCode[HttpStatusCode["ImUsed"] = 226] = "ImUsed"; // ********************************************************************************************************** // 300s - Redirections // ********************************************************************************************************** /** * Indicates multiple options for the resource from which the client may choose (via agent-driven content negotiation). * For example, this code could be used to present multiple video format options, * to list files with different filename extensions, or to suggest word-sense disambiguation. */ HttpStatusCode[HttpStatusCode["MultipleChoices"] = 300] = "MultipleChoices"; /** * This and all future requests should be directed to the given URI. */ HttpStatusCode[HttpStatusCode["MovedPermanently"] = 301] = "MovedPermanently"; /** * This is an example of industry practice contradicting the standard. * The HTTP/1.0 specification (RFC 1945) required the client to perform a temporary redirect * (the original describing phrase was "Moved Temporarily"), but popular browsers implemented 302 * with the functionality of a 303 See Other. Therefore, HTTP/1.1 added status codes 303 and 307 * to distinguish between the two behaviours. However, some Web applications and frameworks * use the 302 status code as if it were the 303. */ HttpStatusCode[HttpStatusCode["Found"] = 302] = "Found"; /** * SINCE HTTP/1.1 * The response to the request can be found under another URI using a GET method. * When received in response to a POST (or PUT/DELETE), the client should presume that * the server has received the data and should issue a redirect with a separate GET message. */ HttpStatusCode[HttpStatusCode["SeeOther"] = 303] = "SeeOther"; /** * Indicates that the resource has not been modified since the version specified by the request headers If-Modified-Since or If-None-Match. * In such case, there is no need to retransmit the resource since the client still has a previously-downloaded copy. */ HttpStatusCode[HttpStatusCode["NotModified"] = 304] = "NotModified"; /** * SINCE HTTP/1.1 * The requested resource is available only through a proxy, the address for which is provided in the response. * Many HTTP clients (such as Mozilla and Internet Explorer) do not correctly handle responses with this status code, primarily for security reasons. */ HttpStatusCode[HttpStatusCode["UseProxy"] = 305] = "UseProxy"; /** * No longer used. Originally meant "Subsequent requests should use the specified proxy." */ HttpStatusCode[HttpStatusCode["SwitchProxy"] = 306] = "SwitchProxy"; /** * SINCE HTTP/1.1 * In this case, the request should be repeated with another URI; however, future requests should still use the original URI. * In contrast to how 302 was historically implemented, the request method is not allowed to be changed when reissuing the original request. * For example, a POST request should be repeated using another POST request. */ HttpStatusCode[HttpStatusCode["TemporaryRedirect"] = 307] = "TemporaryRedirect"; /** * The request and all future requests should be repeated using another URI. * 307 and 308 parallel the behaviors of 302 and 301, but do not allow the HTTP method to change. * So, for example, submitting a form to a permanently redirected resource may continue smoothly. */ HttpStatusCode[HttpStatusCode["PermanentRedirect"] = 308] = "PermanentRedirect"; // ********************************************************************************************************** // 400s - Client / User messed up // ********************************************************************************************************** /** * The server cannot or will not process the request due to an apparent client error * (e.g., malformed request syntax, too large size, invalid request message framing, or deceptive request routing). */ HttpStatusCode[HttpStatusCode["BadRequest"] = 400] = "BadRequest"; /** * Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet * been provided. The response must include a WWW-Authenticate header field containing a challenge applicable to the * requested resource. See Basic access authentication and Digest access authentication. 401 semantically means * "unauthenticated",i.e. the user does not have the necessary credentials. */ HttpStatusCode[HttpStatusCode["Unauthorized"] = 401] = "Unauthorized"; /** * Reserved for future use. The original intention was that this code might be used as part of some form of digital * cash or micro payment scheme, but that has not happened, and this code is not usually used. * Google Developers API uses this status if a particular developer has exceeded the daily limit on requests. */ HttpStatusCode[HttpStatusCode["PaymentRequired"] = 402] = "PaymentRequired"; /** * The request was valid, but the server is refusing action. * The user might not have the necessary permissions for a resource. */ HttpStatusCode[HttpStatusCode["Forbidden"] = 403] = "Forbidden"; /** * The requested resource could not be found but may be available in the future. * Subsequent requests by the client are permissible. */ HttpStatusCode[HttpStatusCode["NotFound"] = 404] = "NotFound"; /** * A request method is not supported for the requested resource; * for example, a GET request on a form that requires data to be presented via POST, or a PUT request on a read-only resource. */ HttpStatusCode[HttpStatusCode["MethodNotAllowed"] = 405] = "MethodNotAllowed"; /** * The requested resource is capable of generating only content not acceptable according to the Accept headers sent in the request. */ HttpStatusCode[HttpStatusCode["NotAcceptable"] = 406] = "NotAcceptable"; /** * The client must first authenticate itself with the proxy. */ HttpStatusCode[HttpStatusCode["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; /** * The server timed out waiting for the request. * According to HTTP specifications: * "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time." */ HttpStatusCode[HttpStatusCode["RequestTimeout"] = 408] = "RequestTimeout"; /** * Indicates that the request could not be processed because of conflict in the request, * such as an edit conflict between multiple simultaneous updates. */ HttpStatusCode[HttpStatusCode["Conflict"] = 409] = "Conflict"; /** * Indicates that the resource requested is no longer available and will not be available again. * This should be used when a resource has been intentionally removed and the resource should be purged. * Upon receiving a 410 status code, the client should not request the resource in the future. * Clients such as search engines should remove the resource from their indices. * Most use cases do not require clients and search engines to purge the resource, and a "404 Not Found" may be used instead. */ HttpStatusCode[HttpStatusCode["Gone"] = 410] = "Gone"; /** * The request did not specify the length of its content, which is required by the requested resource. */ HttpStatusCode[HttpStatusCode["LengthRequired"] = 411] = "LengthRequired"; /** * The server does not meet one of the preconditions that the requester put on the request. */ HttpStatusCode[HttpStatusCode["PreconditionFailed"] = 412] = "PreconditionFailed"; /** * The request is larger than the server is willing or able to process. Previously called "Request Entity Too Large". */ HttpStatusCode[HttpStatusCode["PayloadTooLarge"] = 413] = "PayloadTooLarge"; /** * The URI provided was too long for the server to process. Often the result of too much data being encoded as a query-string of a GET request, * in which case it should be converted to a POST request. * Called "Request-URI Too Long" previously. */ HttpStatusCode[HttpStatusCode["UriTooLong"] = 414] = "UriTooLong"; /** * The request entity has a media type which the server or resource does not support. * For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format. */ HttpStatusCode[HttpStatusCode["UnsupportedMediaType"] = 415] = "UnsupportedMediaType"; /** * The client has asked for a portion of the file (byte serving), but the server cannot supply that portion. * For example, if the client asked for a part of the file that lies beyond the end of the file. * Called "Requested Range Not Satisfiable" previously. */ HttpStatusCode[HttpStatusCode["RangeNotSatisfiable"] = 416] = "RangeNotSatisfiable"; /** * The server cannot meet the requirements of the Expect request-header field. */ HttpStatusCode[HttpStatusCode["ExpectationFailed"] = 417] = "ExpectationFailed"; /** * This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, * and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by * teapots requested to brew coffee. This HTTP status is used as an Easter egg in some websites, including Google.com. */ HttpStatusCode[HttpStatusCode["IAmATeapot"] = 418] = "IAmATeapot"; /** * The request was directed at a server that is not able to produce a response (for example because a connection reuse). */ HttpStatusCode[HttpStatusCode["MisdirectedRequest"] = 421] = "MisdirectedRequest"; /** * The request was well-formed but was unable to be followed due to semantic errors. */ HttpStatusCode[HttpStatusCode["UnprocessableEntity"] = 422] = "UnprocessableEntity"; /** * The resource that is being accessed is locked. */ HttpStatusCode[HttpStatusCode["Locked"] = 423] = "Locked"; /** * The request failed due to failure of a previous request (e.g., a PROPPATCH). */ HttpStatusCode[HttpStatusCode["FailedDependency"] = 424] = "FailedDependency"; /** * The client should switch to a different protocol such as TLS/1.0, given in the Upgrade header field. */ HttpStatusCode[HttpStatusCode["UpgradeRequired"] = 426] = "UpgradeRequired"; /** * The origin server requires the request to be conditional. * Intended to prevent "the 'lost update' problem, where a client * GETs a resource's state, modifies it, and PUTs it back to the server, * when meanwhile a third party has modified the state on the server, leading to a conflict." */ HttpStatusCode[HttpStatusCode["PreconditionRequired"] = 428] = "PreconditionRequired"; /** * The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes. */ HttpStatusCode[HttpStatusCode["TooManyRequests"] = 429] = "TooManyRequests"; /** * The server is unwilling to process the request because either an individual header field, * or all the header fields collectively, are too large. */ HttpStatusCode[HttpStatusCode["RequestHeaderFieldsTooLarge"] = 431] = "RequestHeaderFieldsTooLarge"; /** * A server operator has received a legal demand to deny access to a resource or to a set of resources * that includes the requested resource. The code 451 was chosen as a reference to the novel Fahrenheit 451. */ HttpStatusCode[HttpStatusCode["UnavailableForLegalReasons"] = 451] = "UnavailableForLegalReasons"; // ********************************************************************************************************** // 500s - Server messed up // ********************************************************************************************************** /** * A generic error message, given when an unexpected condition was encountered and no more specific message is suitable. */ HttpStatusCode[HttpStatusCode["InternalServerError"] = 500] = "InternalServerError"; /** * The server either does not recognize the request method, or it lacks the ability to fulfill the request. * Usually this implies future availability (e.g., a new feature of a web-service API). */ HttpStatusCode[HttpStatusCode["NotImplemented"] = 501] = "NotImplemented"; /** * The server was acting as a gateway or proxy and received an invalid response from the upstream server. */ HttpStatusCode[HttpStatusCode["BadGateway"] = 502] = "BadGateway"; /** * The server is currently unavailable (because it is overloaded or down for maintenance). * Generally, this is a temporary state. */ HttpStatusCode[HttpStatusCode["ServiceUnavailable"] = 503] = "ServiceUnavailable"; /** * The server was acting as a gateway or proxy and did not receive a timely response from the upstream server. */ HttpStatusCode[HttpStatusCode["GatewayTimeout"] = 504] = "GatewayTimeout"; /** * The server does not support the HTTP protocol version used in the request */ HttpStatusCode[HttpStatusCode["HttpVersionNotSupported"] = 505] = "HttpVersionNotSupported"; /** * Transparent content negotiation for the request results in a circular reference. */ HttpStatusCode[HttpStatusCode["VariantAlsoNegotiates"] = 506] = "VariantAlsoNegotiates"; /** * The server is unable to store the representation needed to complete the request. */ HttpStatusCode[HttpStatusCode["InsufficientStorage"] = 507] = "InsufficientStorage"; /** * The server detected an infinite loop while processing the request. */ HttpStatusCode[HttpStatusCode["LoopDetected"] = 508] = "LoopDetected"; /** * Further extensions to the request are required for the server to fulfill it. */ HttpStatusCode[HttpStatusCode["NotExtended"] = 510] = "NotExtended"; /** * The client needs to authenticate to gain network access. * Intended for use by intercepting proxies used to control access to the network (e.g., "captive portals" used * to require agreement to Terms of Service before granting full Internet access via a Wi-Fi hotspot). */ HttpStatusCode[HttpStatusCode["NetworkAuthenticationRequired"] = 511] = "NetworkAuthenticationRequired"; })(HttpStatusCode || (HttpStatusCode = {})); ;// ../../libs/common/src/enums/integration-type.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var IntegrationType; (function (IntegrationType) { IntegrationType["Integration"] = "integration"; IntegrationType["SDK"] = "sdk"; IntegrationType["SSO"] = "sso"; IntegrationType["SCIM"] = "scim"; IntegrationType["BWDC"] = "bwdc"; IntegrationType["EVENT"] = "event"; IntegrationType["DEVICE"] = "device"; })(IntegrationType || (IntegrationType = {})); ;// ../../libs/common/src/enums/native-messaging-version.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var NativeMessagingVersion; (function (NativeMessagingVersion) { NativeMessagingVersion[NativeMessagingVersion["One"] = 1] = "One"; NativeMessagingVersion[NativeMessagingVersion["Latest"] = 1] = "Latest"; })(NativeMessagingVersion || (NativeMessagingVersion = {})); ;// ../../libs/common/src/enums/notification-type.enum.ts // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums var NotificationType; (function (NotificationType) { NotificationType[NotificationType["SyncCipherUpdate"] = 0] = "SyncCipherUpdate"; NotificationType[NotificationType["SyncCipherCreate"] = 1] = "SyncCipherCreate"; NotificationType[NotificationType["SyncLoginDelete"] = 2] = "SyncLoginDelete"; NotificationType[NotificationType["SyncFolderDelete"] = 3] = "SyncFolderDelete"; NotificationType[NotificationType["SyncCiphers"] = 4] = "SyncCiphers"; NotificationType[NotificationType["SyncVault"] = 5] = "SyncVault"; NotificationType[NotificationType["SyncOrgKeys"] = 6] = "SyncOrgKeys"; NotificationType[NotificationType["SyncFolderCreate"] = 7] = "SyncFolderCreate"; NotificationType[NotificationType["SyncFolderUpdate"] = 8] = "SyncFolderUpdate"; NotificationType[NotificationType["SyncCipherDelete"] = 9] = "SyncCipherDelete"; NotificationType[NotificationType["SyncSettings"] = 10] = "SyncSettings"; NotificationType[NotificationType["LogOut"] = 11] = "LogOut"; NotificationType[NotificationType["SyncSendCreate"] = 12] = "SyncSendCreate"; NotificationType[NotificationType["SyncSendUpdate"] = 13] = "SyncSendUpdate"; NotificationType[NotificationType["SyncSendDelete"] = 14] = "SyncSendDelete"; NotificationType[NotificationType["AuthRequest"] = 15] = "AuthRequest"; NotificationType[NotificationType["AuthRequestResponse"] = 16] = "AuthRequestResponse"; NotificationType[NotificationType["SyncOrganizations"] = 17] = "SyncOrganizations"; NotificationType[NotificationType["SyncOrganizationStatusChanged"] = 18] = "SyncOrganizationStatusChanged"; NotificationType[NotificationType["SyncOrganizationCollectionSettingChanged"] = 19] = "SyncOrganizationCollectionSettingChanged"; NotificationType[NotificationType["Notification"] = 20] = "Notification"; NotificationType[NotificationType["NotificationStatus"] = 21] = "NotificationStatus"; NotificationType[NotificationType["RefreshSecurityTasks"] = 22] = "RefreshSecurityTasks"; NotificationType[NotificationType["OrganizationBankAccountVerified"] = 23] = "OrganizationBankAccountVerified"; NotificationType[NotificationType["ProviderBankAccountVerified"] = 24] = "ProviderBankAccountVerified"; NotificationType[NotificationType["SyncPolicy"] = 25] = "SyncPolicy"; })(NotificationType || (NotificationType = {})); ;// ../../libs/common/src/enums/push-notification-logout-reason.enum.ts const PushNotificationLogOutReasonType = Object.freeze({ KdfChange: 0, }); ;// ../../libs/common/src/enums/index.ts ;// ../../libs/platform/src/services/browser-service.ts function isBrowserSafariApi() { return (navigator.userAgent.indexOf(" Safari/") !== -1 && navigator.userAgent.indexOf(" Chrome/") === -1 && navigator.userAgent.indexOf(" Chromium/") === -1); } ;// ../../libs/common/src/platform/scheduling/task-scheduler.service.ts // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore /** * Creates a RXJS scheduler based on a {@link TaskSchedulerService}. * * @description This API defers to `TaskSchedulerService` to schedule a task to be ran * in the future but the task that is ran is NOT the remainder of your RXJS pipeline. The * task you want ran must instead be registered in a location reachable on a service worker * startup (on browser). An example of an acceptible location is the constructor of a service * you know is created in `MainBackground`. Uses of this API in other clients _can_ have the * `registerTaskHandler` call in more places, but in order to have it work across clients * it is recommended to register it according to the rules of browser. * * @link https://rxjs.dev/guide/scheduler#using-schedulers * * @example * ```ts * class MyService { * constructor(messageListener: MessageListener, taskScheduler: TaskSchedulerService) { * // VERY IMPORTANT! * this.taskSchedulerService.registerTaskHandler(SchedulerTaskNames.myTaskName, async () => { * await this.runEvent(); * }); * * messageListener.messages$(MY_MESSAGE).pipe( * debounceTime( * 10 * 1000, * toScheduler(taskScheduler, ShedulerTaskNames.myTaskName), * ), * switchMap(() => this.runEvent()), * ) * } * } * ``` * * @param taskScheduler The task scheduler service to use to shedule RXJS work. * @param taskName The name of the task that the handler should be registered and scheduled based on. * @returns A SchedulerLike object that can be passed in to RXJS operators like `delay` and `timeout`. */ function toScheduler(taskScheduler, taskName) { return new TaskSchedulerSheduler(taskScheduler, taskName); } class TaskSchedulerSheduler { constructor(taskSchedulerService, taskName) { this.taskSchedulerService = taskSchedulerService; this.taskName = taskName; } schedule(work, delay, state) { return this.taskSchedulerService.setTimeout(this.taskName, delay !== null && delay !== void 0 ? delay : 0); } now() { return asyncScheduler.now(); } } class TaskSchedulerService { } ;// ../../libs/common/src/platform/scheduling/default-task-scheduler.service.ts var default_task_scheduler_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; class DefaultTaskSchedulerService extends TaskSchedulerService { constructor(logService) { super(); this.logService = logService; this.taskHandlers = new Map(); } /** * Sets a timeout and returns the timeout id. * * @param taskName - The name of the task. Unused in the base implementation. * @param delayInMs - The delay in milliseconds. */ setTimeout(taskName, delayInMs) { this.validateRegisteredTask(taskName); const timeoutHandle = globalThis.setTimeout(() => this.triggerTask(taskName), delayInMs); return new Subscription(() => globalThis.clearTimeout(timeoutHandle)); } /** * Sets an interval and returns the interval id. * * @param taskName - The name of the task. Unused in the base implementation. * @param intervalInMs - The interval in milliseconds. * @param _initialDelayInMs - The initial delay in milliseconds. Unused in the base implementation. */ setInterval(taskName, intervalInMs, _initialDelayInMs) { this.validateRegisteredTask(taskName); const intervalHandle = globalThis.setInterval(() => this.triggerTask(taskName), intervalInMs); return new Subscription(() => globalThis.clearInterval(intervalHandle)); } /** * Registers a task handler. * * @param taskName - The name of the task. * @param handler - The task handler. */ registerTaskHandler(taskName, handler) { const existingHandler = this.taskHandlers.get(taskName); if (existingHandler) { this.logService.warning(`Task handler for ${taskName} already exists. Overwriting.`); this.unregisterTaskHandler(taskName); } this.taskHandlers.set(taskName, handler); } /** * Unregisters a task handler. * * @param taskName - The name of the task. */ unregisterTaskHandler(taskName) { this.taskHandlers.delete(taskName); } /** * Triggers a task. * * @param taskName - The name of the task. * @param _periodInMinutes - The period in minutes. Unused in the base implementation. */ triggerTask(taskName, _periodInMinutes) { return default_task_scheduler_service_awaiter(this, void 0, void 0, function* () { const handler = this.taskHandlers.get(taskName); if (handler) { handler(); } }); } /** * Validates that a task handler is registered. * * @param taskName - The name of the task. */ validateRegisteredTask(taskName) { if (!this.taskHandlers.has(taskName)) { throw new Error(`Task handler for ${taskName} not registered. Unable to schedule task.`); } } } ;// ../../libs/common/src/platform/scheduling/scheduled-task-name.enum.ts const scheduled_task_name_enum_ScheduledTaskNames = { generatePasswordClearClipboardTimeout: "generatePasswordClearClipboardTimeout", systemClearClipboardTimeout: "systemClearClipboardTimeout", loginStrategySessionTimeout: "loginStrategySessionTimeout", notificationsReconnectTimeout: "notificationsReconnectTimeout", fido2ClientAbortTimeout: "fido2ClientAbortTimeout", scheduleNextSyncInterval: "scheduleNextSyncInterval", eventUploadsInterval: "eventUploadsInterval", vaultTimeoutCheckInterval: "vaultTimeoutCheckInterval", clearPopupViewCache: "clearPopupViewCache", phishingDomainUpdate: "phishingDomainUpdate", }; ;// ../../libs/common/src/platform/scheduling/index.ts ;// ../../libs/platform/src/background-sync/background-sync.service.ts /** * The default interval between background syncs. * 300,000ms = 5 minutes */ const DEFAULT_SYNC_INTERVAL_MS = 300000; /** * Service responsible for registering and managing background synchronization for the browser extension. * Handles scheduling of periodic sync operations using the task scheduler infrastructure. */ class BackgroundSyncService { /** * Creates a new instance of BackgroundSyncService. * @param taskSchedulerService - Service that handles scheduling and execution of periodic tasks */ constructor(taskSchedulerService) { this.taskSchedulerService = taskSchedulerService; } /** * Registers a callback function to be executed when the sync interval task is triggered. * This associates the sync task name with the provided callback in the task scheduler. * * @param syncCallback - The function to execute when the sync task is triggered */ register(syncCallback) { this.taskSchedulerService.registerTaskHandler(ScheduledTaskNames.scheduleNextSyncInterval, syncCallback); } /** * Initializes the background sync service by scheduling the sync interval task. * This sets up a recurring timer that triggers the registered sync callback at regular intervals. * * @param intervalMs - The interval in milliseconds between sync operations (defaults to 300000ms/5 minutes) */ init(intervalMs = DEFAULT_SYNC_INTERVAL_MS) { intervalMs = intervalMs < 1 ? DEFAULT_SYNC_INTERVAL_MS : intervalMs; this.taskSchedulerService.setInterval(ScheduledTaskNames.scheduleNextSyncInterval, intervalMs); } } ;// ../../libs/platform/src/background-sync/index.ts ;// ../../libs/platform/src/index.ts ;// ./src/browser/safariApp.ts class SafariApp { static sendMessageToApp(command, data = null, resolveNow = false) { if (!browser_api_BrowserApi.isSafariApi) { return Promise.resolve(null); } return new Promise((resolve) => { const now = new Date(); const messageId = now.getTime().toString() + "_" + Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); browser.runtime.sendNativeMessage("com.bitwarden.desktop", { id: messageId, command: command, data: data, responseData: null, }, (response) => { resolve(response); }); }); } } ;// ../../libs/common/src/platform/services/console-log.service.ts ;// ./src/platform/services/browser-clipboard.service.ts var browser_clipboard_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; class BrowserClipboardService { /** * Copies the given text to the user's clipboard. * * @param globalContext - The global window context. * @param text - The text to copy. */ static copy(globalContext, text) { return browser_clipboard_service_awaiter(this, void 0, void 0, function* () { if (!BrowserClipboardService.isClipboardApiSupported(globalContext, "writeText")) { this.useLegacyCopyMethod(globalContext, text); return; } try { yield globalContext.navigator.clipboard.writeText(text); } catch (error) { BrowserClipboardService.consoleLogService.debug(`Error copying to clipboard using the clipboard API, attempting legacy method: ${error}`); this.useLegacyCopyMethod(globalContext, text); } }); } /** * Reads the user's clipboard and returns the text. * * @param globalContext - The global window context. */ static read(globalContext) { return browser_clipboard_service_awaiter(this, void 0, void 0, function* () { if (!BrowserClipboardService.isClipboardApiSupported(globalContext, "readText")) { return this.useLegacyReadMethod(globalContext); } try { return yield globalContext.navigator.clipboard.readText(); } catch (error) { BrowserClipboardService.consoleLogService.debug(`Error reading from clipboard using the clipboard API, attempting legacy method: ${error}`); return this.useLegacyReadMethod(globalContext); } }); } /** * Copies the given text to the user's clipboard using the legacy `execCommand` method. This * method is used as a fallback when the clipboard API is not supported or fails. * * @param globalContext - The global window context. * @param text - The text to copy. */ static useLegacyCopyMethod(globalContext, text) { if (!BrowserClipboardService.isLegacyClipboardMethodSupported(globalContext, "copy")) { BrowserClipboardService.consoleLogService.warning("Legacy copy method not supported"); return; } const textareaElement = globalContext.document.createElement("textarea"); textareaElement.textContent = !text ? " " : text; textareaElement.style.position = "fixed"; globalContext.document.body.appendChild(textareaElement); textareaElement.select(); try { globalContext.document.execCommand("copy"); } catch (error) { BrowserClipboardService.consoleLogService.warning(`Error writing to clipboard: ${error}`); } finally { globalContext.document.body.removeChild(textareaElement); } } /** * Reads the user's clipboard using the legacy `execCommand` method. This method is used as a * fallback when the clipboard API is not supported or fails. * * @param globalContext - The global window context. */ static useLegacyReadMethod(globalContext) { if (!BrowserClipboardService.isLegacyClipboardMethodSupported(globalContext, "paste")) { BrowserClipboardService.consoleLogService.warning("Legacy paste method not supported"); return ""; } const textareaElement = globalContext.document.createElement("textarea"); textareaElement.style.position = "fixed"; globalContext.document.body.appendChild(textareaElement); textareaElement.focus(); try { return globalContext.document.execCommand("paste") ? textareaElement.value : ""; } catch (error) { BrowserClipboardService.consoleLogService.warning(`Error reading from clipboard: ${error}`); } finally { globalContext.document.body.removeChild(textareaElement); } return ""; } /** * Checks if the clipboard API is supported in the current environment. * * @param globalContext - The global window context. * @param method - The clipboard API method to check for support. */ static isClipboardApiSupported(globalContext, method) { return "clipboard" in globalContext.navigator && method in globalContext.navigator.clipboard; } /** * Checks if the legacy clipboard method is supported in the current environment. * * @param globalContext - The global window context. * @param method - The legacy clipboard method to check for support. */ static isLegacyClipboardMethodSupported(globalContext, method) { return ("queryCommandSupported" in globalContext.document && globalContext.document.queryCommandSupported(method)); } } BrowserClipboardService.consoleLogService = new ConsoleLogService(false); /* harmony default export */ var browser_clipboard_service = (BrowserClipboardService); ;// ./src/platform/services/platform-utils/browser-platform-utils.service.ts var browser_platform_utils_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore class BrowserPlatformUtilsService { constructor(clipboardWriteCallback, globalContext, offscreenDocumentService) { this.clipboardWriteCallback = clipboardWriteCallback; this.globalContext = globalContext; this.offscreenDocumentService = offscreenDocumentService; } static getDevice(globalContext) { if (this.deviceCache) { return this.deviceCache; } // ORDERING MATTERS HERE // Ordered from most specific to least specific. We try to discern the greatest detail // for the type of extension the user is on by checking specific cases first and as we go down // the list we hope to catch all by the most generic clients they could be on. if (BrowserPlatformUtilsService.isFirefox()) { this.deviceCache = DeviceType.FirefoxExtension; } else if (BrowserPlatformUtilsService.isOpera(globalContext)) { this.deviceCache = DeviceType.OperaExtension; } else if (BrowserPlatformUtilsService.isEdge()) { this.deviceCache = DeviceType.EdgeExtension; } else if (BrowserPlatformUtilsService.isVivaldi()) { this.deviceCache = DeviceType.VivaldiExtension; } else if (BrowserPlatformUtilsService.isChrome(globalContext)) { this.deviceCache = DeviceType.ChromeExtension; } else if (BrowserPlatformUtilsService.isSafari(globalContext)) { this.deviceCache = DeviceType.SafariExtension; } return this.deviceCache; } getDevice() { return BrowserPlatformUtilsService.getDevice(this.globalContext); } getDeviceString() { const device = DeviceType[this.getDevice()].toLowerCase(); return device.replace("extension", ""); } getClientType() { return ClientType.Browser; } static isFirefox() { return (navigator.userAgent.indexOf(" Firefox/") !== -1 || navigator.userAgent.indexOf(" Gecko/") !== -1); } isFirefox() { return this.getDevice() === DeviceType.FirefoxExtension; } static isChrome(globalContext) { return globalContext.chrome && navigator.userAgent.indexOf(" Chrome/") !== -1; } isChrome() { return this.getDevice() === DeviceType.ChromeExtension; } static isEdge() { return navigator.userAgent.indexOf(" Edg/") !== -1; } isEdge() { return this.getDevice() === DeviceType.EdgeExtension; } static isOpera(globalContext) { var _a; return (!!((_a = globalContext.opr) === null || _a === void 0 ? void 0 : _a.addons) || !!globalContext.opera || navigator.userAgent.indexOf(" OPR/") >= 0); } isOpera() { return this.getDevice() === DeviceType.OperaExtension; } static isVivaldi() { return navigator.userAgent.indexOf(" Vivaldi/") !== -1; } isVivaldi() { return this.getDevice() === DeviceType.VivaldiExtension; } static isSafari(globalContext) { // Opera masquerades as Safari, so make sure we're not there first return (!BrowserPlatformUtilsService.isOpera(globalContext) && navigator.userAgent.indexOf(" Safari/") !== -1); } static safariVersion() { var _a; return (_a = navigator.userAgent.match("Version/([0-9.]*)")) === null || _a === void 0 ? void 0 : _a[1]; } isSafari() { return this.getDevice() === DeviceType.SafariExtension; } isChromium() { return this.isChrome() || this.isEdge() || this.isOpera() || this.isVivaldi(); } /** * Safari previous to version 16.1 had a bug which caused artifacts on hover in large extension popups. * https://bugs.webkit.org/show_bug.cgi?id=218704 */ static shouldApplySafariHeightFix(globalContext) { var _a; if (BrowserPlatformUtilsService.getDevice(globalContext) !== DeviceType.SafariExtension) { return false; } const version = BrowserPlatformUtilsService.safariVersion(); const parts = (_a = version === null || version === void 0 ? void 0 : version.split(".")) === null || _a === void 0 ? void 0 : _a.map((v) => Number(v)); return (parts === null || parts === void 0 ? void 0 : parts[0]) < 16 || ((parts === null || parts === void 0 ? void 0 : parts[0]) === 16 && (parts === null || parts === void 0 ? void 0 : parts[1]) === 0); } isIE() { return false; } isMacAppStore() { return false; } /** * Identifies if the vault popup is currently open. This is done by sending a * message to the popup and waiting for a response. If a response is received, * the view is open. */ isPopupOpen() { return browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { if (this.isSafari()) { // Query views on safari since chrome.runtime.sendMessage does not timeout and will hang. return browser_api_BrowserApi.isPopupOpen(); } return new Promise((resolve, reject) => { chrome.runtime.sendMessage({ command: "checkVaultPopupHeartbeat" }, (response) => { if (chrome.runtime.lastError != null) { // This error means that nothing was there to listen to the message, // meaning the view is not open. if (chrome.runtime.lastError.message === "Could not establish connection. Receiving end does not exist.") { resolve(false); return; } // All unhandled errors still reject reject(chrome.runtime.lastError); return; } resolve(Boolean(response)); }); }); }); } lockTimeout() { return null; } launchUri(uri, options) { // FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling. // eslint-disable-next-line @typescript-eslint/no-floating-promises browser_api_BrowserApi.createNewTab(uri, options && options.extensionPage === true); } getApplicationVersion() { var _a; const manifest = chrome.runtime.getManifest(); return Promise.resolve((_a = manifest.version_name) !== null && _a !== void 0 ? _a : manifest.version); } getApplicationVersionNumber() { const manifest = chrome.runtime.getManifest(); return Promise.resolve(manifest.version.split(RegExp("[+|-]"))[0].trim()); } supportsWebAuthn(win) { return typeof PublicKeyCredential !== "undefined"; } supportsDuo() { return true; } supportsAutofill() { return true; } supportsFileDownloads() { return false; } isDev() { return "production" === "development"; } isSelfHost() { return false; } /** * Copies the passed text to the clipboard. For Safari, this will use * the native messaging API to send the text to the Bitwarden app. If * the extension is using manifest v3, the offscreen document API will * be used to copy the text to the clipboard. Otherwise, the browser's * clipboard API will be used. * * @param text - The text to copy to the clipboard. * @param options - Options for the clipboard operation. */ copyToClipboard(text, options) { const windowContext = (options === null || options === void 0 ? void 0 : options.window) || this.globalContext; const clearing = Boolean(options === null || options === void 0 ? void 0 : options.clearing); const clearMs = (options === null || options === void 0 ? void 0 : options.clearMs) || null; const handleClipboardWriteCallback = () => { if (!clearing && this.clipboardWriteCallback != null) { this.clipboardWriteCallback(text, clearMs); } }; if (this.isSafari()) { void SafariApp.sendMessageToApp("copyToClipboard", text).then(handleClipboardWriteCallback); return; } if (this.isChrome() && text === "") { text = "\u0000"; } if (browser_api_BrowserApi.isManifestVersion(3) && this.offscreenDocumentService.offscreenApiSupported()) { void this.triggerOffscreenCopyToClipboard(text).then(handleClipboardWriteCallback); return; } void browser_clipboard_service.copy(windowContext, text).then(handleClipboardWriteCallback); } /** * Reads the text from the clipboard. For Safari, this will use the * native messaging API to request the text from the Bitwarden app. If * the extension is using manifest v3, the offscreen document API will * be used to read the text from the clipboard. Otherwise, the browser's * clipboard API will be used. * * @param options - Options for the clipboard operation. */ readFromClipboard(options) { return browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { const windowContext = (options === null || options === void 0 ? void 0 : options.window) || this.globalContext; if (this.isSafari()) { return yield SafariApp.sendMessageToApp("readFromClipboard"); } if (browser_api_BrowserApi.isManifestVersion(3) && this.offscreenDocumentService.offscreenApiSupported()) { return yield this.triggerOffscreenReadFromClipboard(); } return yield browser_clipboard_service.read(windowContext); }); } supportsSecureStorage() { return false; } getAutofillKeyboardShortcut() { return browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { let autofillCommand; // You can not change the command in Safari or obtain it programmatically if (this.isSafari()) { autofillCommand = "Cmd+Shift+L"; } else if (this.isFirefox()) { autofillCommand = (yield browser.commands.getAll()).find((c) => c.name === ExtensionCommand.AutofillLogin).shortcut; // Firefox is returning Ctrl instead of Cmd for the modifier key on macOS if // the command is the default one set on installation. if ((yield browser.runtime.getPlatformInfo()).os === "mac" && autofillCommand === "Ctrl+Shift+L") { autofillCommand = "Cmd+Shift+L"; } } else { yield new Promise((resolve) => chrome.commands.getAll((c) => resolve((autofillCommand = c.find((c) => c.name === ExtensionCommand.AutofillLogin).shortcut)))); } return autofillCommand; }); } packageType() { return browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { switch (this.getDevice()) { case DeviceType.ChromeExtension: return "Chrome Extension"; case DeviceType.FirefoxExtension: return "Firefox Extension"; case DeviceType.OperaExtension: return "Opera Extension"; case DeviceType.EdgeExtension: return "Edge Extension"; case DeviceType.VivaldiExtension: return "Vivaldi Extension"; case DeviceType.SafariExtension: return "Safari Extension"; default: return "Unknown Browser Extension"; } }); } /** * Triggers the offscreen document API to copy the text to the clipboard. */ triggerOffscreenCopyToClipboard(text) { return browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { yield this.offscreenDocumentService.withDocument([chrome.offscreen.Reason.CLIPBOARD], "Write text to the clipboard.", () => browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { yield browser_api_BrowserApi.sendMessageWithResponse("offscreenCopyToClipboard", { text }); })); }); } /** * Triggers the offscreen document API to read the text from the clipboard. */ triggerOffscreenReadFromClipboard() { return browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { const response = yield this.offscreenDocumentService.withDocument([chrome.offscreen.Reason.CLIPBOARD], "Read text from the clipboard.", () => browser_platform_utils_service_awaiter(this, void 0, void 0, function* () { return yield browser_api_BrowserApi.sendMessageWithResponse("offscreenReadFromClipboard"); })); if (typeof response === "string") { return response; } return ""; }); } } BrowserPlatformUtilsService.deviceCache = null; ;// ./src/platform/browser/browser-api.register-content-scripts-polyfill.ts var browser_api_register_content_scripts_polyfill_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore /** * MIT License * * Copyright (c) Federico Brigante (https://fregante.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * @see https://github.com/fregante/content-scripts-register-polyfill * @version 4.0.2 */ let registerContentScripts; function registerContentScriptsPolyfill(contentScriptOptions, callback) { return browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { if (!registerContentScripts) { registerContentScripts = buildRegisterContentScriptsPolyfill(); } return registerContentScripts(contentScriptOptions, callback); }); } function buildRegisterContentScriptsPolyfill() { var _a, _b; const logService = new ConsoleLogService(false); const chromeProxy = globalThis.chrome && NestedProxy(globalThis.chrome); const patternValidationRegex = /^(https?|wss?|file|ftp|\*):\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^file:\/\/\/.*$|^resource:\/\/(\*|\*\.[^*/]+|[^*/]+)\/.*$|^about:/; const isFirefox = (_a = globalThis.navigator) === null || _a === void 0 ? void 0 : _a.userAgent.includes("Firefox/"); const gotScripting = Boolean((_b = globalThis.chrome) === null || _b === void 0 ? void 0 : _b.scripting); const gotNavigation = typeof chrome === "object" && "webNavigation" in chrome; function NestedProxy(target) { return new Proxy(target, { get(target, prop) { if (!target[prop]) { return; } if (typeof target[prop] !== "function") { return NestedProxy(target[prop]); } return (...arguments_) => new Promise((resolve, reject) => { target[prop](...arguments_, (result) => { if (chrome.runtime.lastError) { reject(new Error(chrome.runtime.lastError.message)); } else { resolve(result); } }); }); }, }); } function assertValidPattern(matchPattern) { if (!isValidPattern(matchPattern)) { throw new Error(`${matchPattern} is an invalid pattern, it must match ${String(patternValidationRegex)}`); } } function isValidPattern(matchPattern) { return matchPattern === "" || patternValidationRegex.test(matchPattern); } function getRawPatternRegex(matchPattern) { assertValidPattern(matchPattern); let [, protocol, host = "", pathname] = matchPattern.split(/(^[^:]+:[/][/])([^/]+)?/); protocol = protocol .replace("*", isFirefox ? "(https?|wss?)" : "https?") .replaceAll(/[/]/g, "[/]"); if (host === "*") { host = "[^/]+"; } else if (host) { host = host .replace(/^[*][.]/, "([^/]+.)*") .replaceAll(/[.]/g, "[.]") .replace(/[*]$/, "[^.]+"); } pathname = pathname .replaceAll(/[/]/g, "[/]") .replaceAll(/[.]/g, "[.]") .replaceAll(/[*]/g, ".*"); return "^" + protocol + host + "(" + pathname + ")?$"; } function patternToRegex(...matchPatterns) { if (matchPatterns.length === 0) { return /$./; } if (matchPatterns.includes("")) { // regex return /^(https?|file|ftp):[/]+/; } if (matchPatterns.includes("*://*/*")) { // all stars regex return isFirefox ? /^(https?|wss?):[/][/][^/]+([/].*)?$/ : /^https?:[/][/][^/]+([/].*)?$/; } return new RegExp(matchPatterns.map((x) => getRawPatternRegex(x)).join("|")); } function castAllFramesTarget(target) { if (typeof target === "object") { return Object.assign(Object.assign({}, target), { allFrames: false }); } return { tabId: target, frameId: undefined, allFrames: true, }; } function castArray(possibleArray) { if (Array.isArray(possibleArray)) { return possibleArray; } return [possibleArray]; } function createTarget(tabId, frameId, allFrames) { if (frameId === undefined) { return { tabId, frameIds: undefined, allFrames: allFrames, }; } else { return { tabId, frameIds: [frameId], allFrames: undefined, }; } } function insertCSS(_a) { return browser_api_register_content_scripts_polyfill_awaiter(this, arguments, void 0, function* ({ tabId, frameId, files, allFrames, matchAboutBlank, runAt, }, { ignoreTargetErrors } = {}) { const everyInsertion = Promise.all(files.map((content) => browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { if (typeof content === "string") { content = { file: content }; } if (gotScripting) { if ("file" in content) { return chrome.scripting.insertCSS({ target: createTarget(tabId, frameId, allFrames), files: [content.file], }); } else { return chrome.scripting.insertCSS({ target: createTarget(tabId, frameId, allFrames), css: content.code, }); } } return chromeProxy.tabs.insertCSS(tabId, Object.assign(Object.assign({}, content), { matchAboutBlank, allFrames, frameId, runAt: runAt !== null && runAt !== void 0 ? runAt : "document_start" })); }))); if (ignoreTargetErrors) { yield catchTargetInjectionErrors(everyInsertion); } else { yield everyInsertion; } }); } function assertNoCode(files) { if (files.some((content) => "code" in content)) { throw new Error("chrome.scripting does not support injecting strings of `code`"); } } function executeScript(_a) { return browser_api_register_content_scripts_polyfill_awaiter(this, arguments, void 0, function* ({ tabId, frameId, files, allFrames, matchAboutBlank, runAt, }, { ignoreTargetErrors } = {}) { const normalizedFiles = files.map((file) => (typeof file === "string" ? { file } : file)); if (gotScripting) { assertNoCode(normalizedFiles); const injection = chrome.scripting.executeScript({ target: createTarget(tabId, frameId, allFrames), files: normalizedFiles.map(({ file }) => file), }); if (ignoreTargetErrors) { yield catchTargetInjectionErrors(injection); } else { yield injection; } return; } const executions = []; for (const content of normalizedFiles) { if ("code" in content) { yield executions.at(-1); } executions.push(chromeProxy.tabs.executeScript(tabId, Object.assign(Object.assign({}, content), { matchAboutBlank, allFrames, frameId, runAt }))); } if (ignoreTargetErrors) { yield catchTargetInjectionErrors(Promise.all(executions)); } else { yield Promise.all(executions); } }); } function injectContentScript(where_1, scripts_1) { return browser_api_register_content_scripts_polyfill_awaiter(this, arguments, void 0, function* (where, scripts, options = {}) { const targets = castArray(where); yield Promise.all(targets.map((target) => browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { return injectContentScriptInSpecificTarget(castAllFramesTarget(target), scripts, options); }))); }); } function injectContentScriptInSpecificTarget(_a, scripts_1) { return browser_api_register_content_scripts_polyfill_awaiter(this, arguments, void 0, function* ({ frameId, tabId, allFrames }, scripts, options = {}) { const injections = castArray(scripts).flatMap((script) => { var _a, _b, _c, _d, _e, _f; return [ insertCSS({ tabId, frameId, allFrames, files: (_a = script.css) !== null && _a !== void 0 ? _a : [], matchAboutBlank: (_b = script.matchAboutBlank) !== null && _b !== void 0 ? _b : script.match_about_blank, runAt: (_c = script.runAt) !== null && _c !== void 0 ? _c : script.run_at, }, options), executeScript({ tabId, frameId, allFrames, files: (_d = script.js) !== null && _d !== void 0 ? _d : [], matchAboutBlank: (_e = script.matchAboutBlank) !== null && _e !== void 0 ? _e : script.match_about_blank, runAt: (_f = script.runAt) !== null && _f !== void 0 ? _f : script.run_at, }, options), ]; }); yield Promise.all(injections); }); } function catchTargetInjectionErrors(promise) { return browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { try { yield promise; } catch (error) { const targetErrors = /^No frame with id \d+ in tab \d+.$|^No tab with id: \d+.$|^The tab was closed.$|^The frame was removed.$/; if (!targetErrors.test(error === null || error === void 0 ? void 0 : error.message)) { throw error; } } }); } function isOriginPermitted(url) { return browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { return chromeProxy.permissions.contains({ origins: [new URL(url).origin + "/*"], }); }); } return (contentScriptOptions, callback) => browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { const { js = [], css = [], matchAboutBlank, matches = [], excludeMatches, runAt, } = contentScriptOptions; let { allFrames } = contentScriptOptions; if (gotNavigation) { allFrames = false; } else if (allFrames) { logService.warning("`allFrames: true` requires the `webNavigation` permission to work correctly: https://github.com/fregante/content-scripts-register-polyfill#permissions"); } if (matches.length === 0) { 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(matches.map((pattern) => browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { if (!(yield chromeProxy.permissions.contains({ origins: [pattern] }))) { throw new Error(`Permission denied to register a content script for ${pattern}`); } }))); const matchesRegex = patternToRegex(...matches); const excludeMatchesRegex = patternToRegex(...(excludeMatches !== null && excludeMatches !== void 0 ? excludeMatches : [])); const inject = (url_1, tabId_1, ...args_1) => browser_api_register_content_scripts_polyfill_awaiter(this, [url_1, tabId_1, ...args_1], void 0, function* (url, tabId, frameId = 0) { if (!matchesRegex.test(url) || excludeMatchesRegex.test(url) || !(yield isOriginPermitted(url))) { return; } yield injectContentScript({ tabId, frameId }, { css, js, matchAboutBlank, runAt }, { ignoreTargetErrors: true }); }); const tabListener = (tabId_1, _a, _b) => browser_api_register_content_scripts_polyfill_awaiter(this, [tabId_1, _a, _b], void 0, function* (tabId, { status }, { url }) { if (status === "loading" && url) { void inject(url, tabId); } }); const navListener = (_a) => browser_api_register_content_scripts_polyfill_awaiter(this, [_a], void 0, function* ({ tabId, frameId, url, }) { void inject(url, tabId, frameId); }); if (gotNavigation) { browser_api_BrowserApi.addListener(chrome.webNavigation.onCommitted, navListener); } else { browser_api_BrowserApi.addListener(chrome.tabs.onUpdated, tabListener); } const registeredContentScript = { unregister() { return browser_api_register_content_scripts_polyfill_awaiter(this, void 0, void 0, function* () { if (gotNavigation) { chrome.webNavigation.onCommitted.removeListener(navListener); } else { chrome.tabs.onUpdated.removeListener(tabListener); } }); }, }; if (typeof callback === "function") { callback(registeredContentScript); } return registeredContentScript; }); } ;// ./src/platform/browser/browser-api.ts var browser_api_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore class browser_api_BrowserApi { static get manifestVersion() { return chrome.runtime.getManifest().manifest_version; } /** * Determines if the extension manifest version is the given version. * * @param expectedVersion - The expected manifest version to check against. */ static isManifestVersion(expectedVersion) { return browser_api_BrowserApi.manifestVersion === expectedVersion; } /** * Helper method that attempts to distinguish whether a message sender is internal to the extension or not. * * Currently this is done through source origin matching, and frameId checking (only top-level frames are internal). * @param sender a message sender * @param logger an optional logger to log validation results * @returns whether or not the sender appears to be internal to the extension */ static senderIsInternal(sender, logger) { var _a, _b; if (!(sender === null || sender === void 0 ? void 0 : sender.origin)) { logger === null || logger === void 0 ? void 0 : logger.warning("[BrowserApi] Message sender has no origin"); return false; } const extensionUrl = (typeof chrome !== "undefined" && ((_a = chrome.runtime) === null || _a === void 0 ? void 0 : _a.getURL(""))) || (typeof browser !== "undefined" && ((_b = browser.runtime) === null || _b === void 0 ? void 0 : _b.getURL(""))) || ""; if (!extensionUrl) { logger === null || logger === void 0 ? void 0 : logger.warning("[BrowserApi] Unable to determine extension URL"); return false; } // Normalize both URLs by removing trailing slashes const normalizedOrigin = sender.origin.replace(/\/$/, "").toLowerCase(); const normalizedExtensionUrl = extensionUrl.replace(/\/$/, "").toLowerCase(); if (!normalizedOrigin.startsWith(normalizedExtensionUrl)) { logger === null || logger === void 0 ? void 0 : logger.warning(`[BrowserApi] Message sender origin (${normalizedOrigin}) does not match extension URL (${normalizedExtensionUrl})`); return false; } // We only send messages from the top-level frame, but frameId is only set if tab is set, which for popups it is not. if ("frameId" in sender && sender.frameId !== 0) { logger === null || logger === void 0 ? void 0 : logger.warning("[BrowserApi] Message sender is not from the top-level frame"); return false; } logger === null || logger === void 0 ? void 0 : logger.info("[BrowserApi] Message sender appears to be internal"); return true; } /** * Gets all open browser windows, including their tabs. * * @returns A promise that resolves to an array of browser windows. */ static getWindows() { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.windows.getAll({ populate: true }, resolve)); }); } /** * Gets the current window or the window with the given id. * * @param windowId - The id of the window to get. If not provided, the current window is returned. */ static getWindow(windowId) { return browser_api_awaiter(this, void 0, void 0, function* () { if (!windowId) { return browser_api_BrowserApi.getCurrentWindow(); } return yield browser_api_BrowserApi.getWindowById(windowId); }); } /** * Gets the currently active browser window. */ static getCurrentWindow() { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.windows.getCurrent({ populate: true }, resolve)); }); } /** * Gets the window with the given id. * * @param windowId - The id of the window to get. */ static getWindowById(windowId) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.windows.get(windowId, { populate: true }, resolve)); }); } static createWindow(options) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => { chrome.windows.create(options, (newWindow) => browser_api_awaiter(this, void 0, void 0, function* () { if (!browser_api_BrowserApi.isSafariApi) { return resolve(newWindow); } // Safari doesn't close the default extension popup when a new window is created so we need to // manually trigger the close by focusing the main window after the new window is created const allWindows = yield new Promise((resolve) => { chrome.windows.getAll({ windowTypes: ["normal"] }, (windows) => resolve(windows)); }); const mainWindow = allWindows.find((window) => window.id !== newWindow.id); // No main window found, resolve the new window if (mainWindow == null || !mainWindow.id) { return resolve(newWindow); } // Focus the main window to close the extension popup chrome.windows.update(mainWindow.id, { focused: true }, () => { // Refocus the newly created window chrome.windows.update(newWindow.id, { focused: true }, () => { resolve(newWindow); }); }); })); }); }); } /** * Removes the window with the given id. * * @param windowId - The id of the window to remove. */ static removeWindow(windowId) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.windows.remove(windowId, () => resolve())); }); } /** * Updates the properties of the window with the given id. * * @param windowId - The id of the window to update. * @param options - The window properties to update. */ static updateWindowProperties(windowId, options) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.windows.update(windowId, options, () => { resolve(); })); }); } /** * Focuses the window with the given id. * * @param windowId - The id of the window to focus. */ static focusWindow(windowId) { return browser_api_awaiter(this, void 0, void 0, function* () { yield browser_api_BrowserApi.updateWindowProperties(windowId, { focused: true }); }); } static getTabFromCurrentWindowId() { return browser_api_awaiter(this, void 0, void 0, function* () { return yield browser_api_BrowserApi.tabsQueryFirstCurrentWindowForSafari({ active: true, windowId: chrome.windows.WINDOW_ID_CURRENT, }); }); } static getBrowserClientVendor(clientWindow) { const device = BrowserPlatformUtilsService.getDevice(clientWindow); switch (device) { case DeviceType.ChromeExtension: case DeviceType.ChromeBrowser: return BrowserClientVendors.Chrome; case DeviceType.OperaExtension: case DeviceType.OperaBrowser: return BrowserClientVendors.Opera; case DeviceType.EdgeExtension: case DeviceType.EdgeBrowser: return BrowserClientVendors.Edge; case DeviceType.VivaldiExtension: case DeviceType.VivaldiBrowser: return BrowserClientVendors.Vivaldi; default: return BrowserClientVendors.Unknown; } } /** * Gets the tab with the given id. * * @param tabId - The id of the tab to get. */ static getTab(tabId) { return browser_api_awaiter(this, void 0, void 0, function* () { if (!tabId) { return null; } if (browser_api_BrowserApi.isManifestVersion(3)) { return yield chrome.tabs.get(tabId); } return new Promise((resolve) => chrome.tabs.get(tabId, (tab) => { resolve(tab); })); }); } static getTabFromCurrentWindow() { return browser_api_awaiter(this, void 0, void 0, function* () { return yield browser_api_BrowserApi.tabsQueryFirstCurrentWindowForSafari({ active: true, currentWindow: true, }); }); } static getActiveTabs() { return browser_api_awaiter(this, void 0, void 0, function* () { return yield browser_api_BrowserApi.tabsQuery({ active: true, }); }); } /** * Fetch the currently open browser tab */ static getCurrentTab() { return browser_api_awaiter(this, void 0, void 0, function* () { if (browser_api_BrowserApi.isManifestVersion(3)) { return yield chrome.tabs.getCurrent(); } return new Promise((resolve) => chrome.tabs.getCurrent((tab) => { resolve(tab); })); }); } /** * Closes a browser tab with the given id * * @param tabId The id of the tab to close */ static closeTab(tabId) { return browser_api_awaiter(this, void 0, void 0, function* () { if (tabId) { if (browser_api_BrowserApi.isWebExtensionsApi) { yield browser.tabs.remove(tabId).catch((error) => { throw new Error("[BrowserApi] Failed to remove current tab: " + error.message); }); } else if (browser_api_BrowserApi.isChromeApi) { yield chrome.tabs.remove(tabId).catch((error) => { throw new Error("[BrowserApi] Failed to remove current tab: " + error.message); }); } } }); } /** * Navigates a browser tab to the given URL * * @param tabId The id of the tab to navigate * @param url The URL to navigate to */ static navigateTabToUrl(tabId, url) { return browser_api_awaiter(this, void 0, void 0, function* () { if (tabId) { if (browser_api_BrowserApi.isWebExtensionsApi) { yield browser.tabs.update(tabId, { url: url.href }).catch((error) => { throw new Error("Failed to navigate tab to URL: " + error.message); }); } else if (browser_api_BrowserApi.isChromeApi) { chrome.tabs.update(tabId, { url: url.href }, () => { if (chrome.runtime.lastError) { throw new Error("Failed to navigate tab to URL: " + chrome.runtime.lastError.message); } }); } } }); } static tabsQuery(options) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => { chrome.tabs.query(options, (tabs) => { resolve(tabs); }); }); }); } static tabsQueryFirst(options) { return browser_api_awaiter(this, void 0, void 0, function* () { const tabs = yield browser_api_BrowserApi.tabsQuery(options); if (tabs.length > 0) { return tabs[0]; } return null; }); } /** * Drop-in replacement for {@link BrowserApi.tabsQueryFirst}. * * Safari sometimes returns >1 tabs unexpectedly even when * specifying a `windowId` or `currentWindow: true` query option. * * For all of these calls, * ``` * await chrome.tabs.query({active: true, currentWindow: true}) * await chrome.tabs.query({active: true, windowId: chrome.windows.WINDOW_ID_CURRENT}) * await chrome.tabs.query({active: true, windowId: 10}) * ``` * * Safari could return: * ``` * [ * {windowId: 2, pinned: true, title: "Incorrect tab in another window", …}, * {windowId: 10, title: "Correct tab in foreground", …}, * ] * ``` * * This function captures the current window ID manually before running the query, * then finds and returns the tab with the matching window ID. * * See the `SafariTabsQuery` tests in `browser-api.spec.ts`. * * This workaround can be removed when Safari fixes this bug. */ static tabsQueryFirstCurrentWindowForSafari(options) { return browser_api_awaiter(this, void 0, void 0, function* () { var _a; if (!browser_api_BrowserApi.isSafariApi) { return yield browser_api_BrowserApi.tabsQueryFirst(options); } const currentWindowId = (yield browser_api_BrowserApi.getCurrentWindow()).id; const tabs = yield browser_api_BrowserApi.tabsQuery(options); if (tabs.length <= 1 || currentWindowId == null) { return tabs[0]; } return (_a = tabs.find((t) => t.windowId === currentWindowId)) !== null && _a !== void 0 ? _a : tabs[0]; }); } static tabSendMessageData(tab, command, data = null) { const obj = { command: command, }; if (data != null) { obj.data = data; } return browser_api_BrowserApi.tabSendMessage(tab, obj); } static tabSendMessage(tab_1, obj_1) { return browser_api_awaiter(this, arguments, void 0, function* (tab, obj, options = null, rejectOnError = false) { if (!tab || !tab.id) { return; } return new Promise((resolve, reject) => { chrome.tabs.sendMessage(tab.id, obj, options, (response) => { if (chrome.runtime.lastError && rejectOnError) { // Some error happened reject(); } resolve(response); }); }); }); } static sendTabsMessage(tabId, message, options, responseCallback) { chrome.tabs.sendMessage(tabId, message, options, responseCallback); } static getRuntimeURL(path) { if (browser_api_BrowserApi.isWebExtensionsApi) { return browser.runtime.getURL(path); } else if (browser_api_BrowserApi.isChromeApi) { return chrome.runtime.getURL(path); } } static onWindowCreated(callback) { return browser_api_awaiter(this, void 0, void 0, function* () { // FIXME: Make sure that is does not cause a memory leak in Safari or use BrowserApi.AddListener // and test that it doesn't break. // eslint-disable-next-line no-restricted-syntax return chrome.windows.onCreated.addListener(callback); }); } /** * Gets the background page for the extension. This method is * not valid within manifest v3 background service workers. As * a result, it will return null when called from that context. */ static getBackgroundPage() { if (typeof chrome.extension.getBackgroundPage === "undefined") { return null; } return chrome.extension.getBackgroundPage(); } /** * Accepts a window object and determines if it is * associated with the background page of the extension. * * @param window - The window to check. */ static isBackgroundPage(window) { return typeof window !== "undefined" && window === browser_api_BrowserApi.getBackgroundPage(); } /** * Gets the extension views that match the given properties. This method is not * available within background service worker. As a result, it will return an * empty array when called from that context. * * @param fetchProperties - The properties used to filter extension views. */ static getExtensionViews(fetchProperties) { if (typeof chrome.extension.getViews === "undefined") { return []; } return chrome.extension.getViews(fetchProperties); } /** * Queries all extension views that are of type `popup` * and returns whether any are currently open. */ static isPopupOpen() { return browser_api_awaiter(this, void 0, void 0, function* () { return Promise.resolve(browser_api_BrowserApi.getExtensionViews({ type: "popup" }).length > 0); }); } static createNewTab(url, active = true) { return new Promise((resolve) => chrome.tabs.create({ url: url, active: active }, (tab) => resolve(tab))); } /** * Gathers the details for a specified sub-frame of a tab. * * @param details - The details of the frame to get. */ static getFrameDetails(details) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.webNavigation.getFrame(details, resolve)); }); } /** * Gets all frames associated with a tab. * * @param tabId - The id of the tab to get the frames for. */ static getAllFrameDetails(tabId) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.webNavigation.getAllFrames({ tabId }, resolve)); }); } static messageListener(name, callback) { browser_api_BrowserApi.addListener(chrome.runtime.onMessage, callback); } static messageListener$() { return new Observable_Observable((subscriber) => { const handler = (message) => { subscriber.next(message); }; browser_api_BrowserApi.addListener(chrome.runtime.onMessage, handler); return () => browser_api_BrowserApi.removeListener(chrome.runtime.onMessage, handler); }); } static storageChangeListener(callback) { browser_api_BrowserApi.addListener(chrome.storage.onChanged, callback); } /** * Adds a callback to the given chrome event in a cross-browser platform manner. * * **Important:** All event listeners in the browser extension popup context must * use this instead of the native APIs to handle unsubscribing from Safari properly. * * @param event - The event in which to add the listener to. * @param callback - The callback you want registered onto the event. */ static addListener(event, callback) { event.addListener(callback); if (browser_api_BrowserApi.isSafariApi && !browser_api_BrowserApi.isBackgroundPage(self)) { browser_api_BrowserApi.trackedChromeEventListeners.push([event, callback]); browser_api_BrowserApi.setupUnloadListeners(); } } /** * Removes a callback from the given chrome event in a cross-browser platform manner. * @param event - The event in which to remove the listener from. * @param callback - The callback you want removed from the event. */ static removeListener(event, callback) { event.removeListener(callback); if (browser_api_BrowserApi.isSafariApi && !browser_api_BrowserApi.isBackgroundPage(self)) { const index = browser_api_BrowserApi.trackedChromeEventListeners.findIndex(([_event, eventListener]) => { return eventListener == callback; }); if (index !== -1) { browser_api_BrowserApi.trackedChromeEventListeners.splice(index, 1); } } } // Setup the event to destroy all the listeners when the popup gets unloaded in Safari, otherwise we get a memory leak static setupUnloadListeners() { // The MDN recommend using 'visibilitychange' but that event is fired any time the popup window is obscured as well // 'pagehide' works just like 'unload' but is compatible with the back/forward cache, so we prefer using that one self.addEventListener("pagehide", () => { for (const [event, callback] of browser_api_BrowserApi.trackedChromeEventListeners) { event.removeListener(callback); } }); } static sendMessage(subscriber, arg = {}) { const message = Object.assign({}, { command: subscriber }, arg); return chrome.runtime.sendMessage(message); } static sendMessageWithResponse(subscriber, arg = {}) { const message = Object.assign({}, { command: subscriber }, arg); return new Promise((resolve) => chrome.runtime.sendMessage(message, resolve)); } static focusTab(tabId) { return browser_api_awaiter(this, void 0, void 0, function* () { // FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling. // eslint-disable-next-line @typescript-eslint/no-floating-promises chrome.tabs.update(tabId, { active: true, highlighted: true }); }); } static closePopup(win) { if (browser_api_BrowserApi.isWebExtensionsApi && browser_api_BrowserApi.isFirefoxOnAndroid) { // Reactivating the active tab dismisses the popup tab. The promise final // condition is only called if the popup wasn't already dismissed (future proofing). // ref: https://bugzilla.mozilla.org/show_bug.cgi?id=1433604 // FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling. // eslint-disable-next-line @typescript-eslint/no-floating-promises browser.tabs.update({ active: true }).finally(win.close); } else { win.close(); } } static gaFilter() { return "production" !== "production"; } static getUILanguage() { return chrome.i18n.getUILanguage(); } /** * Handles reloading the extension using the underlying functionality exposed by the browser API. */ static reloadExtension() { // If we do `chrome.runtime.reload` on safari they will send an onInstalled reason of install // and that prompts us to show a new tab, this apparently doesn't happen on sideloaded // extensions and only shows itself production scenarios. See: https://bitwarden.atlassian.net/browse/PM-12298 if (this.isSafariApi) { return self.location.reload(); } return chrome.runtime.reload(); } /** * Reloads all open extension views, except the background page. Will also * skip reloading the current window location if exemptCurrentHref is true. * * @param exemptCurrentHref - Whether to exempt the current window location from the reload. */ static reloadOpenWindows(exemptCurrentHref = false) { const views = browser_api_BrowserApi.getExtensionViews(); if (!views.length) { return; } const currentHref = self.location.href; views .filter((w) => w.location.href != null && !w.location.href.includes("background.html")) .filter((w) => !exemptCurrentHref || w.location.href !== currentHref) .forEach((w) => w.location.reload()); } static connectNative(application) { if (browser_api_BrowserApi.isWebExtensionsApi) { return browser.runtime.connectNative(application); } else if (browser_api_BrowserApi.isChromeApi) { return chrome.runtime.connectNative(application); } } static requestPermission(permission) { if (browser_api_BrowserApi.isWebExtensionsApi) { return browser.permissions.request(permission); } return new Promise((resolve) => { chrome.permissions.request(permission, resolve); }); } /** * Checks if the user has provided the given permissions to the extension. * * @param permissions - The permissions to check. */ static permissionsGranted(permissions) { return browser_api_awaiter(this, void 0, void 0, function* () { return new Promise((resolve) => chrome.permissions.contains({ permissions }, (result) => resolve(result))); }); } static getPlatformInfo() { if (browser_api_BrowserApi.isWebExtensionsApi) { return browser.runtime.getPlatformInfo(); } return new Promise((resolve) => { chrome.runtime.getPlatformInfo(resolve); }); } /** * Returns the supported BrowserAction API based on the manifest version. */ static getBrowserAction() { return browser_api_BrowserApi.isManifestVersion(3) ? chrome.action : chrome.browserAction; } static getSidebarAction(win) { var _a; const deviceType = BrowserPlatformUtilsService.getDevice(win); if (deviceType === DeviceType.FirefoxExtension) { return browser.sidebarAction; } if (deviceType === DeviceType.OperaExtension) { return (_a = win.opr) === null || _a === void 0 ? void 0 : _a.sidebarAction; } return null; } static captureVisibleTab() { return new Promise((resolve) => { chrome.tabs.captureVisibleTab(null, { format: "png" }, resolve); }); } /** * Extension API helper method used to execute a script in a tab. * * @see https://developer.chrome.com/docs/extensions/reference/tabs/#method-executeScript * @param tabId - The id of the tab to execute the script in. * @param details {@link "InjectDetails" https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/extensionTypes/InjectDetails} * @param scriptingApiDetails {@link "ExecutionWorld" https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/ExecutionWorld} */ static executeScriptInTab(tabId, details, scriptingApiDetails) { if (browser_api_BrowserApi.isManifestVersion(3)) { let target; if (typeof details.frameId === "number") { target = { tabId, frameIds: [details.frameId] }; } else if (details.allFrames) { target = { tabId, allFrames: true }; } else { target = { tabId }; } return chrome.scripting.executeScript({ target, files: details.file ? [details.file] : null, injectImmediately: details.runAt === "document_start", world: (scriptingApiDetails === null || scriptingApiDetails === void 0 ? void 0 : scriptingApiDetails.world) || chrome.scripting.ExecutionWorld.ISOLATED, }); } return new Promise((resolve) => { chrome.tabs.executeScript(tabId, details, (result) => { resolve(result); }); }); } /** * Identifies if the browser autofill settings are overridden by the extension. */ static browserAutofillSettingsOverridden() { return browser_api_awaiter(this, void 0, void 0, function* () { if (!(yield browser_api_BrowserApi.permissionsGranted(["privacy"]))) { return false; } const checkOverrideStatus = (details) => details.levelOfControl === "controlled_by_this_extension" && !details.value; const autofillAddressOverridden = yield new Promise((resolve) => chrome.privacy.services.autofillAddressEnabled.get({}, (details) => resolve(checkOverrideStatus(details)))); const autofillCreditCardOverridden = yield new Promise((resolve) => chrome.privacy.services.autofillCreditCardEnabled.get({}, (details) => resolve(checkOverrideStatus(details)))); const passwordSavingOverridden = yield new Promise((resolve) => chrome.privacy.services.passwordSavingEnabled.get({}, (details) => resolve(checkOverrideStatus(details)))); return autofillAddressOverridden && autofillCreditCardOverridden && passwordSavingOverridden; }); } /** * Updates the browser autofill settings to the given value. * * @param value - Determines whether to enable or disable the autofill settings. */ static updateDefaultBrowserAutofillSettings(value) { return browser_api_awaiter(this, void 0, void 0, function* () { yield chrome.privacy.services.autofillAddressEnabled.set({ value }); yield chrome.privacy.services.autofillCreditCardEnabled.set({ value }); yield chrome.privacy.services.passwordSavingEnabled.set({ value }); }); } /** * Handles registration of static content scripts within manifest v2. * * @param contentScriptOptions - Details of the registered content scripts */ static registerContentScriptsMv2(contentScriptOptions) { return browser_api_awaiter(this, void 0, void 0, function* () { var _a; if (typeof browser !== "undefined" && !!((_a = browser.contentScripts) === null || _a === void 0 ? void 0 : _a.register)) { return yield browser.contentScripts.register(contentScriptOptions); } return yield registerContentScriptsPolyfill(contentScriptOptions); }); } /** * Handles registration of static content scripts within manifest v3. * * @param scripts - Details of the registered content scripts */ static registerContentScriptsMv3(scripts) { return browser_api_awaiter(this, void 0, void 0, function* () { yield chrome.scripting.registerContentScripts(scripts); }); } /** * Handles unregistering of static content scripts within manifest v3. * * @param filter - Optional filter to unregister content scripts. Passing an empty object will unregister all content scripts. */ static unregisterContentScriptsMv3(filter) { return browser_api_awaiter(this, void 0, void 0, function* () { yield chrome.scripting.unregisterContentScripts(filter); }); } } browser_api_BrowserApi.isWebExtensionsApi = typeof browser !== "undefined"; browser_api_BrowserApi.isSafariApi = isBrowserSafariApi(); browser_api_BrowserApi.isChromeApi = !browser_api_BrowserApi.isSafariApi && typeof chrome !== "undefined"; browser_api_BrowserApi.isFirefoxOnAndroid = navigator.userAgent.indexOf("Firefox/") !== -1 && navigator.userAgent.indexOf("Android") !== -1; // Keep track of all the events registered in a Safari popup so we can remove // them when the popup gets unloaded, otherwise we cause a memory leak browser_api_BrowserApi.trackedChromeEventListeners = []; ;// ./src/autofill/overlay/inline-menu/iframe-content/autofill-inline-menu-iframe.service.ts var autofill_inline_menu_iframe_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore class AutofillInlineMenuIframeService { constructor(shadow, portName, initStyles, iframeTitle, ariaAlert) { var _a; this.shadow = shadow; this.portName = portName; this.initStyles = initStyles; this.iframeTitle = iframeTitle; this.ariaAlert = ariaAlert; this.setElementStyles = setElementStyles; this.sendExtensionMessage = sendExtensionMessage; this.port = null; this.fadeInOpacityTransition = "opacity 125ms ease-out 0s"; this.fadeOutOpacityTransition = "opacity 65ms ease-out 0s"; this.iframeStyles = { all: "initial", position: "fixed", display: "block", zIndex: "2147483647", lineHeight: "0", overflow: "hidden", transition: this.fadeInOpacityTransition, visibility: "visible", clipPath: "none", pointerEvents: "auto", margin: "0", padding: "0", colorScheme: "normal", opacity: "0", }; this.defaultIframeAttributes = { src: "", title: "", allowtransparency: "true", tabIndex: "-1", scrolling: "no", }; this.foreignMutationsCount = 0; this.mutationObserverIterations = 0; this.backgroundPortMessageHandlers = { initAutofillInlineMenuButton: ({ message }) => this.initAutofillInlineMenu(message), initAutofillInlineMenuList: ({ message }) => this.initAutofillInlineMenu(message), updateAutofillInlineMenuPosition: ({ message }) => this.updateIframePosition(message.styles), toggleAutofillInlineMenuHidden: ({ message }) => this.updateElementStyles(this.iframe, message.styles), updateAutofillInlineMenuColorScheme: () => this.updateAutofillInlineMenuColorScheme(), triggerDelayedAutofillInlineMenuClosure: () => this.handleDelayedAutofillInlineMenuClosure(), fadeInAutofillInlineMenuIframe: () => this.handleFadeInInlineMenuIframe(), updateAutofillInlineMenuGeneratedPassword: ({ message }) => this.handleUpdateGeneratedPassword(message), }; /** * Sets up the port message listener to the extension background script. This * listener is used to communicate between the iframe and the background script. * This also facilitates announcing to screen readers when the iframe is loaded. */ this.setupPortMessageListener = () => { this.port = chrome.runtime.connect({ name: this.portName }); this.port.onDisconnect.addListener(this.handlePortDisconnect); this.port.onMessage.addListener(this.handlePortMessage); this.announceAriaAlert(this.ariaAlert, 2000); }; /** * Handles disconnecting the port message listener from the extension background * script. This also removes the listener that facilitates announcing to screen * readers when the iframe is loaded. * * @param port - The port that is disconnected */ this.handlePortDisconnect = (port) => { var _a, _b, _c; if (port.name !== this.portName) { return; } this.updateElementStyles(this.iframe, { opacity: "0", height: "0px" }); this.unobserveIframe(); this.clearAriaAlert(); (_a = this.port) === null || _a === void 0 ? void 0 : _a.onMessage.removeListener(this.handlePortMessage); (_b = this.port) === null || _b === void 0 ? void 0 : _b.onDisconnect.removeListener(this.handlePortDisconnect); (_c = this.port) === null || _c === void 0 ? void 0 : _c.disconnect(); this.port = null; }; /** * Handles messages sent from the extension background script to the iframe. * Triggers behavior within the iframe as well as on the custom element that * contains the iframe element. * * @param message * @param port */ this.handlePortMessage = (message, port) => { if (port.name !== this.portName) { return; } if (this.backgroundPortMessageHandlers[message.command]) { this.backgroundPortMessageHandlers[message.command]({ message, port }); return; } this.postMessageToIFrame(message); }; /** * Handles updating the generated password in the inline menu iframe. Triggers * an aria alert if the user initiated the password regeneration. * * @param message - The message sent from the iframe */ this.handleUpdateGeneratedPassword = (message) => { this.postMessageToIFrame(message); if (message.refreshPassword) { this.clearAriaAlert(); this.createAriaAlertElement(true); this.announceAriaAlert(chrome.i18n.getMessage("passwordRegenerated"), 500, true); } }; /** * Handles mutations to the iframe element. The ensures that the iframe * element's styles are not modified by a third party source. * * @param mutations - The mutations to the iframe element */ this.handleMutations = (mutations) => { if (this.isTriggeringExcessiveMutationObserverIterations()) { return; } for (let index = 0; index < mutations.length; index++) { const mutation = mutations[index]; if (mutation.type !== "attributes") { continue; } const element = mutation.target; if (mutation.attributeName !== "style") { this.handleElementAttributeMutation(element); continue; } this.iframe.removeAttribute("style"); this.updateElementStyles(this.iframe, this.iframeStyles); } }; this.extensionOrigin = (_a = browser_api_BrowserApi.getRuntimeURL("")) === null || _a === void 0 ? void 0 : _a.slice(0, -1); this.iframeMutationObserver = new MutationObserver(this.handleMutations); } /** * Handles initialization of the iframe which includes applying initial styles * to the iframe, setting the source, and adding listener that connects the * iframe to the background script each time it loads. Can conditionally * create an aria alert element to announce to screen readers when the iframe * is loaded. The end result is append to the shadowDOM of the custom element * that is declared. */ initMenuIframe() { this.defaultIframeAttributes.src = browser_api_BrowserApi.getRuntimeURL("overlay/menu.html"); this.defaultIframeAttributes.title = this.iframeTitle; this.iframe = globalThis.document.createElement("iframe"); for (const [attribute, value] of Object.entries(this.defaultIframeAttributes)) { this.iframe.setAttribute(attribute, value); } this.iframeStyles = Object.assign(Object.assign({}, this.iframeStyles), this.initStyles); this.setElementStyles(this.iframe, this.iframeStyles, true); this.iframe.addEventListener(EVENTS.LOAD, this.setupPortMessageListener); if (this.ariaAlert) { this.createAriaAlertElement(); } this.shadow.appendChild(this.iframe); this.observeIframe(); } /** * Creates an aria alert element that is used to announce to screen readers * when the iframe is loaded. */ createAriaAlertElement(assertive = false) { this.ariaAlertElement = globalThis.document.createElement("div"); this.ariaAlertElement.setAttribute("role", "alert"); this.ariaAlertElement.setAttribute("aria-live", assertive ? "assertive" : "polite"); this.ariaAlertElement.setAttribute("aria-atomic", "true"); this.updateElementStyles(this.ariaAlertElement, { position: "absolute", top: "-9999px", left: "-9999px", width: "1px", height: "1px", overflow: "hidden", opacity: "0", pointerEvents: "none", }); } /** * Announces the aria alert element to screen readers when the iframe is loaded. * * @param textContent - The text content to announce * @param delay - The delay before announcing the text content * @param triggeredByUser - Identifies whether we should present the alert regardless of field focus */ announceAriaAlert(textContent, delay, triggeredByUser = false) { if (!this.ariaAlertElement || !textContent) { return; } this.ariaAlertElement.remove(); this.ariaAlertElement.textContent = textContent; this.clearAriaAlert(); this.ariaAlertTimeout = globalThis.setTimeout(() => autofill_inline_menu_iframe_service_awaiter(this, void 0, void 0, function* () { const isFieldFocused = yield this.sendExtensionMessage("checkIsFieldCurrentlyFocused"); if (isFieldFocused || triggeredByUser) { this.shadow.appendChild(this.ariaAlertElement); } this.ariaAlertTimeout = null; }), delay); } /** * Clears any existing aria alert that could be announced. */ clearAriaAlert() { if (this.ariaAlertTimeout) { clearTimeout(this.ariaAlertTimeout); this.ariaAlertTimeout = null; } } /** * Handles the initialization of the autofill inline menu. This includes setting * the port key and sending a message to the iframe to initialize the inline menu. * * @param message * @private */ initAutofillInlineMenu(message) { this.portKey = message.portKey; if (message.command === "initAutofillInlineMenuList") { this.initAutofillInlineMenuList(message); return; } this.postMessageToIFrame(message); } /** * Handles initialization of the autofill inline menu list. This includes setting * the theme and sending a message to the iframe to initialize the inline menu. * * @param message - The message sent from the iframe */ initAutofillInlineMenuList(message) { const { theme } = message; let borderColor; let verifiedTheme = theme; if (verifiedTheme === ThemeTypes.System) { verifiedTheme = globalThis.matchMedia("(prefers-color-scheme: dark)").matches ? ThemeTypes.Dark : ThemeTypes.Light; } if (verifiedTheme === ThemeTypes.Dark) { borderColor = "#4c525f"; } if (borderColor) { this.updateElementStyles(this.iframe, { borderColor }); } message.theme = verifiedTheme; this.postMessageToIFrame(message); } postMessageToIFrame(message) { var _a; (_a = this.iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.postMessage(Object.assign({ portKey: this.portKey }, message), this.extensionOrigin); } /** * Updates the position of the iframe element. Will also announce * to screen readers that the iframe is open. * * @param position - The position styles to apply to the iframe */ updateIframePosition(position) { if (!globalThis.document.hasFocus()) { return; } const styles = this.fadeInTimeout ? Object.assign(position, { opacity: "0" }) : position; this.updateElementStyles(this.iframe, styles); const elementHeightCompletelyInViewport = this.isElementCompletelyWithinViewport(this.iframe.getBoundingClientRect()); if (!elementHeightCompletelyInViewport) { this.forceCloseInlineMenu(); return; } if (this.fadeInTimeout) { this.handleFadeInInlineMenuIframe(); } this.announceAriaAlert(this.ariaAlert, 2000); } /** * Check if element is completely within the browser viewport. */ isElementCompletelyWithinViewport(elementPosition) { // An element that lacks size should be considered within the viewport if (!elementPosition.height || !elementPosition.width) { return true; } const [viewportHeight, viewportWidth] = this.getViewportSize(); const rightSideIsWithinViewport = (elementPosition.right || 0) <= viewportWidth; const leftSideIsWithinViewport = (elementPosition.left || 0) >= 0; const topSideIsWithinViewport = (elementPosition.top || 0) >= 0; const bottomSideIsWithinViewport = (elementPosition.bottom || 0) <= viewportHeight; return (rightSideIsWithinViewport && leftSideIsWithinViewport && topSideIsWithinViewport && bottomSideIsWithinViewport); } /** Use Visual Viewport API if available (better for mobile/zoom) */ getViewportSize() { if ("visualViewport" in globalThis.window && globalThis.window.visualViewport) { return [globalThis.window.visualViewport.height, globalThis.window.visualViewport.width]; } return [globalThis.window.innerHeight, globalThis.window.innerWidth]; } /** * Gets the page color scheme meta tag and sends a message to the iframe * to update its color scheme. Will default to "normal" if the meta tag * does not exist. */ updateAutofillInlineMenuColorScheme() { var _a; const colorSchemeValue = (_a = globalThis.document .querySelector("meta[name='color-scheme']")) === null || _a === void 0 ? void 0 : _a.getAttribute("content"); this.postMessageToIFrame({ command: "updateAutofillInlineMenuColorScheme", colorScheme: colorSchemeValue || "normal", }); } /** * Accepts an element and updates the styles for that element. This method * will also unobserve the element if it is the iframe element. This is * done to ensure that we do not trigger the mutation observer when we * update the styles for the iframe. * * @param customElement - The element to update the styles for * @param styles - The styles to apply to the element */ updateElementStyles(customElement, styles) { if (!customElement) { return; } this.unobserveIframe(); this.setElementStyles(customElement, styles, true); if (customElement === this.iframe) { this.iframeStyles = Object.assign(Object.assign({}, this.iframeStyles), styles); } this.observeIframe(); } /** * Triggers a forced closure of the autofill inline menu. This is used when the * mutation observer is triggered excessively. */ forceCloseInlineMenu() { void this.sendExtensionMessage("closeAutofillInlineMenu", { forceCloseInlineMenu: true }); } /** * Triggers a fade in effect for the inline menu iframe. Initialized by the background context. */ handleFadeInInlineMenuIframe() { this.clearFadeInTimeout(); this.fadeInTimeout = globalThis.setTimeout(() => { this.updateElementStyles(this.iframe, { display: "block", opacity: "1" }); this.clearFadeInTimeout(); }, 10); } /** * Clears the fade in timeout for the inline menu iframe. */ clearFadeInTimeout() { if (this.fadeInTimeout) { clearTimeout(this.fadeInTimeout); this.fadeInTimeout = null; } } /** * Triggers a delayed closure of the inline menu to ensure that click events are * caught if focus is programmatically redirected away from the inline menu. */ handleDelayedAutofillInlineMenuClosure() { if (this.delayedCloseTimeout) { clearTimeout(this.delayedCloseTimeout); } this.updateElementStyles(this.iframe, { transition: this.fadeOutOpacityTransition, opacity: "0", }); this.delayedCloseTimeout = globalThis.setTimeout(() => { var _a; this.updateElementStyles(this.iframe, { transition: this.fadeInOpacityTransition }); (_a = this.port) === null || _a === void 0 ? void 0 : _a.disconnect(); this.port = null; this.forceCloseInlineMenu(); }, 100); } /** * Handles mutations to the iframe element's attributes. This ensures that * the iframe element's attributes are not modified by a third party source. * * @param element - The element to handle attribute mutations for */ handleElementAttributeMutation(element) { const attributes = Array.from(element.attributes); for (let attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) { const attribute = attributes[attributeIndex]; if (attribute.name === "style") { continue; } if (this.foreignMutationsCount >= 10) { this.forceCloseInlineMenu(); break; } const defaultIframeAttribute = this.defaultIframeAttributes[attribute.name]; if (!defaultIframeAttribute) { this.iframe.removeAttribute(attribute.name); this.foreignMutationsCount++; continue; } if (attribute.value === defaultIframeAttribute) { continue; } this.iframe.setAttribute(attribute.name, defaultIframeAttribute); this.foreignMutationsCount++; } } /** * Observes the iframe element for mutations to its style attribute. */ observeIframe() { this.iframeMutationObserver.observe(this.iframe, { attributes: true }); } /** * Unobserves the iframe element for mutations to its style attribute. */ unobserveIframe() { var _a; (_a = this.iframeMutationObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); } /** * Identifies if the mutation observer is triggering excessive iterations. * Will remove the autofill inline menu if any set mutation observer is * triggering excessive iterations. */ isTriggeringExcessiveMutationObserverIterations() { const resetCounters = () => { this.mutationObserverIterations = 0; this.foreignMutationsCount = 0; }; if (this.mutationObserverIterationsResetTimeout) { clearTimeout(this.mutationObserverIterationsResetTimeout); } this.mutationObserverIterations++; this.mutationObserverIterationsResetTimeout = globalThis.setTimeout(() => resetCounters(), 2000); if (this.mutationObserverIterations > 20) { clearTimeout(this.mutationObserverIterationsResetTimeout); resetCounters(); this.forceCloseInlineMenu(); return true; } return false; } } ;// ./src/autofill/overlay/inline-menu/iframe-content/autofill-inline-menu-iframe-element.ts class AutofillInlineMenuIframeElement { constructor(element, portName, initStyles, iframeTitle, ariaAlert) { const style = this.createInternalStyleNode(); const shadow = element.attachShadow({ mode: "closed" }); shadow.prepend(style); const autofillInlineMenuIframeService = new AutofillInlineMenuIframeService(shadow, portName, initStyles, iframeTitle, ariaAlert); autofillInlineMenuIframeService.initMenuIframe(); } /** * Builds and prepends an internal stylesheet to the container node with rules * to prevent targeting by the host's global styling rules. This should only be * used for pseudo elements such as `::backdrop` or `::before`. All other * styles should be applied inline upon the parent container itself for improved * specificity priority. */ createInternalStyleNode() { const css = document.createTextNode(` :host::backdrop, :host::before, :host::after { all: initial !important; backdrop-filter: none !important; filter: none !important; inset: auto !important; touch-action: auto !important; user-select: text !important; display: none !important; position: relative !important; top: auto !important; right: auto !important; bottom: auto !important; left: auto !important; transform: none !important; transform-origin: 50% 50% !important; opacity: 1 !important; mix-blend-mode: normal !important; isolation: isolate !important; z-index: 0 !important; background: none !important; background-color: transparent !important; background-image: none !important; width: 0 !important; height: 0 !important; content: "" !important; pointer-events: all !important; } `); const style = globalThis.document.createElement("style"); style.setAttribute("type", "text/css"); style.appendChild(css); return style; } } ;// ./src/autofill/overlay/inline-menu/iframe-content/autofill-inline-menu-button-iframe.ts class AutofillInlineMenuButtonIframe extends AutofillInlineMenuIframeElement { constructor(element) { super(element, AutofillOverlayPort.Button, { background: "transparent", border: "none", }, chrome.i18n.getMessage("bitwardenOverlayButton"), chrome.i18n.getMessage("bitwardenOverlayMenuAvailable")); } } ;// ./src/autofill/overlay/inline-menu/iframe-content/autofill-inline-menu-list-iframe.ts class AutofillInlineMenuListIframe extends AutofillInlineMenuIframeElement { constructor(element) { super(element, AutofillOverlayPort.List, { height: "0px", minWidth: "260px", maxHeight: "180px", boxShadow: "rgba(0, 0, 0, 0.1) 2px 4px 6px 0px", borderRadius: "4px", borderWidth: "1px", borderStyle: "solid", borderColor: "rgb(206, 212, 220)", }, chrome.i18n.getMessage("bitwardenVault")); } } ;// ./src/autofill/overlay/inline-menu/content/autofill-inline-menu-content.service.ts var autofill_inline_menu_content_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; const experienceValidationBackoffThresholds = { topLayer: { countLimit: 5, timeSpanLimit: 5000, }, popoverAttribute: { countLimit: 10, timeSpanLimit: 5000, }, }; class AutofillInlineMenuContentService { constructor() { this.sendExtensionMessage = sendExtensionMessage; this.generateRandomCustomElementName = generateRandomCustomElementName; this.setElementStyles = setElementStyles; this.isFirefoxBrowser = globalThis.navigator.userAgent.indexOf(" Firefox/") !== -1 || globalThis.navigator.userAgent.indexOf(" Gecko/") !== -1; this.refreshCountWithinTimeThreshold = { topLayer: 0, popoverAttribute: 0, }; this.lastTrackedTimestamp = { topLayer: Date.now(), popoverAttribute: Date.now(), }; /** * Distinct from preventing inline menu script injection, this is for cases * where the page is subsequently determined to be risky. */ this.inlineMenuEnabled = true; this.mutationObserverIterations = 0; this.lastElementOverrides = new WeakMap(); this.customElementDefaultStyles = { all: "initial", position: "fixed", display: "block", zIndex: "2147483647", }; this.extensionMessageHandlers = { closeAutofillInlineMenu: ({ message }) => this.closeInlineMenu(message), appendAutofillInlineMenuToDom: ({ message }) => this.appendInlineMenuElements(message), }; /** * Removes the autofill inline menu from the page. This will initially * unobserve the menu container to ensure the mutation observer no * longer triggers. */ this.closeInlineMenu = (message) => { if ((message === null || message === void 0 ? void 0 : message.overlayElement) === AutofillOverlayElement.Button) { this.closeInlineMenuButton(); return; } if ((message === null || message === void 0 ? void 0 : message.overlayElement) === AutofillOverlayElement.List) { this.closeInlineMenuList(); return; } this.unobserveContainerElement(); this.closeInlineMenuButton(); this.closeInlineMenuList(); }; /** * Sets up mutation observers for the inline menu elements, the menu container, and * the document element. The mutation observers are used to remove any styles that * are added to the inline menu elements by the website. They are also used to ensure * that the inline menu elements are always present at the bottom of the menu container. */ this.setupMutationObserver = () => { this.htmlMutationObserver = new MutationObserver(this.handlePageMutations); this.bodyMutationObserver = new MutationObserver(this.handlePageMutations); this.inlineMenuElementsMutationObserver = new MutationObserver(this.handleInlineMenuElementMutationObserverUpdate); this.containerElementMutationObserver = new MutationObserver(this.handleContainerElementMutationObserverUpdate); this.observePageAttributes(); }; /** * Handles the mutation observer update for the inline menu elements. This method will * remove any attributes or styles that might be added to the inline menu elements by * a separate process within the website where this script is injected. * * @param mutationRecord - The mutation record that triggered the update. */ this.handleInlineMenuElementMutationObserverUpdate = (mutationRecord) => { if (this.isTriggeringExcessiveMutationObserverIterations()) { return; } for (let recordIndex = 0; recordIndex < mutationRecord.length; recordIndex++) { const record = mutationRecord[recordIndex]; if (record.type !== "attributes") { continue; } const element = record.target; if (record.attributeName === "popover" && this.inlineMenuEnabled) { const attributeValue = element.getAttribute(record.attributeName); if (attributeValue !== "manual") { this.refreshPopoverAttribute(element); } continue; } if (record.attributeName === "style") { element.removeAttribute("style"); this.updateCustomElementDefaultStyles(element); continue; } this.removeModifiedElementAttributes(element); } }; /** * Handles the mutation observer update for the element that contains the inline menu. * This method will ensure that the inline menu elements are always present at the * bottom of the container. */ this.handleContainerElementMutationObserverUpdate = (mutations) => { if ((!this.buttonElement && !this.listElement) || this.isTriggeringExcessiveMutationObserverIterations()) { return; } const containerElement = mutations[0].target; requestIdleCallbackPolyfill(() => this.processContainerElementMutation(containerElement), { timeout: 500, }); }; this.checkPageRisks = () => autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { const pageIsOpaque = yield this.getPageIsOpaque(); const risksFound = !pageIsOpaque || !this.inlineMenuEnabled; if (risksFound) { this.closeInlineMenu(); } return risksFound; }); /* * Checks for known risks at the page level */ this.handlePageMutations = (mutations) => autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { if (mutations.some(({ type }) => type === "attributes")) { yield this.checkPageRisks(); } }); /** * Returns the name of the generated container tags for usage internally to avoid * unintentional targeting of the owned experience. */ this.getOwnedTagNames = () => { var _a, _b; return [ ...(((_a = this.buttonElement) === null || _a === void 0 ? void 0 : _a.tagName) ? [this.buttonElement.tagName] : []), ...(((_b = this.listElement) === null || _b === void 0 ? void 0 : _b.tagName) ? [this.listElement.tagName] : []), ]; }; /** * Queries and return elements (excluding those of the inline menu) that exist in the * top-layer via popover or dialog * @param {boolean} [includeCandidates=false] indicate whether top-layer candidate (which * may or may not be active) should be included in the query */ this.getUnownedTopLayerItems = (includeCandidates = false) => { var _a, _b; const inlineMenuTagExclusions = [ ...(((_a = this.buttonElement) === null || _a === void 0 ? void 0 : _a.tagName) ? [`:not(${this.buttonElement.tagName})`] : []), ...(((_b = this.listElement) === null || _b === void 0 ? void 0 : _b.tagName) ? [`:not(${this.listElement.tagName})`] : []), ":popover-open", ].join(""); const selector = [ ":modal", inlineMenuTagExclusions, ...(includeCandidates ? ["[popover], dialog"] : []), ].join(","); const otherTopLayeritems = globalThis.document.querySelectorAll(selector); return otherTopLayeritems; }; /** * Internally track owned injected experience refreshes as a side-effect * of host page interference. */ this.checkAndUpdateRefreshCount = (countType) => { if (!this.inlineMenuEnabled) { return; } const { countLimit, timeSpanLimit } = experienceValidationBackoffThresholds[countType]; const now = Date.now(); const timeSinceLastTrackedRefresh = now - this.lastTrackedTimestamp[countType]; const currentlyWithinTimeThreshold = timeSinceLastTrackedRefresh <= timeSpanLimit; const withinCountThreshold = this.refreshCountWithinTimeThreshold[countType] <= countLimit; if (currentlyWithinTimeThreshold) { if (withinCountThreshold) { this.refreshCountWithinTimeThreshold[countType]++; } else { // Set inline menu to be off; page is aggressively trying to take top position of top layer this.inlineMenuEnabled = false; void this.checkPageRisks(); const warningMessage = chrome.i18n.getMessage("topLayerHijackWarning"); globalThis.window.alert(warningMessage); } } else { this.lastTrackedTimestamp[countType] = now; this.refreshCountWithinTimeThreshold[countType] = 0; } }; this.refreshPopoverAttribute = (element) => { this.checkAndUpdateRefreshCount("popoverAttribute"); element.setAttribute("popover", "manual"); element.showPopover(); }; this.refreshTopLayerPosition = () => { if (!this.inlineMenuEnabled) { return; } const otherTopLayerItems = this.getUnownedTopLayerItems(); // No need to refresh if there are no other top-layer items if (!otherTopLayerItems.length) { return; } const buttonInDocument = this.buttonElement && globalThis.document.getElementsByTagName(this.buttonElement.tagName)[0]; const listInDocument = this.listElement && globalThis.document.getElementsByTagName(this.listElement.tagName)[0]; if (buttonInDocument) { buttonInDocument.hidePopover(); buttonInDocument.showPopover(); } if (listInDocument) { listInDocument.hidePopover(); listInDocument.showPopover(); } if (buttonInDocument || listInDocument) { this.checkAndUpdateRefreshCount("topLayer"); } }; /** * Checks the opacity of the page body and body parent, since the inline menu experience * will inherit the opacity, despite being otherwise encapsulated from styling changes * of parents below the body. Assumes the target element will be a direct child of the page * `body` (enforced elsewhere). */ this.getPageIsOpaque = () => { // @TODO for definitive checks, traverse up the node tree from the inline menu container; // nodes can exist between `html` and `body` /** * `querySelectorAll` for (non-standard) cases where the page has additional copies of * page nodes that should be unique */ const pageElements = globalThis.document.querySelectorAll("html, body"); if (!pageElements.length) { return false; } return [...pageElements].every((element) => { var _a; // These are computed style values, so we don't need to worry about non-float values // for `opacity`, here const elementOpacity = ((_a = globalThis.window.getComputedStyle(element)) === null || _a === void 0 ? void 0 : _a.opacity) || "0"; // Any value above this is considered "opaque" for our purposes const opacityThreshold = 0.6; return parseFloat(elementOpacity) > opacityThreshold; }); }; /** * Processes the mutation of the element that contains the inline menu. Will trigger when an * idle moment in the execution of the main thread is detected. */ this.processContainerElementMutation = (containerElement) => autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { // If the page contains risks, tear down and prevent building the inline menu experience. const pageRisksFound = yield this.checkPageRisks(); if (pageRisksFound) { return; } const lastChild = containerElement.lastElementChild; const secondToLastChild = lastChild === null || lastChild === void 0 ? void 0 : lastChild.previousElementSibling; const lastChildIsInlineMenuList = lastChild === this.listElement; const lastChildIsInlineMenuButton = lastChild === this.buttonElement; const secondToLastChildIsInlineMenuButton = secondToLastChild === this.buttonElement; if (!lastChild) { return; } const lastChildEncounterCount = this.lastElementOverrides.get(lastChild) || 0; if (!lastChildIsInlineMenuList && !lastChildIsInlineMenuButton && lastChildEncounterCount < 3) { this.lastElementOverrides.set(lastChild, lastChildEncounterCount + 1); } if (this.lastElementOverrides.get(lastChild) >= 3) { this.handlePersistentLastChildOverride(lastChild); return; } const isInlineMenuListVisible = yield this.isInlineMenuListVisible(); if (!lastChild || (lastChildIsInlineMenuList && secondToLastChildIsInlineMenuButton) || (lastChildIsInlineMenuButton && !isInlineMenuListVisible)) { return; } if ((lastChildIsInlineMenuList && !secondToLastChildIsInlineMenuButton) || (lastChildIsInlineMenuButton && isInlineMenuListVisible)) { containerElement.insertBefore(this.buttonElement, this.listElement); return; } containerElement.insertBefore(lastChild, this.buttonElement); }); /** * Verifies if the last child of the menu container is overlaying the inline menu elements. * This is triggered when the last child of the menu container is being forced by some * script to be an element other than the inline menu elements. * * @param lastChild - The last child of the menu container. */ this.verifyInlineMenuIsNotObscured = (lastChild) => autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { const inlineMenuPosition = yield this.sendExtensionMessage("getAutofillInlineMenuPosition"); const { button, list } = inlineMenuPosition; if (!!button && this.elementAtCenterOfInlineMenuPosition(button) === lastChild) { this.closeInlineMenu(); return; } if (!!list && this.elementAtCenterOfInlineMenuPosition(list) === lastChild) { this.closeInlineMenu(); } }); this.setupMutationObserver(); } /** * Returns the message handlers for the autofill inline menu content service. */ get messageHandlers() { return this.extensionMessageHandlers; } /** * Identifies if the passed element corresponds to the inline menu button or list. * * @param element - The element being checked */ isElementInlineMenu(element) { return element === this.buttonElement || element === this.listElement; } /** * Checks if the inline menu button is visible at the top frame. */ isInlineMenuButtonVisible() { return autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { return (!!this.buttonElement && (yield this.sendExtensionMessage("checkIsAutofillInlineMenuButtonVisible")) === true); }); } /** * Checks if the inline menu list if visible at the top frame. */ isInlineMenuListVisible() { return autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { return (!!this.listElement && (yield this.sendExtensionMessage("checkIsAutofillInlineMenuListVisible")) === true); }); } /** * Removes the inline menu button from the DOM if it is currently present. Will * also remove the inline menu reposition event listeners. */ closeInlineMenuButton() { if (this.buttonElement) { this.buttonElement.remove(); void this.sendExtensionMessage("autofillOverlayElementClosed", { overlayElement: AutofillOverlayElement.Button, }); } } /** * Removes the inline menu list from the DOM if it is currently present. */ closeInlineMenuList() { if (this.listElement) { this.listElement.remove(); void this.sendExtensionMessage("autofillOverlayElementClosed", { overlayElement: AutofillOverlayElement.List, }); } } /** * Updates the position of both the inline menu button and inline menu list. */ appendInlineMenuElements(_a) { return autofill_inline_menu_content_service_awaiter(this, arguments, void 0, function* ({ overlayElement }) { if (!this.inlineMenuEnabled) { return; } if (overlayElement === AutofillOverlayElement.Button) { return this.appendButtonElement(); } return this.appendListElement(); }); } /** * Updates the position of the inline menu button. */ appendButtonElement() { return autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { if (!this.inlineMenuEnabled) { return; } if (!this.buttonElement) { this.createButtonElement(); this.updateCustomElementDefaultStyles(this.buttonElement); } if (!(yield this.isInlineMenuButtonVisible())) { this.appendInlineMenuElementToDom(this.buttonElement); this.updateInlineMenuElementIsVisibleStatus(AutofillOverlayElement.Button, true); this.buttonElement.showPopover(); } }); } /** * Updates the position of the inline menu list. */ appendListElement() { return autofill_inline_menu_content_service_awaiter(this, void 0, void 0, function* () { if (!this.inlineMenuEnabled) { return; } if (!this.listElement) { this.createListElement(); this.updateCustomElementDefaultStyles(this.listElement); } if (!(yield this.isInlineMenuListVisible())) { this.appendInlineMenuElementToDom(this.listElement); this.updateInlineMenuElementIsVisibleStatus(AutofillOverlayElement.List, true); this.listElement.showPopover(); } }); } /** * Updates the visibility status of the inline menu element within the background script. * * @param overlayElement - The inline menu element to update the visibility status for. * @param isVisible - The visibility status to update the inline menu element to. */ updateInlineMenuElementIsVisibleStatus(overlayElement, isVisible) { void this.sendExtensionMessage("updateAutofillInlineMenuElementIsVisibleStatus", { overlayElement, isVisible, }); } /** * Appends the inline menu element to the menu container. This method will also * observe the menu container to ensure that the inline menu element is not * interfered with by any DOM changes. * * @param element - The inline menu element to append to the menu container. */ appendInlineMenuElementToDom(element) { var _a; const parentDialogElement = (_a = globalThis.document.activeElement) === null || _a === void 0 ? void 0 : _a.closest("dialog"); if ((parentDialogElement === null || parentDialogElement === void 0 ? void 0 : parentDialogElement.open) && parentDialogElement.matches(":modal")) { this.observeContainerElement(parentDialogElement); parentDialogElement.appendChild(element); return; } this.observeContainerElement(globalThis.document.body); globalThis.document.body.appendChild(element); } /** * Creates the autofill inline menu button element. Will not attempt * to create the element if it already exists in the DOM. */ createButtonElement() { var _a; if (!this.inlineMenuEnabled) { return; } if (this.isFirefoxBrowser) { this.buttonElement = globalThis.document.createElement("div"); this.buttonElement.setAttribute("popover", "manual"); new AutofillInlineMenuButtonIframe(this.buttonElement); return; } const customElementName = this.generateRandomCustomElementName(); (_a = globalThis.customElements) === null || _a === void 0 ? void 0 : _a.define(customElementName, class extends HTMLElement { constructor() { super(); new AutofillInlineMenuButtonIframe(this); } }); this.buttonElement = globalThis.document.createElement(customElementName); this.buttonElement.setAttribute("popover", "manual"); } /** * Creates the autofill inline menu list element. Will not attempt * to create the element if it already exists in the DOM. */ createListElement() { var _a; if (!this.inlineMenuEnabled) { return; } if (this.isFirefoxBrowser) { this.listElement = globalThis.document.createElement("div"); this.listElement.setAttribute("popover", "manual"); new AutofillInlineMenuListIframe(this.listElement); return; } const customElementName = this.generateRandomCustomElementName(); (_a = globalThis.customElements) === null || _a === void 0 ? void 0 : _a.define(customElementName, class extends HTMLElement { constructor() { super(); new AutofillInlineMenuListIframe(this); } }); this.listElement = globalThis.document.createElement(customElementName); this.listElement.setAttribute("popover", "manual"); } /** * Updates the default styles for the custom element. This method will * remove any styles that are added to the custom element by other methods. * * @param element - The custom element to update the default styles for. */ updateCustomElementDefaultStyles(element) { this.unobserveCustomElements(); this.setElementStyles(element, this.customElementDefaultStyles, true); this.observeCustomElements(); } /** * Sets up mutation observers to verify that the inline menu * elements are not modified by the website. */ observeCustomElements() { var _a, _b; if (this.buttonElement) { (_a = this.inlineMenuElementsMutationObserver) === null || _a === void 0 ? void 0 : _a.observe(this.buttonElement, { attributes: true, }); } if (this.listElement) { (_b = this.inlineMenuElementsMutationObserver) === null || _b === void 0 ? void 0 : _b.observe(this.listElement, { attributes: true }); } } /** * Sets up mutation observers to verify that the page `html` and `body` attributes * are not altered in a way that would impact safe display of the inline menu. */ observePageAttributes() { var _a, _b; if (document.documentElement) { (_a = this.htmlMutationObserver) === null || _a === void 0 ? void 0 : _a.observe(document.documentElement, { attributes: true }); } if (document.body) { (_b = this.bodyMutationObserver) === null || _b === void 0 ? void 0 : _b.observe(document.body, { attributes: true }); } } unobservePageAttributes() { var _a, _b; (_a = this.htmlMutationObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); (_b = this.bodyMutationObserver) === null || _b === void 0 ? void 0 : _b.disconnect(); } /** * Disconnects the mutation observers that are used to verify that the inline menu * elements are not modified by the website. */ unobserveCustomElements() { var _a; (_a = this.inlineMenuElementsMutationObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); } /** * Sets up a mutation observer for the element which contains the inline menu. */ observeContainerElement(element) { var _a; (_a = this.containerElementMutationObserver) === null || _a === void 0 ? void 0 : _a.observe(element, { childList: true }); } /** * Disconnects the mutation observer for the element which contains the inline menu. */ unobserveContainerElement() { var _a; (_a = this.containerElementMutationObserver) === null || _a === void 0 ? void 0 : _a.disconnect(); } /** * Removes all elements from a passed inline menu * element except for the style attribute. * * @param element - The element to remove the attributes from. */ removeModifiedElementAttributes(element) { const attributes = Array.from(element.attributes); for (let attributeIndex = 0; attributeIndex < attributes.length; attributeIndex++) { const attribute = attributes[attributeIndex]; if (attribute.name === "style" || attribute.name === "popover") { continue; } element.removeAttribute(attribute.name); } } /** * Handles the behavior of a persistent child element that is forcing itself to * the bottom of the menu container. This method will ensure that the inline menu * elements are not obscured by the persistent child element. * * @param lastChild - The last child of the menu container. */ handlePersistentLastChildOverride(lastChild) { const lastChildZIndex = parseInt(lastChild.style.zIndex); if (lastChildZIndex >= 2147483647) { lastChild.style.zIndex = "2147483646"; } this.clearPersistentLastChildOverrideTimeout(); this.handlePersistentLastChildOverrideTimeout = globalThis.setTimeout(() => this.verifyInlineMenuIsNotObscured(lastChild), 500); } /** * Returns the element present at the center of the inline menu position. * * @param position - The position of the inline menu element. */ elementAtCenterOfInlineMenuPosition(position) { return globalThis.document.elementFromPoint(position.left + position.width / 2, position.top + position.height / 2); } /** * Clears the timeout that is used to verify that the last child of the menu container * is not overlaying the inline menu elements. */ clearPersistentLastChildOverrideTimeout() { if (this.handlePersistentLastChildOverrideTimeout) { globalThis.clearTimeout(this.handlePersistentLastChildOverrideTimeout); } } /** * Identifies if the mutation observer is triggering excessive iterations. * Will trigger a blur of the most recently focused field and remove the * autofill inline menu if any set mutation observer is triggering * excessive iterations. */ isTriggeringExcessiveMutationObserverIterations() { if (this.mutationObserverIterationsResetTimeout) { clearTimeout(this.mutationObserverIterationsResetTimeout); } this.mutationObserverIterations++; this.mutationObserverIterationsResetTimeout = setTimeout(() => (this.mutationObserverIterations = 0), 2000); if (this.mutationObserverIterations > 100) { clearTimeout(this.mutationObserverIterationsResetTimeout); this.mutationObserverIterations = 0; this.closeInlineMenu(); return true; } return false; } /** * Disconnects the mutation observers and removes the inline menu elements from the DOM. */ destroy() { this.closeInlineMenu(); this.clearPersistentLastChildOverrideTimeout(); this.unobservePageAttributes(); } } ;// ./src/autofill/notification/abstractions/notification-bar.ts const NotificationTypes = { Add: "add", Change: "change", Unlock: "unlock", AtRiskPassword: "at-risk-password", }; ;// ./src/autofill/overlay/notifications/content/overlay-notifications-content.service.ts var overlay_notifications_content_service_awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var overlay_notifications_content_service_rest = (undefined && undefined.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore class OverlayNotificationsContentService { constructor() { var _a; this.notificationBarRootElement = null; this.notificationBarElement = null; this.notificationBarIframeElement = null; this.notificationBarShadowRoot = null; this.currentNotificationBarType = null; this.notificationBarContainerStyles = { height: "400px", width: "430px", maxWidth: "calc(100% - 20px)", minHeight: "initial", top: "10px", right: "0px", padding: "0", position: "fixed", zIndex: "2147483647", visibility: "visible", borderRadius: "4px", border: "none", backgroundColor: "transparent", overflow: "hidden", transition: "box-shadow 0.15s ease", transitionDelay: "0.15s", }; this.notificationBarIframeElementStyles = { width: "100%", height: "100%", border: "0", display: "block", position: "relative", transition: "transform 0.15s ease-out, opacity 0.15s ease", borderRadius: "4px", colorScheme: "auto", }; this.extensionMessageHandlers = { openNotificationBar: ({ message }) => this.handleOpenNotificationBarMessage(message), closeNotificationBar: ({ message }) => this.handleCloseNotificationBarMessage(message), adjustNotificationBar: ({ message }) => this.handleAdjustNotificationBarHeightMessage(message), saveCipherAttemptCompleted: ({ message }) => this.handleSaveCipherAttemptCompletedMessage(message), }; /** * Handles the load event for the notification bar iframe. * This will animate the notification bar into view. */ this.handleNotificationBarIframeOnLoad = () => { var _a; setElementStyles(this.notificationBarIframeElement, { transform: "translateX(0)", opacity: "1" }, true); (_a = this.notificationBarIframeElement) === null || _a === void 0 ? void 0 : _a.removeEventListener(EVENTS.LOAD, this.handleNotificationBarIframeOnLoad); }; this.extensionOrigin = (_a = browser_api_BrowserApi.getRuntimeURL("")) === null || _a === void 0 ? void 0 : _a.slice(0, -1); void sendExtensionMessage("checkNotificationQueue"); } /** * Returns the message handlers for the content script. */ get messageHandlers() { return this.extensionMessageHandlers; } /** * Opens the notification bar with the provided init data. Will trigger a closure * of the notification bar if the type of the notification bar changes. * * @param message - The message containing the initialization data for the notification bar. */ handleOpenNotificationBarMessage(message) { return overlay_notifications_content_service_awaiter(this, void 0, void 0, function* () { if (!message.data) { return; } const { type, typeData, params } = message.data; if (this.currentNotificationBarType && type !== this.currentNotificationBarType) { this.closeNotificationBar(); } const initData = { type: type, isVaultLocked: typeData.isVaultLocked, theme: typeData.theme, removeIndividualVault: typeData.removeIndividualVault, importType: typeData.importType, launchTimestamp: typeData.launchTimestamp, params, }; if (globalThis.document.readyState === "loading") { document.addEventListener("DOMContentLoaded", () => this.openNotificationBar(initData)); return; } this.openNotificationBar(initData); }); } /** * Closes the notification bar. If the message contains a flag to fade out the notification, * the notification bar will fade out before being removed from the DOM. * * @param message - The message containing the data for closing the notification bar. */ handleCloseNotificationBarMessage(message) { var _a, _b; const closedByUser = typeof ((_a = message.data) === null || _a === void 0 ? void 0 : _a.closedByUser) === "boolean" ? message.data.closedByUser : true; if ((_b = message.data) === null || _b === void 0 ? void 0 : _b.fadeOutNotification) { setElementStyles(this.notificationBarIframeElement, { opacity: "0" }, true); globalThis.setTimeout(() => this.closeNotificationBar(closedByUser), 150); return; } this.closeNotificationBar(closedByUser); } /** * Adjusts the height of the notification bar. * * @param message - The message containing the height of the notification bar. */ handleAdjustNotificationBarHeightMessage(message) { var _a; if (this.notificationBarElement && ((_a = message.data) === null || _a === void 0 ? void 0 : _a.height)) { this.notificationBarElement.style.height = `${message.data.height}px`; } } /** * Handles the message for when a save cipher attempt has completed. This triggers an update * to the presentation of the notification bar, facilitating a visual indication of the save * attempt's success or failure. * * @param message * @private */ handleSaveCipherAttemptCompletedMessage(message) { // destructure error out of data const _a = (message === null || message === void 0 ? void 0 : message.data) || {}, { error } = _a, otherData = overlay_notifications_content_service_rest(_a, ["error"]); this.sendMessageToNotificationBarIframe({ command: "saveCipherAttemptCompleted", data: Object.keys(otherData).length ? otherData : undefined, error, }); } /** * Opens the notification bar with the given initialization data. * * @param initData * @private */ openNotificationBar(initData) { if (!this.notificationBarRootElement && !this.notificationBarIframeElement) { this.createNotificationBarIframeElement(initData); this.createNotificationBarElement(); this.setupInitNotificationBarMessageListener(initData); globalThis.document.body.appendChild(this.notificationBarRootElement); } } /** * Creates the iframe element for the notification bar. * * @param initData - The initialization data for the notification bar. */ createNotificationBarIframeElement(initData) { const isNotificationFresh = initData.launchTimestamp && Date.now() - initData.launchTimestamp < 250; this.currentNotificationBarType = initData.type; this.notificationBarIframeElement = globalThis.document.createElement("iframe"); this.notificationBarIframeElement.id = "bit-notification-bar-iframe"; const parentOrigin = globalThis.location.origin; const iframeUrl = new URL(browser_api_BrowserApi.getRuntimeURL("notification/bar.html")); iframeUrl.searchParams.set("parentOrigin", parentOrigin); this.notificationBarIframeElement.src = iframeUrl.toString(); setElementStyles(this.notificationBarIframeElement, Object.assign(Object.assign({}, this.notificationBarIframeElementStyles), { transform: isNotificationFresh ? "translateX(100%)" : "translateX(0)", opacity: isNotificationFresh ? "1" : "0" }), true); this.notificationBarIframeElement.addEventListener(EVENTS.LOAD, this.handleNotificationBarIframeOnLoad); } /** * Creates the container for the notification bar iframe with shadow DOM. */ createNotificationBarElement() { if (this.notificationBarIframeElement) { this.notificationBarRootElement = globalThis.document.createElement("bit-notification-bar-root"); this.notificationBarShadowRoot = this.notificationBarRootElement.attachShadow({ mode: "closed", delegatesFocus: true, }); this.notificationBarElement = globalThis.document.createElement("div"); this.notificationBarElement.id = "bit-notification-bar"; setElementStyles(this.notificationBarElement, this.notificationBarContainerStyles, true); this.notificationBarShadowRoot.appendChild(this.notificationBarElement); this.notificationBarElement.appendChild(this.notificationBarIframeElement); } } /** * Sets up the message listener for the initialization of the notification bar. * This will send the initialization data to the notification bar iframe. * * @param initData - The initialization data for the notification bar. */ setupInitNotificationBarMessageListener(initData) { const handleInitNotificationBarMessage = (event) => { const { source, data } = event; if (source !== this.notificationBarIframeElement.contentWindow || (data === null || data === void 0 ? void 0 : data.command) !== "initNotificationBar") { return; } this.sendMessageToNotificationBarIframe({ command: "initNotificationBar", initData, parentOrigin: globalThis.location.origin, }); globalThis.removeEventListener("message", handleInitNotificationBarMessage); }; if (this.notificationBarIframeElement) { globalThis.addEventListener("message", handleInitNotificationBarMessage); } } /** * Closes the notification bar. Will trigger a removal of the notification bar * from the background queue if the notification bar was closed by the user. * * @param closedByUserAction - Whether the notification bar was closed by the user. */ closeNotificationBar(closedByUserAction = false) { if (!this.notificationBarRootElement && !this.notificationBarIframeElement) { return; } this.notificationBarIframeElement.remove(); this.notificationBarIframeElement = null; this.notificationBarElement.remove(); this.notificationBarElement = null; this.notificationBarShadowRoot = null; this.notificationBarRootElement.remove(); this.notificationBarRootElement = null; const removableNotificationTypes = new Set([ NotificationTypes.Add, NotificationTypes.Change, NotificationTypes.AtRiskPassword, ]); if (closedByUserAction && removableNotificationTypes.has(this.currentNotificationBarType)) { void sendExtensionMessage("bgRemoveTabFromNotificationQueue"); } this.currentNotificationBarType = null; } /** * Sends a message to the notification bar iframe. * * @param message - The message to send to the notification bar iframe. */ sendMessageToNotificationBarIframe(message) { if (this.notificationBarIframeElement) { this.notificationBarIframeElement.contentWindow.postMessage(message, this.extensionOrigin); } } /** * Destroys the notification bar. */ destroy() { this.closeNotificationBar(true); } } // EXTERNAL MODULE: ../../node_modules/@webcomponents/custom-elements/custom-elements.min.js var custom_elements_min = __webpack_require__(70526); ;// ../../node_modules/lit/polyfill-support.js !function(i){"function"==typeof define&&define.amd?define(i):i();}(function(){"use strict";/** * @license * Copyright 2017 Google LLC * SPDX-License-Identifier: BSD-3-Clause */var i,n,o="__scoped";null!==(i=globalThis.reactiveElementPolyfillSupport)&&void 0!==i||(globalThis.reactiveElementPolyfillSupport=function(i){var n=i.ReactiveElement;if(void 0!==window.ShadyCSS&&(!window.ShadyCSS.nativeShadow||window.ShadyCSS.ApplyShim)){var t=n.prototype;window.ShadyDOM&&window.ShadyDOM.inUse&&!0===window.ShadyDOM.noPatch&&window.ShadyDOM.patchElementProto(t);var d=t.createRenderRoot;t.createRenderRoot=function(){var i,n,t,w=this.localName;if(window.ShadyCSS.nativeShadow)return d.call(this);if(!this.constructor.hasOwnProperty(o)){this.constructor[o]=!0;var v=this.constructor.elementStyles.map(function(i){return i instanceof CSSStyleSheet?Array.from(i.cssRules).reduce(function(i,n){return i+n.cssText;},""):i.cssText;});null===(n=null===(i=window.ShadyCSS)||void 0===i?void 0:i.ScopingShim)||void 0===n||n.prepareAdoptedCssText(v,w),void 0===this.constructor._$AJ&&window.ShadyCSS.prepareTemplateStyles(document.createElement("template"),w);}return null!==(t=this.shadowRoot)&&void 0!==t?t:this.attachShadow(this.constructor.shadowRootOptions);};var w=t.connectedCallback;t.connectedCallback=function(){w.call(this),this.hasUpdated&&window.ShadyCSS.styleElement(this);};var v=t._$AE;t._$AE=function(i){this.hasUpdated||window.ShadyCSS.styleElement(this),v.call(this,i);};}});var t,d=new Set(),w=new Map();null!==(n=globalThis.litHtmlPolyfillSupport)&&void 0!==n||(globalThis.litHtmlPolyfillSupport=function(i,n){if(void 0!==window.ShadyCSS&&(!window.ShadyCSS.nativeShadow||window.ShadyCSS.ApplyShim)){var o=function(i){return void 0!==i&&!d.has(i);},t=function(i){var n=w.get(i);return void 0===n&&w.set(i,n=[]),n;},v=new Map(),l=i.createElement;i.createElement=function(n,d){var w=l.call(i,n,d),v=null==d?void 0:d.scope;if(void 0!==v&&(window.ShadyCSS.nativeShadow||window.ShadyCSS.prepareTemplateDom(w,v),o(v))){var r=t(v),u=w.content.querySelectorAll("style");r.push.apply(r,Array.from(u).map(function(i){var n;return null===(n=i.parentNode)||void 0===n||n.removeChild(i),i.textContent;}));}return w;};var r=document.createDocumentFragment(),u=document.createComment(""),s=n.prototype,e=s._$AI;s._$AI=function(i,n){var v,l;void 0===n&&(n=this);var s=this._$AA.parentNode,a=null===(v=this.options)||void 0===v?void 0:v.scope;if(s instanceof ShadowRoot&&o(a)){var h=this._$AA,f=this._$AB;r.appendChild(u),this._$AA=u,this._$AB=null,e.call(this,i,n);var c=(null==i?void 0:i._$litType$)?this._$AH._$AD.el:document.createElement("template");if(function(i,n){var o,v=t(i),l=0!==v.length;l&&((o=document.createElement("style")).textContent=v.join("\n"),n.content.appendChild(o)),d.add(i),w.delete(i),window.ShadyCSS.prepareTemplateStyles(n,i),l&&window.ShadyCSS.nativeShadow&&null!==(o=n.content.querySelector("style"))&&n.content.appendChild(o);}(a,c),r.removeChild(u),null===(l=window.ShadyCSS)||void 0===l?void 0:l.nativeShadow){var y=c.content.querySelector("style");null!==y&&r.appendChild(y.cloneNode(!0));}s.insertBefore(r,f),this._$AA=h,this._$AB=f;}else e.call(this,i,n);},s._$AC=function(n){var o,t=null===(o=this.options)||void 0===o?void 0:o.scope,d=v.get(t);void 0===d&&v.set(t,d=new Map());var w=d.get(n.strings);return void 0===w&&d.set(n.strings,w=new i(n,this.options)),w;};}}),null!==(t=globalThis.litElementPolyfillSupport)&&void 0!==t||(globalThis.litElementPolyfillSupport=function(i){var n=i.LitElement;if(void 0!==window.ShadyCSS&&(!window.ShadyCSS.nativeShadow||window.ShadyCSS.ApplyShim)){n._$AJ=!0;var o=n.prototype,t=o.createRenderRoot;o.createRenderRoot=function(){return this.renderOptions.scope=this.localName,t.call(this);};}});}); ;// ../../node_modules/tabbable/dist/index.esm.js /*! * tabbable 6.3.0 * @license MIT, https://github.com/focus-trap/tabbable/blob/master/LICENSE */// NOTE: separate `:not()` selectors has broader browser support than the newer // `:not([inert], [inert] *)` (Feb 2023) // CAREFUL: JSDom does not support `:not([inert] *)` as a selector; using it causes // the entire query to fail, resulting in no nodes found, which will break a lot // of things... so we have to rely on JS to identify nodes inside an inert container var candidateSelectors=['input:not([inert])','select:not([inert])','textarea:not([inert])','a[href]:not([inert])','button:not([inert])','[tabindex]:not(slot):not([inert])','audio[controls]:not([inert])','video[controls]:not([inert])','[contenteditable]:not([contenteditable="false"]):not([inert])','details>summary:first-of-type:not([inert])','details:not([inert])'];var candidateSelector=/* #__PURE__ */candidateSelectors.join(',');var NoElement=typeof Element==='undefined';var matches=NoElement?function(){}:Element.prototype.matches||Element.prototype.msMatchesSelector||Element.prototype.webkitMatchesSelector;var getRootNode=!NoElement&&Element.prototype.getRootNode?function(element){var _element$getRootNode;return element===null||element===void 0?void 0:(_element$getRootNode=element.getRootNode)===null||_element$getRootNode===void 0?void 0:_element$getRootNode.call(element);}:function(element){return element===null||element===void 0?void 0:element.ownerDocument;};/** * Determines if a node is inert or in an inert ancestor. * @param {Element} [node] * @param {boolean} [lookUp] If true and `node` is not inert, looks up at ancestors to * see if any of them are inert. If false, only `node` itself is considered. * @returns {boolean} True if inert itself or by way of being in an inert ancestor. * False if `node` is falsy. */var _isInert=function isInert(node,lookUp){var _node$getAttribute;if(lookUp===void 0){lookUp=true;}// CAREFUL: JSDom does not support inert at all, so we can't use the `HTMLElement.inert` // JS API property; we have to check the attribute, which can either be empty or 'true'; // if it's `null` (not specified) or 'false', it's an active element var inertAtt=node===null||node===void 0?void 0:(_node$getAttribute=node.getAttribute)===null||_node$getAttribute===void 0?void 0:_node$getAttribute.call(node,'inert');var inert=inertAtt===''||inertAtt==='true';// NOTE: this could also be handled with `node.matches('[inert], :is([inert] *)')` // if it weren't for `matches()` not being a function on shadow roots; the following // code works for any kind of node // CAREFUL: JSDom does not appear to support certain selectors like `:not([inert] *)` // so it likely would not support `:is([inert] *)` either... var result=inert||lookUp&&node&&_isInert(node.parentNode);// recursive return result;};/** * Determines if a node's content is editable. * @param {Element} [node] * @returns True if it's content-editable; false if it's not or `node` is falsy. */var isContentEditable=function isContentEditable(node){var _node$getAttribute2;// CAREFUL: JSDom does not support the `HTMLElement.isContentEditable` API so we have // to use the attribute directly to check for this, which can either be empty or 'true'; // if it's `null` (not specified) or 'false', it's a non-editable element var attValue=node===null||node===void 0?void 0:(_node$getAttribute2=node.getAttribute)===null||_node$getAttribute2===void 0?void 0:_node$getAttribute2.call(node,'contenteditable');return attValue===''||attValue==='true';};/** * @param {Element} el container to check in * @param {boolean} includeContainer add container to check * @param {(node: Element) => boolean} filter filter candidates * @returns {Element[]} */var getCandidates=function getCandidates(el,includeContainer,filter){// even if `includeContainer=false`, we still have to check it for inertness because // if it's inert, all its children are inert if(_isInert(el)){return[];}var candidates=Array.prototype.slice.apply(el.querySelectorAll(candidateSelector));if(includeContainer&&matches.call(el,candidateSelector)){candidates.unshift(el);}candidates=candidates.filter(filter);return candidates;};/** * @callback GetShadowRoot * @param {Element} element to check for shadow root * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available. *//** * @callback ShadowRootFilter * @param {Element} shadowHostNode the element which contains shadow content * @returns {boolean} true if a shadow root could potentially contain valid candidates. *//** * @typedef {Object} CandidateScope * @property {Element} scopeParent contains inner candidates * @property {Element[]} candidates list of candidates found in the scope parent *//** * @typedef {Object} IterativeOptions * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not; * if a function, implies shadow support is enabled and either returns the shadow root of an element * or a boolean stating if it has an undisclosed shadow root * @property {(node: Element) => boolean} filter filter candidates * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list * @property {ShadowRootFilter} shadowRootFilter filter shadow roots; *//** * @param {Element[]} elements list of element containers to match candidates from * @param {boolean} includeContainer add container list to check * @param {IterativeOptions} options * @returns {Array.} */var _getCandidatesIteratively=function getCandidatesIteratively(elements,includeContainer,options){var candidates=[];var elementsToCheck=Array.from(elements);while(elementsToCheck.length){var element=elementsToCheck.shift();if(_isInert(element,false)){// no need to look up since we're drilling down // anything inside this container will also be inert continue;}if(element.tagName==='SLOT'){// add shadow dom slot scope (slot itself cannot be focusable) var assigned=element.assignedElements();var content=assigned.length?assigned:element.children;var nestedCandidates=_getCandidatesIteratively(content,true,options);if(options.flatten){candidates.push.apply(candidates,nestedCandidates);}else{candidates.push({scopeParent:element,candidates:nestedCandidates});}}else{// check candidate element var validCandidate=matches.call(element,candidateSelector);if(validCandidate&&options.filter(element)&&(includeContainer||!elements.includes(element))){candidates.push(element);}// iterate over shadow content if possible var shadowRoot=element.shadowRoot||// check for an undisclosed shadow typeof options.getShadowRoot==='function'&&options.getShadowRoot(element);// no inert look up because we're already drilling down and checking for inertness // on the way down, so all containers to this root node should have already been // vetted as non-inert var validShadowRoot=!_isInert(shadowRoot,false)&&(!options.shadowRootFilter||options.shadowRootFilter(element));if(shadowRoot&&validShadowRoot){// add shadow dom scope IIF a shadow root node was given; otherwise, an undisclosed // shadow exists, so look at light dom children as fallback BUT create a scope for any // child candidates found because they're likely slotted elements (elements that are // children of the web component element (which has the shadow), in the light dom, but // slotted somewhere _inside_ the undisclosed shadow) -- the scope is created below, // _after_ we return from this recursive call var _nestedCandidates=_getCandidatesIteratively(shadowRoot===true?element.children:shadowRoot.children,true,options);if(options.flatten){candidates.push.apply(candidates,_nestedCandidates);}else{candidates.push({scopeParent:element,candidates:_nestedCandidates});}}else{// there's not shadow so just dig into the element's (light dom) children // __without__ giving the element special scope treatment elementsToCheck.unshift.apply(elementsToCheck,element.children);}}}return candidates;};/** * @private * Determines if the node has an explicitly specified `tabindex` attribute. * @param {HTMLElement} node * @returns {boolean} True if so; false if not. */var hasTabIndex=function hasTabIndex(node){return!isNaN(parseInt(node.getAttribute('tabindex'),10));};/** * Determine the tab index of a given node. * @param {HTMLElement} node * @returns {number} Tab order (negative, 0, or positive number). * @throws {Error} If `node` is falsy. */var getTabIndex=function getTabIndex(node){if(!node){throw new Error('No node provided');}if(node.tabIndex<0){// in Chrome,
,