diff --git a/dist/sw.js b/dist/sw.js index be66dde2..3430e0ba 100644 --- a/dist/sw.js +++ b/dist/sw.js @@ -118,4 +118,4 @@ var rm=function(t,e){return rm=Object.setPrototypeOf||{__proto__:[]}instanceof A * SOFTWARE. * */ -const Rw="crypto.algorithm";const kw="crypto.algorithmProvider";var Nw;Tm.registerSingleton(kw,class{getAlgorithms(){return Tm.resolveAll(Rw)}toAsnAlgorithm(t){for(const e of this.getAlgorithms()){const r=e.toAsnAlgorithm(t);if(r)return r}if(/[0-9.]+/.test(t.name)){const e=new bd({algorithm:t.name});if("parameters"in t){const r=t;e.parameters=r.parameters}return e}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(t){for(const e of this.getAlgorithms()){const r=e.toWebAlgorithm(t);if(r)return r}return{name:t.algorithm,parameters:t.parameters}}});const Ow="1.3.36.3.3.2.8.1.1",Bw=`${Ow}.1`,Pw=`${Ow}.2`,Lw=`${Ow}.3`,Dw=`${Ow}.4`,Uw=`${Ow}.5`,Mw=`${Ow}.6`,Fw=`${Ow}.7`,Hw=`${Ow}.8`,Ww=`${Ow}.9`,jw=`${Ow}.10`,Vw=`${Ow}.11`,Gw=`${Ow}.12`,qw=`${Ow}.13`,zw=`${Ow}.14`,Qw="brainpoolP160r1",Kw="brainpoolP160t1",Yw="brainpoolP192r1",Jw="brainpoolP192t1",Xw="brainpoolP224r1",Zw="brainpoolP224t1",$w="brainpoolP256r1",ty="brainpoolP256t1",ey="brainpoolP320r1",ry="brainpoolP320t1",iy="brainpoolP384r1",ny="brainpoolP384t1",sy="brainpoolP512r1",oy="brainpoolP512t1",ay="ECDSA";let cy=Nw=class{toAsnAlgorithm(t){if(t.name.toLowerCase()===ay.toLowerCase())if("hash"in t){switch(("string"==typeof t.hash?t.hash:t.hash.name).toLowerCase()){case"sha-1":return fg;case"sha-256":return gg;case"sha-384":return mg;case"sha-512":return wg}}else if("namedCurve"in t){let e="";switch(t.namedCurve){case"P-256":e=hg;break;case"K-256":e=Nw.SECP256K1;break;case"P-384":e=ug;break;case"P-521":e=pg;break;case Qw:e=Bw;break;case Kw:e=Pw;break;case Yw:e=Lw;break;case Jw:e=Dw;break;case Xw:e=Uw;break;case Zw:e=Mw;break;case $w:e=Fw;break;case ty:e=Hw;break;case ey:e=Ww;break;case ry:e=jw;break;case iy:e=Vw;break;case ny:e=Gw;break;case sy:e=qw;break;case oy:e=zw}if(e)return new bd({algorithm:ng,parameters:Du.serialize(new yg({namedCurve:e}))})}return null}toWebAlgorithm(t){switch(t.algorithm){case sg:return{name:ay,hash:{name:"SHA-1"}};case ag:return{name:ay,hash:{name:"SHA-256"}};case cg:return{name:ay,hash:{name:"SHA-384"}};case lg:return{name:ay,hash:{name:"SHA-512"}};case ng:if(!t.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(Du.parse(t.parameters,yg).namedCurve){case hg:return{name:ay,namedCurve:"P-256"};case Nw.SECP256K1:return{name:ay,namedCurve:"K-256"};case ug:return{name:ay,namedCurve:"P-384"};case pg:return{name:ay,namedCurve:"P-521"};case Bw:return{name:ay,namedCurve:Qw};case Pw:return{name:ay,namedCurve:Kw};case Lw:return{name:ay,namedCurve:Yw};case Dw:return{name:ay,namedCurve:Jw};case Uw:return{name:ay,namedCurve:Xw};case Mw:return{name:ay,namedCurve:Zw};case Fw:return{name:ay,namedCurve:$w};case Hw:return{name:ay,namedCurve:ty};case Ww:return{name:ay,namedCurve:ey};case jw:return{name:ay,namedCurve:ry};case Vw:return{name:ay,namedCurve:iy};case Gw:return{name:ay,namedCurve:ny};case qw:return{name:ay,namedCurve:sy};case zw:return{name:ay,namedCurve:oy}}}return null}};cy.SECP256K1="1.3.132.0.10",cy=Nw=$g([Cm()],cy),Tm.registerSingleton(Rw,cy);const ly=Symbol("name"),hy=Symbol("value");class uy{constructor(t,e={},r=""){this[ly]=t,this[hy]=r;for(const t in e)this[t]=e[t]}}uy.NAME=ly,uy.VALUE=hy;class py{static toString(t){const e=this.items[t];return e||t}}py.items={[Lg]:"sha1",[Dg]:"sha224",[Ug]:"sha256",[Mg]:"sha384",[Fg]:"sha512",[_g]:"rsaEncryption",[Ig]:"sha1WithRSAEncryption",[Rg]:"sha224WithRSAEncryption",[kg]:"sha256WithRSAEncryption",[Ng]:"sha384WithRSAEncryption",[Og]:"sha512WithRSAEncryption",[ng]:"ecPublicKey",[sg]:"ecdsaWithSHA1",[og]:"ecdsaWithSHA224",[ag]:"ecdsaWithSHA256",[cg]:"ecdsaWithSHA384",[lg]:"ecdsaWithSHA512",[Mp]:"TLS WWW server authentication",[Fp]:"TLS WWW client authentication",[Hp]:"Code Signing",[Wp]:"E-mail Protection",[jp]:"Time Stamping",[Vp]:"OCSP Signing","1.2.840.113549.1.7.2":"Signed Data"};class dy{static serialize(t){return this.serializeObj(t).join("\n")}static pad(t=0){return"".padStart(2*t," ")}static serializeObj(t,e=0){const r=[];let i=this.pad(e++),n="";const s=t[uy.VALUE];s&&(n=` ${s}`),r.push(`${i}${t[uy.NAME]}:${n}`),i=this.pad(e);for(const n in t){if("symbol"==typeof n)continue;const s=t[n],o=n?`${n}: `:"";if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)r.push(`${i}${o}${s}`);else if(s instanceof Date)r.push(`${i}${o}${s.toUTCString()}`);else if(Array.isArray(s))for(const t of s)t[uy.NAME]=n,r.push(...this.serializeObj(t,e));else if(s instanceof uy)s[uy.NAME]=n,r.push(...this.serializeObj(s,e));else if(Dc.vJ.isBufferSource(s))n?(r.push(`${i}${o}`),r.push(...this.serializeBufferSource(s,e+1))):r.push(...this.serializeBufferSource(s,e));else{if(!("toTextObject"in s))throw new TypeError("Cannot serialize data in text format. Unsupported type.");{const t=s.toTextObject();t[uy.NAME]=n,r.push(...this.serializeObj(t,e))}}}return r}static serializeBufferSource(t,e=0){const r=this.pad(e),i=Dc.vJ.toUint8Array(t),n=[];for(let t=0;t255)return!1}return!0}getField(t){const e=this.extraNames.findId(t)||vy.findId(t),r=[];for(const t of this.asn)for(const i of t)i.type===e&&r.push(i.value.toString());return r}getName(t){return this.extraNames.get(t)||vy.get(t)}toString(){return this.asn.map((t=>t.map((t=>{const e=this.getName(t.type)||t.type,r=t.value.anyValue?`#${Dc.ep.ToHex(t.value.anyValue)}`:function(t){return t.replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,_y)}(t.value.toString());return`${e}=${r}`})).join("+"))).join(", ")}toJSON(){var t;const e=[];for(const r of this.asn){const i={};for(const e of r){const r=this.getName(e.type)||e.type;null!==(t=i[r])&&void 0!==t||(i[r]=[]),i[r].push(e.value.anyValue?`#${Dc.ep.ToHex(e.value.anyValue)}`:e.value.toString())}e.push(i)}return e}fromString(t){const e=new Ku,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g;let i=null,n=",";for(;i=r.exec(`${t},`);){let[,t,r]=i;const s=r[r.length-1];","!==s&&"+"!==s||(r=r.slice(0,r.length-1),i[3]=s);const o=i[3];if(/[\d.]+/.test(t)||(t=this.getName(t)||""),!t)throw new Error(`Cannot get OID for name type '${t}'`);const a=new qu({type:t});if("#"===r.charAt(0))a.value.anyValue=Dc.ep.FromHex(r.slice(1));else{const e=/"(.*?[^\\])?"/.exec(r);e&&(r=e[1]),r=r.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1"),t===this.getName("E")||t===this.getName("DC")?a.value.ia5String=r:Ey.isASCII(r)?a.value.printableString=r:a.value.utf8String=r}"+"===n?e[e.length-1].push(a):e.push(new zu([a])),n=o}return e}fromJSON(t){const e=new Ku;for(const r of t){const t=new zu;for(const e in r){let i=e;if(/[\d.]+/.test(e)||(i=this.getName(e)||""),!i)throw new Error(`Cannot get OID for name type '${e}'`);const n=r[e];for(const e of n){const r=new qu({type:i});if("object"==typeof e)for(const t in e)switch(t){case"ia5String":r.value.ia5String=e[t];break;case"utf8String":r.value.utf8String=e[t];break;case"universalString":r.value.universalString=e[t];break;case"bmpString":r.value.bmpString=e[t];break;case"printableString":r.value.printableString=e[t]}else"#"===e[0]?r.value.anyValue=Dc.ep.FromHex(e.slice(1)):i===this.getName("E")||i===this.getName("DC")?r.value.ia5String=e:r.value.printableString=e;t.push(r)}}e.push(t)}return e}toArrayBuffer(){return Du.serialize(this.asn)}async getThumbprint(...t){var e;let r,i="SHA-1";return t.length>=1&&!(null===(e=t[0])||void 0===e?void 0:e.subtle)?(i=t[0]||i,r=t[1]||yy.get()):r=t[0]||yy.get(),await r.subtle.digest(i,this.toArrayBuffer())}}const Sy="Cannot initialize GeneralName from ASN.1 data.",Ty=`${Sy} Unsupported string format in use.`,xy=`${Sy} Value doesn't match to GUID regular expression.`,Cy=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,Iy="1.3.6.1.4.1.311.25.1",Ry="1.3.6.1.4.1.311.20.2.3",ky="dns",Ny="dn",Oy="email",By="ip",Py="url",Ly="guid",Dy="upn",Uy="id";class My extends fy{constructor(...t){let e;if(2===t.length)switch(t[0]){case Ny:{const r=new Ey(t[1]).toArrayBuffer(),i=Du.parse(r,Ku);e=new Zu({directoryName:i});break}case ky:e=new Zu({dNSName:t[1]});break;case Oy:e=new Zu({rfc822Name:t[1]});break;case Ly:{const r=new RegExp(Cy,"i").exec(t[1]);if(!r)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");const i=r.slice(1).map(((t,e)=>e<3?Dc.ep.ToHex(new Uint8Array(Dc.ep.FromHex(t)).reverse()):t)).join("");e=new Zu({otherName:new Ju({typeId:Iy,value:Du.serialize(new $h(Dc.ep.FromHex(i)))})});break}case By:e=new Zu({iPAddress:t[1]});break;case Uy:e=new Zu({registeredID:t[1]});break;case Dy:e=new Zu({otherName:new Ju({typeId:Ry,value:Du.serialize(hu.toASN(t[1]))})});break;case Py:e=new Zu({uniformResourceIdentifier:t[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else e=Dc.vJ.isBufferSource(t[0])?Du.parse(t[0],Zu):t[0];super(e)}onInit(t){if(null!=t.dNSName)this.type=ky,this.value=t.dNSName;else if(null!=t.rfc822Name)this.type=Oy,this.value=t.rfc822Name;else if(null!=t.iPAddress)this.type=By,this.value=t.iPAddress;else if(null!=t.uniformResourceIdentifier)this.type=Py,this.value=t.uniformResourceIdentifier;else if(null!=t.registeredID)this.type=Uy,this.value=t.registeredID;else if(null!=t.directoryName)this.type=Ny,this.value=new Ey(t.directoryName).toString();else{if(null==t.otherName)throw new Error(Ty);if(t.otherName.typeId===Iy){this.type=Ly;const e=Du.parse(t.otherName.value,$h),r=new RegExp(Cy,"i").exec(Dc.ep.ToHex(e));if(!r)throw new Error(xy);this.value=r.slice(1).map(((t,e)=>e<3?Dc.ep.ToHex(new Uint8Array(Dc.ep.FromHex(t)).reverse()):t)).join("-")}else{if(t.otherName.typeId!==Ry)throw new Error(Ty);this.type=Dy,this.value=Du.parse(t.otherName.value,Vu).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){let t;switch(this.type){case Ny:case ky:case Ly:case By:case Uy:case Dy:case Py:t=this.type.toUpperCase();break;case Oy:t="Email";break;default:throw new Error("Unsupported GeneralName type")}let e=this.value;return this.type===Uy&&(e=py.toString(e)),new uy(t,void 0,e)}}class Fy extends fy{constructor(t){let e;if(t instanceof hp)e=t;else if(Array.isArray(t)){const r=[];for(const e of t)if(e instanceof Zu)r.push(e);else{const t=Du.parse(new My(e.type,e.value).rawData,Zu);r.push(t)}e=new hp(r)}else{if(!Dc.vJ.isBufferSource(t))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");e=Du.parse(t,hp)}super(e)}onInit(t){const e=[];for(const r of t){let t=null;try{t=new My(r)}catch{continue}e.push(t)}this.items=e}toJSON(){return this.items.map((t=>t.toJSON()))}toTextObject(){const t=super.toTextObjectEmpty();for(const e of this.items){const r=e.toTextObject();let i=t[r[uy.NAME]];Array.isArray(i)||(i=[],t[r[uy.NAME]]=i),i.push(r)}return t}}Fy.NAME="GeneralNames";const Hy="\\n",Wy="-{5}BEGIN ([^\\n]+(?=-{5}))-{5}\\n(?:((?:[^:\\n]+: (?:[^\\n]+\\n(?: +[^\\n]+\\n)*))+))?\\n?((?:[a-zA-Z0-9=+/]+\\n)+)-{5}END \\1-{5}";class jy{static isPem(t){return"string"==typeof t&&new RegExp(Wy,"g").test(t)}static decodeWithHeaders(t){t=t.replace(/\r/g,"");const e=new RegExp(Wy,"g"),r=[];let i=null;for(;i=e.exec(t);){const t=i[3].replace(new RegExp("[\\n]+","g"),""),e={type:i[1],headers:[],rawData:Dc.ep.FromBase64(t)},n=i[2];if(n){const t=n.split(new RegExp(Hy,"g"));let r=null;for(const i of t){const[t,n]=i.split(/:(.*)/);if(void 0===n){if(!r)throw new Error("Cannot parse PEM string. Incorrect header value");r.value+=t.trim()}else r&&e.headers.push(r),r={key:t,value:n.trim()}}r&&e.headers.push(r)}r.push(e)}return r}static decode(t){return this.decodeWithHeaders(t).map((t=>t.rawData))}static decodeFirst(t){const e=this.decode(t);if(!e.length)throw new RangeError("PEM string doesn't contain any objects");return e[0]}static encode(t,e){if(Array.isArray(t)){const r=new Array;return e?t.forEach((t=>{if(!Dc.vJ.isBufferSource(t))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:e,rawData:Dc.vJ.toArrayBuffer(t)}))})):t.forEach((t=>{if(!("type"in t))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(t))})),r.join("\n")}if(!e)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:e,rawData:Dc.vJ.toArrayBuffer(t)})}static encodeStruct(t){var e;const r=t.type.toLocaleUpperCase(),i=[];if(i.push(`-----BEGIN ${r}-----`),null===(e=t.headers)||void 0===e?void 0:e.length){for(const e of t.headers)i.push(`${e.key}: ${e.value}`);i.push("")}const n=Dc.ep.ToBase64(t.rawData);let s,o=0;const a=Array();for(;o1?(i=t[0]||i,r=t[1]||r,e=t[2]||yy.get()):e=t[0]||yy.get(),e.subtle.importKey("spki",this.rawData,i,!0,r)}onInit(t){const e=Tm.resolve(kw),r=this.algorithm=e.toWebAlgorithm(t.algorithm);switch(t.algorithm.algorithm){case _g:{const e=Du.parse(t.subjectPublicKey,Zg),i=Dc.vJ.toUint8Array(e.modulus);r.publicExponent=Dc.vJ.toUint8Array(e.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3;break}}}async getThumbprint(...t){var e;let r,i="SHA-1";return t.length>=1&&!(null===(e=t[0])||void 0===e?void 0:e.subtle)?(i=t[0]||i,r=t[1]||yy.get()):r=t[0]||yy.get(),await r.subtle.digest(i,this.rawData)}async getKeyIdentifier(t){t||(t=yy.get());const e=Du.parse(this.rawData,Ad);return await t.subtle.digest("SHA-1",e.subjectPublicKey)}toTextObject(){const t=this.toTextObjectEmpty(),e=Du.parse(this.rawData,Ad);if(t.Algorithm=dy.serializeAlgorithm(e.algorithm),e.algorithm.algorithm===ng)t["EC Point"]=e.subjectPublicKey;else t["Raw Data"]=e.subjectPublicKey;return t}}class qy{static register(t,e){this.items.set(t,e)}static create(t){const e=new gy(t),r=this.items.get(e.type);return r?new r(t):e}}qy.items=new Map;const zy="crypto.signatureFormatter";class Qy extends Vy{constructor(t){Vy.isAsnEncoded(t)?super(t,Rd):super(t),this.tag=jy.CertificateTag}onInit(t){const e=t.tbsCertificate;this.tbs=Du.serialize(e),this.serialNumber=Dc.ep.ToHex(e.serialNumber),this.subjectName=new Ey(e.subject),this.subject=new Ey(e.subject).toString(),this.issuerName=new Ey(e.issuer),this.issuer=this.issuerName.toString();const r=Tm.resolve(kw);this.signatureAlgorithm=r.toWebAlgorithm(t.signatureAlgorithm),this.signature=t.signatureValue;const i=e.validity.notBefore.utcTime||e.validity.notBefore.generalTime;if(!i)throw new Error("Cannot get 'notBefore' value");this.notBefore=i;const n=e.validity.notAfter.utcTime||e.validity.notAfter.generalTime;if(!n)throw new Error("Cannot get 'notAfter' value");this.notAfter=n,this.extensions=[],e.extensions&&(this.extensions=e.extensions.map((t=>qy.create(Du.serialize(t))))),this.publicKey=new Gy(e.subjectPublicKeyInfo)}getExtension(t){for(const e of this.extensions)if("string"==typeof t){if(e.type===t)return e}else if(e instanceof t)return e;return null}getExtensions(t){return this.extensions.filter((e=>"string"==typeof t?e.type===t:e instanceof t))}async verify(t={},e=yy.get()){let r,i;const n=t.publicKey;try{if(n)if("publicKey"in n)r={...n.publicKey.algorithm,...this.signatureAlgorithm},i=await n.publicKey.export(r,["verify"]);else if(n instanceof Gy)r={...n.algorithm,...this.signatureAlgorithm},i=await n.export(r,["verify"]);else if(Dc.vJ.isBufferSource(n)){const t=new Gy(n);r={...t.algorithm,...this.signatureAlgorithm},i=await t.export(r,["verify"])}else r={...n.algorithm,...this.signatureAlgorithm},i=n;else r={...this.publicKey.algorithm,...this.signatureAlgorithm},i=await this.publicKey.export(r,["verify"],e)}catch(t){return!1}const s=Tm.resolveAll(zy).reverse();let o=null;for(const t of s)if(o=t.toWebSignature(r,this.signature),o)break;if(!o)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");const a=await e.subtle.verify(this.signatureAlgorithm,i,o,this.tbs);if(t.signatureOnly)return a;{const e=(t.date||new Date).getTime();return a&&this.notBefore.getTime()t))}else{const e=new Up(t[0]);super(Dp,t[1],Du.serialize(e)),this.usages=t[0]}}toTextObject(){const t=this.toTextObjectWithoutValue();return t[""]=this.usages.map((t=>py.toString(t))).join(", "),t}}Zy.NAME="Extended Key Usages",function(t){t[t.digitalSignature=1]="digitalSignature",t[t.nonRepudiation=2]="nonRepudiation",t[t.keyEncipherment=4]="keyEncipherment",t[t.dataEncipherment=8]="dataEncipherment",t[t.keyAgreement=16]="keyAgreement",t[t.keyCertSign=32]="keyCertSign",t[t.cRLSign=64]="cRLSign",t[t.encipherOnly=128]="encipherOnly",t[t.decipherOnly=256]="decipherOnly"}(Xy||(Xy={}));class $y extends gy{constructor(...t){if(Dc.vJ.isBufferSource(t[0])){super(t[0]);const e=Du.parse(this.value,Xp);this.usages=e.toNumber()}else{const e=new Xp(t[0]);super(Kp,t[1],Du.serialize(e)),this.usages=t[0]}}toTextObject(){const t=this.toTextObjectWithoutValue(),e=Du.parse(this.value,Xp);return t[""]=e.toJSON().join(", "),t}}$y.NAME="Key Usages";class tb extends gy{constructor(...t){if(Dc.vJ.isBufferSource(t[0])){super(t[0]);const e=Du.parse(this.value,pd);this.keyId=Dc.ep.ToHex(e)}else{const e="string"==typeof t[0]?Dc.ep.FromHex(t[0]):t[0],r=new pd(e);super(ud,t[1],Du.serialize(r)),this.keyId=Dc.ep.ToHex(e)}}static async create(t,e=!1,r=yy.get()){let i;i=t instanceof Gy?t.rawData:"publicKey"in t?t.publicKey.rawData:Dc.vJ.isBufferSource(t)?t:await r.subtle.exportKey("spki",t);const n=new Gy(i),s=await n.getKeyIdentifier(r);return new tb(Dc.ep.ToHex(s),e)}toTextObject(){const t=this.toTextObjectWithoutValue(),e=Du.parse(this.value,pd);return t[""]=e,t}}tb.NAME="Subject Key Identifier";class eb extends gy{constructor(...t){Dc.vJ.isBufferSource(t[0])?super(t[0]):super(od,t[1],new Fy(t[0]||[]).rawData)}onInit(t){super.onInit(t);const e=Du.parse(t.extnValue,ad);this.names=new Fy(e)}toTextObject(){const t=this.toTextObjectWithoutValue(),e=this.names.toTextObject();for(const r in e)t[r]=e[r];return t}}eb.NAME="Subject Alternative Name";class rb extends gy{constructor(...t){var e;if(Dc.vJ.isBufferSource(t[0])){super(t[0]);const e=Du.parse(this.value,vp);this.policies=e.map((t=>t.policyIdentifier))}else{const r=t[0],i=null!==(e=t[1])&&void 0!==e&&e,n=new vp(r.map((t=>new Ap({policyIdentifier:t}))));super(fp,i,Du.serialize(n)),this.policies=r}}toTextObject(){const t=this.toTextObjectWithoutValue();return t.Policy=this.policies.map((t=>new uy("",{},py.toString(t)))),t}}rb.NAME="Certificate Policies",qy.register(fp,rb);class ib extends fy{constructor(...t){let e;if(Dc.vJ.isBufferSource(t[0]))e=Dc.vJ.toArrayBuffer(t[0]);else{const r=t[0],i=Array.isArray(t[1])?t[1].map((t=>Dc.vJ.toArrayBuffer(t))):[];e=Du.serialize(new cd({type:r,values:i}))}super(e,cd)}onInit(t){this.type=t.type,this.values=t.values}toTextObject(){const t=this.toTextObjectWithoutValue();return t.Value=this.values.map((t=>new uy("",{"":t}))),t}toTextObjectWithoutValue(){const t=this.toTextObjectEmpty();return t[uy.NAME]===ib.NAME&&(t[uy.NAME]=py.toString(this.type)),t}}ib.NAME="Attribute";class nb extends ib{constructor(...t){var e;if(Dc.vJ.isBufferSource(t[0]))super(t[0]);else{const e=new bw({printableString:t[0]});super(tw,[Du.serialize(e)])}null!==(e=this.password)&&void 0!==e||(this.password="")}onInit(t){if(super.onInit(t),this.values[0]){const t=Du.parse(this.values[0],bw);this.password=t.toString()}}toTextObject(){const t=this.toTextObjectWithoutValue();return t[uy.VALUE]=this.password,t}}nb.NAME="Challenge Password";class sb extends ib{constructor(...t){var e;if(Dc.vJ.isBufferSource(t[0]))super(t[0]);else{const e=t[0],r=new Td;for(const t of e)r.push(Du.parse(t.rawData,Sd));super(ew,[Du.serialize(r)])}null!==(e=this.items)&&void 0!==e||(this.items=[])}onInit(t){if(super.onInit(t),this.values[0]){const t=Du.parse(this.values[0],Td);this.items=t.map((t=>qy.create(Du.serialize(t))))}}toTextObject(){const t=this.toTextObjectWithoutValue(),e=this.items.map((t=>t.toTextObject()));for(const r of e)t[r[uy.NAME]]=r;return t}}sb.NAME="Extensions";class ob{static register(t,e){this.items.set(t,e)}static create(t){const e=new ib(t),r=this.items.get(e.type);return r?new r(t):e}}ob.items=new Map;let ab=class{toAsnAlgorithm(t){if("rsassa-pkcs1-v1_5"===t.name.toLowerCase()){if(!t.hash)return new bd({algorithm:_g,parameters:null});switch(t.hash.name.toLowerCase()){case"sha-1":return new bd({algorithm:Ig,parameters:null});case"sha-256":return new bd({algorithm:kg,parameters:null});case"sha-384":return new bd({algorithm:Ng,parameters:null});case"sha-512":return new bd({algorithm:Og,parameters:null})}}return null}toWebAlgorithm(t){switch(t.algorithm){case _g:return{name:"RSASSA-PKCS1-v1_5"};case Ig:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case kg:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case Ng:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case Og:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}}}return null}};ab=$g([Cm()],ab),Tm.registerSingleton(Rw,ab);class cb{addPadding(t,e){const r=Dc.vJ.toUint8Array(e),i=new Uint8Array(t);return i.set(r,t-r.length),i}removePadding(t,e=!1){let r=Dc.vJ.toUint8Array(t);for(let t=0;t127){const t=new Uint8Array(r.length+1);return t.set(r,1),t.buffer}return r.buffer}toAsnSignature(t,e){if("ECDSA"===t.name){const r=t.namedCurve,i=cb.namedCurveSize.get(r)||cb.defaultNamedCurveSize,n=new Ag,s=Dc.vJ.toUint8Array(e);return n.r=this.removePadding(s.slice(0,i),!0),n.s=this.removePadding(s.slice(i,i+i),!0),Du.serialize(n)}return null}toWebSignature(t,e){if("ECDSA"===t.name){const r=Du.parse(e,Ag),i=t.namedCurve,n=cb.namedCurveSize.get(i)||cb.defaultNamedCurveSize,s=this.addPadding(n,this.removePadding(r.r)),o=this.addPadding(n,this.removePadding(r.s));return(0,Dc.$e)(s,o)}return null}}cb.namedCurveSize=new Map,cb.defaultNamedCurveSize=32;const lb="1.3.101.110",hb="1.3.101.111",ub="1.3.101.112",pb="1.3.101.113";let db=class{toAsnAlgorithm(t){let e=null;switch(t.name.toLowerCase()){case"eddsa":switch(t.namedCurve.toLowerCase()){case"ed25519":e=ub;break;case"ed448":e=pb}break;case"ecdh-es":switch(t.namedCurve.toLowerCase()){case"x25519":e=lb;break;case"x448":e=hb}}return e?new bd({algorithm:e}):null}toWebAlgorithm(t){switch(t.algorithm){case ub:return{name:"EdDSA",namedCurve:"Ed25519"};case pb:return{name:"EdDSA",namedCurve:"Ed448"};case lb:return{name:"ECDH-ES",namedCurve:"X25519"};case hb:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};db=$g([Cm()],db),Tm.registerSingleton(Rw,db);class fb extends Vy{constructor(t){Vy.isAsnEncoded(t)?super(t,Iw):super(t),this.tag=jy.CertificateRequestTag}onInit(t){this.tbs=Du.serialize(t.certificationRequestInfo),this.publicKey=new Gy(t.certificationRequestInfo.subjectPKInfo);const e=Tm.resolve(kw);this.signatureAlgorithm=e.toWebAlgorithm(t.signatureAlgorithm),this.signature=t.signature,this.attributes=t.certificationRequestInfo.attributes.map((t=>ob.create(Du.serialize(t))));const r=this.getAttribute(ew);this.extensions=[],r instanceof sb&&(this.extensions=r.items),this.subjectName=new Ey(t.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(t){for(const e of this.attributes)if(e.type===t)return e;return null}getAttributes(t){return this.attributes.filter((e=>e.type===t))}getExtension(t){for(const e of this.extensions)if(e.type===t)return e;return null}getExtensions(t){return this.extensions.filter((e=>e.type===t))}async verify(t=yy.get()){const e={...this.publicKey.algorithm,...this.signatureAlgorithm},r=await this.publicKey.export(e,["verify"],t),i=Tm.resolveAll(zy).reverse();let n=null;for(const t of i)if(n=t.toWebSignature(e,this.signature),n)break;if(!n)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return await t.subtle.verify(this.signatureAlgorithm,r,n,this.tbs)}toTextObject(){const t=this.toTextObjectEmpty(),e=Du.parse(this.rawData,Iw),r=e.certificationRequestInfo,i=new uy("",{Version:`${xd[r.version]} (${r.version})`,Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){const t=new uy("");for(const e of this.attributes){const r=e.toTextObject();t[r[uy.NAME]]=r}i.Attributes=t}return t.Data=i,t.Signature=new uy("",{Algorithm:dy.serializeAlgorithm(e.signatureAlgorithm),"":e.signature}),t}}fb.NAME="PKCS#10 Certificate Request";var gb;!function(t){t[t.unspecified=0]="unspecified",t[t.keyCompromise=1]="keyCompromise",t[t.cACompromise=2]="cACompromise",t[t.affiliationChanged=3]="affiliationChanged",t[t.superseded=4]="superseded",t[t.cessationOfOperation=5]="cessationOfOperation",t[t.certificateHold=6]="certificateHold",t[t.removeFromCRL=8]="removeFromCRL",t[t.privilegeWithdrawn=9]="privilegeWithdrawn",t[t.aACompromise=10]="aACompromise"}(gb||(gb={}));qy.register(ap,Yy),qy.register(Dp,Zy),qy.register(Kp,$y),qy.register(ud,tb),qy.register(np,Ky),qy.register(od,eb),ob.register(tw,nb),ob.register(ew,sb),Tm.registerSingleton(zy,class{toAsnSignature(t,e){return Dc.vJ.toArrayBuffer(e)}toWebSignature(t,e){return Dc.vJ.toArrayBuffer(e)}}),Tm.registerSingleton(zy,cb),cb.namedCurveSize.set("P-256",32),cb.namedCurveSize.set("K-256",32),cb.namedCurveSize.set("P-384",48),cb.namedCurveSize.set("P-521",66);const mb=/-{5}(BEGIN|END) .*-{5}/gm;async function wb({hash:t,signature:e,publicKey:r,domain:i,domainCert:n,created:s,software:o}={}){let a;const c=[];if(e=(0,Lc.toByteArray)(e),n&&i&&!r){const t=n.split("\n\n"),i=(0,Lc.toByteArray)(t[0].replace(mb,"").replace(/\s/gm,"")),s=p(await crypto.subtle.digest("SHA-256",i));c.push({id:"certFingerprint",expected:s,matched:null});const o=new Qy(i);r=await o.publicKey.export();const l=(0,Lc.fromByteArray)(new Uint8Array(o.publicKey.rawData));c.push({id:"publicKey",expected:l,matched:null}),o.subject&&o.subject.startsWith("CN=")&&(a=o.subject.split(3)),e=function(t){try{const e=Bu.parse(t,Ag),r=0===e.r[0]?e.r.slice(1):e.r,i=0===e.s[0]?e.s.slice(1):e.s;t=lt([r,i],r.length+i.length)}catch(t){console.log(t)}return t}(e)}else{const t={name:"ECDSA",namedCurve:"P-384"};c.push({id:"publicKey",expected:r,matched:null}),r=await crypto.subtle.importKey("spki",(0,Lc.toByteArray)(r),t,!0,["verify"])}const l=new TextEncoder,h=await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},r,e,l.encode(t));return c.push({id:"signature",expected:!0,matched:h}),s&&c.push({id:"created",expected:s,matched:null}),o&&c.push({id:"software",expected:o,matched:null}),i&&c.push({id:"domain",expected:i,matched:a}),c}const yb="pages/pages.jsonl",bb="pages/extraPages.jsonl",Ab="datapackage.json",vb="datapackage-digest.json",_b="webarchive.yaml";class Eb{constructor(t,e,r=!0){this.file=e,this.waczname=e.waczname,this.store=t,this.isRoot=r}async loadFileFromWACZ(t,e){return this.store.loadFileFromWACZ?await this.store.loadFileFromWACZ(this.file,t,e):await this.file.loadFile(t,e)}async load(){let t,e=null;return this.file.containsFile(vb)&&(e=await this.loadDigestData(vb)),this.file.containsFile(Ab)?t=await this.loadPackage(Ab,e):this.file.containsFile(_b)&&(t=await this.loadOldPackageYAML(_b)),t||{}}async loadTextFileFromWACZ(t,e=!1){const{reader:r,hasher:i}=await this.loadFileFromWACZ(t,{computeHash:!!e}),n=(new TextDecoder).decode(await r.readFully());return e&&i&&await this.store.addVerifyData(this.waczname,t,e,i.getHash()),n}async loadDigestData(t){try{const e=JSON.parse(await this.loadTextFileFromWACZ(t));let r;e.path===Ab&&e.hash&&(r=e.hash);const i=this.store,n=this.isRoot?"":this.waczname+":";if(!e.signedData||e.signedData.hash!==r)return void await i.addVerifyData(n,"signature");await i.addVerifyData(n,"datapackageHash",r);const s=await wb(e.signedData);return await i.addVerifyDataList(n,s),r}catch(t){console.warn(t)}}async loadPackage(t,e){const r=await this.loadTextFileFromWACZ(t,e),i=JSON.parse(r);switch(this.isRoot&&void 0!==i.config&&this.store.initConfig(i.config),i.profile){case"data-package":case"wacz-package":case void 0:case null:return await this.loadLeafWACZPackage(i);case"multi-wacz-package":return await this.loadMultiWACZPackage(i);default:throw new Error(`Unknown package profile: ${i.profile}`)}}async loadMultiWACZPackage(t){return this.file.markAsMultiWACZ(),await this.store.loadWACZFiles(t,this.file),t}async loadLeafWACZPackage(t){const e=t.metadata||{};let r=null;for(const e of t.resources)e.path===yb?(r=e.hash,await this.store.addVerifyData(this.waczname,e.path,e.hash)):(e.path.endsWith(".idx")||e.path.endsWith(".cdx"))&&await this.store.addVerifyData(this.waczname,e.path,e.hash);if(this.file.containsFile(yb)){(await this.loadPages(yb,r)).hasText&&(this.store.textIndex=e.textIndex=yb)}return this.file.containsFile(bb)&&(this.store.textIndex=e.textIndex=bb),e}async loadOldPackageYAML(t){const e=await this.loadTextFileFromWACZ(t),r=Pc.load(e),i={desc:r.desc,title:r.title};r.textIndex&&(i.textIndex=r.textIndex,r.config||(r.config={}),r.config.textIndex=r.textIndex),this.isRoot&&void 0!==r.config&&this.store.initConfig(r.config),i.title||(i.title=this.store.config.sourceName);const n=r.pages||[];n&&n.length&&await this.store.addPages(n);const s=r.pageLists||[];return s&&s.length&&await this.store.addCuratedPageLists(s,"pages","show"),i}async loadPages(t=yb,e=null){const{reader:r,hasher:i}=await this.loadFileFromWACZ(t,{unzip:!0,computeHash:!0});let n=null,s=[];for await(const t of r.iterLines()){const e=JSON.parse(t);this.waczname&&(e.wacz=this.waczname),n?(s.push(e),500===s.length&&(await this.store.addPages(s),s=[])):n=e}return s.length&&await this.store.addPages(s),i&&e&&await this.store.addVerifyData(this.waczname,t,e,i.getHash()),n}}class Sb{constructor(t,e,r=null){this.loader=t,this.loadId=r,this.loadUrl=e.loadUrl}async load(t){t.fullConfig&&this.loader.arrayBuffer&&this.loader.arrayBuffer.byteLength<=s&&(t.fullConfig.extra||(t.fullConfig.extra={}),t.fullConfig.extra.arrayBuffer=this.loader.arrayBuffer);const e=this.loadUrl,r=this.loader;return await t.addNewWACZ({name:"default",path:e,loader:r})}}class Tb{constructor(t,e,r=null){this.config=e,this.loadId=r,this.loader=t}async load(t,e=null,r=0){const i=new Do({loader:this.loader});await i.init();const n=i.zipreader,s=new Eb(t,i),o=await s.load();let a=0;const c=(t,i,n)=>{n+=a,e&&r&&e(Math.round(100*n/r),null,n,r)};for(const e of i.iterContainedFiles()){const r=n.getCompressedSize(e);(e.endsWith(".warc.gz")||e.endsWith(".warc"))&&await this.loadWARC(t,n,e,c,r),a+=r}return o||{}}async loadWARC(t,e,r,i,n){const{reader:s}=await e.loadFile(r,{unzip:!0}),o=new vs(s,null,r);return o.detectPages=!1,await o.load(t,i,n)}}class xb{constructor(t){this.response=t}async load(t){return await t.loadFromJSON(this.response)}}class Cb{constructor(t,{cloneResponse:e=!1,allowBody:r=!1,hostProxyOnly:i=!1}={}){if(t=t||{},this.prefix=t.prefix||"",this.proxyPathOnly=t.proxyPathOnly||!1,this.isLive=void 0===t.isLive||t.isLive,this.archivePrefix=t.archivePrefix||"",this.cloneResponse=e,this.allowBody=r||this.isLive,this.hostProxy=t.hostProxy,this.hostProxy instanceof Array){const t={};for(const e of this.hostProxy)t[e.host]=e;this.hostProxy=t}this.hostProxyOnly=i}async getAllPages(){return[]}getFetchUrl(t,e,r){let i;if(this.hostProxy){i=new URL(t);const e=this.hostProxy[i.host];if(e)return r.set("X-Proxy-Host",i.host),e.prefix+(e.pathOnly?i.pathname+i.search:t)}return this.hostProxyOnly?null:this.proxyPathOnly?(i||(i=new URL(t)),this.prefix+i.pathname+i.search):this.isLive||!e.timestamp?this.prefix+t:this.prefix+this.archivePrefix+e.timestamp+"id_/"+t}async getResource(t,e){const{headers:r,credentials:i,url:n}=t.prepareProxyRequest(e,!0),s=this.getFetchUrl(n,t,r);if(!s)return null;let o=null;!this.allowBody||"POST"!==t.method&&"PUT"!==t.method||(o=await t.getBody());const a=await fetch(s,{method:t.method,body:o,headers:r,credentials:i,mode:"cors",redirect:"follow"});let c=null;this.cloneResponse&&(c=a.clone());const l=vn.fromResponse({url:n,response:a,date:new Date,noRW:!1,isLive:this.isLive,archivePrefix:this.archivePrefix});return c&&(l.clonedResponse=c),l}}const Ib=/^([\w-]+,)*[\w-]+(:\d+)?,?\)\//;class Rb extends bo{constructor(t,e,r="wacz"){super(t.dbname,t.noCache),this.config=t,this.waczfiles={},this.waczNameForHash={},this.ziploadercache={},this.updating=null,this.rootSourceType=r,this.sourceLoader=e,this.externalSource=null,this.fuzzyUrlRules=[],this.textIndex=t&&t.metadata&&t.metadata.textIndex||bb,t.extraConfig&&this.initConfig(t.extraConfig)}initConfig(t){if(void 0!==t.decodeResponses&&(this.config.decode=t.decodeResponses),t.hostProxy&&(this.externalSource=new Cb(t,{hostProxyOnly:!0})),t.fuzzy)for(const[e,r]of t.fuzzy){const t=new RegExp(e);this.fuzzyUrlRules.push({match:t,replace:r})}t.textIndex&&(this.textIndex=t.textIndex)}updateHeaders(t){this.sourceLoader&&(this.sourceLoader.headers=t)}_initDB(t,e,r,i){super._initDB(t,e,r,i),e||(t.createObjectStore("ziplines",{keyPath:["waczname","prefix"]}),t.createObjectStore("waczfiles",{keyPath:"waczname"}),t.createObjectStore("verification",{keyPath:"id"})),2===e&&this.convertV2WACZDB(t,i),3===e&&t.createObjectStore("verification",{keyPath:"id"})}async convertV2WACZDB(t,e){try{const r=await e.objectStore("ziplines").getAll(),i=await e.objectStore("zipEntries").getAll();t.deleteObjectStore("ziplines"),t.deleteObjectStore("zipEntries"),t.createObjectStore("ziplines",{keyPath:["waczname","prefix"]}),t.createObjectStore("waczfiles",{keyPath:"waczname"}),t.createObjectStore("verification",{keyPath:"id"});const n=this.config.loadUrl;for(const t of r)t.waczname=n,e.objectStore("ziplines").put(t);const s=r.length>0?2:1,o=await this.computeHash(n),a=new Do({waczname:n,hash:o,url:n,entries:i,indexType:s});e.objectStore("waczfiles").put(a.serialize()),await e.done}catch(t){console.warn(t)}}addWACZFile(t){return this.waczfiles[t.waczname]=new Do(t),this.waczNameForHash[t.hash]=t.waczname,this.waczfiles[t.waczname]}async init(){await super.init();const t=await this.db.getAll("waczfiles")||[];for(const e of t)this.addWACZFile({...e,parent:this});for(const[t,e]of Object.entries(this.waczfiles)){e.path=e.path||t;const r=e.path.lastIndexOf("#!/");if(r>0){const t=e.path.slice(0,r),i=this.waczfiles[t];e.parent=i}else"json"!==this.rootSourceType&&(e.loader=this.sourceLoader)}await this.checkUpdates()}async close(){super.close(),caches.delete("cache:"+this.name.slice("db:".length))}async clearZipData(){const t=["waczfiles","ziplines"];for(const e of t)await this.db.clear(e)}async addVerifyData(t="",e,r,i,n=!1){let s=null;t&&(e=t+e),i&&(s=r===i,n&&console.log(`verify ${e}: ${s}`)),await this.db.put("verification",{id:e,expected:r,matched:s})}async addVerifyDataList(t,e){const r=this.db.transaction("verification","readwrite");for(const i of e)t&&(i.id=t+i.id),r.store.put(i);try{await r.done}catch(t){console.warn(t)}}async getVerifyInfo(){const t=await this.db.getAll("verification");let e=0,r=0,i={};const n=["domain","created","certFingerprint","software","datapackageHash","publicKey"];for(const s of t)n.includes(s.id)?i[s.id]=s.expected:"signature"===s.id||!0===s.matched?e++:!1===s.matched&&r++;return i.numInvalid=r,i.numValid=e,i}async getVerifyExpected(t){const e=await this.db.get("verification",t);return e&&e.expected}async clearAll(){await super.clearAll(),await this.clearZipData()}async loadRecordFromSource(t){const{start:e,length:r,path:i,wacz:n}=t.source,s={offset:e,length:r,unzip:!0,computeHash:!0},o=n,{reader:a,hasher:c}=await this.loadFileFromNamedWACZ(o,"archive/"+i,s),l=new _s(a,c);await this.waczfiles[o].save(this.db);const h=await l.load();return t[xo]&&(h.respHeaders["x-wabac-preset-cookie"]=t[xo]),{remote:h,hasher:c}}async loadIndex(t){if(!this.waczfiles[t])throw new Error("unknown waczfile: "+t);if(this.waczfiles[t].indexType)return{indexType:this.waczfiles[t].indexType,isNew:!1};let e=0;for(const r of this.waczfiles[t].iterContainedFiles())r.endsWith(".cdx")||r.endsWith(".cdxj")?(console.log(`Loading CDX for ${t}`),await this.loadCDX(r,t),e=1):r.endsWith(".idx")&&(console.log(`Loading IDX for ${t}`),await this.loadIDX(r,t),e=2);return this.waczfiles[t].indexType=e,await this.waczfiles[t].save(this.db,!0),{indexType:e,isNew:!0}}async loadCDX(t,e,r,i){const{reader:n,hasher:s}=await this.loadFileFromNamedWACZ(e,t,{computeHash:!0}),o=new Io(n,null,e,{wacz:e}),a=await o.load(this,r,i);if(s){const r=await this.getVerifyExpected(t);r&&this.addVerifyData(e,t,r,s.getHash())}return a}async loadIDX(t,e,r,i){const{reader:n,hasher:s}=await this.loadFileFromNamedWACZ(e,t,{computeHash:!0});let o=[],a="",c=!0,l=0;for await(const t of n.iterLines()){if(l+=t.length,l===t.length&&t.startsWith("!meta")){const e=t.indexOf(" {");if(e<0){console.warn("Invalid Meta Line: "+t);continue}const r=JSON.parse(t.slice(e));r.filename&&(a=r.filename),"cdxj-gzip-1.0"!==r.format&&console.log(`Unknown CDXJ format "${r.format}", archive may not parse correctly`);continue}let n;if(t.indexOf("\t")>0){let[r,i,s,o]=t.split("\t");s=Number(s),o=Number(o),n={waczname:e,prefix:r,filename:i,offset:s,length:o,loaded:!1},c=!1}else{const r=t.indexOf(" {");if(r<0){console.log("Invalid Index Line: "+t);continue}const i=t.slice(0,r);let{offset:s,length:o,filename:l,digest:h}=JSON.parse(t.slice(r));c=c&&!Ib.test(i),l=l||a,n={waczname:e,prefix:i,filename:l,offset:s,length:o,digest:h,loaded:!1}}r&&r(l/i,l,i),o.push(n)}if(s){const r=await this.getVerifyExpected(t);r&&this.addVerifyData(e,t,r,s.getHash())}const h=this.db.transaction("ziplines","readwrite");for(const t of o)h.store.put(t);try{await h.done}catch(t){console.log("Error loading ziplines index: ",t)}c&&c!==this.waczfiles[e].nonSurt&&(this.waczfiles[e].nonSurt=c,await this.waczfiles[e].save(this.db,!0))}async loadCDXFromIDX(t,e,r=0,i=!1){const n=this.waczfiles[t].nonSurt?e:nt(e),s=i?this.prefixUpperBound(n):n+" 9999",o=IDBKeyRange.upperBound([t,s],!0),a=this.db.transaction("ziplines","readonly"),c=[];for await(const e of a.store.iterate(o,"prev")){if(e.value.waczname!==t)break;if(c.unshift(e.value),!e.value.prefix.split(" ")[0].startsWith(n))break}await a.done;const l=[];c.length>3&&r&&c.sort(((t,e)=>{const i=t.prefix.split(" ")[1],n=e.prefix.split(" ")[1];if(!i||!n)return 0;const s=Math.abs(u(i).getTime()-r),o=Math.abs(u(n).getTime()-r);return s===o?0:s3)break}return l.length&&await Promise.allSettled(l),await this.waczfiles[t].save(this.db),l.length>0}async doCDXLoad(t,e,r){try{const i="indexes/"+e.filename,n={offset:e.offset,length:e.length,unzip:!0,computeHash:!!e.digest},{reader:s,hasher:o}=await this.loadFileFromNamedWACZ(r,i,n),a=new Io(s,null,null,{wacz:r});if(await a.load(this),o){const t=o.getHash(),n=`${i}:${e.offset}-${e.length}`;await this.addVerifyData(r,n,e.digest,t)}e.loaded=!0,await this.db.put("ziplines",e)}catch(t){await _(t,this.config)||console.warn(t)}finally{delete this.ziploadercache[t]}}async findPageAtUrl(t,e){const r=await this.db.getAllFromIndex("pages","url",t);let i=null,n=Number.MAX_SAFE_INTEGER;for(const t of r){const r=Math.abs(t.ts-e);if(r<1e3)return t;r0)return r;for(const i of Object.keys(this.waczfiles))if(i&&"local"!==i){const{indexType:n,isNew:s}=await this.loadIndex(i);switch(n){case 2:if(!await this.loadCDXFromIDX(i,t,0,!0))continue;break;case 1:if(!s)continue;break;default:continue}const o=await super.resourcesByUrlAndMime(t,...e);o&&o.length&&(r=r.concat(o))}return r}async loadFileFromWACZ(t,e,r){try{return await t.loadFile(e,r)}catch(i){if(await this.retryLoad(i))return await t.loadFile(e,r);throw i}}async loadFileFromNamedWACZ(t,e,r){const i=this.waczfiles[t];if(!i)throw new Error("No WACZ Found for: "+t);return await this.loadFileFromWACZ(i,e,r)}async addNewWACZ({name:t,hash:e,path:r,parent:i=null,loader:n=null}={}){const s=t||r;e?e.indexOf(":")>0&&(e=e.split(":")[1]):e=await d(s,"sha-256","");const o=this.addWACZFile({waczname:s,hash:e,path:r,parent:i,loader:n},!0);await o.init(),await o.save(this.db,!0);const a=new Eb(this,o,!i);return await a.load()}async loadWACZFiles(t,e=this){const r=[],i=async(t,e)=>{await this.waczfiles[t].init(e),await this.waczfiles[t].save(this.db,!0)},n=t.resources.map((t=>{const r=e.getLoadPath(t.path);return{name:e.getName(t.name),hash:t.hash,path:r}}));for(const{name:t,hash:s,path:o}of n)this.waczfiles[t]?this.waczfiles[t].path!==o&&r.push(i(t,o)):r.push(this.addNewWACZ({name:t,hash:s,path:o,parent:e}));r.length&&await Promise.allSettled(r)}async getTextIndex(){const t={"Content-Type":"application/ndjson"},e=Object.keys(this.waczfiles);if(!this.textIndex||!e.length)return new Response("",{headers:t});if(1===e.length){const r=e[0];let i;try{i=await this.loadFileFromNamedWACZ(r,this.textIndex,{unzip:!0})}catch(e){return new Response("",{headers:t})}const{reader:n}=i;if(!n)return new Response("",{headers:t});const s=this.waczfiles[r].getSizeOf(this.textIndex);return s>0&&(t["Content-Length"]=""+s),new Response(n.getReadableStream(),{headers:t})}{const r=[];for(const t of e)try{const{reader:e}=await this.loadFileFromNamedWACZ(t,this.textIndex,{unzip:!0});e&&r.push(e)}catch(t){continue}const i=new ReadableStream({async pull(t){for(const e of r)for await(const r of e)t.enqueue(r);t.close()}});return new Response(i,{headers:t})}}async getResource(t,e,r,{pageId:i}={}){if(await this.initing,this.externalSource){const i=await this.externalSource.getResource(t,e,r);if(i)return i}let n=i,s=null,o=null;if(n){if(s=this.waczNameForHash[n],!s)return null;if(o=await super.getResource(t,e,r,{waczname:s}),o)return o}let a=null;for(const[i,c]of Object.entries(this.waczfiles))if(c.fileType===Lo&&c.hash!==n&&(o=await super.getResource(t,e,r,{waczname:i,noFuzzyCheck:!0}),o)){s=i,a=c.hash;break}if(s)return Response.redirect(`${e}:${a}/${t.timestamp}mp_/${t.url}`);if(this.fuzzyUrlRules.length)for(const{match:i,replace:n}of this.fuzzyUrlRules){const s=decodeURIComponent(t.url.replace(i,n));if(s&&s!==t.url){t.url=s;const i=await super.getResource(t,e,r);if(i)return i}}return null}async retryLoad(t){return"json"===this.rootSourceType&&(t instanceof C?(this.updating||(this.updating=this.checkUpdates()),await this.updating,this.updating=null,!0):await _(t,this.config))}async checkUpdates(){"json"===this.rootSourceType&&await this.loadFromJSON()}async loadFromJSON(t=null){if(!t){t=(await this.sourceLoader.doInitialFetch(!1)).response}if(206!==t.status&&200!==t.status)return console.warn("WACZ update failed from: "+this.config.loadUrl),{};const e=await t.json();return e.profile,await this.loadWACZFiles(e),e}getLoadPath(t){return new URL(t,this.config.loadUrl).href}getName(t){return t}async createLoader(t){return await lo(t)}}class kb{constructor(t){const e=t.extraConfig||{};this.sourceUrl=e.prefix,this.type=e.sourceType||"kiwix",this.notFoundPageUrl=e.notFoundPageUrl}async getAllPages(){return[]}async getResource(t,e){const{url:r,headers:i}=t.prepareProxyRequest(e);let n=i;if("kiwix"===this.type){let e=await this.resolveHeaders(r);if(!e)for(const t of fs.getFuzzyCanonsWithArgs(r))if(t!==r&&(e=await this.resolveHeaders(t),e))break;if(!e){if(this.notFoundPageUrl&&"navigate"===t.mode){const t=await fetch(this.notFoundPageUrl);if(200===t.status){const e={"Content-Type":"text/html"},i=await t.text();return new Response(i.replace("$URL",r),{status:404,headers:e})}}return null}let{headers:i,encodedUrl:s,date:o,status:a,statusText:c,hasPayload:l}=e;if(n.has("Range")){const t=n.get("Range");n={Range:t}}let h=null,u=null;l&&(u=await fetch(this.sourceUrl+"A/"+s,{headers:n}),u.body&&(h=new ft(u.body.getReader(),!1)),206===u.status&&(a=206,c="Partial Content",i.set("Content-Length",u.headers.get("Content-Length")),i.set("Content-Range",u.headers.get("Content-Range")),i.set("Accept-Ranges","bytes"))),h||(h=new Uint8Array([])),o||(o=new Date),i||(i=new Headers);return new vn({payload:h,status:a,statusText:c,headers:i,url:r,date:o,noRW:!1,isLive:!1})}}async resolveHeaders(t){const e=t.slice(t.indexOf("//")+2);let r=encodeURI(e);r=encodeURIComponent(e);let i=await fetch(this.sourceUrl+"H/"+r);if(200!==i.status)return null;let n=null,s=null,o=null,a=null,c=!1;try{const e=await Rt.parse(i.body);if("revisit"===e.warcType){const r=e.warcHeaders.headers.get("WARC-Refers-To-Target-URI");if(r&&r!==t)return await this.resolveHeaders(r)}s=new Date(e.warcDate),e.httpHeaders?(n=e.httpHeaders.headers,o=Number(e.httpHeaders.statusCode),a=e.httpHeaders.statusText,c="0"!==e.httpHeaders.headers.get("Content-Length")):"resource"===e.warcType&&(n=new Headers,n.set("Content-Type",e.warcContentType),n.set("Content-Length",e.warcContentLength),o=200,a="OK",c=e.warcContentLength>0),o||(o=200)}catch(e){console.warn(e),console.warn("Ignoring headers, error parsing headers response for: "+t)}return{encodedUrl:r,headers:n,date:s,status:o,statusText:a,hasPayload:c}}}const Nb=Pb([80,75,3,4]),Ob=Pb([31,139,8]),Bb=Pb([87,65,82,67]);function Pb(t){return e=>{for(const[r,i]of t.entries())if(i!==e[r])return!1;return!0}}async function Lb(t){const e=t.body.getReader();let r="";const{value:i,done:n}=await e.read();var s;return!n&&i.length>=4&&(s=i.slice(0,4),r=Nb(s)?".wacz":Bb(s)?".warc":Ob(s)?".warc.gz":void 0,r||(r=function(t){try{const e=(new TextDecoder).decode(t).split("\n");if(e>1&&e.indexOf(" {"))return".cdxj"}catch(t){return""}}(i))),n||e.cancel(),r}globalThis.self||(globalThis.self=globalThis),self.interruptLoads={};class Db extends class{constructor(){this.colldb=null,this.root=null,this.checkIpfs=!0,this._init_db=this._initDB()}async _initDB(){this.colldb=await Jn("collDB",1,{upgrade:t=>{t.createObjectStore("colls",{keyPath:"name"}).createIndex("type","type")}})}async loadAll(t){if(await this._init_db,t)for(const e of t.split(",")){const t=e.split(":");if(2===t.length){const e={dbname:t[1],sourceName:t[1],decode:!1},r={name:t[0],type:"archive",config:e};console.log("Adding Coll: "+JSON.stringify(r)),await this.colldb.put("colls",r)}}try{const t=(await this.listAll()).map((t=>this._initColl(t)));await Promise.all(t)}catch(t){console.warn(t.toString())}return!0}async listAll(){return await this._init_db,await this.colldb.getAll("colls")}async loadColl(t){await this._init_db;const e=await this.colldb.get("colls",t);return e?await this._initColl(e):null}async reload(t){return this.loadColl(t)}async deleteColl(t){await this._init_db;const e=await this.colldb.get("colls",t);if(!e)return!1;if(e.config.dbname)try{await Xn(e.config.dbname,{blocked(t,r){console.log(`Unable to delete ${e.config.dbname}, blocked: ${r}`)}})}catch(t){return console.warn(t),!1}return await this.colldb.delete("colls",t),!0}async updateAuth(t,e){await this._init_db;const r=await this.colldb.get("colls",t);return!!r&&(r.config.headers=e,await this.colldb.put("colls",r),!0)}async updateMetadata(t,e){await this._init_db;const r=await this.colldb.get("colls",t);return!!r&&(r.config.metadata={...r.config.metadata,...e},await this.colldb.put("colls",r),r.config.metadata)}async updateSize(t,e,r,i){await this._init_db;const n=await this.colldb.get("colls",t);if(!n)return!1;const s=n.config.metadata;return s.fullSize=(s.fullSize||0)+e,s.size=(s.size||0)+r,s.mtime=(new Date).getTime(),void 0!==i&&(n.config.decode=i),await this.colldb.put("colls",n),s}async initNewColl(t,e={},r="archive"){await this._init_db;const i=m(),n="local://"+i,s={name:i,type:r,config:{dbname:"db:"+i,ctime:(new Date).getTime(),decode:!1,metadata:t,sourceUrl:n,extraConfig:e}},o=await this._initColl(s);return await this.colldb.put("colls",s),o}async _initColl(t){const e=await this._initStore(t.type,t.config),r=t.name,i=t.config;return t.config.root&&!this.root&&(this.root=r),this._createCollection({name:r,store:e,config:i})}async _initStore(t,e){let r=null,i=null;switch(t){case"archive":i=new ws(e.dbname);break;case"remotesource":r=await lo({url:e.loadUrl,headers:e.headers,size:e.size,extra:e.extra}),i=new Ao(e.dbname,r,e.noCache);break;case"remoteprefix":i=new vo(e.dbname,e.remotePrefix,e.headers,e.noCache);break;case"wacz":case"remotezip":case"multiwacz":r=await lo({url:e.loadUrl||e.sourceUrl,headers:e.headers,extra:e.extra}),i=new Rb(e,r,"multiwacz"===t?"json":"wacz");break;case"remotewarcproxy":i=new kb(e);break;case"live":i=new Cb(e.extraConfig)}return i?(i.initing&&await i.initing,i):(console.log("no store found: "+t),null)}_createCollection(t){return t}}{constructor(t){super(),this.registerListener(t)}async hasCollection(t){return await this._init_db,null!=await this.colldb.getKey("colls",t)}registerListener(t){t.addEventListener("message",(t=>{t.waitUntil?t.waitUntil(this._handleMessage(t)):this._handleMessage(t)}))}async _handleMessage(t){await this._init_db;const e=t.source||self;switch(t.data.msg_type){case"addColl":{const r=t.data.name,i=(t,i,n,s,o=null,a=null)=>{e.postMessage({msg_type:"collProgress",name:r,percent:t,error:i,currentSize:n,totalSize:s,fileHandle:o,extraMsg:a})};let n;try{if(n=await this.colldb.get("colls",r),n?t.data.skipExisting||(await this.deleteColl(r),n=await this.addCollection(t.data,i)):n=await this.addCollection(t.data,i),!n){if(t.data.name)try{await Xn("db:"+t.data.name,{blocked(e,r){console.log(`Load failed and unable to delete ${t.data.name}: ${r}`)}})}catch(t){console.warn(t)}return}}catch(t){if(t instanceof x)return console.warn(t),void i(0,"permission_needed",null,null,t.info&&t.info.fileHandle);if("ConstraintError"!==t.name)return console.warn(t),void i(0,"An unexpected error occured: "+t.toString());console.log("already being added, just continue..."),n=await this.colldb.get("colls",r)}e.postMessage({msg_type:"collAdded",name:r,sourceUrl:n.config.sourceUrl});break}case"cancelLoad":{const e=t.data.name,r=new Promise((t=>self.interruptLoads[e]=t));await r,await this.deleteColl(e),delete self.interruptLoads[e];break}case"removeColl":{const r=t.data.name;await this.hasCollection(r)&&(await this.deleteColl(r),this.doListAll(e));break}case"listAll":this.doListAll(e);break;case"reload":this.reload(t.data.name)}}async doListAll(t){const e=[],r=await this.listAll();for(const t of r)e.push({name:t.name,prefix:t.name,pageList:[],sourceName:t.config.sourceName});t.postMessage({msg_type:"listAll",colls:e})}async addCollection(t,e){let r=t.name,i=null,n={root:t.root||!1},o=null,a=null;const c=t.file;if(!c||!c.sourceUrl)return e(0,"Invalid Load Request"),!1;if(n.dbname="db:"+r,c.sourceUrl.startsWith("proxy:"))n.sourceUrl=c.sourceUrl.slice("proxy:".length),n.extraConfig=t.extraConfig,n.extraConfig.prefix||(n.extraConfig.prefix=n.sourceUrl),n.topTemplateUrl=t.topTemplateUrl,n.metadata={},i=t.type||n.extraConfig.type||"remotewarcproxy",o=await this._initStore(i,n);else{let l=null;if(c.newFullImport&&(r=m(),c.loadUrl=c.loadUrl||c.sourceUrl,c.name=c.name||c.sourceUrl,c.sourceUrl="local://"+r),i="archive",c.newFullImport&&c.importCollId){const t=await this.colldb.get("colls",c.importCollId);if(!t||"archive"!==t.type)return void e(0,"Invalid Existing Collection: "+c.importCollId);n.dbname=t.config.dbname,a=t.config,a.decode=!0}let h=c.loadUrl||c.sourceUrl;h.match(/[\w]+:\/\//)||(h=new URL(h,self.location.href).href),n.decode=!0,n.onDemand=!1,n.loadUrl=h,n.sourceUrl=c.sourceUrl,n.sourceName=c.name||c.sourceUrl;try{if(n.sourceName.match(/https?:\/\//)){const t=new URL(n.sourceName);n.sourceName=t.pathname+t.hash}}catch(t){}if(n.sourceName=n.sourceName.slice(n.sourceName.lastIndexOf("/")+1),n.size="number"==typeof c.size?c.size:null,n.extra=c.extra,n.loadUrl.startsWith("file://")&&!c.blob&&!n.extra){if(!this._fileHandles||!this._fileHandles[n.sourceUrl])return void e(0,"missing_local_file");n.extra={fileHandle:this._fileHandles[n.sourceUrl]}}n.extraConfig=t.extraConfig,n.headers=c.headers||n.extraConfig&&n.extraConfig.headers,n.noCache=c.noCache;let u=await lo({url:h,headers:n.headers,size:c.size,extra:n.extra,blob:c.blob});if(c.loadEager){const{response:t}=await u.doInitialFetch(!1,!0),e={arrayBuffer:new Uint8Array(await t.arrayBuffer())};c.newFullImport=!0,u=await lo({url:h,headers:n.headers,size:c.size,extra:e})}let p=function(t){const e=[".warc",".warc.gz",".cdx",".cdxj",".har",".json",".wacz",".zip"];for(const r of e)if(t.endsWith(r))return r;return""}(n.sourceName),{abort:d,response:f}=await u.doInitialFetch(".wacz"===p);p||(p=await Lb(await f.clone()));const g=f.body;if(n.onDemand=u.canLoadOnDemand&&!c.newFullImport,!u.isValid){const t=u.length<=1e3?await f.text():"";return e(0,`Sorry, this URL could not be loaded.\nMake sure this is a valid URL and you have access to this file.\nStatus: ${f.status} ${f.statusText}\nError Details:\n${t}`),d&&d.abort(),!1}if(!u.length)return e(0,"Sorry, this URL could not be loaded because the size of the file is not accessible.\nMake sure this is a valid URL and you have access to this file."),d&&d.abort(),!1;const w=u.length;if(".wacz"===p)if(n.onDemand)l=new Sb(u,n,r),o=new Rb(n,u,"wacz"),i="wacz";else{if(!u.canLoadOnDemand||!c.newFullImport)return e(0,"Sorry, can't load this WACZ file due to lack of range request support on the server"),d&&d.abort(),!1;l=new Tb(u,n,r),o=null,delete n.extra}else".warc"===p||".warc.gz"===p?n.noCache||!(w300&&e<400)return;let s=null;void 0===this.timeRanges[n]?(s={count:0,children:[]},this.timeRanges[n]=s,r.referrer.indexOf("mp_/")>0&&self.clients.matchAll({type:"window"}).then((t=>this.updateStatsParent(n,r.referrer,t)))):s=this.timeRanges[n];const o=t.getTime();(!s.min||os.max)&&(s.max=o),s.count++}updateStatsParent(t,e,r){for(let i of r)if(i.url===e){this.timeRanges[i.id]?this.timeRanges[i.id].children[t]=1:this.timeRanges[i.id]={count:0,children:{id:1}};break}}async getStats(t){const e=new URL(t.request.url);let r=0;const i=new URLSearchParams(e.search).get("url"),n=await self.clients.matchAll({type:"window"}),s={};for(let t of n)t.url===i&&(r=t.id),s[t.id]=1;const o=this.timeRanges[r]||{},a={count:o.count||0,min:o.min,max:o.max},c=this.timeRanges[r]&&Object.keys(this.timeRanges[r].children)||[];for(let t of c){const e=this.timeRanges[t];e&&((!a.min||e.mina.max)&&(a.max=e.max),a.count+=e.count)}for(let t of Object.keys(this.timeRanges))s[t]||delete this.timeRanges[t];return new Response(JSON.stringify(a),{headers:{"Content-Type":"application/json"}})}}var Mb=function(){return Mb=Object.assign||function(t){for(var e,r=1,i=arguments.length;r$)/g,""):"[a-zA-Z0-9-_.~%':|=+\\*@$]+")+")"},Zb=[{name:"url-parameter",pattern:/^:([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,regex:function(t){return new RegExp(Xb(t[2]))}},{name:"url-parameter-splat",pattern:/^\*([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/,regex:/([^?]*)/},{name:"url-parameter-matrix",pattern:/^;([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})(<(.+?)>)?/,regex:function(t){return new RegExp(";"+t[1]+"="+Xb(t[2]))}},{name:"query-parameter",pattern:/^(?:\?|&)(?::)?([a-zA-Z0-9-_]*[a-zA-Z0-9]{1})/},{name:"delimiter",pattern:/^(\/|\?)/,regex:function(t){return new RegExp("\\"+t[0])}},{name:"sub-delimiter",pattern:/^(!|&|-|_|\.|;)/,regex:function(t){return new RegExp(t[0])}},{name:"fragment",pattern:/^([0-9a-zA-Z]+)/,regex:function(t){return new RegExp(t[0])}}],$b=function t(e,r){if(void 0===r&&(r=[]),!Zb.some((function(i){var n=e.match(i.pattern);return!!n&&(r.push({type:i.name,match:n[0],val:n.slice(1,2),otherVal:n.slice(2),regex:i.regex instanceof Function?i.regex(n):i.regex}),n[0].length0,this.hasSpatParam=this.tokens.filter((function(t){return/splat$/.test(t.type)})).length>0,this.hasMatrixParams=this.tokens.filter((function(t){return/matrix$/.test(t.type)})).length>0,this.hasQueryParams=this.tokens.filter((function(t){return/^query-parameter/.test(t.type)})).length>0,this.spatParams=this.getParams("url-parameter-splat"),this.urlParams=this.getParams(/^url-parameter/),this.queryParams=this.getParams("query-parameter"),this.params=this.urlParams.concat(this.queryParams),this.source=this.tokens.filter((function(t){return void 0!==t.regex})).map((function(t){return t.regex.source})).join("")}return t.createPath=function(e,r){return new t(e,r)},t.prototype.isQueryParam=function(t){return-1!==this.queryParams.indexOf(t)},t.prototype.isSpatParam=function(t){return-1!==this.spatParams.indexOf(t)},t.prototype.test=function(t,e){var r=this,i=Mb(Mb({caseSensitive:!1,strictTrailingSlash:!1},this.options),e),n=function(t,e){return e||"\\/"===t?t:t.replace(/\\\/$/,"")+"(?:\\/)?"}(this.source,i.strictTrailingSlash),s=this.urlTest(t,n+(this.hasQueryParams?"(\\?.*$|$)":"$"),i.caseSensitive,i.urlParamsEncoding);if(!s||!this.hasQueryParams)return s;var o=qb(t,i.queryParams);return 0===Object.keys(o).filter((function(t){return!r.isQueryParam(t)})).length?(Object.keys(o).forEach((function(t){return s[t]=o[t]})),s):null},t.prototype.partialTest=function(t,e){var r=this,i=Mb(Mb({caseSensitive:!1,delimited:!0},this.options),e),n=function(t,e){return e?/(\/)$/.test(t)?t:t+"(\\/|\\?|\\.|;|$)":t}(this.source,i.delimited),s=this.urlTest(t,n,i.caseSensitive,i.urlParamsEncoding);if(!s)return s;if(!this.hasQueryParams)return s;var o=qb(t,i.queryParams);return Object.keys(o).filter((function(t){return r.isQueryParam(t)})).forEach((function(t){return function(t,e,r){void 0===r&&(r="");var i=t[e];return t[e]=void 0===i?r:Array.isArray(i)?i.concat(r):[i,r],t}(s,t,o[t])})),s},t.prototype.build=function(t,e){var r=this;void 0===t&&(t={});var i=Mb(Mb({ignoreConstraints:!1,ignoreSearch:!1,queryParams:{}},this.options),e),n=Object.keys(t).filter((function(t){return!r.isQueryParam(t)})).reduce((function(e,n){if(!tA(t[n]))return e;var s=t[n],o=r.isSpatParam(n);return"boolean"==typeof s?e[n]=s:Array.isArray(s)?e[n]=s.map((function(t){return Jb(t,i.urlParamsEncoding,o)})):e[n]=Jb(s,i.urlParamsEncoding,o),e}),{});if(this.urlParams.some((function(e){return!tA(t[e])}))){var s=this.urlParams.filter((function(e){return!tA(t[e])}));throw new Error("Cannot build path: '"+this.path+"' requires missing parameters { "+s.join(", ")+" }")}if(!i.ignoreConstraints&&!this.tokens.filter((function(t){return/^url-parameter/.test(t.type)&&!/-splat$/.test(t.type)})).every((function(t){return new RegExp("^"+Xb(t.otherVal[0])+"$").test(n[t.val])})))throw new Error("Some parameters of '"+this.path+"' are of invalid format");var o=this.tokens.filter((function(t){return!1===/^query-parameter/.test(t.type)})).map((function(t){return"url-parameter-matrix"===t.type?";"+t.val+"="+n[t.val[0]]:/^url-parameter/.test(t.type)?n[t.val[0]]:t.match})).join("");if(i.ignoreSearch)return o;var a=function(t,e){var r=Fb(e);return Object.keys(t).filter((function(e){return function(t){return void 0!==t}(t[e])})).map((function(e){return jb(e,t[e],r)})).filter(Boolean).join("&")}(this.queryParams.filter((function(e){return-1!==Object.keys(t).indexOf(e)})).reduce((function(e,r){return e[r]=t[r],e}),{}),i.queryParams);return a?o+"?"+a:o},t.prototype.getParams=function(t){var e=t instanceof RegExp?function(e){return t.test(e.type)}:function(e){return e.type===t};return this.tokens.filter(e).map((function(t){return t.val[0]}))},t.prototype.urlTest=function(t,e,r,i){var n=this,s=new RegExp("^"+e,r?"":"i"),o=t.match(s);return o?this.urlParams.length?o.slice(1,this.urlParams.length+1).reduce((function(t,e,r){return t[n.urlParams[r]]=(Yb[i]||decodeURIComponent)(e),t}),{}):{}:null},t}();class iA{constructor(t){this.routes={};for(const[e,r]of Object.entries(t)){let t,i;r instanceof Array?(t=r[0],i=r[1]||"GET"):(t=r,i="GET"),this.routes[i]=this.routes[i]||{},this.routes[i][e]=new rA(t)}}match(t,e="GET"){for(const[r,i]of Object.entries(this.routes[e]||[])){const e=t.split("?",2),n=e[0],s=i.test(n);if(s)return s._route=r,s._query=new URLSearchParams(2===e.length?e[1]:""),s}return{_route:null}}}class nA{constructor(t){this.router=new iA(this.routes),this.collections=t}get routes(){return{index:"coll-index",coll:"c/:coll",urls:"c/:coll/urls",urlsTs:"c/:coll/ts/",createColl:["c/create","POST"],deleteColl:["c/:coll","DELETE"],updateAuth:["c/:coll/updateAuth","POST"],updateMetadata:["c/:coll/metadata","POST"],curated:"c/:coll/curated/:list",pages:"c/:coll/pages",textIndex:"c/:coll/textIndex",deletePage:["c/:coll/page/:page","DELETE"]}}async apiResponse(t,e,r){const i=this.router.match(t,e.method),n=await this.handleApi(e,i,r);if(n instanceof Response)return n;const s=n.error?404:200;return this.makeResponse(n,s)}async handleApi(t,e){switch(e._route){case"index":return await this.listAll(e._query.get("filter"));case"createColl":{const e=await t.json();return S(await this.collections.initNewColl(e.metadata||{},e.extraConfig||{}))}case"coll":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=S(t);return"1"===e._query.get("all")?(t.store.db?(r.pages=await t.store.getAllPages(),r.lists=await t.store.db.getAll("pageLists"),r.curatedPages=await t.store.db.getAll("curatedPages")):(r.pages=[],r.lists=[],r.curatedPages=[]),r.verify=await t.store.getVerifyInfo()):(r.numLists=await t.store.db.count("pageLists"),r.numPages=await t.store.db.count("pages")),t.config.metadata.ipfsPins&&(r.ipfsPins=t.config.metadata.ipfsPins),r}case"deleteColl":{const t="1"===e._query.get("reload");return await this.collections.deleteColl(e.coll,t)?await this.listAll():{error:"collection_not_found"}}case"updateAuth":{const r=await t.json();return{success:await this.collections.updateAuth(e.coll,r.headers)}}case"updateMetadata":{const r=await t.json();return{metadata:await this.collections.updateMetadata(e.coll,r)}}case"urls":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=e._query.get("url"),i=Number(e._query.get("count")||100),n=e._query.get("mime"),s="1"===e._query.get("prefix"),o=e._query.get("fromUrl"),a=e._query.get("fromTs"),c=e._query.get("fromMime"),l=Number(e._query.get("fromStatus")||0);if(!t.store.resourcesByMime)return{urls:[]};let h;return h=r?await t.store.resourcesByUrlAndMime(r,n,i,s,o,a):await t.store.resourcesByMime(n,i,c,o,l),h=h||[],{urls:h}}case"urlsTs":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=e._query.get("url");return{timestamps:await t.store.getTimestampsByURL(r)}}case"pages":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};return{pages:await t.store.getAllPages()}}case"textIndex":{const t=await this.collections.getColl(e.coll);return t?t.store.getTextIndex?await t.store.getTextIndex():{}:{error:"collection_not_found"}}case"curated":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const r=Number(e.list);return{curated:await t.store.db.getAllFromIndex("curatedPages","listPages",IDBKeyRange.bound([r],[r+1]))}}case"deletePage":{const t=await this.collections.getColl(e.coll);if(!t)return{error:"collection_not_found"};const{pageSize:r,deleteSize:i}=t.store.deletePage(e.page);return this.collections.updateSize(e.coll,r,i),{pageSize:r,deleteSize:i}}default:return{error:"not_found"}}}async listAll(t){const e=await this.collections.listAll(),r=[];return e.forEach((e=>{"live"!==e.type&&"remoteproxy"!==e.type&&(t&&0!==e.type.indexOf(t)||r.push(S(e)))})),{colls:r}}makeResponse(t,e=200){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":"application/json"}})}}var sA=r(24);const oA=/^(?::([\w-]+)\/)?(\d*)([a-z]+_|[$][a-z0-9:.-]+)?(?:\/|\||%7C|%7c)(.+)/;class aA{constructor(t,e,{isRoot:r=!1,mod:i="",ts:n="",proxyOrigin:s=null,localOrigin:o=null}={}){const a=oA.exec(t);if(this.url="",this.timestamp=n,this.mod=i,this.pageId="",this.hash="",!a&&(t.startsWith("https:")||t.startsWith("http:")||t.startsWith("blob:")))this.url=t;else if(!a&&r)this.url="https://"+t;else{if(!a)return void(this.url=null);this.pageId=a[1]||"",this.timestamp=a[2],this.mod=a[3],this.url=a[4]}if(s&&o){const t=new URL(this.url);t.origin===o&&(this.url=s+t.pathname+(t.search?t.search:""))}const c=this.url.indexOf("#");c>0&&(this.hash=this.url.slice(c),this.url=this.url.substring(0,c)),this.request=e,this.method=e.method,this.mode=e.mode,this._postToGetConverted=!1}get headers(){return this.request.headers}get destination(){return this.request.destination}get referrer(){return this.request.referrer}async convertPostToGet(){if(this._postToGetConverted)return this.url;const t=this.request;if("POST"!==t.method&&"PUT"!==t.method)return this.url;const e={method:t.method,postData:await t.text(),headers:t.headers,url:this.url};return st(e)&&(this.url=e.url,this.method="GET",this.mode="navigate"===this.request.mode?"same-origin":this.request.mode,this._postToGetConverted=!0),this.url}prepareProxyRequest(t,e=!0){let r,i,n;if(e){r=new Headers(this.request.headers),i=this.request.referrer;const e=i.indexOf("/http",t.length-1);e>0&&(i=i.slice(e+1),r.set("X-Proxy-Referer",i)),n=this.request.credentials,this.cookie&&r.set("X-Proxy-Cookie",this.cookie)}else r=new Headers,n="omit";let s=this.url;if(s.startsWith("//"))try{s=new URL(i).protocol+s}catch(t){s="https:"+s}return{referrer:i,headers:r,credentials:n,url:s}}async getBody(){const t=this.request.clone();return new Uint8Array(await t.arrayBuffer())}}const cA="x-wabac-is-ajax-req";class lA extends Db{constructor(t,e=null,r={}){super(self),this.prefixes=t,this.colls={},this.inited=null,this.root=e,this.defaultConfig=r,this._fileHandles={}}_createCollection(t){return new Ln(t,this.prefixes,this.defaultConfig)}loadAll(t){return this.colls={},this.inited=super.loadAll(t),this.inited}async getColl(t){return this.colls[t]||(this.colls[t]=await this.loadColl(t)),this.colls[t]}async reload(t){delete this.colls[t],await this.getColl(t)}async addCollection(t,e){const r=await super.addCollection(t,e);return r&&r.name&&(this.colls[r.name]=this._createCollection(r)),r}async deleteColl(t,e=!1){return this.colls[t]&&(this.colls[t].store&&this.colls[t].store.delete&&await this.colls[t].store.delete(),e&&this.colls[t].config&&this.colls[t].config.extra&&this.colls[t].config.extra.fileHandle&&(this._fileHandles[this.colls[t].config.sourceUrl]=this.colls[t].config.extra.fileHandle)),!!await super.deleteColl(t)&&(delete this.colls[t],!0)}async initNewColl(t,e={},r="archive"){const i=await super.initNewColl(t,e,r);return i&&(this.colls[i.name]=i),i}async updateAuth(t,e){this.colls[t]&&this.colls[t].store.updateHeaders&&this.colls[t].store.updateHeaders(e),await super.updateAuth(t,e)}async updateMetadata(t,e){const r=await super.updateMetadata(t,e);return this.colls[t]&&r&&(this.colls[t].config.metadata=r,this.colls[t].metadata=r),r}async updateSize(t,e,r,i){const n=await super.updateSize(t,e,r,i);return this.colls[t]&&n&&(this.colls[t].config.metadata=n,this.colls[t].metadata=n),void 0!==i&&this.colls[t]&&(this.colls[t].config.decode=i),n}}class hA{constructor({staticData:t=null,ApiClass:e=nA,defaultConfig:r={},CollectionsClass:i=lA}={}){this.prefix=self.registration?self.registration.scope:"",this.replayPrefix=this.prefix;const n=new URLSearchParams(self.location.search);let s="w";n.has("replayPrefix")&&(s=n.get("replayPrefix")),s&&(this.replayPrefix+=s+"/"),this.staticPrefix=this.prefix+"static/",this.distPrefix=this.prefix+"dist/";const o={static:this.staticPrefix,root:this.prefix,main:this.replayPrefix};if(this.staticData=t||new Map,this.staticData.set(this.staticPrefix+"wombat.js",{type:"application/javascript",content:'/*! wombat.js (wabac.js 2.19.4) is part of Webrecorder project. Copyright (C) 2020-2024, Webrecorder Software. Licensed under the Affero General Public License v3. */(()=>{"use strict";function t(){this._map=[]}function e(t,e){void 0!==self.Symbol&&void 0!==self.Symbol.toStringTag&&Object.defineProperty(t.prototype,self.Symbol.toStringTag,{value:e,enumerable:!1})}function r(t){for(var e,r,i=t.__proto__||t.constructor.prototype||t.prototype,o=Object.getOwnPropertyNames(i),n=o.length,s=0;s=0?this._map.splice(e,1)[0][1]:null},t.prototype.map=function(t){for(var e=0;et+=String.fromCharCode(e)),""):t?t.toString():"";try{return"__wb_post_data="+btoa(e)}catch{return"__wb_post_data="}}function _(t){let{method:e,headers:r,postData:i}=t;if("GET"===e)return!1;function o(t){return t instanceof Uint8Array&&(t=(new TextDecoder).decode(t)),t}let n="";switch((r.get("content-type")||"").split(";")[0]){case"application/x-www-form-urlencoded":n=o(i);break;case"application/json":n=d(o(i));break;case"text/plain":try{n=d(o(i),!1)}catch{n=l(i)}break;case"multipart/form-data":{let t=r.get("content-type");if(!t)throw new Error("utils cannot call postToGetURL when missing content-type header");n=function(t,e){return function(t,e){let r=new URLSearchParams;t instanceof Uint8Array&&(t=(new TextDecoder).decode(t));try{let i=e.split("boundary=")[1],o=t.split(new RegExp("-*"+i+"-*","mi"));for(let t of o){let e=t.trim().match(/name="([^"]+)"\\r\\n\\r\\n(.*)/im);e&&r.set(e[1],e[2])}}catch{}return r}(t,e).toString()}(o(i),t);break}default:n=l(i)}return null!==n&&(t.url=function(t,e,r){if(!r)return t;let i=t.indexOf("?")>0?"&":"?";return`${t}${i}__wb_method=${r}&${e}`}(t.url,n,t.method),t.method="GET",t.requestBody=n,!0)}function u(t,e=!0){if("string"==typeof t)try{t=JSON.parse(t)}catch{t={}}let r=new URLSearchParams,i={};try{JSON.stringify(t,((t,e)=>(["object","function"].includes(typeof e)||r.set((t=>r.has(t)?(t in i||(i[t]=1),t+"."+ ++i[t]+"_"):t)(t),e),e)))}catch(t){if(!e)throw t}return r}function d(t,e=!0){return u(t,e).toString()}function f(e,i){if(!(this instanceof f))return new f(e,i);this.debug_rw=!1,this.$wbwindow=e,this.WBWindow=Window,this.URL=URL,this.origHost=e.location.host,this.origHostname=e.location.hostname,this.origProtocol=e.location.protocol,this.HTTP_PREFIX="http://",this.HTTPS_PREFIX="https://",this.REL_PREFIX="//",this.VALID_PREFIXES=[this.HTTP_PREFIX,this.HTTPS_PREFIX,this.REL_PREFIX],this.IGNORE_PREFIXES=["#","about:","data:","blob:","mailto:","javascript:","{","*"],"ignore_prefixes"in i&&(this.IGNORE_PREFIXES=this.IGNORE_PREFIXES.concat(i.ignore_prefixes)),this.WB_CHECK_THIS_FUNC="_____WB$wombat$check$this$function_____",this.WB_ASSIGN_FUNC="_____WB$wombat$assign$function_____",this.SKIP_OWN_FUNC_PROPS=["name","length","__WB_is_native_func__","arguments","caller","callee","prototype"],this.wb_setAttribute=e.Element.prototype.setAttribute,this.wb_getAttribute=e.Element.prototype.getAttribute,this.wb_funToString=Function.prototype.toString,this.WBAutoFetchWorker=null,this.wbUseAFWorker=i.enable_auto_fetch&&null!=e.Worker&&i.is_live,this.wb_rel_prefix="",this.wb_wombat_updating=!1,this.message_listeners=new t,this.storage_listeners=new t,this.linkAsTypes={script:"js_",worker:"js_",style:"cs_",image:"im_",document:"if_",fetch:"mp_",font:"oe_",audio:"oe_",video:"oe_",embed:"oe_",object:"oe_",track:"oe_","":"mp_",null:"mp_",undefined:"mp_"},this.linkTagMods={linkRelToAs:{import:this.linkAsTypes,preload:this.linkAsTypes},stylesheet:"cs_",null:"mp_",undefined:"mp_","":"mp_"},this.tagToMod={A:{href:"mp_"},AREA:{href:"mp_"},AUDIO:{src:"oe_",poster:"im_"},BASE:{href:"mp_"},EMBED:{src:"oe_"},FORM:{action:"mp_"},FRAME:{src:"fr_"},IFRAME:{src:"if_"},IMAGE:{href:"im_","xlink:href":"im_"},IMG:{src:"im_",srcset:"im_"},INPUT:{src:"oe_"},INS:{cite:"mp_"},META:{content:"mp_"},OBJECT:{data:"oe_",codebase:"oe_"},Q:{cite:"mp_"},SCRIPT:{src:"js_","xlink:href":"js_"},SOURCE:{src:"oe_",srcset:"oe_"},TRACK:{src:"oe_"},VIDEO:{src:"oe_",poster:"im_"},image:{href:"im_","xlink:href":"im_"}},this.URL_PROPS=["href","hash","pathname","host","hostname","protocol","origin","search","port"],this.wb_info=i,this.wb_opts=i.wombat_opts,this.wb_replay_prefix=i.prefix,this.wb_is_proxy=this.wb_info.proxy_magic||!this.wb_replay_prefix,this.wb_info.top_host=this.wb_info.top_host||"*",this.wb_curr_host=e.location.protocol+"//"+e.location.host,this.wb_info.wombat_opts=this.wb_info.wombat_opts||{},this.wb_orig_scheme=this.wb_info.wombat_scheme+"://",this.wb_orig_origin=this.wb_orig_scheme+this.wb_info.wombat_host,this.wb_abs_prefix=this.wb_replay_prefix,this.wb_capture_date_part="",!this.wb_info.is_live&&this.wb_info.wombat_ts&&(this.wb_capture_date_part="/"+this.wb_info.wombat_ts+"/"),this.BAD_PREFIXES=["http:"+this.wb_replay_prefix,"https:"+this.wb_replay_prefix,"http:/"+this.wb_replay_prefix,"https:/"+this.wb_replay_prefix],this.hostnamePortRe=/^[\\w-]+(\\.[\\w-_]+)+(:\\d+)(\\/|$)/,this.ipPortRe=/^\\d+\\.\\d+\\.\\d+\\.\\d+(:\\d+)?(\\/|$)/,this.workerBlobRe=/__WB_pmw\\(.*?\\)\\.(?=postMessage\\()/g,this.rmCheckThisInjectRe=/_____WB\\$wombat\\$check\\$this\\$function_____\\(.*?\\)/g,this.STYLE_REGEX=/(url\\s*\\(\\s*[\\\\"\']*)([^)\'"]+)([\\\\"\']*\\s*\\))/gi,this.IMPORT_REGEX=/(@import\\s*[\\\\"\']*)([^)\'";]+)([\\\\"\']*\\s*;?)/gi,this.IMPORT_JS_REGEX=/^(import\\s*\\([\'"]+)([^\'"]+)(["\'])/i,this.no_wombatRe=/WB_wombat_/g,this.srcsetRe=/\\s*(\\S*\\s+[\\d.]+[wx]),|(?:\\s*,(?:\\s+|(?=https?:)))/,this.cookie_path_regex=/\\bPath=\'?"?([^;\'"\\s]+)/i,this.cookie_domain_regex=/\\bDomain=([^;\'"\\s]+)/i,this.cookie_expires_regex=/\\bExpires=([^;\'"]+)/gi,this.SetCookieRe=/,(?![|])/,this.IP_RX=/^(\\d)+\\.(\\d)+\\.(\\d)+\\.(\\d)+$/,this.FullHTMLRegex=/^\\s*<(?:html|head|body|!doctype html)/i,this.IsTagRegex=/^\\s*0&&e.preserveMedia(r)}))},h.prototype.terminate=function(){this.worker.terminate()},h.prototype.justFetch=function(t){this.worker.postMessage({type:"fetch-all",values:t})},h.prototype.fetchAsPage=function(t,e,r){if(t){var i={"X-Wombat-History-Page":e};if(r){var o=encodeURIComponent(r.trim());r&&(i["X-Wombat-History-Title"]=o)}var n={url:t,options:{headers:i,cache:"no-store"}};this.justFetch([n])}},h.prototype.postMessage=function(t,e){if(e){var r=this;Promise.resolve().then((function(){r.worker.postMessage(t)}))}else this.worker.postMessage(t)},h.prototype.preserveSrcset=function(t,e){this.postMessage({type:"values",srcset:{value:t,mod:e,presplit:!0}},!0)},h.prototype.preserveDataSrcset=function(t){this.postMessage({type:"values",srcset:{value:t.dataset.srcset,mod:this.rwMod(t),presplit:!1}},!0)},h.prototype.preserveMedia=function(t){this.postMessage({type:"values",media:t},!0)},h.prototype.getSrcset=function(t){return this.wombat.wb_getAttribute?this.wombat.wb_getAttribute.call(t,"srcset"):t.getAttribute("srcset")},h.prototype.rwMod=function(t){switch(t.tagName){case"SOURCE":return t.parentElement&&"PICTURE"===t.parentElement.tagName?"im_":"oe_";case"IMG":return"im_"}return"oe_"},h.prototype.extractFromLocalDoc=function(){var t=this;Promise.resolve().then((function(){for(var e={type:"values",context:{docBaseURI:document.baseURI}},r=[],i=0,o=document.styleSheets;i=0||t.indexOf("ecmascript")>=0)&&(t.indexOf("json")>=0||t.indexOf("text/")>=0))},f.prototype.skipWrapScriptTextBasedOnText=function(t){if(!t||t.indexOf(this.WB_ASSIGN_FUNC)>=0||0===t.indexOf("<"))return!0;for(var e=["window","self","document","location","top","parent","frames","opener"],r=0;r=0)return!1;return!0},f.prototype.nodeHasChildren=function(t){if(!t)return!1;if("function"==typeof t.hasChildNodes)return t.hasChildNodes();var e=t.children||t.childNodes;return!!e&&e.length>0},f.prototype.rwModForElement=function(t,e){if(t){var r="mp_";if("LINK"===t.tagName&&"href"===e){if(t.rel){var i=t.rel.trim().toLowerCase(),o=this.wb_getAttribute.call(t,"as");if(o&&null!=this.linkTagMods.linkRelToAs[i])r=this.linkTagMods.linkRelToAs[i][o.toLowerCase()];else null!=this.linkTagMods[i]&&(r=this.linkTagMods[i])}}else{if("SCRIPT"===t.tagName)return"module"===t.type?"esm_":"js_";var n=this.tagToMod[t.tagName];null!=n&&(r=n[e])}return r}},f.prototype.removeWBOSRC=function(t){"SCRIPT"!==t.tagName||t.__$removedWBOSRC$__||(t.hasAttribute("__wb_orig_src")&&t.removeAttribute("__wb_orig_src"),t.__$removedWBOSRC$__=!0)},f.prototype.retrieveWBOSRC=function(t){var e;if("SCRIPT"===t.tagName&&!t.__$removedWBOSRC$__)return null==(e=this.wb_getAttribute?this.wb_getAttribute.call(t,"__wb_orig_src"):t.getAttribute("__wb_orig_src"))&&(t.__$removedWBOSRC$__=!0),e},f.prototype.wrapScriptTextJsProxy=function(t){return\'var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };\\nif (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }\\n{\\nlet window = _____WB$wombat$assign$function_____("window");\\nlet globalThis = _____WB$wombat$assign$function_____("globalThis");\\nlet self = _____WB$wombat$assign$function_____("self");\\nlet document = _____WB$wombat$assign$function_____("document");\\nlet location = _____WB$wombat$assign$function_____("location");\\nlet top = _____WB$wombat$assign$function_____("top");\\nlet parent = _____WB$wombat$assign$function_____("parent");\\nlet frames = _____WB$wombat$assign$function_____("frames");\\nlet opener = _____WB$wombat$assign$function_____("opener");\\n{\\n\'+t.replace(this.DotPostMessageRe,".__WB_pmw(self.window)$1")+"\\n\\n}}"},f.prototype.watchElem=function(t,e){if(!this.$wbwindow.MutationObserver)return!1;new this.$wbwindow.MutationObserver((function(t,r){for(var i=0;i"},f.prototype.getFinalUrl=function(t,e,r){var i=t?this.wb_rel_prefix:this.wb_abs_prefix;return null==e&&(e=this.wb_info.mod),this.wb_info.is_live||(i+=this.wb_info.wombat_ts),"/"!==(i+=e)[i.length-1]&&(i+="/"),i+r},f.prototype.resolveRelUrl=function(t,e){var r=this;function i(t){return!(!t||!t.baseURI)&&(t.baseURI.startsWith(r.HTTPS_PREFIX)||t.baseURI.startsWith(r.HTTP_PREFIX))}var o=null;return o=i(e)?e.baseURI:i(this.$wbwindow.document)?this.$wbwindow.document.baseURI:this.$wbwindow.__WB_replay_top.document.baseURI,new this.URL(t,o).href},f.prototype.extractOriginalURL=function(t){if(!t)return"";if(this.wb_is_proxy)return t;var e,r=t.toString(),i=r;if(this.startsWithOneOf(i,this.IGNORE_PREFIXES))return i;if(i.startsWith(this.wb_info.static_prefix))return i;e=this.startsWith(i,this.wb_abs_prefix)?this.wb_abs_prefix.length:this.wb_rel_prefix&&this.startsWith(i,this.wb_rel_prefix)?this.wb_rel_prefix.length:this.wb_rel_prefix?1:0;var o=i.indexOf("/http",e);return o<0&&(o=i.indexOf("///",e)),o<0&&(o=i.indexOf("/blob:",e)),o<0&&(o=i.indexOf("/about:blank",e)),o>=0?i=i.substr(o+1):((o=i.indexOf(this.wb_replay_prefix))>=0&&(i=i.substr(o+this.wb_replay_prefix.length)),i.length>4&&"_"===i.charAt(2)&&"/"===i.charAt(3)&&(i=i.substr(4)),i===r||this.startsWithOneOf(i,this.VALID_PREFIXES)||this.startsWith(i,"blob:")||(i=this.wb_orig_scheme+i)),"/"===r.charAt(0)&&"/"!==r.charAt(1)&&this.startsWith(i,this.wb_orig_origin)&&(i=i.substr(this.wb_orig_origin.length)),this.startsWith(i,this.REL_PREFIX)?this.wb_info.wombat_scheme+":"+i:i},f.prototype.makeParser=function(t,e){var r=this.extractOriginalURL(t),i=e;return e||(i="about:blank"===this.$wbwindow.location.href&&this.$wbwindow.opener?this.$wbwindow.opener.document:this.$wbwindow.document),this._makeURLParser(r,i)},f.prototype._makeURLParser=function(t,e){try{return new this.URL(t,e.baseURI)}catch(t){}var r=e.createElement("a");return r._no_rewrite=!0,r.href=t,r},f.prototype.defProp=function(t,e,r,i,o){var n=Object.getOwnPropertyDescriptor(t,e);if(n&&!n.configurable)return!1;if(!i)return!1;var s={configurable:!0,enumerable:o||!1,get:i};r&&(s.set=r);try{return Object.defineProperty(t,e,s),!0}catch(t){return console.warn("Failed to redefine property %s",e,t.message),!1}},f.prototype.defGetterProp=function(t,e,r,i){var o=Object.getOwnPropertyDescriptor(t,e);if(o&&!o.configurable)return!1;if(!r)return!1;try{return Object.defineProperty(t,e,{configurable:!0,enumerable:i||!1,get:r}),!0}catch(t){return console.warn("Failed to redefine property %s",e,t.message),!1}},f.prototype.getOrigGetter=function(t,e){var r;if(t.__lookupGetter__&&(r=t.__lookupGetter__(e)),!r&&Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(t,e);i&&(r=i.get)}return r},f.prototype.getOrigSetter=function(t,e){var r;if(t.__lookupSetter__&&(r=t.__lookupSetter__(e)),!r&&Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(t,e);i&&(r=i.set)}return r},f.prototype.getAllOwnProps=function(t){for(var e=[],r=Object.getOwnPropertyNames(t),i=0;i "+n),r.href=n}}},f.prototype.checkLocationChange=function(t,e){var r=typeof t,i=e?this.$wbwindow.__WB_replay_top.location:this.$wbwindow.location;"string"===r?this.updateLocation(t,i.href,i):"object"===r&&this.updateLocation(t.href,t._orig_href,i)},f.prototype.checkAllLocations=function(){if(this.wb_wombat_updating)return!1;this.wb_wombat_updating=!0,this.checkLocationChange(this.$wbwindow.WB_wombat_location,!1),this.$wbwindow.WB_wombat_location!=this.$wbwindow.__WB_replay_top.WB_wombat_location&&this.checkLocationChange(this.$wbwindow.__WB_replay_top.WB_wombat_location,!0),this.wb_wombat_updating=!1},f.prototype.proxyToObj=function(t){if(t)try{var e=t.__WBProxyRealObj__;if(e)return e}catch(t){}return t},f.prototype.objToProxy=function(t){if(t)try{var e=t._WB_wombat_obj_proxy;if(e)return e}catch(t){}return t},f.prototype.defaultProxyGet=function(t,e,r,i){switch(e){case"__WBProxyRealObj__":return t;case"location":case"WB_wombat_location":return t.WB_wombat_location;case"_WB_wombat_obj_proxy":return t._WB_wombat_obj_proxy;case"__WB_pmw":case this.WB_ASSIGN_FUNC:case this.WB_CHECK_THIS_FUNC:return t[e];case"origin":return t.WB_wombat_location.origin;case"constructor":return t.constructor}var o=Reflect.get(t,e),n=typeof o;if("string"===n&&o){var s=parseInt(e);if(o&&!isNaN(s))try{return this.initNewWindowWombat(o),o._WB_wombat_obj_proxy}catch(t){}}else{if("function"===n&&-1!==r.indexOf(e)){switch(e){case"requestAnimationFrame":case"cancelAnimationFrame":if(!this.isNativeFunction(o))return o;break;case"eval":if(this.isNativeFunction(o))return this.wrappedEval(o)}var a=i[e];if(!a||a.original!==o){const r=o.bind(t);for(const t of Object.getOwnPropertyNames(o))if(!this.SKIP_OWN_FUNC_PROPS.includes(t))try{r[t]=o[t]}catch(t){}return i[e]={original:o,boundFn:r},r}return a.boundFn}if("object"===n&&o&&o._WB_wombat_obj_proxy)return o instanceof this.WBWindow&&this.initNewWindowWombat(o),o._WB_wombat_obj_proxy}return o},f.prototype.setLoc=function(t,e){var r=this.makeParser(e,t.ownerDocument);t._orig_href=e,t._parser=r;var i=r.href;t._hash=r.hash,t._href=i,t._host=r.host,t._hostname=r.hostname,r.origin?t._origin=r.host?r.origin:"null":t._origin=r.protocol+"//"+r.hostname+(r.port?":"+r.port:""),t._pathname=r.pathname,t._port=r.port,t._protocol=r.protocol,t._search=r.search,Object.defineProperty||(t.href=i,t.hash=r.hash,t.host=t._host,t.hostname=t._hostname,t.origin=t._origin,t.pathname=t._pathname,t.port=t._port,t.protocol=t._protocol,t.search=t._search)},f.prototype.makeGetLocProp=function(t,e){var r=this;return function(){if(this._no_rewrite)return e.call(this,t);var i=e.call(this,"href");return"href"===t?r.extractOriginalURL(i):"ancestorOrigins"===t?[]:(this._orig_href!==i&&r.setLoc(this,i),this["_"+t])}},f.prototype.makeSetLocProp=function(t,e,r){var i=this;return function(o){if(this._no_rewrite)return e.call(this,t,o);if(this["_"+t]!==o){this["_"+t]=o;var n=r.call(this),s=i.makeParser(n,this.ownerDocument),a=!1;if("href"===t&&"string"==typeof o)if(o&&s instanceof i.URL)try{o=new i.URL(o,s).href}catch(t){console.warn("Error resolving URL",t)}else o&&("."===o[0]||"#"===o[0]?o=i.resolveRelUrl(o,this.ownerDocument):"/"===o[0]&&(o.length>1&&"/"===o[1]?o=s.protocol+o:(a=!0,o=WB_wombat_location.origin+o)));try{s[t]=o}catch(e){console.log("Error setting "+t+" = "+o)}"hash"===t?(o=s[t],e.call(this,"hash",o)):(a=a||o===s.pathname,o=i.rewriteUrl(s.href,a),e.call(this,"href",o))}}},f.prototype.styleReplacer=function(t,e,r,i,o,n){return e+this.rewriteUrl(r)+i},f.prototype.domConstructorErrorChecker=function(t,e,r,i){var o,n="number"==typeof i?i:1;if(t instanceof this.WBWindow?o="Failed to construct \'"+e+"\': Please use the \'new\' operator, this DOM object constructor cannot be called as a function.":r&&r.length=0)return o;if(0===o.indexOf(this.wb_rel_prefix)&&o.indexOf("http")>1){var a=o.indexOf(":/");return a>0&&"/"!==o[a+2]?o.substring(0,a+2)+"/"+o.substring(a+2):o}return this.getFinalUrl(!0,r,this.wb_orig_origin+o)}"."===o.charAt(0)&&(o=this.resolveRelUrl(o,i));var w=this.startsWithOneOf(o.toLowerCase(),this.VALID_PREFIXES);if(w){var h=this.replayTopHost,p=this.replayTopProtocol,c=w+h+"/";if(this.startsWith(o,c)){if(this.startsWith(o,this.wb_replay_prefix))return o;var l=p+"//",_=o.substring(c.length),u=!1;return _.indexOf(this.wb_rel_prefix)<0&&o.indexOf("/static/")<0&&(_=this.getFinalUrl(!0,r,WB_wombat_location.origin+"/"+_),u=!0),w!==l&&w!==this.REL_PREFIX&&(u=!0),u&&(o=e?"":l+h,_&&"/"!==_[0]&&(o+="/"),o+=_),o}return this.getFinalUrl(e,r,o)}return(w=this.startsWithOneOf(o,this.BAD_PREFIXES))?this.getFinalUrl(e,r,this.extractOriginalURL(o)):o},f.prototype.rewriteUrl=function(t,e,r,i){var o;return o=this.wb_info.rewrite_function?this.wb_info.rewrite_function(t,e,r,i):this.rewriteUrl_(t,e,r,i),this.debug_rw&&(t!==o?console.log("REWRITE: "+t+" -> "+o):console.log("NOT REWRITTEN "+t)),o},f.prototype.performAttributeRewrite=function(t,e,r,i){switch(e){case"innerHTML":case"outerHTML":return this.rewriteHtml(r);case"filter":return this.rewriteInlineStyle(r);case"style":return this.rewriteStyle(r);case"srcset":return this.rewriteSrcset(r,t)}if(i&&!this.startsWithOneOf(r,this.VALID_PREFIXES))return r;var o=this.rwModForElement(t,e);this.wbUseAFWorker&&this.WBAutoFetchWorker&&this.isSavedDataSrcSrcset(t)&&this.WBAutoFetchWorker.preserveDataSrcset(t);var n=this.rewriteUrl(r,!1,o,t.ownerDocument);return"esm_"===o&&n&&n.indexOf("esm_/")<0&&(n=n.replace(/(\\/[\\d]*)([\\w]+_)(?=\\/)/,"$1esm_")),n},f.prototype.rewriteAttr=function(t,e,r){var i=!1;if(!t||!t.getAttribute||t._no_rewrite||t["_"+e]||t.tagName&&t.tagName.indexOf("-")>0)return i;var o=this.wb_getAttribute.call(this.proxyToObj(t),e);if(!o||this.startsWith(o,"javascript:"))return i;var n=this.performAttributeRewrite(t,e,o,r);return n!==o&&(this.removeWBOSRC(t),this.wb_setAttribute.call(t,e,n),i=!0),i},f.prototype.noExceptRewriteStyle=function(t){try{return this.rewriteStyle(t)}catch(e){return t}},f.prototype.rewriteStyle=function(t){if(!t)return t;var e=t;return"object"==typeof t&&(e=t.toString()),"string"==typeof e?e.replace(this.STYLE_REGEX,this.styleReplacer).replace(this.IMPORT_REGEX,this.styleReplacer).replace(this.no_wombatRe,""):e},f.prototype.rewriteSrcset=function(t,e){if(!t)return"";for(var r=t.split(this.srcsetRe),i=[],o=this.rwModForElement(e,"srcset"),n=0;n=0){var o="javascript:";r=o+"window.parent._wb_wombat.initNewWindowWombat(window);"+i.substr(o.length)}return r||(r=this.rewriteUrl(i,!1,this.rwModForElement(t,e))),r!==i&&(this.wb_setAttribute.call(t,e,r),!0)},f.prototype.rewriteScript=function(t){if(t.hasAttribute("src")||!t.textContent||!this.$wbwindow.Proxy)return this.rewriteAttr(t,"src");if(this.skipWrapScriptBasedOnType(t.type))return!1;var e=t.textContent.trim();return!this.skipWrapScriptTextBasedOnText(e)&&(t.textContent=this.wrapScriptTextJsProxy(e),this.wb_info.injectDocClose&&t.textContent.trim().length&&(t.textContent+=";document.close();"),!0)},f.prototype.rewriteSVGElem=function(t){var e=this.rewriteAttr(t,"filter");return e=this.rewriteAttr(t,"style")||e,e=this.rewriteAttr(t,"xlink:href")||e,e=this.rewriteAttr(t,"href")||e,e=this.rewriteAttr(t,"src")||e},f.prototype.rewriteElem=function(t){var e=!1;if(!t)return e;if(t instanceof SVGElement)e=this.rewriteSVGElem(t);else switch(t.tagName){case"META":var r=this.wb_getAttribute.call(t,"http-equiv");r&&"content-security-policy"===r.toLowerCase()&&(this.wb_setAttribute.call(t,"http-equiv","_"+r),e=!0);break;case"STYLE":var i=this.rewriteStyle(t.textContent);t.textContent!==i&&(t.textContent=i,e=!0,this.wbUseAFWorker&&this.WBAutoFetchWorker&&null!=t.sheet&&this.WBAutoFetchWorker.deferredSheetExtraction(t.sheet));break;case"LINK":e=this.rewriteAttr(t,"href"),this.wbUseAFWorker&&"stylesheet"===t.rel&&this._addEventListener(t,"load",this.utilFns.wbSheetMediaQChecker);break;case"IMG":e=this.rewriteAttr(t,"src"),e=this.rewriteAttr(t,"srcset")||e,e=this.rewriteAttr(t,"style")||e,this.wbUseAFWorker&&this.WBAutoFetchWorker&&t.dataset.srcset&&this.WBAutoFetchWorker.preserveDataSrcset(t);break;case"OBJECT":if(this.wb_info.isSW&&t.parentElement){var o;"application/pdf"===t.getAttribute("type")?o="IFRAME":"image/svg+xml"===t.getAttribute("type")&&(o="IMG");for(var n=this.$wbwindow.document.createElement(o),s=0;s0;)for(var i=r.shift(),o=0;o=0&&(r=r.replace(/((id|class)=".*)WB_wombat_([^"]+)/,"$1$3")),!this.$wbwindow.HTMLTemplateElement||this.FullHTMLRegex.test(r))return this.rewriteHtmlFull(r,e);var i=(new DOMParser).parseFromString("","text/html");if(!i||!this.nodeHasChildren(i.head)||!i.head.children[0].content)return r;var o=i.head.children[0];if(o._no_rewrite=!0,this.recurseRewriteElem(o.content)){var n=o.innerHTML;if(e){var s=o.content.children&&o.content.children[0];if(s){var a="";if(this.endsWith(n,a)&&!this.endsWith(r.toLowerCase(),a))n=n.substring(0,n.length-a.length);else if(n.trimEnd().endsWith(a)&&!r.trimEnd().endsWith(a)){var w=r.lastIndexOf(a);w>0&&(n+=r.slice(w+a.length))}}else if("<"!==r[0]||">"!==r[r.length-1])return void(this.write_buff+=r)}return n}return r},f.prototype.rewriteHtmlFull=function(t,e){var r=(new DOMParser).parseFromString(t,"text/html");if(!r)return t;for(var i=!1,o=0;o=0)r.documentElement._no_rewrite=!0,n=this.reconstructDocType(r.doctype)+r.documentElement.outerHTML;else{r.head._no_rewrite=!0,r.body._no_rewrite=!0;var s=this.nodeHasChildren(r.head),a=this.nodeHasChildren(r.body);if(n=(s?r.head.outerHTML:"")+(a?r.body.outerHTML:""),e)if(r.all.length>3){var w="";this.endsWith(n,w)&&!this.endsWith(t.toLowerCase(),w)&&(n=n.substring(0,n.length-w.length))}else if("<"!==t[0]||">"!==t[t.length-1])return void(this.write_buff+=t);n=this.reconstructDocType(r.doctype)+n}return n}return t},f.prototype.rewriteInlineStyle=function(t){var e;try{e=decodeURIComponent(t)}catch(r){e=t}if(e!==t){var r=this.rewriteStyle(e).split(",",2);return r[0]+","+encodeURIComponent(r[1])}return this.rewriteStyle(t)},f.prototype.rewriteCookie=function(t){var e=this,r=t.replace(this.wb_abs_prefix,"").replace(this.wb_rel_prefix,"");return r=r.replace(this.cookie_domain_regex,(function(t,i){var o={domain:i,cookie:r,wb_type:"cookie"};return e.sendTopMessage(o,!0),e.$wbwindow.location.hostname.indexOf(".")>=0&&!e.IP_RX.test(e.$wbwindow.location.hostname)?"Domain=."+e.$wbwindow.location.hostname:""})).replace(this.cookie_path_regex,(function(t,r){var i=e.rewriteUrl(r);return 0===i.indexOf(e.wb_curr_host)&&(i=i.substring(e.wb_curr_host.length)),"Path="+i})),"https:"!==e.$wbwindow.location.protocol&&(r=r.replace("secure","")),r.replace(",|",",")},f.prototype.rewriteWorker=function(t){if(!t)return t;var e=0===(t=t.toString()).indexOf("blob:"),r=0===t.indexOf("javascript:");if(!e&&!r){if(!this.startsWithOneOf(t,this.VALID_PREFIXES)&&!this.startsWith(t,"/")&&!this.startsWithOneOf(t,this.BAD_PREFIXES)){var i=this.resolveRelUrl(t,this.$wbwindow.document);return this.rewriteUrl(i,!1,"wkr_",this.$wbwindow.document)}return this.rewriteUrl(t,!1,"wkr_",this.$wbwindow.document)}var o=r?t.replace("javascript:",""):null;if(e){var n=new XMLHttpRequest;this.utilFns.XHRopen.call(n,"GET",t,!1),this.utilFns.XHRsend.call(n),o=n.responseText.replace(this.workerBlobRe,"").replace(this.rmCheckThisInjectRe,"this")}if(this.wb_info.static_prefix||this.wb_info.ww_rw_script){var s=this.$wbwindow.document.baseURI;o="(function() { self.importScripts(\'"+(this.wb_info.ww_rw_script||this.wb_info.static_prefix+"wombatWorkers.js")+"\'); new WBWombat({\'prefix\': \'"+this.wb_abs_prefix+"\', \'prefixMod\': \'"+this.wb_abs_prefix+"wkrf_/\', \'originalURL\': "+JSON.stringify(s)+"}); })();"+o}var a=new Blob([o],{type:"application/javascript"});return this.URL.createObjectURL(a)},f.prototype.rewriteTextNodeFn=function(t,e,r){var i,o=this.proxyToObj(t);if(r.length>0&&o.parentElement&&"STYLE"===o.parentElement.tagName){i=new Array(r.length);var n=r.length-1;2===n?(i[0]=r[0],i[1]=r[1]):1===n&&(i[0]=r[0]),i[n]=this.rewriteStyle(r[n])}else i=r;return e.__WB_orig_apply?e.__WB_orig_apply(o,i):e.apply(o,i)},f.prototype.rewriteChildNodeFn=function(t,e,r){var i=this.proxyToObj(t);if(0===r.length)return e.call(i);var o=this.rewriteElementsInArguments(r);return e.__WB_orig_apply?e.__WB_orig_apply(i,o):e.apply(i,o)},f.prototype.rewriteInsertAdjHTMLOrElemArgs=function(t,e,r,i,o){var n=this.proxyToObj(t);return n._no_rewrite?e.call(n,r,i):o?e.call(n,r,this.rewriteHtml(i)):(this.rewriteElemComplete(i),e.call(n,r,i))},f.prototype.rewriteSetTimeoutInterval=function(t,e,r){var i=this.isString(r[0]),o=i?new Array(r.length):r;if(i){this.$wbwindow.Proxy?o[0]=this.wrapScriptTextJsProxy(r[0]):o[0]=r[0].replace(/\\blocation\\b/g,"WB_wombat_$&");for(var n=1;n(t.includes(r)&&(i=o.rewriteStyle(i)),e[r]=i,!0),get(t,i,n){var s=t[i];return"function"!=typeof s||"setProperty"!==i&&!o.isNativeFunction(s)?s:(r[i]||(r[i]=s.bind(e)),r[i])}})}))},f.prototype.overrideIframeContentAccess=function(t){if(this.$wbwindow.HTMLIFrameElement&&this.$wbwindow.HTMLIFrameElement.prototype){var e=this.$wbwindow.HTMLIFrameElement.prototype,r=this.getOrigGetter(e,t);if(r){var i=this.getOrigSetter(e,t),o=this;this.defProp(e,t,i,(function(){return o.initIframeWombat(this),o.objToProxy(r.call(this))})),e["_get_"+t]=r}}},f.prototype.overrideSWAccess=function(t){if(t.navigator.serviceWorker&&t.navigator.serviceWorker.controller){t._WB_wombat_sw=t.navigator.serviceWorker;var e={controller:null,ready:Promise.resolve({unregister:function(){}}),register:function(){return Promise.reject()},addEventListener:function(){},removeEventListener:function(){},onmessage:null,oncontrollerchange:null,getRegistrations:function(){return Promise.resolve([])},getRegistration:function(){return Promise.resolve(void 0)},startMessages:function(){}};this.defGetterProp(t.navigator,"serviceWorker",(function(){return e}))}},f.prototype.overrideFuncThisProxyToObj=function(t,e,r){if(t){var i=r;if(!r&&t.prototype&&t.prototype[e]?i=t.prototype:!r&&t[e]&&(i=t),i){var o=this,n=i[e];i[e]=function(){return n.apply(o.proxyToObj(this),arguments)}}}},f.prototype.overrideFuncArgProxyToObj=function(t,e,r){if(t&&t.prototype){var i=r||0,o=t.prototype[e];if(o){var n=this;t.prototype[e]=function(){for(var t=new Array(arguments.length),e=0;e0&&i(this.$wbwindow.CSSStyleValue,"parse"),this.$wbwindow.CSSStyleValue.parseAll&&this.$wbwindow.CSSStyleValue.parseAll.toString().indexOf("[native code]")>0&&i(this.$wbwindow.CSSStyleValue,"parseAll")}if(this.$wbwindow.CSSKeywordValue&&this.$wbwindow.CSSKeywordValue.prototype){var o=this.$wbwindow.CSSKeywordValue;this.$wbwindow.CSSKeywordValue=(t=this.$wbwindow.CSSKeywordValue,function(e){return r.domConstructorErrorChecker(this,"CSSKeywordValue",arguments),new t(r.rewriteStyle(e))}),this.$wbwindow.CSSKeywordValue.prototype=o.prototype,Object.defineProperty(this.$wbwindow.CSSKeywordValue.prototype,"constructor",{value:this.$wbwindow.CSSKeywordValue}),e(this.$wbwindow.CSSKeywordValue,"CSSKeywordValue")}if(this.$wbwindow.StylePropertyMap&&this.$wbwindow.StylePropertyMap.prototype){var n=this.$wbwindow.StylePropertyMap.prototype.set;this.$wbwindow.StylePropertyMap.prototype.set=function(){if(arguments.length<=1)return n.__WB_orig_apply?n.__WB_orig_apply(this,arguments):n.apply(this,arguments);var t=new Array(arguments.length);t[0]=arguments[0];for(var e=1;e")&&(e[0]=r.rewriteHtml(e[0]),i.type="text/html"),new t(e,i)}),this.$wbwindow.Blob.prototype=e.prototype}},f.prototype.initIntersectionObsOverride=function(){var t,e=this.$wbwindow.IntersectionObserver,r=this;this.$wbwindow.IntersectionObserver=(t=this.$wbwindow.IntersectionObserver,function(e,i){return i&&i.root&&(i.root=r.proxyToObj(i.root)),new t(e,i)}),this.$wbwindow.IntersectionObserver.prototype=e.prototype,Object.defineProperty(this.$wbwindow.IntersectionObserver.prototype,"constructor",{value:this.$wbwindow.IntersectionObserver})},f.prototype.initWSOverride=function(){this.$wbwindow.WebSocket&&this.$wbwindow.WebSocket.prototype&&(this.$wbwindow.WebSocket=function(t){function e(t,r){this.openCallbacks=[],this.addEventListener=function(t,r){"open"===t&&e.openCallbacks.push(r)},this.removeEventListener=function(){},this.close=function(){},this.send=function(t){console.log("ws send",t)},this.protocol=r&&r.length?r[0]:"",this.url=t,this.readyState=1;var i=this;setTimeout((function(){var t=new CustomEvent("open");i.onopen&&i.onopen(t),i.openCallbacks.forEach((e=>e(t)))}),500)}return e.CONNECTING=0,e.OPEN=1,e.CLOSING=2,e.CLOSED=3,e}(this.$wbwindow.WebSocket),Object.defineProperty(this.$wbwindow.WebSocket.prototype,"constructor",{value:this.$wbwindow.WebSocket}),e(this.$wbwindow.WebSocket,"WebSocket"))},f.prototype.initDocTitleOverride=function(){var t=this.getOrigGetter(this.$wbwindow.document,"title"),e=this.getOrigSetter(this.$wbwindow.document,"title"),r=this;this.defProp(this.$wbwindow.document,"title",(function(t){var i=e.call(this,t),o={wb_type:"title",title:t};return r.sendTopMessage(o),i}),t)},f.prototype.initFontFaceOverride=function(){if(this.$wbwindow.FontFace){var t,r=this,i=this.$wbwindow.FontFace;this.$wbwindow.FontFace=(t=this.$wbwindow.FontFace,function(e,i,o){r.domConstructorErrorChecker(this,"FontFace",arguments,2);var n=i;return null!=i&&(n="string"!=typeof i?r.rewriteInlineStyle(i.toString()):r.rewriteInlineStyle(i)),new t(e,n,o)}),this.$wbwindow.FontFace.prototype=i.prototype,Object.defineProperty(this.$wbwindow.FontFace.prototype,"constructor",{value:this.$wbwindow.FontFace}),e(this.$wbwindow.FontFace,"FontFace")}},f.prototype.initFixedRatio=function(t){try{this.$wbwindow.devicePixelRatio=t}catch(t){}if(Object.defineProperty)try{Object.defineProperty(this.$wbwindow,"devicePixelRatio",{value:t,writable:!1})}catch(t){}},f.prototype.initPaths=function(t){t.wombat_opts=t.wombat_opts||{},Object.assign(this.wb_info,t),this.wb_opts=t.wombat_opts,this.wb_replay_prefix=t.prefix,this.wb_is_proxy=t.proxy_magic||!this.wb_replay_prefix,this.wb_info.top_host=this.wb_info.top_host||"*",this.wb_curr_host=this.$wbwindow.location.protocol+"//"+this.$wbwindow.location.host,this.wb_info.wombat_opts=this.wb_info.wombat_opts||{},this.wb_orig_scheme=t.wombat_scheme+"://",this.wb_orig_origin=this.wb_orig_scheme+t.wombat_host,this.wb_abs_prefix=this.wb_replay_prefix,!t.is_live&&t.wombat_ts?this.wb_capture_date_part="/"+t.wombat_ts+"/":this.wb_capture_date_part="",this.initBadPrefixes(this.wb_replay_prefix),this.initCookiePreset()},f.prototype.initSeededRandom=function(t){this.$wbwindow.Math.seed=parseInt(t);var e=this;this.$wbwindow.Math.random=function(){return e.$wbwindow.Math.seed=(9301*e.$wbwindow.Math.seed+49297)%233280,e.$wbwindow.Math.seed/233280}},f.prototype.initHistoryOverrides=function(){this.overrideHistoryFunc("pushState"),this.overrideHistoryFunc("replaceState");var t=this;this.$wbwindow.addEventListener("popstate",(function(e){t.sendHistoryUpdate(t.$wbwindow.WB_wombat_location.href,t.$wbwindow.document.title)}))},f.prototype.initCookiePreset=function(){if(this.wb_info.presetCookie)for(var t=this.wb_info.presetCookie.split(";"),e=0;e2&&!this.__WB_xhr_open_arguments[2]&&-1===navigator.userAgent.indexOf("Firefox")&&(this.__WB_xhr_open_arguments[2]=!0,console.warn("wombat.js: Sync XHR not supported in SW-based replay in this browser, converted to async")),this._no_rewrite||(this.__WB_xhr_open_arguments[1]=i.rewriteUrl(this.__WB_xhr_open_arguments[1])),o.apply(this,this.__WB_xhr_open_arguments),!i.startsWith(this.__WB_xhr_open_arguments[1],"data:")){for(const[t,e]of this.__WB_xhr_headers.entries())n.call(this,t,e);n.call(this,"X-Pywb-Requested-With","XMLHttpRequest")}return s.call(this,t)}}else if(this.$wbwindow.XMLHttpRequest.prototype.open){var w=this.$wbwindow.XMLHttpRequest.prototype.open;this.utilFns.XHRopen=w,this.utilFns.XHRsend=this.$wbwindow.XMLHttpRequest.prototype.send,this.$wbwindow.XMLHttpRequest.prototype.open=function(t,e,r,o,n){var s=this._no_rewrite?e:i.rewriteUrl(e),a=!0;null==r||r||(a=!1),w.call(this,t,s,a,o,n),i.startsWith(s,"data:")||this.setRequestHeader("X-Pywb-Requested-With","XMLHttpRequest")}}if(this.$wbwindow.fetch){var h=this.$wbwindow.fetch;this.$wbwindow.fetch=function(t,e){var r;if(t instanceof Request){var o=i.rewriteUrl(t.url);t.__WB_no_unrewrite=!0,r=o===t.url?t:new Request(o,t),delete t.__WB_no_unrewrite}else t=i.rewriteUrl(t.toString()),r=new Request(t,e);return h.call(i.proxyToObj(this),r)}}if(this.$wbwindow.Request&&this.$wbwindow.Request.prototype){var p=this.$wbwindow.Request;this.$wbwindow.Request=(t=this.$wbwindow.Request,function e(r,o){i.domConstructorErrorChecker(this,"Request",arguments);var n=o||{},s=r,a=typeof r;switch(a){case"string":s=i.rewriteUrl(r);break;case"object":if(s=r,r.url){var w=i.rewriteUrl(r.url);w!==r.url&&(s=new t(w,r))}else r.href&&(s=i.rewriteUrl(r.toString(),!0))}let h=!1;if(n&&n.referrer){var p=i.rewriteUrl(n.referrer);p!==n.referrer&&(n instanceof e?(n.__WB_no_unrewrite=!0,h=!0):n.referrer=p)}var c=new t(s,n);return h&&delete n.__WB_no_unrewrite,c}),this.$wbwindow.Request.prototype=p.prototype,Object.defineProperty(this.$wbwindow.Request.prototype,"constructor",{value:this.$wbwindow.Request}),this.overridePropExtract(this.$wbwindow.Request.prototype,"url"),this.overridePropExtract(this.$wbwindow.Request.prototype,"referrer")}if(this.$wbwindow.Response&&this.$wbwindow.Response.prototype){var c=this.$wbwindow.Response.prototype.redirect;this.$wbwindow.Response.prototype.redirect=function(t,e){var r=i.rewriteUrl(t,!0,null,i.$wbwindow.document);return c.call(this,r,e)},this.overridePropExtract(this.$wbwindow.Response.prototype,"url")}if(this.$wbwindow.EventSource&&this.$wbwindow.EventSource.prototype){var l=this.$wbwindow.EventSource;this.$wbwindow.EventSource=(r=this.$wbwindow.EventSource,function(t,e){i.domConstructorErrorChecker(this,"EventSource",arguments);var o=t;return null!=t&&(o=i.rewriteUrl(t)),new r(o,e)}),this.$wbwindow.EventSource.prototype=l.prototype,Object.defineProperty(this.$wbwindow.EventSource.prototype,"constructor",{value:this.$wbwindow.EventSource}),e(this.$wbwindow.EventSource,"EventSource")}},f.prototype.initElementGetSetAttributeOverride=function(){if(!this.wb_opts.skip_setAttribute&&this.$wbwindow.Element&&this.$wbwindow.Element.prototype){var t=this,e=this.$wbwindow.Element.prototype;if(e.setAttribute){var r=e.setAttribute;e._orig_setAttribute=r,e.setAttribute=function(e,i){var o=i;if(e&&"string"==typeof o){var n=e.toLowerCase();if("LINK"===this.tagName&&"href"===n&&0===o.indexOf("data:text/css"))o=t.rewriteInlineStyle(i);else if("style"===n)o=t.rewriteStyle(i);else if("srcset"===n||"imagesrcset"===n&&"LINK"===this.tagName)o=t.rewriteSrcset(i,this);else{t.shouldRewriteAttr(this.tagName,n)&&(t.removeWBOSRC(this),this._no_rewrite||(o=t.rewriteUrl(i,!1,t.rwModForElement(this,n))))}}return r.call(this,e,o)}}if(e.getAttribute){var i=e.getAttribute;this.wb_getAttribute=i,e.getAttribute=function(e){var r=i.call(this,e);if(null===r)return r;var o=e;if(e&&(o=e.toLowerCase()),t.shouldRewriteAttr(this.tagName,o)){var n=t.retrieveWBOSRC(this);return n||t.extractOriginalURL(r)}return t.startsWith(o,"data-")&&t.startsWithOneOf(r,t.wb_prefixes)?t.extractOriginalURL(r):r}}}},f.prototype.initSvgImageOverrides=function(){if(this.$wbwindow.SVGImageElement){var t=this.$wbwindow.SVGImageElement.prototype,e=t.getAttribute,r=t.getAttributeNS,i=t.setAttribute,o=t.setAttributeNS,n=this;t.getAttribute=function(t){var r=e.call(this,t);return t.indexOf("xlink:href")>=0||"href"===t?n.extractOriginalURL(r):r},t.getAttributeNS=function(t,e){var i=r.call(this,t,e);return e.indexOf("xlink:href")>=0||"href"===e?n.extractOriginalURL(i):i},t.setAttribute=function(t,e){var r=e;return(t.indexOf("xlink:href")>=0||"href"===t)&&(r=n.rewriteUrl(e)),i.call(this,t,r)},t.setAttributeNS=function(t,e,r){var i=r;return(e.indexOf("xlink:href")>=0||"href"===e)&&(i=n.rewriteUrl(r)),o.call(this,t,e,i)}}},f.prototype.initCreateElementNSFix=function(){if(this.$wbwindow.document.createElementNS&&this.$wbwindow.Document.prototype.createElementNS){var t=this.$wbwindow.document.createElementNS,e=this,r=function(r,i){return t.call(e.proxyToObj(this),e.extractOriginalURL(r),i)};this.$wbwindow.Document.prototype.createElementNS=r,this.$wbwindow.document.createElementNS=r}},f.prototype.initQuerySelectorOverride=function(){if(this.$wbwindow.document.querySelector&&this.$wbwindow.Document.prototype.querySelector){var t=this,e=this.$wbwindow.document.querySelector,r=function(r){return e.call(t.proxyToObj(this),n(r))},i=this.$wbwindow.document.querySelectorAll,o=function(e){return i.call(t.proxyToObj(this),n(e))};this.$wbwindow.Document.prototype.querySelector=r,this.$wbwindow.document.querySelector=r,this.$wbwindow.Document.prototype.querySelectorAll=o,this.$wbwindow.document.querySelectorAll=o}function n(t){if("string"==typeof t)try{t=t.replace(/((?:^|\\s)\\b\\w+\\[(?:src|href|data-href))[\\^]?(=[\'"]?(?:https?[:])?\\/\\/)/,"$1*$2")}catch(t){}return t}},f.prototype.initInsertAdjacentElementHTMLOverrides=function(){var t=this.$wbwindow.Element;if(t&&t.prototype){var e=t.prototype,r=this.rewriteInsertAdjHTMLOrElemArgs;if(e.insertAdjacentHTML){var i=e.insertAdjacentHTML;e.insertAdjacentHTML=function(t,e){return r(this,i,t,e,!0)}}if(e.insertAdjacentElement){var o=e.insertAdjacentElement;e.insertAdjacentElement=function(t,e){return r(this,o,t,e,!1)}}}},f.prototype.initDomOverride=function(){var t=this.$wbwindow.Node;if(t&&t.prototype){var e=this.rewriteNodeFuncArgs;if(t.prototype.appendChild){var r=t.prototype.appendChild;t.prototype.appendChild=function(t,i){return e(this,r,t,i)}}if(t.prototype.insertBefore){var i=t.prototype.insertBefore;t.prototype.insertBefore=function(t,r){return e(this,i,t,r)}}if(t.prototype.replaceChild){var o=t.prototype.replaceChild;t.prototype.replaceChild=function(t,r){return e(this,o,t,r)}}this.overridePropToProxy(t.prototype,"ownerDocument"),this.overridePropToProxy(this.$wbwindow.HTMLHtmlElement.prototype,"parentNode"),this.overridePropToProxy(this.$wbwindow.Event.prototype,"target")}this.$wbwindow.Element&&this.$wbwindow.Element.prototype&&(this.overrideParentNodeAppendPrepend(this.$wbwindow.Element),this.overrideChildNodeInterface(this.$wbwindow.Element,!1)),this.$wbwindow.DocumentFragment&&this.$wbwindow.DocumentFragment.prototype&&this.overrideParentNodeAppendPrepend(this.$wbwindow.DocumentFragment)},f.prototype.initDocOverrides=function(t){if(Object.defineProperty){this.overrideReferrer(t),this.defGetterProp(t,"origin",(function(){return this.WB_wombat_location.origin})),this.defGetterProp(this.$wbwindow,"origin",(function(){return this.WB_wombat_location.origin}));var e=this;this.defProp(t,"domain",(function(t){var r=this.WB_wombat_location;r&&e.endsWith(r.hostname,t)&&(this.__wb_domain=t)}),(function(){return this.__wb_domain||this.WB_wombat_location.hostname}))}},f.prototype.initDocWriteOpenCloseOverride=function(){if(this.$wbwindow.DOMParser){var t=this.$wbwindow.Document.prototype,e=this.$wbwindow.document;this._writeBuff="";var r=this,i=e.write,o=function(){return d(this,i,u(arguments))};e.write=o,t.write=o;var n=e.writeln,s=function(){return d(this,n,u(arguments))};e.writeln=s,t.writeln=s;var a=e.open,w=function(){var t,e=r.proxyToObj(this);if(3===arguments.length){var i=r.rewriteUrl(arguments[0],!1,"mp_");t=a.call(e,i,arguments[1],arguments[2]),r.initNewWindowWombat(t,arguments[0])}else t=a.call(e),_()?r._writeBuff="":r.initNewWindowWombat(e.defaultView);return t};e.open=w,t.open=w;var h=e.close,p=function(){if(!r._writeBuff){var t=r.proxyToObj(this);return r.initNewWindowWombat(t.defaultView),h.__WB_orig_apply?h.__WB_orig_apply(t,arguments):h.apply(t,arguments)}if("loading"===this.readyState&&i.call(e,r.rewriteHtml(r._writeBuff,!0)),_()){r.blobUrlForIframe(r.$wbwindow.frameElement,r._writeBuff);const t=this;try{if(t.documentElement){new r.$wbwindow.MutationObserver(((e,i)=>{r.blobUrlForIframe(r.$wbwindow.frameElement,t.documentElement.outerHTML)})).observe(t.documentElement,{childList:!0,subtree:!0})}}catch(t){}}r._writeBuff=""};e.close=p,t.close=p;var c=this.getOrigGetter(t,"body"),l=this.getOrigSetter(t,"body");c&&l&&this.defProp(t,"body",(function(t){return t&&(t instanceof HTMLBodyElement||t instanceof HTMLFrameSetElement)&&r.rewriteElemComplete(t),l.call(r.proxyToObj(this),t)}),c)}function _(){return r.wb_info.isSW&&r.$wbwindow.frameElement}function u(t){return 0===t.length?"":1===t.length?t[0]:Array.prototype.join.call(t,"")}function d(t,e,i){r.$wbwindow;if(!(_()||"loading"===t.readyState&&r.wb_info.injectDocClose)){i=r.rewriteHtml(i,!0);var o=r.proxyToObj(t),n=e.call(o,i);return r.initNewWindowWombat(o.defaultView),n}r._writeBuff+=i}},f.prototype.initIframeWombat=function(t){var e;e=t._get_contentWindow?t._get_contentWindow.call(t):t.contentWindow;try{if(!e||e===this.$wbwindow||e._skip_wombat||e._wb_wombat)return}catch(t){return}var r=t.src;this.initNewWindowWombat(e,r)},f.prototype.initNewWindowWombat=function(t,e){var r=!1;if(t&&!t._wb_wombat){if(e&&""!==e&&!this.startsWithOneOf(e,["about:blank","javascript:"])||(r=!0),!r&&this.wb_info.isSW){var i=this.extractOriginalURL(e);("about:blank"===i||i.startsWith("srcdoc:")||i.startsWith("blob:"))&&(r=!0)}if(r){var o={};Object.assign(o,this.wb_info);var n=new f(t,o);t._wb_wombat=n.wombatInit()}else this.initProtoPmOrigin(t),this.initPostMessageOverride(t),this.initMessageEventOverride(t),this.initCheckThisFunc(t),this.initImportWrapperFunc(t)}},f.prototype.initTimeoutIntervalOverrides=function(){var t=this.rewriteSetTimeoutInterval;if(this.$wbwindow.setTimeout&&!this.$wbwindow.setTimeout.__$wbpatched$__){var e=this.$wbwindow.setTimeout;this.$wbwindow.setTimeout=function(){return t(this,e,arguments)},this.$wbwindow.setTimeout.__$wbpatched$__=!0}if(this.$wbwindow.setInterval&&!this.$wbwindow.setInterval.__$wbpatched$__){var r=this.$wbwindow.setInterval;this.$wbwindow.setInterval=function(){return t(this,r,arguments)},this.$wbwindow.setInterval.__$wbpatched$__=!0}},f.prototype.initWorkerOverrides=function(){var t,e,r=this;if(this.$wbwindow.Worker&&!this.$wbwindow.Worker._wb_worker_overridden){var i=this.$wbwindow.Worker;this.$wbwindow.Worker=(t=i,function(e,i){return r.domConstructorErrorChecker(this,"Worker",arguments),new t(r.rewriteWorker(e),i)}),this.$wbwindow.Worker.prototype=i.prototype,Object.defineProperty(this.$wbwindow.Worker.prototype,"constructor",{value:this.$wbwindow.Worker}),this.$wbwindow.Worker._wb_worker_overridden=!0}if(this.$wbwindow.SharedWorker&&!this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden){var o=this.$wbwindow.SharedWorker;this.$wbwindow.SharedWorker=(e=o,function(t,i){return r.domConstructorErrorChecker(this,"SharedWorker",arguments),new e(r.rewriteWorker(t),i)}),this.$wbwindow.SharedWorker.prototype=o.prototype,Object.defineProperty(this.$wbwindow.SharedWorker.prototype,"constructor",{value:this.$wbwindow.SharedWorker}),this.$wbwindow.SharedWorker.__wb_sharedWorker_overridden=!0}if(this.$wbwindow.ServiceWorkerContainer&&this.$wbwindow.ServiceWorkerContainer.prototype&&this.$wbwindow.ServiceWorkerContainer.prototype.register){var n=this.$wbwindow.ServiceWorkerContainer.prototype.register;this.$wbwindow.ServiceWorkerContainer.prototype.register=function(t,e){var i=new r.URL(t,r.$wbwindow.document.baseURI).href,o=r.getPageUnderModifier();return e&&e.scope?e.scope=r.rewriteUrl(e.scope,!1,o):e={scope:r.rewriteUrl("/",!1,o)},n.call(this,r.rewriteUrl(i,!1,"sw_"),e)}}if(this.$wbwindow.Worklet&&this.$wbwindow.Worklet.prototype&&this.$wbwindow.Worklet.prototype.addModule&&!this.$wbwindow.Worklet.__wb_workerlet_overridden){var s=this.$wbwindow.Worklet.prototype.addModule;this.$wbwindow.Worklet.prototype.addModule=function(t,e){var i=r.rewriteUrl(t,!1,"js_");return s.call(this,i,e)},this.$wbwindow.Worklet.__wb_workerlet_overridden=!0}},f.prototype.initLocOverride=function(t,e,r){if(Object.defineProperty)for(var i=0;i=0&&i.splice(n,1)}return i}})}catch(t){console.log(t)}},f.prototype.initHashChange=function(){if(this.$wbwindow.__WB_top_frame){var t=this;this.$wbwindow.addEventListener("message",(function(e){if(e.data&&e.data.from_top){var r=e.data.message;r.wb_type&&"outer_hashchange"===r.wb_type&&t.$wbwindow.location.hash!=r.hash&&(t.$wbwindow.location.hash=r.hash)}})),this.$wbwindow.addEventListener("hashchange",(function(){var e={wb_type:"hashchange",hash:t.$wbwindow.location.hash};t.sendTopMessage(e)}))}},f.prototype.initPostMessageOverride=function(t){if(t.postMessage&&!t.__orig_postMessage){var e=t.postMessage,r=this;t.__orig_postMessage=e;var i=function(i,o,n,s){var a,w,h,p=r.proxyToObj(this);if(p||((p=t).__WB_source=t),p.__WB_source&&p.__WB_source.WB_wombat_location){var c=p.__WB_source;if(a=c.WB_wombat_location.origin,p.__WB_win_id||(p.__WB_win_id={},p.__WB_counter=0),!c.__WB_id){var l=p.__WB_counter;c.__WB_id=l+c.WB_wombat_location.href,p.__WB_counter+=1}p.__WB_win_id[c.__WB_id]=c,w=c.__WB_id,p.__WB_source=void 0}else a=window.WB_wombat_location.origin;"object"==typeof o?(h=o.targetOrigin,n=o.transfer):h=o;var _=h;_===p.location.origin&&(_=a);var u={from:a,to_origin:_,src_id:w,message:i,from_top:s};if("*"!==h){if("null"===p.location.origin||""===p.location.origin)return;h=p.location.origin}return e.call(p,u,h,n)};t.postMessage=i,t.Window.prototype.postMessage=i;var o=null,n=(o=t.EventTarget&&t.EventTarget.prototype?t.EventTarget.prototype:t).addEventListener;o.addEventListener=function(t,e,i){var o,s=r.proxyToObj(this);if("message"===t?o=r.message_listeners.add_or_get(e,(function(){return c(e,s,r)})):"storage"===t?r.storage_listeners.add_or_get(e,(function(){return p(e,s)})):o=e,o)return n.call(s,t,o,i)};var s=o.removeEventListener;o.removeEventListener=function(t,e,i){var o,n=r.proxyToObj(this);if("message"===t?o=r.message_listeners.remove(e):"storage"===t?r.storage_listeners.remove(e):o=e,o)return s.call(n,t,o,i)};var a=function(e,i){var o=r.getOrigSetter(t,e);r.defProp(t,e,(function(t){this["__orig_"+e]=t;var n=r.proxyToObj(this),s=t?i(t,n,r):t;return o.call(n,s)}),(function(){return this["__orig_"+e]}))};a("onmessage",c),a("onstorage",p)}},f.prototype.initMessageEventOverride=function(t){t.MessageEvent&&!t.MessageEvent.prototype.__extended&&(this.addEventOverride("target"),this.addEventOverride("srcElement"),this.addEventOverride("currentTarget"),this.addEventOverride("eventPhase"),this.addEventOverride("path"),this.overridePropToProxy(t.MessageEvent.prototype,"source"),t.MessageEvent.prototype.__extended=!0)},f.prototype.initUIEventsOverrides=function(){this.overrideAnUIEvent("UIEvent"),this.overrideAnUIEvent("MouseEvent"),this.overrideAnUIEvent("TouchEvent"),this.overrideAnUIEvent("FocusEvent"),this.overrideAnUIEvent("KeyboardEvent"),this.overrideAnUIEvent("WheelEvent"),this.overrideAnUIEvent("InputEvent"),this.overrideAnUIEvent("CompositionEvent")},f.prototype.initOpenOverride=function(){var t=this.$wbwindow.open;this.$wbwindow.Window.prototype.open&&(t=this.$wbwindow.Window.prototype.open);var e=this,r=function(r,i,o){i&&(i=e.rewriteAttrTarget(i));var n=e.rewriteUrl(r,!1),s=t.call(e.proxyToObj(this),n,i,o);return e.initNewWindowWombat(s,r),s};this.$wbwindow.open=r,this.$wbwindow.Window.prototype.open&&(this.$wbwindow.Window.prototype.open=r);for(var i=0;ithis.staticPrefix+"proxy/"+t))),n.has("adblockUrl")&&(r.adblockUrl=n.get("adblockUrl")),this.collections=new i(o,n.get("root"),r),this.collections.loadAll(n.get("dbColl")),this.proxyOriginMode=!!n.get("proxyOriginMode"),this.api=new e(this.collections),this.apiPrefix=this.replayPrefix+"api/",this.allowRewrittenCache=!!n.get("allowCache"),this.stats=n.get("stats")?new Ub:null,self.addEventListener("install",(()=>{self.skipWaiting()})),self.addEventListener("activate",(t=>{t.waitUntil(self.clients.claim()),console.log("Activate!")})),self.addEventListener("fetch",(t=>{t.respondWith(this.handleFetch(t))})),self.addEventListener("message",(t=>{"reload_all"===t.data.msg_type&&t.waitUntil(this.collections.loadAll())}))}getIndexHtml(t){const e=t.get("indexScript")||"./ui.js",r=t.get("indexAppTag")||"replay-app-main";return`\n \n \n