varmikuDelivery=function(k){"use strict";varjr=Object.defineProperty,Kr=Object.defineProperties;varVr=Object.getOwnPropertyDescriptors;varHe=Object.getOwnPropertySymbols;varkn=Object.prototype.hasOwnProperty,Ln=Object.prototype.propertyIsEnumerable;var_t=(k,I,B)=>Iink?jr(k,I,{enumerable:!0,configurable:!0,writable:!0,value:B}):k[I]=B,T=(k,I)=>{for(varBinI||(I={}))kn.call(I,B)&&_t(k,B,I[B]);if(He)for(varBofHe(I))Ln.call(I,B)&&_t(k,B,I[B]);returnk},j=(k,I)=>Kr(k,Vr(I));varTt=(k,I)=>{varB={};for(varqink)kn.call(k,q)&&I.indexOf(q)<0&&(B[q]=k[q]);if(k!=null&&He)for(varqofHe(k))I.indexOf(q)<0&&Ln.call(k,q)&&(B[q]=k[q]);returnB};varR=(k,I,B)=>(_t(k,typeofI!="symbol"?I+"":I,B),B);varb=(k,I,B)=>newPromise((q,oe)=>{varUe=Z=>{try{pe(B.next(Z))}catch(me){oe(me)}},qe=Z=>{try{pe(B.throw(Z))}catch(me){oe(me)}},pe=Z=>Z.done?q(Z.value):Promise.resolve(Z.value).then(Ue,qe);pe((B=B.apply(k,I)).next())});functionI(s){conste=[],t=s.length;for(letn=0;n<t;n++){letr=s.charCodeAt(n);if(r>=55296&&r<=56319&&t>n+1){consti=s.charCodeAt(n+1);i>=56320&&i<=57343&&(r=(r-55296)*1024+i-56320+65536,n+=1)}if(r<128){e.push(r);continue}if(r<2048){e.push(r>>6|192),e.push(r&63|128);continue}if(r<55296||r>=57344&&r<65536){e.push(r>>12|224),e.push(r>>6&63|128),e.push(r&63|128);continue}if(r>=65536&&r<=1114111){e.push(r>>18|240),e.push(r>>12&63|128),e.push(r>>6&63|128),e.push(r&63|128);continue}e.push(239,191,189)}returnnewUint8Array(e).buffer}functionB(s){returns^=s>>>16,s=Math.imul(s,2246822507),s^=s>>>13,s=Math.imul(s,3266489909),s^=s>>>16,s>>>0}constq=newUint32Array([3432918353,461845907]);functionoe(s,e){returns<<e|s>>>32-e}functionUe(s,e){constt=s.byteLength/4|0,n=newUint32Array(s,0,t);for(letr=0;r<t;r++)n[r]=Math.imul(n[r],q[0]),n[r]=oe(n[r],15),n[r]=Math.imul(n[r],q[1]),e[0]=e[0]^n[r],e[0]=oe(e[0],13),e[0]=Math.imul(e[0],5)+3864292196}functionqe(s,e){constt=s.byteLength/4|0,n=s.byteLength%4;letr=0;consti=newUint8Array(s,t*4,n);switch(n){case3:r=r^i[2]<<16;case2:r=r^i[1]<<8;case1:r=r^i[0]<<0,r=Math.imul(r,q[0]),r=oe(r,15),r=Math.imul(r,q[1]),e[0]=e[0]^r}}functionpe(s,e){e[0]=e[0]^s.byteLength,e[0]=B(e[0])}functionZ(s,e){if(e=e?e|0:0,typeofs=="string"&&(s=I(s)),!(sinstanceofArrayBuffer))thrownewTypeError("Expected key to be ArrayBuffer or string");constt=newUint32Array([e]);returnUe(s,t),qe(s,t),pe(s,t),t.buffer}classme{constructor(e=Bn){R(this,"circle",newMap);R(this,"members",newSet);R(this,"membersReplicas",newMap);R(this,"sortedHashes",[]);this.hasher=e}updateSortedHashes(){this.sortedHashes=[...this.circle.keys()].sort((e,t)=>e-t)}_add({key:e,replicas:t}){for(letn=0;n<t;n++){constr=this.hasher(At(e,n));this.circle.set(r,e)}this.members.add(e),this.membersReplicas.set(e,t)}_remove({key:e,replicas:t}){for(letn=0;n<t;n++){constr=this.hasher(At(e,n));this.circle.delete(r)}this.members.delete(e),this.membersReplicas.delete(e)}search(e){constt=this.sortedHashes.findIndex(n=>n>e);returnt<0?0:t}get(e){if(this.members.size===0)returnnull;constt=this.hasher(e),n=this.search(t),r=this.sortedHashes[n];returnthis.circle.get(r)}getN(e,t,n){constr=n?n.size:this.members.size;if(r===0||t===0)return[];t>r&&(t=r);consti=this.hasher(e),o=this.search(i),a=[];for(letc=o;;c++){c>=this.sortedHashes.length&&(c=0);consth=this.sortedHashes[c],d=this.circle.get(h);if(!a.includes(d)&&(!n||n.has(d))&&(a.push(d),a.length>=t))returna}}add(e,t){returnthis.members.has(e)?!1:(this._add({key:e,replicas:t}),this.updateSortedHashes(),!0)}remove(e){if(!this.members.has(e))return!1;constt=this.membersReplicas.get(e);returnthis._remove({key:e,replicas:t}),this.updateSortedHashes(),!0}set(e){this.circle.clear(),this.members.clear(),this.membersReplicas.clear(),e.forEach(t=>{this._add(t)}),this.updateSortedHashes()}}functionAt(s,e){returne+s}constBn=Pn;functionPn(s){conste=Z(s);returnnewUint32Array(e)[0]}classJ{constructor(e){R(this,"value");this.value=e!=null?T({},e.value):{}}set(e,t){this.value[e]=t}get(e){returnthis.value[e]}}letDt=!1;functionQ(s){return(...e)=>{Dt&&console.debug(`[${s}] [${(Date.now()/1e3).toFixed(3)}]`,...e)}}functionkt(){Dt=!0}functionte(s){return(...e)=>{console.warn(`[${s}] [${(Date.now()/1e3).toFixed(3)}]`,...e)}}const$e="https://api.qiniudns.com/v1/resolve",Lt="https://api.qiniudns.com",We="https://pili-zeus.qiniuapi.com/v1/scheduling";functionMn(s){s[0]==="?"&&(s=s.slice(1));conste={};returns.split("&").forEach(t=>{const[n,r]=t.split("=");e[decodeURIComponent(n)]=r==null?null:decodeURIComponent(r)}),e}functionFe(s){returnObject.keys(s).map(e=>[e,s[e]]).filter(([e,t])=>t!==void0).map(([e,t])=>t===null?encodeURIComponent(e):[e,t].map(encodeURIComponent).join("=")).join("&")}functionIn(s,e){constt=newURLSearchParams(e).toString(),n=s.includes("?")?"&":"?";returns+n+t}functionje(){consts="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",e=s.length;lett="";for(letn=0;n<20;n++)t+=s[Math.floor(Math.random()*e)];returnt}functionOn(s,e){constt={};returnObject.keys(s).forEach(n=>{t[n]=e(s[n])}),t}classBtextendsError{constructor(){super(...arguments);R(this,"name","TimeoutError")}}functionPt(s,e){returnnewPromise((t,n)=>{setTimeout(()=>n(newBt(e+" timeout")),s)})}functionzn(s,e){e.aborted?s.abort(e.reason):e.addEventListener("abort",()=>{s.abort(e.reason)})}constMt={image:[/\.(jpe?g|png|gif|webp|svg|bmp|ico|tiff|avif|svga)$/],media:[/\.(3gp|aac|flac|mpe?g|mp3|mp4|m4a|m4v|m4p|oga|ogg|ogv|wav|webm|mov)$/],live:[/\.(flv|m3u8|ts|m4s)$/],other:[]};functionNn(s,e,t=["image","media","other"]){s.search="",s.hash="";constn=s.toString();returnt.some(r=>{vari;return((i=e[r])!=null?i:[]).some(o=>o.test(n))})}functionxe(s){conste=newURL(s);returne.search="",e.hash="",e.toString()}functionae(s){returnsinstanceofError?{err_msg:s.name,err_desc:s.message}:{err_msg:"Unknown",err_desc:s+""}}functionz(s,e){returns==null||s===-1||e==null||e===-1?-1:(s-e)/1e3}functionHn(s,e=80){const[t,n]=s.split(":"),r=n?parseInt(n,10):e;return[t,r]}functionIt(s){conste=s.split("/"),t=e[e.length-1],n=t.lastIndexOf(".");returnn>=0?t.slice(n+1):""}functionUn(s,e){returnnewURL(s,e).toString()}function_e(s){const[e]=s.split("?");returne.endsWith(".m3u8")}functionOt(s){const[e]=s.split("?");returne.endsWith(".flv")}varee=typeofglobalThis!="undefined"?globalThis:typeofwindow!="undefined"?window:typeofglobal!="undefined"?global:typeofself!="undefined"?self:{};functionqn(s){vare=s.default;if(typeofe=="function"){vart=function(){returne.apply(this,arguments)};t.prototype=e.prototype}elset={};returnObject.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(n){varr=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){returns[n]}})}),t}varzt={exports:{}};function$n(s){thrownewError('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}varKe={exports:{}};constWn=qn(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));varNt;functionTe(){returnNt||(Nt=1,function(s,e){(function(t,n){s.exports=n()})(ee,function(){vart=t||function(n,r){vari;if(typeofwindow!="undefined"&&window.crypto&&(i=window.crypto),typeofself!="undefined"&&self.crypto&&(i=self.crypto),typeofglobalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeofwindow!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&typeofee!="undefined"&&ee.crypto&&(i=ee.crypto),!i&&typeof$n=="function")try{i=Wn}catch(m){}varo=function(){if(i){if(typeofi.getRandomValues=="function")try{returni.getRandomValues(newUint32Array(1))[0]}catch(m){}if(typeofi.randomBytes=="function")try{returni.randomBytes(4).readInt32LE()}catch(m){}}thrownewError("Native crypto module could not be used to get secure random number.")},a=Object.create||function(){functionm(){}returnfunction(v){vary;returnm.prototype=v,y=newm,m.prototype=null,y}}(),c={},h=c.lib={},d=h.Base=function(){return{extend:function(m){varv=a(this);returnm&&v.mixIn(m),(!v.hasOwnProperty("init")||this.init===v.init)&&(v.init=function(){v.$super.init.apply(this,arguments)}),v.init.prototype=v,v.$super=this,v},create:function(){varm=this.extend();returnm.init.apply(m,arguments),m},init:function(){},mixIn:function(m){for(varvinm)m.hasOwnProperty(v)&&(this[v]=m[v]);m.hasOwnProperty("toString")&&(this.toString=m.toString)},clone:function(){returnthis.init.prototype.extend(this)}}}(),p=h.WordArray=d.extend({init:function(m,v){m=this.words=m||[],v!=r?this.sigBytes=v:this.sigBytes=m.length*4},toString:function(m){return(m||f).stringify(this)},concat:function(m){varv=this.words,y=m.words,S=this.sigBytes,A=m.sigBytes;if(this.clamp(),S%4)for(varM=0;M<A;M++){varX=y[M>>>2]>>>24-M%4*8&255;v[S+M>>>2]|=X<<24-(S+M)%4*8}elsefor(varU=0;U<A;U+=4)v[S+U>>>2]=y[U>>>2];returnthis.sigBytes+=A,this},clamp:function(){varm=this.words,v=this.sigBytes;m[v>>>2]&=4294967295<<32-v%4*8,m.length=n.ceil(v/4)},clone:function(){varm=d.clone.call(this);returnm.words=this.words.slice(0),m},random:function(m){for(varv=[],y=0;y<m;y+=4)v.push(o());returnnewp.init(v,m)}}),l=c.enc={},f=l.Hex={stringify:function(m){for(varv=m.words,y=m.sigBytes,S=[],A=0;A<y;A++){varM=v[A>>>2]>>>24-A%4*8&255;S.push((M>>>4).toString(16)),S.push((M&15).toString(16))}returnS.join("")},parse:function(m){for(varv=m.length,y=[],S=0;S<v;S+=2)y[S>>>3]|=parseInt(m.substr(S,2),16)<<24-S%8*4;returnnewp.init(y,v/2)}},u=l.Latin1={stringify:function(m){for(varv=m.words,y=m.sigBytes,S=[],A=0;A<y;A++){varM=v[A>>>2]>>>24-A%4*8&255;S.push(String.fromCharCode(M))}returnS.join("")},parse:function(m){for(varv=m.length,y=[],S=0;S<v;S++)y[S>>>2]|=(m.charCodeAt(S)&255)<<24-S%4*8;returnnewp.init(y,v)}},w=l.Utf8={stringify:function(m){try{returndecodeURIComponent(escape(u.stringify(m)))}catch(v){thrownewError("Malformed UTF-8 data")}},parse:function(m){returnu.parse(unescape(encodeURIComponent(m)))}},g=h.BufferedBlockAlgorithm=d.extend({reset:function(){this._data=newp.init,this._nDataBytes=0},_append:function(m){typeofm=="string"&&(m=w.parse(m)),this._data.concat(m),this._nDataBytes+=m.sigBytes},_process:function(m){varv,y=this._data,S=y.words,A=y.sigBytes,M=this.blockSize,X=M*4,U=A/X;m?U=n.ceil(U):U=n.max((U|0)-this._minBufferSize,0);varK=U*M,V=n.min(K*4,A);if(K){for(varN=0;N<K;N+=M)this._doProcessBlock(S,N);v=S.splice(0,K),y.sigBytes-=V}returnnewp.init(v,V)},clone:function(){varm=d.clone.call(this);returnm._data=this._data.clone(),m},_minBufferSize:0});h.Hasher=g.extend({cfg:d.extend(),init:function(m){this.cfg=this.cfg.extend(m),this.reset()},reset:function(){g.reset.call(this),this._doReset()},update:function(m){returnthis._append(m),this._process(),this},finalize:function(m){m&&this._append(m);varv=this._doFinalize();returnv},blockSize:16,_createHelper:function(m){returnfunction(v,y){returnnewm.init(y).finalize(v)}},_createHmacHelper:function(m){returnfunction(v,y){returnnewx.HMAC.init(m,y).finalize(v)}}});varx=c.algo={};returnc}(Math);returnt})}(Ke)),Ke.exports}varVe={exports:{}},Ht;functionFn(){returnHt||(Ht=1,function(s,e){(function(t,n){s.exports=n(Te())})(ee,function(t){returnfunction(){varn=t,r=n.lib,i=r.WordArray,o=r.Hasher,a=n.algo,c=[],h=a.SHA1=o.extend({_doReset:function(){this._hash=newi.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(d,p){for(varl=this._hash.words,f=l[0],u=l[1],w=l[2],g=l[3],x=l[4],m=0;m<80;m++){if(m<16)c[m]=d[p+m]|0;else{varv=c[m-3]^c[m-8]^c[m-14]^c[m-16];c[m]=v<<1|v>>>31}vary=(f<<5|f>>>27)+x+c[m];m<20?y+=(u&w|~u&g)+1518500249:m<40?y+=(u^w^g)+1859775393:m<60?y+=(u&w|u&g|w&g)-1894007588:y+=(u^w^g)-899497514,x=g,g=w,w=u<<30|u>>>2,u=f,f=y}l[0]=l[0]+f|0,l[1]=l[1]+u|0,l[2]=l[2]+w|0,l[3]=l[3]+g|0,l[4]=l[4]+x|0},_doFinalize:function(){vard=this._data,p=d.words,l=this._nDataBytes*8,f=d.sigBytes*8;returnp[f>>>5]|=128<<24-f%32,p[(f+64>>>9<<4)+14]=Math.floor(l/4294967296),p[(f+64>>>9<<4)+15]=l,d.sigBytes=p.length*4,this._process(),this._hash},clone:function(){vard=o.clone.call(this);returnd._hash=this._hash.clone(),d}});n.SHA1=o._createHelper(h),n.HmacSHA1=o._createHmacHelper(h)}(),t.SHA1})}(Ve)),Ve.exports}varGe={exports:{}},Ut;functionjn(){returnUt||(Ut=1,function(s,e){(function(t,n){s.exports=n(Te())})(ee,function(t){(function(){varn=t,r=n.lib,i=r.Base,o=n.enc,a=o.Utf8,c=n.algo;c.HMAC=i.extend({init:function(h,d){h=this._hasher=newh.init,typeofd=="string"&&(d=a.parse(d));varp=h.blockSize,l=p*4;d.sigBytes>l&&(d=h.finalize(d)),d.clamp();for(varf=this._oKey=d.clone(),u=this._iKey=d.clone(),w=f.words,g=u.words,x=0;x<p;x++)w[x]^=1549556828,g[x]^=909522486;f.sigBytes=u.sigBytes=l,this.reset()},reset:function(){varh=this._hasher;h.reset(),h.update(this._iKey)},update:function(h){returnthis._hasher.update(h),this},finalize:function(h){vard=this._hasher,p=d.finalize(h);d.reset();varl=d.finalize(this._oKey.clone().concat(p));returnl}})})()})}(Ge)),Ge.exports}(function(s,e){(function(t,n,r){s.exports=n(Te(),Fn(),jn())})(ee,function(t){returnt.HmacSHA1})})(zt);constKn=zt.exports;varqt={exports:{}};(function(s,e){(function(t,n){s.exports=n(Te())})(ee,function(t){returnfunction(){varn=t,r=n.lib,i=r.WordArray,o=n.enc;o.Base64={stringify:function(c){varh=c.words,d=c.sigBytes,p=this._map;c.clamp();for(varl=[],f=0;f<d;f+=3)for(varu=h[f>>>2]>>>24-f%4*8&255,w=h[f+1>>>2]>>>24-(f+1)%4*8&255,g=h[f+2>>>2]>>>24-(f+2)%4*8&255,x=u<<16|w<<8|g,m=0;m<4&&f+m*.75<d;m++)l.push(p.charAt(x>>>6*(3-m)&63));varv=p.charAt(64);if(v)for(;l.length%4;)l.push(v);returnl.join("")},parse:function(c){varh=c.length,d=this._map,p=this._reverseMap;if(!p){p=this._reverseMap=[];for(varl=0;l<d.length;l++)p[d.charCodeAt(l)]=l}varf=d.charAt(64);if(f){varu=c.indexOf(f);u!==-1&&(h=u)}returna(c,h,p)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="};functiona(c,h,d){for(varp=[],l=0,f=0;f<h;f++)if(f%4){varu=d[c.charCodeAt(f-1)]<<f%4*2,w=d[c.charCodeAt(f)]>>>6-f%4*2,g=u|w;p[l>>>2]|=g<<24-l%4*8,l++}returni.create(p,l)}}(),t.enc.Base64})})(qt);constVn=qt.exports;functionGn(s){lete=s.query?`${s.path}?${s.query}
`:`${s.path}
`;returns.body&&(e+=s.body),e}functionQe(s){lete;try{e=newURL(s.path).pathname}catch(a){e=s.path}lett=Gn(j(T({},s),{path:e}));consti=Kn(t,s.appSalt).toString(Vn).replace(/\+/g,"-").replace(/\//g,"_");leto=`QApp ${s.appID}:${i}`;returno=o.replace(/\//g,"_"),o=o.replace(/\+/g,"-"),o}classQn{constructor(e){this.logger=e}log(e){returnthis.logger.log("DnsResolveLog",e)}}functionXn(s){conste="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",t=e.length;letn="";for(letr=0;r<s;r++)n+=e[Math.floor(Math.random()*t)];returnn}constYn=newURL($e).hostname,Zn=te("dns/httpdns");functionJn(s,e,t,n){returnb(this,null,function*(){varp,l;constr=newQn(n),i=Fe({name:e,type:"A",rid:Xn(10)}),o=`${$e}?${i}`,a=Qe(j(T({},t),{path:$e,query:i}));letc,h=null,d=null;try{if(h=yieldfetch(o,{headers:{Authorization:a}}),!h.ok){constu=yieldns(h);if(u==null)thrownewError(`Resolve failed, unexpected HTTP status: ${h.status}`);if(u.code==="NotSupportedArea")return{reason:"NotSupportedArea",ttl:300};thrownewError(`Resolve failed, code: ${u.code}, error: ${u.error}`)}returnd=yieldh.json()}catch(f){throwc=f}finally{constu=performance.getEntriesByName(o,"resource").pop();if(u==null)Zn("Corresponding performance entry not found for",o);else{constw=d==null?ae(c):{err_msg:"",err_desc:""};r.log(j(T({r_id:(p=h==null?void0:h.headers.get("x-reqid"))!=null?p:"",ip:"",domain:Yn,status_code:(l=h==null?void0:h.status)!=null?l:-1},w),{t_conn:(u.requestStart-u.connectStart)/1e3,t_total:(u.responseEnd-u.fetchStart)/1e3,type:1}))}}})}functionXe(s){returns.groups!=null}functiones(s,e){returns.find(t=>newRegExp(t.pattern).test(e))}functionts(s){returnMath.random()<s.servicerate}functionns(s){returnb(this,null,function*(){try{conste=yields.json();if(e&&typeofe.code=="string"&&typeofe.error=="string")returne}catch(e){}returnnull})}function$t(s){returnb(this,null,function*(){yieldPromise.all(s.map(e=>indexedDB.deleteDatabase(e)))})}classWt{constructor(e,t){R(this,"db");this.dbName=e,this.storeConfigs=t}getDB(){returnb(this,null,function*(){returnthis.db!=null?this.db:(this.db=yieldnewPromise(e=>{constt=indexedDB.open(this.dbName);t.addEventListener("upgradeneeded",()=>{for(constnofthis.storeConfigs){constr=t.result.createObjectStore(n.name);for(constiofn.indexes)r.createIndex(i.name,i.keyPath)}}),e(Ae(t))}),this.db)})}get(e,t){returnb(this,null,function*(){constr=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).get(t);returnAe(r)})}getAll(e){returnb(this,null,function*(){constn=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).getAll();returnAe(n)})}count(e){returnb(this,null,function*(){constn=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).count();returnAe(n)})}set(e,t,n){returnb(this,null,function*(){consti=(yieldthis.getDB()).transaction(e,"readwrite");returni.objectStore(e).put(n,t),Ye(i)})}remove(e,t){returnb(this,null,function*(){constr=(yieldthis.getDB()).transaction(e,"readwrite");returnr.objectStore(e).delete(t),Ye(r)})}clear(){returnb(this,null,function*(){conste=yieldthis.getDB();yieldPromise.all(this.storeConfigs.map(({name:t})=>{constn=e.transaction(t,"readwrite");returnn.objectStore(t).clear(),Ye(n)}))})}walkBy(e,t,n){returnb(this,null,function*(){consti=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).index(t).openCursor(void0,"next");returnnewPromise((o,a)=>{i.addEventListener("error",()=>a(newge(i.error))),i.addEventListener("success",()=>{constc=i.result;if(c==null){o();return}n(c.value,c.primaryKey),c.continue()})})})}dispose(){vare;(e=this.db)==null||e.close()}}classgeextendsError{constructor(t){super(t+"");R(this,"name","IndexedDBError");this.cause=t}}functionAe(s){returnnewPromise((e,t)=>{s.addEventListener("success",()=>e(s.result)),s.addEventListener("error",()=>t(newge(s.error)))})}functionYe(s){returnnewPromise((e,t)=>{s.addEventListener("complete",()=>e()),s.addEventListener("error",()=>t(newge(s.error))),s.addEventListener("abort",()=>t(newge(s.error)))})}classss{constructor(){R(this,"map",newMap)}on(e,t){vari;constr=[...(i=this.map.get(e))!=null?i:[],t];returnthis.map.set(e,r),()=>this.off(e,t)}once(e,t){constn=this.on(e,r=>{n(),t(r)});returnn}off(e,t){vari;constr=((i=this.map.get(e))!=null?i:[]).filter(o=>o!==t);this.map.set(e,r)}emit(...e){vari;const[t,n]=e;((i=this.map.get(t))!=null?i:[]).forEach(o=>{o(n)})}dispose(){this.map.clear()}}functionle(s){conste=s.get("Content-Length");returne?parseInt(e,10):null}functionZe(s){conste=s.get("Content-Range");returne==null?null:rs(e)}functionrs(s){conste=s.trim().toLowerCase(),[t,n]=e.split(/\s+/);if(t!=="bytes")thrownewError(`Unit must be bytes: ${s}`);const[r,i]=n.split("/"),o=i==="*"?null:et(i),[a,c]=(r.includes("-")?r.split("-"):[null,null]).map(h=>et(h));return{totalSize:o,start:a,end:c}}functionJe(s){conste=s.start!=null&&s.end!=null?`${s.start}-${s.end}`:"*",t=s.totalSize==null?"*":s.totalSize+"";return`bytes ${e}/${t}`}functionet(s){returns?Number(s):null}functiontt(s){conste=s.get("Range");returne==null?null:jt(e)}functionFt(s){returns.start===0&&s.end==null}functionjt(s){conste=s.trim().toLowerCase();if(!e.startsWith("bytes="))thrownewError(`Unit must be bytes: ${s}`);if(e.includes(","))thrownewError(`Multiple range: ${s}`);const[,t,n]=/(\d*)-(\d*)/.exec(e)||[];if(!t&&!n)thrownewError(`Invalid range values: ${s}`);if(!t)thrownewError("Suffix range not supported");const[r,i]=[t,n].map(o=>et(o));return{start:r,end:i}}functionbe(s){vare,t;return`bytes=${(e=s.start)!=null?e:0}-${(t=s.end)!=null?t:""}`}constis=/[^\u0000-\u00ff]/;functionKt(s){returnis.test(s)?"REPLACED_BY_Miku_Delivery_SEE_utils_http_encodeHeaderValue":s}functionos(s){if(sinstanceofHeaders){conste={};s.forEach((t,n)=>{e[n]=Kt(t)}),s=e}if(Array.isArray(s)){conste={};s.forEach(([t,n])=>{e[n]=Kt(t)}),s=e}returnnewHeaders(s)}functionnt(s){vart;conste=Ze(s);returne!=null?(t=e.totalSize)!=null?t:null:le(s)}constVt=Q("utils/stream"),Gt=te("utils/stream");functionas(s){returnb(this,null,function*(){conste=s.getReader();lett=newUint8Array;for(;;){const{done:r,value:i}=yielde.read();if(r)break;t=newUint8Array([...t,...i])}returnnewTextDecoder().decode(t)})}functionst(s,e){vara;constt=s.getReader(),n=(a=e[0])!=null?a:0,r=e[1];leti=0;returnnewReadableStream({pull:c=>b(this,null,function*(){leth,d;for(;;){constu=yieldt.read();if(u.done){c.close();return}if(h=u.value,d=i+h.byteLength,d>n)break;i=d}letp=h;constl=n>i?n-i:0,f=r!=null&&r<d?r-i:void0;(l!==0||f!==void0)&&(p=h.slice(l,f)),c.enqueue(p),r!=null&&d>=r&&(t.cancel("Cancelled by slice for target range met"),c.close()),i=d}),cancel:c=>t.cancel(c)})}functionls(s){lete=0;constt=newTransformStream({transform:(r,i)=>{e+=r.byteLength,i.enqueue(r)}}),n=s.pipeTo(t.writable).then(()=>({size:e,success:!0}),r=>({size:e,success:!1,error:r}));return[t.readable,n]}classQtextendsError{constructor(){super(...arguments);R(this,"name","SaveSlicedPieceError")}}functioncs(s,e,t,n){returnb(this,null,function*(){constr=[];leti=e,o=[],a=0;functionc(){returnb(this,null,function*(){consth=i+a;Vt(`saveSlicedPiece [${i}, ${h}]`);try{yieldn(newBlob(o),i,h)}catch(d){throwGt(`saveSlicedPiece [${i}, ${h}] failed`,d),newQt(`saveSlicedPiece [${i}, ${h}] failed`)}r.push([i,h]),Vt(`saveSlicedPiece [${i}, ${h}] finish`,r),i=h})}try{consth=s.getReader();for(;;){const{value:d,done:p}=yieldh.read();if(p)break;o.push(d),a+=d.byteLength,a>=t&&(yieldc(),o=[],a=0)}a>0&&(yieldc())}catch(h){if(!(hinstanceofQt)&&(Gt("exception occurred while reading stream and save by pieces",h),a>0))try{yieldc()}catch(d){}}returnr})}functionus(s){lete,t=!1;constn=newReadableStream({start:a=>{e=a},cancel:()=>{t=!0}}),r=s.getReader();leti=!1;return{main:newReadableStream({pull:a=>b(this,null,function*(){try{const{value:c,done:h}=yieldr.read();if(i)return;if(h){a.close(),t||e.close();return}a.enqueue(c),t||e.enqueue(c)}catch(c){a.error(c),t||e.error(c)}}),cancel:a=>b(this,null,function*(){i=!0,yieldr.cancel(a),e.error(a)})}),minor:n}}varrt={exports:{}};(function(s,e){(function(t,n){varr="1.0.2",i="",o="?",a="function",c="undefined",h="object",d="string",p="major",l="model",f="name",u="type",w="vendor",g="version",x="architecture",m="console",v="mobile",y="tablet",S="smarttv",A="wearable",M="embedded",X=255,U="Amazon",K="Apple",V="ASUS",N="BlackBerry",$="Browser",W="Chrome",ie="Edge",F="Firefox",H="Google",Rn="Huawei",vt="LG",yt="Microsoft",Sn="Motorola",Ie="Opera",Rt="Samsung",St="Sony",Cn="Xiaomi",Ct="Zebra",En="Facebook",$r=function(C,D){varE={};for(varOinC)D[O]&&D[O].length%2===0?E[O]=D[O].concat(C[O]):E[O]=C[O];returnE},Oe=function(C){for(varD={},E=0;E<C.length;E++)D[C[E].toUpperCase()]=C[E];returnD},xn=function(C,D){returntypeofC===d?Se(D).indexOf(Se(C))!==-1:!1},Se=function(C){returnC.toLowerCase()},Wr=function(C){returntypeofC===d?C.replace(/[^\d\.]/g,i).split(".")[0]:n},Et=function(C,D){if(typeofC===d)returnC=C.replace(/^\s\s*/,i).replace(/\s\s*$/,i),typeofD===c?C:C.substring(0,X)},Ce=function(C,D){for(varE=0,O,_,Ne,L,Ee,Y;E<D.length&&!Ee;){varAn=D[E],Dn=D[E+1];for(O=_=0;O<An.length&&!Ee;)if(Ee=An[O++].exec(C),Ee)for(Ne=0;Ne<Dn.length;Ne++)Y=Ee[++_],L=Dn[Ne],typeofL===h&&L.length>0?L.length===2?typeofL[1]==a?this[L[0]]=L[1].call(this,Y):this[L[0]]=L[1]:L.length===3?typeofL[1]===a&&!(L[1].exec&&L[1].test)?this[L[0]]=Y?L[1].call(this,Y,L[2]):n:this[L[0]]=Y?Y.replace(L[1],L[2]):n:L.length===4&&(this[L[0]]=Y?L[3].call(this,Y.replace(L[1],L[2])):n):this[L]=Y||n;E+=2}},xt=function(C,D){for(varEinD)if(typeofD[E]===h&&D[E].length>0){for(varO=0;O<D[E].length;O++)if(xn(D[E][O],C))returnE===o?n:E}elseif(xn(D[E],C))returnE===o?n:E;returnC},Fr={"1.0":"/8","1.2":"/1","1.3":"/3","2.0":"/412","2.0.2":"/416","2.0.3":"/417","2.0.4":"/419","?":"/"},_n={ME:"4.90","NT 3.11":"NT3.51","NT 4.0":"NT4.0",2e3:"NT 5.0",XP:["NT 5.1","NT 5.2"],Vista:"NT 6.0",7:"NT 6.1",8:"NT 6.2","8.1":"NT 6.3",10:["NT 6.4","NT 10.0"],RT:"ARM"},Tn={browser:[[/\b(?:crmo|crios)\/([\w\.]+)/i],[g,[f,"Chrome"]],[/edg(?:e|ios|a)?\/([\w\.]+)/i],[g,[f,"Edge"]],[/(opera mini)\/([-\w\.]+)/i,/(opera [mobiletab]{3,6})\b.+version\/([-\w\.]+)/i,/(opera)(?:.+version\/|[\/]+)([\w\.]+)/i],[f,g],[/opios[\/]+([\w\.]+)/i],[g,[f,Ie+" Mini"]],[/\bopr\/([\w\.]+)/i],[g,[f,Ie]],[/(kindle)\/([\w\.]+)/i,/(lunascape|maxthon|netfront|jasmine|blazer)[\/]?([\w\.]*)/i,/(avant |iemobile|slim)(?:browser)?[\/]?([\w\.]*)/i,/(ba?idubrowser)[\/]?([\w\.]+)/i,/(?:ms|\()(ie)([\w\.]+)/i,/(flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron|vivaldi|iridium|phantomjs|bowser|quark|qupzilla|falkon|rekonq|puffin|brave|whale|qqbrowserlite|qq)\/([-\w\.]+)/i,/(weibo)__([\d\.]+)/i],[f,g],[/(?:\buc??browser|(?:juc.+)ucweb)[\/]?([\w\.]+)/i],[g,[f,"UC"+$]],[/\bqbcore\/([\w\.]+)/i],[g,[f,"WeChat(Win) Desktop"]],[/micromessenger\/([\w\.]+)/i],[g,[f,"WeChat"]],[/konqueror\/([\w\.]+)/i],[g,[f,"Konqueror"]],[/trident.+rv[: ]([\w\.]{1,9})\b.+like gecko/i],[g,[f,"IE"]],[/yabrowser\/([\w\.]+)/i],[g,[f,"Yandex"]],[/(avast|avg)\/([\w\.]+)/i],[[f,/(.+)/,"$1 Secure "+$],g],[/\bfocus\/([\w\.]+)/i],[g,[f,F+" Focus"]],[/\bopt\/([\w\.]+)/i],[g,[f,Ie+" Touch"]],[/coc_coc\w+\/([\w\.]+)/i],[g,[f,"Coc Coc"]],[/dolfin\/([\w\.]+)/i],[g,[f,"Dolphin"]],[/coast\/([\w\.]+)/i],[g,[f,Ie+" Coast"]],[/miuibrowser\/([\w\.]+)/i],[g,[f,"MIUI "+$]],[/fxios\/([-\w\.]+)/i],[g,[f,F]],[/\bqihu|(qi?ho?o?|360)browser/i],[[f,"360 "+$]],[/(oculus|samsung|sailfish)browser\/([\w\.]+)/i],[[f,/(.+)/,"$1 "+$],g],[/(comodo_dragon)\/([\w\.]+)/i],[[f,/_/g,""],g],[/(electron)\/([\w\.]+) safari/i,/(tesla)(?: qtcarbrowser|\/(20\d\d\.[-\w\.]+))/i,/m?(qqbrowser|baiduboxapp|2345Explorer)[\/]?([\w\.]+)/i],[f,g],[/(metasr)[\/]?([\w\.]+)/i,/(lbbrowser)/i],[f],[/((?:fban\/fbios|fb_iab\/fb4a)(?!.+fbav)|;fbav\/([\w\.]+);)/i],[[f,En],g],[/safari (line)\/([\w\.]+)/i,/\b(line)\/([\w\.]+)\/iab/i,/(chromium|instagram)[\/]([-\w\.]+)/i],[f,g],[/\bgsa\/([\w\.]+) .*safari\//i],[g,[f,"GSA"]],[/headlesschrome(?:\/([\w\.]+)| )/i],[g,[f,W+" Headless"]],[/ wv\).+(chrome)\/([\w\.]+)/i],[[f,W+" WebView"],g],[/droid.+ version\/([\w\.]+)\b.+(?:mobile safari|safari)/i],[g,[f,"Android "+$]],[/(chrome|omniweb|arora|[tizenoka]{5}?browser)\/v?([\w\.]+)/i],[f,g],[/version\/([\w\.]+) .*mobile\/\w+ (safari)/i],[g,[f,"Mobile Safari"]],[/version\/([\w\.]+) .*(mobile ?safari|safari)/i],[g,f],[/webkit.+?(mobile ?safari|safari)(\/[\w\.]+)/i],[f,[g,xt,Fr]],[/(webkit|khtml)\/([\w\.]+)/i],[f,g],[/(navigator|netscape\d?)\/([-\w\.]+)/i],[[f,"Netscape"],g],[/mobile vr; rv:([\w\.]+)\).+firefox/i],[g,[f,F+" Reality"]],[/ekiohf.+(flow)\/([\w\.]+)/i,/(swiftfox)/i,/(icedragon|iceweasel|camino|chimera|fennec|maemo browser|minimo|conkeror|klar)[\/]?([\w\.\+]+)/i,/(seamonkey|k-meleon|icecat|iceape|firebird|phoenix|palemoon|basilisk|waterfox)\/([-\w\.]+)$/i,/(firefox)\/([\w\.]+)/i,/(mozilla)\/([\w\.]+) .+rv\:.+gecko\/\d+/i,/(polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|sleipnir|obigo|mosaic|(?:go|ice|up)[\.]?browser)[-\/]?v?([\w\.]+)/i,/(links)\(([\w\.]+)/i],[f,g]],cpu:[[/(?:(amd|x(?:(?:86|64)[-_])?|wow|win)64)[;\)]/i],[[x,"amd64"]],[/(ia32(?=;))/i],[[x,Se]],[/((?:i[346]|x)86)[;\)]/i],[[x,"ia32"]],[/\b(aarch64|arm(v?8e?l?|_?64))\b/i],[[x,"arm64"]],[/\b(arm(?:v[67])?ht?n?[fl]p?)\b/i],[[x,"armhf"]],[/windows (ce|mobile); ppc;/i],[[x,"arm"]],[/((?:ppc|powerpc)(?:64)?)(?: mac|;|\))/i],[[x,/ower/,i,Se]],[/(sun4\w)[;\)]/i],[[x,"sparc"]],[/((?:avr32|ia64(?=;))|68k(?=\))|\barm(?=v(?:[1-7]|[5-7]1)l?|;|eabi)|(?=atmel )avr|(?:irix|mips|sparc)(?:64)?\b|pa-risc)/i],[[x,Se]]],device:[[/\b(sch-i[89]0\d|shw-m380s|sm-[pt]\w{2,4}|gt-[pn]\d{2,4}|sgh-t8[56]9|nexus 10)/i],[l,[w,Rt],[u,y]],[/\b((?:s[cgp]h|gt|sm)-\w+|galaxy nexus)/i,/samsung[- ]([-\w]+)/i,/sec-(sgh\w+)/i],[l,[w,Rt],[u,v]],[/\((ip(?:hone|od)[\w]*);/i],[l,[w,K],[u,v]],[/\((ipad);[-\w\),; ]+apple/i,/applecoremedia\/[\w\.]+ \((ipad)/i,/\b(ipad)\d\d?,\d\d?[;\]].+ios/i],[l,[w,K],[u,y]],[/\b((?:ag[rs][23]?|bah2?|sht?|btv)-a?[lw]\d{2})\b(?!.+d\/s)/i],[l,[w,Rn],[u,y]],[/(?:huawei|honor)([-\w]+)[;\)]/i,/\b(nexus 6p|\w{2,4}-[atu]?[ln][01259x][012359][an]?)\b(?!.+d\/s)/i],[l,[w,Rn],[u,v]],[/\b(poco[\w]+)(?: bui|\))/i,/\b; (\w+) build\/hm\1/i,/\b(hm[-_ ]?note?[_ ]?(?:\d\w)?) bui/i,/\b(redmi[\-_ ]?(?:note|k)?[\w_ ]+)(?: bui|\))/i,/\b(mi[-_ ]?(?:a\d|one|one[_ ]plus|note lte|max)?[_ ]?(?:\d?\w?)[_ ]?(?:plus|se|lite)?)(?: bui|\))/i],[[l,/_/g,""],[w,Cn],[u,v]],[/\b(mi[-_ ]?(?:pad)(?:[\w_ ]+))(?: bui|\))/i],[[l,/_/g,""],[w,Cn],[u,y]],[/; (\w+) bui.+ oppo/i,/\b(cph[12]\d{3}|p(?:af|c[al]|d\w|e[ar])[mt]\d0|x9007|a101op)\b/i],[l,[w,"OPPO"],[u,v]],[/vivo (\w+)(?: bui|\))/i,/\b(v[12]\d{3}\w?[at])(?: bui|;)/i],[l,[w,"Vivo"],[u,v]],[/\b(rmx[12]\d{3})(?: bui|;|\))/i],[l,[w,"Realme"],[u,v]],[/\b(milestone|droid(?:[2-4x]| (?:bionic|x2|pro|razr))?:?( 4g)?)\b[\w]+build\//i,/\bmot(?:orola)?[- ](\w*)/i,/((?:moto[\w\(\)]+|xt\d{3,4}|nexus 6)(?= bui|\)))/i],[l,[w,Sn],[u,v]],[/\b(mz60\d|xoom[2 ]{0,2}) build\//i],[l,[w,Sn],[u,y]],[/((?=lg)?[vl]k\-?\d{3}) bui| 3\.[-\w; ]{10}lg?-([06cv9]{3,4})/i],[l,[w,vt],[u,y]],[/(lm(?:-?f100[nv]?|-[\w\.]+)(?= bui|\))|nexus [45])/i,/\blg[-e;\/]+((?!browser|netcast|android tv)\w+)/i,/\blg-?([\d\w]+) bui/i],[l,[w,vt],[u,v]],[/(ideatab[-\w]+)/i,/lenovo ?(s[56]000[-\w]+|tab(?:[\w]+)|yt[-\d\w]{6}|tb[-\d\w]{6})/i],[l,[w,"Lenovo"],[u,y]],[/(?:maemo|nokia).*(n900|lumia \d+)/i,/nokia[-_ ]?([-\w\.]*)/i],[[l,/_/g,""],[w,"Nokia"],[u,v]],[/(pixel c)\b/i],[l,[w,H],[u,y]],[/droid.+; (pixel[\daxl ]{0,6})(?: bui|\))/i],[l,[w,H],[u,v]],[/droid.+ ([c-g]\d{4}|so[-gl]\w+|xq-a\w[4-7][12])(?= bui|\).+chrome\/(?![1-6]{0,1}\d\.))/i],[l,[w,St],[u,v]],[/sony tablet [ps]/i,/\b(?:sony)?sgp\w+(?: bui|\))/i],[[l,"Xperia Tablet"],[w,St],[u,y]],[/ (kb2005|in20[12]5|be20[12][59])\b/i,/(?:one)?(?:plus)?(a\d0\d\d)(?: b|\))/i],[l,[w,"OnePlus"],[u,v]],[/(alexa)webm/i,/(kf[a-z]{2}wi)( bui|\))/i,/(kf[a-z]+)( bui|\)).+silk\//i],[l,[w,U],[u,y]],[/((?:sd|kf)[0349hijorstuw]+)( bui|\)).+silk\//i],[[l,/(.+)/g,"Fire Phone $1"],[w,U],[u,v]],[/(playbook);[-\w\),; ]+(rim)/i],[l,w,[u,y]],[/\b((?:bb[a-f]|st[hv])100-\d)/i,/\(bb10; (\w+)/i],[l,[w,N],[u,v]],[/(?:\b|asus_)(transfo[prime ]{4,10}\w+|eeepc|slider \w+|nexus 7|padfone|p00[cj])/i],[l,[w,V],[u,y]],[/ (z[bes]6[027][012][km][ls]|zenfone \d\w?)\b/i],[l,[w,V],[u,v]],[/(nexus 9)/i],[l,[w,"HTC"],[u,y]],[/(htc)[-;_ ]{1,2}([\w]+(?=\)| bui)|\w+)/i,/(zte)[- ]([\w]+?)(?: bui|\/|\))/i,/(alcatel|geeksphone|nexian|panasonic|sony)[-_ ]?([-\w]*)/i],[w,[l,/_/g,""],[u,v]],[/droid.+; ([ab][1-7]-?[0178a]\d\d?)/i],[l,[w,"Acer"],[u,y]],[/droid.+; (m[1-5] note) bui/i,/\bmz-([-\w]{2,})/i],[l,[w,"Meizu"],[u,v]],[/\b(sh-?[altvz]?\d\d[a-ekm]?)/i],[l,[w,"Sharp"],[u,v]],[/(blackberry|benq|palm(?=\-)|sonyericsson|acer|asus|dell|meizu|motorola|polytron)[-_ ]?([-\w]*)/i,/(hp)([\w]+\w)/i,/(asus)-?(\w+)/i,/(microsoft); (lumia[\w]+)/i,/(lenovo)[-_ ]?([-\w]+)/i,/(jolla)/i,/(oppo)?([\w]+) bui/i],[w,l,[u,v]],[/(archos)(gamepad2?)/i,/(hp).+(touchpad(?!.+tablet)|tablet)/i,/(kindle)\/([\w\.]+)/i,/(nook)[\w]+build\/(\w+)/i,/(dell)(strea[kpr\d]*[\dko])/i,/(le[- ]+pan)[- ]+(\w{1,9}) bui/i,/(trinity)[- ]*(t\d{3}) bui/i,/(gigaset)[- ]+(q\w{1,9}) bui/i,/(vodafone)([\w]+)(?:\)| bui)/i],[w,l,[u,y]],[/(surface duo)/i],[l,[w,yt],[u,y]],[/droid [\d\.]+; (fp\du?)(?: b|\))/i],[l,[w,"Fairphone"],[u,v]],[/(u304aa)/i],[l,[w,"AT&T"],[u,v]],[/\bsie-(\w*)/i],[l,[w,"Siemens"],[u,v]],[/\b(rct\w+) b/i],[l,[w,"RCA"],[u,y]],[/\b(venue[\d]{2,7}) b/i],[l,[w,"Dell"],[u,y]],[/\b(q(?:mv|ta)\w+) b/i],[l,[w,"Verizon"],[u,y]],[/\b(?:barnes[& ]+noble |bn[rt])([\w\+]*) b/i],[l,[w,"Barnes & Noble"],[u,y]],[/\b(tm\d{3}\w+) b/i],[l,[w,"NuVision"],[u,y]],[/\b(k88) b/i],[l,[w,"ZTE"],[u,y]],[/\b(nx\d{3}j) b/i],[l,[w,"ZTE"],[u,v]],[/\b(gen\d{3}) b.+49h/i],[l,[w,"Swiss"],[u,v]],[/\b(zur\d{3}) b/i],[l,[w,"Swiss"],[u,y]],[/\b((zeki)?tb.*\b) b/i],[l,[w,"Zeki"],[u,y]],[/\b([yr]\d{2}) b/i,/\b(dragon[- ]+touch |dt)(\w{5}) b/i],[[w,"Dragon Touch"],l,[u,y]],[/\b(ns-?\w{0,9}) b/i],[l,[w,"Insignia"],[u,y]],[/\b((nxa|next)-?\w{0,9}) b/i],[l,[w,"NextBook"],[u,y]],[/\b(xtreme\_)?(v(1[045]|2[015]|[3469]0|7[05])) b/i],[[w,"Voice"],l,[u,v]],[/\b(lvtel\-)?(v1[12]) b/i],[[w,"LvTel"],l,[u,v]],[/\b(ph-1) /i],[l,[w,"Essential"],[u,v]],[/\b(v(100md|700na|7011|917g).*\b) b/i],[l,[w,"Envizen"],[u,y]],[/\b(trio[-\w\.]+) b/i],[l,[w,"MachSpeed"],[u,y]],[/\btu_(1491) b/i],[l,[w,"Rotor"],[u,y]],[/(shield[\w]+) b/i],[l,[w,"Nvidia"],[u,y]],[/(sprint)(\w+)/i],[w,l,[u,v]],[/(kin\.[onetw]{3})/i],[[l,/\./g,""],[w,yt],[u,v]],[/droid.+; (cc6666?|et5[16]|mc[239][23]x?|vc8[03]x?)\)/i],[l,[w,Ct],[u,y]],[/droid.+; (ec30|ps20|tc[2-8]\d[kx])\)/i],[l,[w,Ct],[u,v]],[/(ouya)/i,/(nintendo)([wids3utch]+)/i],[w,l,[u,m]],[/droid.+; (shield) bui/i],[l,[w,"Nvidia"],[u,m]],[/(playstation [345portablevi]+)/i],[l,[w,St],[u,m]],[/\b(xbox(?: one)?(?!; xbox))[\); ]/i],[l,[w,yt],[u,m]],[/smart-tv.+(samsung)/i],[w,[u,S]],[/hbbtv.+maple;(\d+)/i],[[l,/^/,"SmartTV"],[w,Rt],[u,S]],[/(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))/i],[[w,vt],[u,S]],[/(apple)?tv/i],[w,[l,K+" TV"],[u,S]],[/crkey/i],[[l,W+"cast"],[w,H],[u,S]],[/droid.+aft(\w)( bui|\))/i],[l,[w,U],[u,S]],[/\(dtv[\);].+(aquos)/i],[l,[w,"Sharp"],[u,S]],[/\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)/i,/hbbtv\/\d+\.\d+\.\d+ +\([\w]*; *(\w[^;]*);([^;]*)/i],[[w,Et],[l,Et],[u,S]],[/\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i],[[u,S]],[/((pebble))app/i],[w,l,[u,A]],[/droid.+; (glass)\d/i],[l,[w,H],[u,A]],[/droid.+; (wt63?0{2,3})\)/i],[l,[w,Ct],[u,A]],[/(quest( 2)?)/i],[l,[w,En],[u,A]],[/(tesla)(?: qtcarbrowser|\/[-\w\.]+)/i],[w,[u,M]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+? mobile safari/i],[l,[u,v]],[/droid .+?; ([^;]+?)(?: bui|\) applew).+?(?! mobile) safari/i],[l,[u,y]],[/\b((tablet|tab)[;\/]|focus\/\d(?!.+mobile))/i],[[u,y]],[/(phone|mobile(?:[;\/]| safari)|pda(?=.+windows ce))/i],[[u,v]],[/(android[-\w\.]{0,9});.+buil/i],[l,[w,"Generic"]]],engine:[[/windows.+ edge\/([\w\.]+)/i],[g,[f,ie+"HTML"]],[/webkit\/537\.36.+chrome\/(?!27)([\w\.]+)/i],[g,[f,"Blink"]],[/(presto)\/([\w\.]+)/i,/(webkit|trident|netfront|netsurf|amaya|lynx|w3m|goanna)\/([\w\.]+)/i,/ekioh(flow)\/([\w\.]+)/i,/(khtml|tasman|links)[\/]\(?([\w\.]+)/i,/(icab)[\/]([23]\.[\d\.]+)/i],[f,g],[/rv\:([\w\.]{1,9})\b.+(gecko)/i],[g,f]],os:[[/microsoft (windows)(vista|xp)/i],[f,g],[/(windows) nt 6\.2; (arm)/i,/(windows (?:phone(?: os)?|mobile))[\/]?([\d\.\w]*)/i,/(windows)[\/]?([ntce\d\.]+\w)(?!.+xbox)/i],[f,[g,xt,_n]],[/(win(?=3|9|n)|win 9x )([nt\d\.]+)/i],[[f,"Windows"],[g,xt,_n]],[/ip[honead]{2,4}\b(?:.*os ([\w]+) like mac|; opera)/i,/cfnetwork\/.+darwin/i],[[g,/_/g,"."],[f,"iOS"]],[/(mac os x)?([\w\.]*)/i,/(macintosh|mac_powerpc\b)(?!.+haiku)/i],[[f,"Mac OS"],[g,/_/g,"."]],[/droid ([\w\.]+)\b.+(android[- ]x86)/i],[g,f],[/(android|webos|qnx|bada|rim tablet os|maemo|meego|sailfish)[-\/]?([\w\.]*)/i,/(blackberry)\w*\/([\w\.]*)/i,/(tizen|kaios)[\/]([\w\.]+)/i,/\((series40);/i],[f,g],[/\(bb(10);/i],[g,[f,N]],[/(?:symbian ?os|symbos|s60(?=;)|series60)[-\/]?([\w\.]*)/i],[g,[f,"Symbian"]],[/mozilla\/[\d\.]+ \((?:mobile|tablet|tv|mobile; [\w]+); rv:.+ gecko\/([\w\.]+)/i],[g,[f,F+" OS"]],[/web0s;.+rt(tv)/i,/\b(?:hp)?wos(?:browser)?\/([\w\.]+)/i],[g,[f,"webOS"]],[/crkey\/([\d\.]+)/i],[g,[f,W+"cast"]],[/(cros)[\w]+ ([\w\.]+\w)/i],[[f,"Chromium OS"],g],[/(nintendo|playstation)([wids345portablevuch]+)/i,/(xbox); +xbox ([^\);]+)/i,/\b(joli|palm)\b?(?:os)?\/?([\w\.]*)/i,/(mint)[\/\(\)]?(\w*)/i,/(mageia|vectorlinux)[; ]/i,/([kxln]?ubuntu|debian|suse|opensuse|gentoo|arch(?= linux)|slackware|fedora|mandriva|centos|pclinuxos|red ?hat|zenwalk|linpus|raspbian|plan 9|minix|risc os|contiki|deepin|manjaro|elementary os|sabayon|linspire)(?: gnu\/linux)?(?: enterprise)?(?:[- ]linux)?(?:-gnu)?[-\/]?(?!chrom|package)([-\w\.]*)/i,/(hurd|linux)?([\w\.]*)/i,/(gnu)?([\w\.]*)/i,/\b([-frentopcghs]{0,5}bsd|dragonfly)[\/]?(?!amd|[ix346]{1,2}86)([\w\.]*)/i,/(haiku)(\w+)/i],[f,g],[/(sunos)?([\w\.\d]*)/i],[[f,"Solaris"],g],[/((?:open)?solaris)[-\/]?([\w\.]*)/i,/(aix)((\d)(?=\.|\)| )[\w\.])*/i,/\b(beos|os\/2|amigaos|morphos|openvms|fuchsia|hp-ux)/i,/(unix)?([\w\.]*)/i],[f,g]]},G=function(C,D){if(typeofC===h&&(D=C,C=n),!(thisinstanceofG))returnnewG(C,D).getResult();varE=C||(typeoft!==c&&t.navigator&&t.navigator.userAgent?t.navigator.userAgent:i),O=D?$r(Tn,D):Tn;returnthis.getBrowser=function(){var_={};return_[f]=n,_[g]=n,Ce.call(_,E,O.browser),_.major=Wr(_.version),_},this.getCPU=function(){var_={};return_[x]=n,Ce.call(_,E,O.cpu),_},this.getDevice=function(){var_={};return_[w]=n,_[l]=n,_[u]=n,Ce.call(_,E,O.device),_},this.getEngine=function(){var_={};return_[f]=n,_[g]=n,Ce.call(_,E,O.engine),_},this.getOS=function(){var_={};return_[f]=n,_[g]=n,Ce.call(_,E,O.os),_},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){returnE},this.setUA=function(_){returnE=typeof_===d&&_.length>X?Et(_,X):_,this},this.setUA(E),this};G.VERSION=r,G.BROWSER=Oe([f,g,p]),G.CPU=Oe([x]),G.DEVICE=Oe([l,w,u,m,v,S,y,A,M]),G.ENGINE=G.OS=Oe([f,g]),s.exports&&(e=s.exports=G),e.UAParser=G;varwe=typeoft!==c&&(t.jQuery||t.Zepto);if(we&&!we.ua){varze=newG;we.ua=ze.getResult(),we.ua.get=function(){returnze.getUA()},we.ua.set=function(C){ze.setUA(C);varD=ze.getResult();for(varEinD)we.ua[E]=D[E]}}})(typeofwindow=="object"?window:ee)})(rt,rt.exports);constXt=rt.exports;Xt(navigator.userAgent);letve;functionit(){if(ve!=null)returnve;try{newResponse(newReadableStream),ve=!0}catch(s){ve=!1}returnve}functionot(){return!(typeofTransformStream=="undefined"||!it())}classce{constructor(e,{method:t,headers:n,signal:r,body:i}){R(this,"url");R(this,"method");R(this,"headers");R(this,"body");R(this,"signal");this.url=e,this.method=t!=null?t:"GET",this.headers=newHeaders(n),this.body=i!=null?i:null,this.signal=r!=null?r:newAbortController().signal}}classne{constructor(e,{status:t,statusText:n,headers:r,underlayer:i}){R(this,"status");R(this,"statusText");R(this,"headers");R(this,"body");R(this,"bodyReadResult");R(this,"underlayer");if(this.status=t!=null?t:200,this.statusText=n!=null?n:"",this.headers=os(r),this.underlayer=i,e==null||!ot())this.body=e,this.bodyReadResult=Promise.resolve({success:!0,size:0});else{const[o,a]=ls(e);this.body=o,this.bodyReadResult=a}}}functionDe(s){const{status:e,statusText:t,headers:n,body:r}=s;returnnewne(r,{status:e,statusText:t,headers:n,underlayer:s})}classatextendsError{constructor(t){super(`Unexpected HTTP status: ${t.status}${t.statusText}`);R(this,"name","UnexpectedHttpStatusError");this.response=t}}consths=newss;letYt;typeofself!="undefined"&&(Yt=self,Yt.addEventListener("message",s=>hs.emit("message",s)));classdsextendsError{constructor(){super(...arguments);R(this,"name","WindowClientError")}}classfsextendsError{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannelCloseError")}}classwsextendsError{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannel1stMessageError")}}functionlt(s,e=()=>1){if(s.length===0)returnnull;constt=s.map(e),n=t.reduce((i,o)=>i+o,0);letr=Math.random()*n;for(leti=0;i<t.length;i++){consto=t[i];if(r<o)returns[i];r-=o}returns[0]}functionse(s){returns&&s.name==="AbortError"}constps=newfs().name,ms=newws().name;functionke(s){return!(s&&[ps,ms].includes(s.name)||se(s)||sinstanceofds)}classctextendsError{constructor(t){super(t+"");R(this,"name","ResolveError");this.cause=t}}classZtextendsError{constructor(){super(...arguments);R(this,"name","NoAvailableNodeError")}}classutextendsError{constructor(t){super(t+"");R(this,"name","DoWithNodeError");this.cause=t}}classreextendsError{constructor(){super(...arguments);R(this,"name","LocalDNSError")}}functiongs(s,e,t){constn=t||newURL(s).hostname;letr,i;s=s.replace(/^\w+:\/\//,"").split("#")[0];consto=s.indexOf("?");o>=0?(i=s.slice(o+1),s=s.slice(0,o)):i="";consta=s.indexOf("/");r=a>=0?s.slice(a):"",r=bs(e.rewrites,r),i=Ss(e.queryString,i);letc=n+r;returni!==""&&(c=c+"?"+i),c}functionbs(s,e){for(consttofs){constn=vs(t,e);if(n!=null){e=Rs(t,n);break}}returne}functionvs(s,e){returnnewRegExp(s.pattern).exec(e)}constys=/\${(\d+)}/g;functionRs(s,e){returns.repl.replace(ys,(t,n)=>{vari;constr=parseInt(n,10);returnr>=e.length?t:(i=e[r])!=null?i:""})}functionSs({type:s,values:e},t){if(s==="none")return"";if(s==="all")returnt;constn=Mn(t),r=e!=null?e:[],i={};returnObject.keys(n).forEach(o=>{s==="include"&&!r.includes(o)||s==="exclude"&&r.includes(o)||(i[o]=n[o])}),Fe(i)}functionJt(s,e){constt=newMap;returnfunction(...r){consti=e(...r),o=t.get(i);if(o!=null)returno;consta=s(...r);returnt.set(i,a),a.finally(()=>{t.delete(i)}),a}}constue=Q("dns"),Le=te("dns"),Cs="miku-delivery/dns/cdn/v1",Es=[];functionxs(){return$t(Es)}constht="result",_s={name:ht,indexes:[{name:"domain",keyPath:"domain"}]};classTs{constructor(e,t,n=Jn,r,i=2e3,o=5e3){R(this,"fingerprints",newMap);R(this,"disabledElts",newMap);R(this,"storage",newWt(Cs,[_s]));R(this,"getResolveResultFromStorage",Jt(e=>this.storage.get(ht,e),e=>e));R(this,"refreshResolveResultInStorage",Jt((e,t)=>b(this,null,function*(){constn=yieldthis.dnsResolver(e,t,this.app,this.logger),r=Date.now()+n.ttl*1e3,i=j(T({},n),{domain:t,expireAt:r});returnthis.saveResolveResultToStorage(t,i),i}),(e,t)=>t));this.logger=e,this.app=t,this.dnsResolver=n,this.cacheKeyFn=r,this.resolveTimeout=i,this.initialDisableDuration=o}getFingerprint(e){constt=this.fingerprints.get(e);if(t==null)thrownewError(`No fingerprint for ${e}`);returnt}isEltDisabled(e){constt=this.disabledElts.get(e);returnt==null?!1:t.after>Date.now()}setEltDisabled(e){constt=this.disabledElts.get(e),n=t==null?this.initialDisableDuration:t.duration,r=Date.now()+n;this.disabledElts.set(e,{duration:n*2,after:r})}removeEltDisabled(e){this.disabledElts.has(e)&&this.disabledElts.delete(e)}getCacheKey(e,t){returnb(this,null,function*(){if(this.cacheKeyFn!=null)returnthis.cacheKeyFn(e);constn=yieldthis.resolveDomain(newJ,t);returnXe(n)?gs(e,n.cacheKey,n.bucket):e})}getMediaOptimization(e){returnb(this,null,function*(){constt=yieldthis.resolveDomain(newJ,e);returnXe(t)?t.mediaOptimization:null})}saveResolveResultToStorage(e,t){returnb(this,null,function*(){returnthis.storage.set(ht,e,t)})}resolveDomain(e,t){returnb(this,null,function*(){constn=Date.now(),r=(()=>b(this,null,function*(){consti=yieldthis.getResolveResultFromStorage(t);returni==null?this.refreshResolveResultInStorage(e,t):(ks(i)&&(ue("result from storage cache expired",t),this.refreshResolveResultInStorage(e,t)),e.set("dnsResolveFromCache",!0),i)}))().then(i=>(e.set("dnsResolveTotalTime",z(Date.now(),n)),i));returnPromise.race([r,Pt(this.resolveTimeout,"Resolve domain")]).catch(i=>{throwLe("DNS resolve failed:",i),newct(i)})})}resolve(e,t){returnb(this,null,function*(){letn=null;returnyieldthis.do(e,t,1,r=>{n=r}),n})}do(e,t,n,r){returnb(this,null,function*(){leti;ue("Resolve for",t);consto=newURL(t).hostname,[a,c]=yieldPromise.all([this.getCacheKey(t,o),this.resolveDomain(e,o)]);if(!Xe(c))thrownewre(`Non-ECDN resolve result: ${o}`);const{groups:h,rules:d}=c;if(h.length===0)thrownewZt(`No available group for ${o}`);ue("Resolved for",t);constp=es(d,a);if(p==null)thrownewre("No matched rule found");if(!ts(p))thrownewre("Do not serve with given rule");letl=p.groups.map(({groupidx:f,weight:u,splitn:w})=>{constg=h[f];if(g==null)thrownewError(`Unexpected groupidx: ${f}`);return{group:g,weight:u,splitn:w}});for(letf=0;f<n;f++){constu=lt(l,w=>w.weight);if(u==null)break;try{ue("doWithGroup",f,a),yieldthis.doWithGroup(e,u.group,a,u.splitn,r);return}catch(w){if(Le("doWithGroup (weight:",u.weight,") failed:",w,a),i=w,se(w))break;ke(w)&&(l=l.filter(g=>g!==u))}}throwi=se(i)?i:newut(i),i})}doWithGroup(e,t,n,r,i){returnb(this,null,function*(){consto=t.elts.filter(l=>!this.isEltDisabled(l.id));if(o.length===0)thrownewError("No available elt");consta=As(t),c=newSet(o.map(l=>l.id)),h=r===1?2:r;letd=a.getN(n,h,c).map(l=>o.find(f=>f.id===l)),p;for(letl=0;l<2;l++){constf=lt(d.slice(0,r),u=>u.replicas);if(f==null)break;try{ue("doWithElt",f.id,n),e.set("downloadEltID",f.id),yieldDs(f,n,i),this.removeEltDisabled(f.id);return}catch(u){if(Le("doWithElt",f.id,"failed:",u,n),p=u,se(u))break;ke(u)&&(d=d.filter(w=>w!==f),this.setEltDisabled(f.id))}}throwp})}}consten=newMap;functionAs({elts:s}){conste=s.map(({id:r,replicas:i})=>`${r}:${i}`).join(","),t=en.get(e);if(t!=null)returnt;constn=newme;returnn.set(s.map(r=>({key:r.id,replicas:r.replicas}))),en.set(e,n),n}functionDs(s,e,t){returnb(this,null,function*(){letn=s.addrs;if(n.length===0)thrownewError("Empty addr list");letr;for(leti=0;i<2;i++){consto=lt(n);if(o==null)break;try{ue("do job with",o,e),yieldt(o);return}catch(a){if(Le("do job with",o,"failed:",a,e),r=a,se(a))break;ke(a)&&(n=n.filter(c=>c!==o))}}throwr})}functionks(s){returns.expireAt<Date.now()}classLs{constructor(){R(this,"front",null);R(this,"back",null)}insertElementBefore(e,t){constn=t.prev;n!=null?(n.next=e,e.prev=n):this.front=e,t.prev=e,e.next=t}insertElementAfter(e,t){constn=t.next;n!=null?(n.prev=e,e.next=n):this.back=e,t.next=e,e.prev=t}pushElementFront(e){constt=this.front;t!=null?(t.prev=e,e.next=t):this.back=e,this.front=e}pushElementBack(e){constt=this.back;t!=null?(t.next=e,e.prev=t):this.front=e,this.back=e}moveBefore(e,t){e!==t&&(this.remove(e),this.insertElementBefore(e,t))}moveAfter(e,t){e!==t&&(this.remove(e),this.insertElementAfter(e,t))}moveToFront(e){this.remove(e),this.pushElementFront(e)}moveToBack(e){this.remove(e),this.pushElementBack(e)}insertBefore(e,t){constn={value:e,prev:null,next:null};returnthis.insertElementBefore(n,t),n}insertAfter(e,t){constn={value:e,prev:null,next:null};returnthis.insertElementAfter(n,t),n}pushFront(e){constt={value:e,prev:null,next:null};returnthis.pushElementFront(t),t}pushBack(e){constt={value:e,prev:null,next:null};returnthis.pushElementBack(t),t}remove(e){constt=e.prev,n=e.next;returnt!=null?(t.next=n,e.prev=null):this.front=n,n!=null?(n.prev=t,e.next=null):this.back=t,e.value}walk(e){lett=this.front;for(;t!=null;){if(e(t.value,t)===!1)return;t=t.next}}reverseWalk(e){lett=this.back;for(;t!=null;){if(e(t.value,t)===!1)return;t=t.prev}}}constBe=Q("dc/cr"),Bs=te("dc/cr"),Ps={reservedQuota:5*1024*1024};classMs{constructor(e,t=Ps){R(this,"inited");R(this,"itemElementMap",newMap);R(this,"itemList",newLs);this.dc=e,this.config=t,this.inited=this.resume()}resume(){returnb(this,null,function*(){conste=[];yieldthis.dc.walkItems((t,n)=>{constr={key:n,usedTime:t.usedTime,size:dt(t)},i=this.itemList.pushBack(r);this.itemElementMap.set(n,i),e.push(...Ws(t,n))});try{constt=yieldthis.dc.getBrowserCacheKeys();for(letnoft)e.includes(n)||(Be("clear inaccessible cache:",n),yieldthis.dc.browserCacheDelete(n))}catch(t){Bs("failed to clear inaccessible caches:",t)}})}addItem(e,t){constn={key:e,usedTime:t.usedTime,size:dt(t)};letr=null;returnthis.itemList.reverseWalk((i,o)=>{if(i.usedTime<=t.usedTime)returnr=this.itemList.insertAfter(n,o),!1}),r==null&&(r=this.itemList.pushFront(n)),this.itemElementMap.set(e,r),r}removeItem(e){constt=this.itemElementMap.get(e);t!=null&&(this.itemElementMap.delete(e),this.itemList.remove(t))}onItemSet(e,t){returnb(this,null,function*(){yieldthis.inited;letn=this.itemElementMap.get(e);if(n==null){this.addItem(e,t);return}n.value.size=dt(t),t.usedTime!==n.value.usedTime&&(n.value.usedTime=t.usedTime,this.itemList.moveToBack(n))})}getLeftSpace(){returnb(this,null,function*(){if(typeofnavigator.storage.estimate=="undefined")returnnull;const{quota:e,usage:t}=yieldnavigator.storage.estimate();returne!=null&&t!=null?e-t:null})}freeUpSpace(e){returnb(this,null,function*(){yieldthis.inited;lett=0;constn=[];this.itemList.walk(({key:r,size:i})=>{if(i!==0&&(n.push(r),t+=i,t>=e))return!1}),Be("to free up space, remove",n),yieldPromise.all(n.map(r=>b(this,null,function*(){yieldthis.dc.removeItemWithContent(r),this.removeItem(r)})))})}beforeContentSet(e,t,n){returnb(this,null,function*(){if(n==null)return;yieldthis.inited;constr=yieldthis.getLeftSpace(),i=this.config.reservedQuota;if(r!=null&&r-i<n){consto=n-r+i;Be("freeUpSpace for",e,t,o),yieldthis.freeUpSpace(o)}})}onQuotaExceeded(e,t,n){returnb(this,null,function*(){Be("quota exceeded",e,t,n);constr=this.config.reservedQuota;yieldthis.freeUpSpace(n?n+r:r)})}}functionIs([s,e],t){returne=e!=null?e:t,e!=null?e-s:0}functiondt(s){returns.pieces.reduce((e,t)=>{varn,r;returne+Is(t,(r=(n=s.meta)==null?void0:n.fsize)!=null?r:null)},0)}constOs=Q("dc"),zs="miku-delivery/dc/v1",tn=["miku/dc","miku/dc/v2","miku/dc/v3"];functionNs(){returnPromise.all([Hs(tn),$t(tn)])}functionHs(s){returnb(this,null,function*(){constt=(yieldcaches.keys()).filter(n=>s.includes(n));yieldPromise.all(t.map(n=>caches.delete(n)))})}constye="item",nn="usedTimeIndex",Us={name:ye,indexes:[{name:nn,keyPath:"usedTime"}]},qs=32*1024*1024;class$s{constructor(e={},t=zs){R(this,"db");R(this,"cr");R(this,"browserCache",null);R(this,"browserCachePromise",null);this.config=e,this.ns=t,this.db=newWt(this.ns,[Us]),this.cr=newMs(this)}openBrowserCache(){returnb(this,null,function*(){returnthis.browserCachePromise!=null?this.browserCachePromise:(this.browserCachePromise=caches.open(this.ns).catch(e=>{thrownewhe(e)}),this.browserCachePromise.then(e=>{this.browserCache=e}),this.browserCachePromise)})}getItem(e){returnb(this,null,function*(){returnthis.db.get(ye,e)})}setItem(e,t){returnb(this,null,function*(){Os("setItem",e,t),yieldthis.db.set(ye,e,t),yieldthis.cr.onItemSet(e,t)})}walkItems(e){returnb(this,null,function*(){returnthis.db.walkBy(ye,nn,e)})}removeItemWithContent(e){returnb(this,null,function*(){constt=yieldthis.getItem(e);t!=null&&(yieldPromise.all(t.pieces.map(n=>this.removeContent(e,n))),yieldthis.db.remove(ye,e))})}browserCacheMatch(e){returnb(this,null,function*(){lett=this.browserCache;returnt==null&&(t=yieldthis.openBrowserCache()),t.match(e).catch(n=>{thrownewhe(n)})})}browserCachePut(e,t){returnb(this,null,function*(){letn=this.browserCache;n==null&&(n=yieldthis.openBrowserCache()),yieldn.put(e,t).catch(r=>{thrownewhe(r)})})}browserCacheDelete(e){returnb(this,null,function*(){lett=this.browserCache;t==null&&(t=yieldthis.openBrowserCache()),yieldt.delete(e).catch(n=>{thrownewhe(n)})})}getBrowserCacheKeys(){returnb(this,null,function*(){lete=this.browserCache;returne==null&&(e=yieldthis.openBrowserCache()),yielde.keys().then(t=>t.map(n=>n.url))})}getContent(e,t){returnb(this,null,function*(){constn=yieldthis.browserCacheMatch(Pe(e,t));if(n!=null){if(n.body==null)thrownewError("Body expected for cached response");returnDe(n)}})}setContent(e,t,n){returnb(this,null,function*(){if(!it())returnyieldthis.cacheResponse(e,t,n.underlayer),[t];const{headers:r,body:i}=n,o=nt(r);returnyieldcs(i,t[0],qs,(a,c,h)=>b(this,null,function*(){r.set("Content-Range",Je({start:c,end:h-1,totalSize:o})),r.set("Content-Length",h-c+"");constd=newResponse(a,{status:200,statusText:"OK",headers:r});yieldthis.cacheResponse(e,[c,h],d)}))})}cacheResponse(e,t,n){returnb(this,null,function*(){constr=Pe(e,t),i=le(n.headers);yieldthis.cr.beforeContentSet(e,t,i);try{yieldthis.browserCachePut(r,n)}catch(o){throwoinstanceofhe&&o.causeinstanceofError&&o.cause.name==="QuotaExceededError"&&this.cr.onQuotaExceeded(e,t,i),o}})}removeContent(e,t){returnb(this,null,function*(){constn=Pe(e,t);returnthis.browserCacheDelete(n)})}dispose(){this.db.dispose()}}functionPe(s,e){vart;return/^https?:\/\//.test(s)||(s="https://miku-cache.com/"+s),`${s}_with_range_${e[0]}_${(t=e[1])!=null?t:""}`}functionWs(s,e){returns.pieces.map(t=>Pe(e,t))}classheextendsError{constructor(t){super(t+"");R(this,"name","BrowserCacheError");this.cause=t}}classFs{constructor(e){this.logger=e}log(e){returnthis.logger.log("DoLog",e)}}constsn="1.1.0",js=3,rn=Q("http");classon{constructor(e,t,n,r=0){R(this,"doLogger");this.client=t,this.resolver=n,this.clientResponseTimeout=r,this.doLogger=newFs(e)}doWithResolved(e,t,n){returnb(this,null,function*(){rn("fetch",t.url,"with resolved",n);constr=newAbortController;zn(r,t.signal);consti=newce(t.url,j(T({},t),{signal:r.signal}));i.headers.set("X-Miku-Agent",`miku-delivery-web/v${sn}`);leto=this.client.fetch(e,i,n);this.clientResponseTimeout>0&&(o=Promise.race([o,Pt(this.clientResponseTimeout,"HTTPClient get response")]),o.catch(c=>{cinstanceofBt&&r.abort(c)}));consta=yieldo;if(rn("fetch",t.url,"succeeded with status",a.status),a.status===429||a.status>=500)thrownewat(a);returna})}originalDo(e,t){returnb(this,null,function*(){if(t.signal.aborted)throwt.signal.reason;letn=-1,r;if(yieldthis.resolver.do(e,t.url,js,i=>b(this,null,function*(){consto=newJ(e);n++,o.set("downloadRetryCount",n),r=yieldthis.doWithResolved(o,t,i)})),r==null)thrownewError(`Http do failed: resolver do finished with no finalResp, url: ${t.url}`);returnr})}do(e,t){returnb(this,null,function*(){constn=Date.now(),r=je();e.set("doID",r);leti,o=null;try{returni=yieldthis.originalDo(e,t),i}catch(a){throwo=a,a}finally{const{onDoError:a,onDoResponsed:c}=this.getDoLog(e,r,n);i==null?a(o):c(i.status)}})}getDoLog(e,t,n){constr=a=>{varc;returnthis.doLogger.log(T({lookup_type:!0,t_lookup:(c=e.get("dnsResolveFromCache")===!0?0:e.get("dnsResolveTotalTime"))!=null?c:-1,t_total:-1,ts_st:n,err_desc:"",err_msg:"",status_code:-1,task_id:e.get("taskID"),id:t},a))};return{onDoError:a=>{constc=Date.now();r(T({t_total:z(c,n)},ae(a)))},onDoResponsed:a=>{constc=Date.now();r({t_total:z(c,n),status_code:a})}}}}classKs{constructor(e){this.logger=e}log(e){returnthis.logger.log("TaskLog",e)}}classan{constructor(e,t,n,r){R(this,"id",je());R(this,"priority",0);R(this,"signal");R(this,"started",!1);R(this,"taskLogger");this.url=e,this.range=t,this.startByClient=r,this.taskLogger=newKs(n)}setPriority(e){this.priority=e}start(e){returnb(this,null,function*(){if(this.started)thrownewError("Task already started");if(this.started=!0,this.signal=e,e&&e.aborted)throwe.reason;constt=Date.now(),n=newJ;n.set("taskID",this.id),n.set("taskDomain",newURL(this.url).hostname);letr,i=null;try{returnr=yieldthis.startByClient(n,this),r}catch(o){throwi=o,o}finally{const{logOnError:o,logOnTransferred:a}=this.log(n,t);r==null?o(i):r.underlayer.bodyReadResult.then(c=>{c.success?a():o(c.error)})}})}log(e,t){constn=e.get("taskCacheMatchAt"),r=e.get("task1stHttpDoAt"),i=e.get("taskResultStreamAt"),o=Date.now(),a=d=>{varp,l,f,u,w;returnthis.taskLogger.log(T({type:(p=e.get("taskType"))!=null?p:1,id:this.id,url:this.url,err_msg:"",err_desc:"",range_st:(f=(l=this.range)==null?void0:l.start)!=null?f:-1,range_end:(w=(u=this.range)==null?void0:u.end)!=null?w:-1,ts_st:t,t_cc_match:z(n,t),t_http_do:z(r,n),t_res_stream:z(i,n),t_res:z(o,i),t_trans:-1,t_total:-1},d))};return{logOnError:d=>{constp=Date.now();a(T({t_total:z(p,t)},ae(d)))},logOnTransferred:()=>{constd=Date.now();a({t_trans:z(d,o),t_total:z(d,t)})}}}}classln{constructor(e,t,n,r,i){this.stream=e,this.size=t,this.fileSize=n,this.contentType=r,this.underlayer=i}blob(){returnb(this,null,function*(){conste=this.stream.getReader(),t=[];for(;;){const{done:n,value:r}=yielde.read();if(n)break;consti=r;t.push(i)}returnnewBlob(t)})}}functionft(s,e,t){returns!=null&&t!=null&&t>=s&&(t=null),(e==null||e<0)&&(e=0),[e,t]}functioncn(s,e){varr;constt=((r=e[0])!=null?r:0)===0,n=e[1]==null||s!=null&&e[1]===s;returnt&&n}functionVs(s,e){varr,i;constt=(r=e[0])!=null?r:0,n=(i=e[1])!=null?i:s;returnn==null?null:n-t}functionGs(s,e,t){varc,h;if(e===0)return[];constn=(d,p)=>hn(d,p,e!=null?e:Number.POSITIVE_INFINITY),r=(c=s==null?void0:s[0])!=null?c:0,i=(h=s==null?void0:s[1])!=null?h:e,o=[];leta=r;for(constdoft){if(a==null||e!=null&&d[1]!=null&&d[1]>e)break;if(!(d[1]!=null&&a>=d[1])){if(i==null||i>d[0]){d[0]>a&&o.push({cached:!1,range:ft(e,a,d[0])});constp=n(d[0],a)?d[0]:a,l=n(d[1],i)?i:d[1];n(l,p)&&(o.push({cached:!0,range:ft(e,p,l)}),a=l);continue}break}}returnn(i,a)&&o.push({cached:!1,range:ft(e,a,i)}),o}functionQs(s,e){varr;constt=(r=e[0])!=null?r:0,n=e[1];for(constiofs){if(i[1]!=null&&i[1]<=t)continue;if(i[0]>t)break;consto=t-i[0],a=Ys(n!=null?n:i[1],i[0]);return{piece:i,start:o,end:a}}thrownewError("Piece not found")}functionXs(s,e){constt=s.filter(o=>!e.some(a=>o[0]===a[0]&&o[1]===a[1])),n=[e[0][0],e[e.length-1][1]];for(letooft)if(un(o,n))return{toSave:t,toRemove:e};constr=[],i=[];for(letooft)un(n,o)?i.push(o):r.push(o);return{toSave:[...r,...e].sort((o,a)=>o[0]-a[0]),toRemove:i}}functionun(s,e){returns[0]<=e[0]&&!hn(e[1],s[1],Number.POSITIVE_INFINITY)}functionhn(s,e,t){constn=s!=null?s:t,r=e!=null?e:t;returnn>r}functionYs(s,e){returns==null||e==null?null:s-e}functiondn(s){conste={},t=s.split(",").map(n=>{let[r,i]=n.split("=").map(o=>o.trim());return[r.toLowerCase(),i]});for(const[n,r]oft)if(n==="max-age"){if(r!=null){consti=parseInt(r,10);Number.isNaN(i)||(e["max-age"]=i)}}else(n==="no-cache"||n==="no-store")&&(e[n]=!0);returne}functionMe(s){returnMath.floor(s/1e3)}functionfn(s,e){constt=s.get("Date");if(t==null)returne;constn=Date.parse(t);returnNumber.isNaN(n)?e:n}functionZs(s,e,t){if(s!=null)returns;constn=e.get("Expires");if(n!=null){letr=Date.parse(n);Number.isNaN(r)&&(r=0);consti=fn(e,t);returnMe(r-i)}return3600}functionJs(s){conste=s.get("Age");if(e==null)return0;constt=parseInt(e,10);returnNumber.isNaN(t)?0:t}functioner(s,e,t,n){constr=Js(s),i=fn(s,t),o=Math.max(0,Me(t-i)),a=Me(t-e),c=r+a,h=Math.max(o,c),d=Me(n-t);returnh+d}functiontr(s,e,t,n,r){varc;consti=(c=s==null?void0:s["max-age"])!=null?c:null,o=Zs(i,e,n),a=er(e,t,n,r);returno>a}functionnr(s,e,t,n){constr=s.get("Cache-Control"),i=r!=null?dn(r):null;return(i==null?void0:i["no-cache"])===!0?!0:!tr(i,s,e,t,n)}functionsr(s){conste=s.get("Cache-Control"),t=e!=null?dn(e):null;return!(t!=null&&t["no-store"]===!0)}functionrr(s){conste=s.get("ETag");returne==null?null:e.startsWith("W/")?e.slice(2):e}functionir(s,e){constt=newHeaders(s),n=rr(e);n!=null&&t.set("If-None-Match",n);constr=e.get("Last-Modified");returnr!=null&&t.set("If-Modified-Since",r),t}functionor(s,e){return!(s.get("Last-Modified")===e.get("Last-Modified")&&s.get("ETag")===e.get("ETag"))}functionar(s,e){constt=newHeaders(s);returne.forEach((n,r)=>{r=r.toLowerCase(),!(r==="content-length"||r==="content-encoding"||r==="content-range")&&t.set(r,n)}),t}constlr={threshold:0,contentRangeExposed:!0},P=Q("ftask"),de=te("ftask");classcr{constructor(e,t,n,r,i,o,a){R(this,"id",je());R(this,"inited");R(this,"meta",null);R(this,"cachePieces",[]);R(this,"usedTime",0);this.cache=e,this.nativeHttpClient=t,this.http=n,this.key=r,this.url=i,this.patterns=o,this.getMediaOptimization=a,this.inited=this.resume()}fileSize(){vare,t;return(t=(e=this.meta)==null?void0:e.fsize)!=null?t:null}cacheValidationRequired(){if(this.meta==null)return!1;const{requestTime:e,responseTime:t,headers:n}=this.meta;returne==null||t==null||n==null?!1:nr(n,e,t,Date.now())}isMedia(e){constt=xe(e.url);returnthis.patterns.media.some(n=>n.test(t))}isRangeStartFirstRequested(e){varn;constt=(n=e[0])!=null?n:0;return!this.cachePieces.some(r=>{vari;returnr[0]<=t&&t<=((i=r[1])!=null?i:Number.POSITIVE_INFINITY)})}startTask(e,t){returnb(this,null,function*(){P("startTask",t.url,t.id,t.range);letn;constr=t.range!=null?[t.range.start,t.range.end]:[0,null];yieldthis.inited,this.usedTime=Date.now(),this.save().catch(a=>de("save failed when startTask:",a)),ot()?n=yieldthis.readRangeWithStream(e,t,r):(P("supportStreamOperation: false",t.url,t.id),n=yieldthis.readRangeWithoutStream(e,t,r));consti=this.meta;if(i==null)thrownewError("Missing meta in fileTask");P("startTask resolved",t.url,t.id);consto=Vs(i.fsize,r);returnnewln(n.body,o,i.fsize,i.headers.get("Content-Type"),n)})}readRangeWithoutStream(e,t,n){returnb(this,null,function*(){vara,c;letr;consti=[(a=n[0])!=null?a:0,n[1]],o=(c=yieldthis.cache.getContent(this.key,i))!=null?c:null;if(e.set("taskCacheMatchAt",Date.now()),o!=null&&!this.cacheValidationRequired())P("use cache",t.url,t.id),r=o;elseif(P("doRequestAndSaveCache",t.url,t.id,o!=null),r=yieldthis.doRequestAndSaveCache(e,t,n,o!=null,!1),r.status===304){if(o==null)thrownewError("Unexpected 304 with no cached response");r=o}returne.set("taskResultStreamAt",Date.now()),r})}readRangeWithStream(e,t,n){returnb(this,null,function*(){constr=this.isMedia(t),i=this.cacheValidationRequired();P("cacheValidationRequired",i);consto=Gs(n,this.fileSize(),this.cachePieces);if(P("applyRange",n,this.fileSize(),this.cachePieces,o),i){consth=o.some(l=>l.cached),d=r?yieldthis.getMediaOptimization():!1,p=yieldthis.doRequestAndSaveCache(e,t,n,h,d);if(p.status===200||p.status===206)returnp}e.set("taskCacheMatchAt",Date.now());consta=newTransformStream(void0),c=yieldnewPromise((h,d)=>b(this,null,function*(){try{for(letp=0;p<o.length;p++){constl=p===0,{cached:f,range:u}=o[p];letw=null;if(f&&(w=yieldthis.readPieceFromLocal(e,t,u)),w==null){constx=r&&l&&this.isRangeStartFirstRequested(u)?yieldthis.getMediaOptimization():!1;w=yieldthis.readPieceFromRemote(e,t,u,x)}l&&h(w);constg=p===o.length-1;yieldw.body.pipeTo(a.writable,{preventClose:!g})}}catch(p){p!=null&&de("readRange stream error for",this.url,p),a.writable.abort(p),d(p)}}));returne.set("taskResultStreamAt",Date.now()),newne(a.readable,c)})}readPieceFromLocal(e,t,n){returnb(this,null,function*(){P("readPieceFromLocal",t.url,n);const{piece:r,start:i,end:o}=Qs(this.cachePieces,n),a=yieldthis.cache.getContent(this.key,r);returna==null?(de(`Missing cache item: ${this.key} [${r})`),null):newne(st(a.body,[i,o]),a)})}readPieceFromRemote(e,t,n,r){returnb(this,null,function*(){P("readPieceFromRemote",t.url,n);consti=yieldthis.doRequestAndSaveCache(e,t,n,!1,r);return!cn(this.fileSize(),n)&&i.status===200?(de("Range request not supported for",this.url),newne(st(i.body,n),i)):i})}doRequest(e,t,n,r,i){returnb(this,null,function*(){varu;e.get("task1stHttpDoAt")==null&&e.set("task1stHttpDoAt",Date.now());consto=newJ(e);o.set("downloadFileTaskID",this.id);leta=newHeaders({"Accept-Encoding":"identity;q=1, *;q=0"});n!=null&&(t.range==null&&cn(this.fileSize(),n)||a.set("Range",be({start:n[0],end:n[1]==null?null:n[1]-1})));constc=(u=this.meta)==null?void0:u.headers;r&&c!=null&&(a=ir(a,c));consth=newce(t.url,{method:"GET",headers:a,signal:t.signal}),d=Date.now();letp;i===!1||i.threshold<=0?p=yieldthis.http.do(o,h):p=yieldur((...w)=>this.http.do(...w),(...w)=>this.nativeHttpClient.fetch(...w),i)(o,h);constl=Date.now();if(p.body==null)thrownewError("Body expected");letf=p.headers;if(r&&c!=null&&p.status===304)P(`updateStoredHeaders for ${this.url}`),f=ar(c,p.headers);elseif(p.status!==200&&p.status!==206)thrownewat(p);returnyieldthis.onResponse(f,d,l),p.bodyReadResult.then(w=>{P(`bodyReadResult for ${this.url}:`,w)}),p})}doRequestAndSaveCache(e,t,n,r,i){returnb(this,null,function*(){consto=yieldthis.doRequest(e,t,n,r,i);return(o.status===200||o.status===206)&&sr(o.headers)?this.saveCachePiece(t,n,o):o})}saveCachePiece(e,t,n){returnb(this,null,function*(){varo,a;letr=n,i;if(ot()){const{main:c,minor:h}=us(n.body);r=newne(c,n),i=newne(h,n)}elseif(!e.range){constc=n.underlayer.clone();i=De(c)}if(i!=null){constc=[(o=t==null?void0:t[0])!=null?o:0,(a=t==null?void0:t[1])!=null?a:null];P("saveCachePiece",this.url,c),this.cache.setContent(this.key,c,i).then(h=>b(this,null,function*(){if(h.length===0)return;const{toSave:d,toRemove:p}=Xs(this.cachePieces,h);if(this.cachePieces=d,p.length>0){P("remove duplicated cache pieces",p);try{yieldPromise.all(p.map(l=>this.cache.removeContent(this.key,l)))}catch(l){P("exception occurred while removing duplicated cache pieces",l)}}returnthis.save()})).then(()=>P("saveCachePiece finish",this.url,c,this.cachePieces),h=>de("saveCachePiece failed",this.url,c,h))}returnr})}onResponse(e,t,n){returnb(this,null,function*(){constr=this.meta;this.meta={fsize:nt(e),requestTime:t,responseTime:n,headers:e},(r==null?void0:r.headers)!=null&&or(r.headers,e)&&(P(`${this.url} modified, clear local cache`),yieldPromise.all(this.cachePieces.map(i=>this.cache.removeContent(this.key,i))),this.cachePieces=[]),this.save().catch(i=>de("save failed when onResponse:",i))})}resume(){returnb(this,null,function*(){conste=yieldthis.cache.getItem(this.key);e==null||e.meta==null||(this.meta=j(T({},e.meta),{headers:e.meta.headers!=null?newHeaders(e.meta.headers):null}),this.cachePieces=e.pieces)})}save(){returnb(this,null,function*(){varr,i;conste=((r=this.meta)==null?void0:r.headers)!=null?[...((i=this.meta)==null?void0:i.headers).entries()]:null,n={meta:this.meta!=null?j(T({},this.meta),{headers:e}):null,pieces:this.cachePieces,usedTime:this.usedTime};yieldthis.cache.setItem(this.key,n)})}}functionur(s,e,{threshold:t,contentRangeExposed:n}){returnfunction(i,o){returnb(this,null,function*(){varX,U;constM=o,{url:a}=M,c=Tt(M,["url"]),h=tt(o.headers);P("doWithInitialOptimization",a);constd=newJ(i),p=newHeaders(c.headers),l=T({start:null,end:null},h);l.start=(X=l.start)!=null?X:0;constf=l.start+t-1;(l.end==null||l.end>f)&&(l.end=f),p.set("Range",be(l));constu=newce(a,j(T({},c),{headers:p})),g=yield((K,V)=>b(this,null,function*(){varie;letN=null;const$=tt(V.headers);$!=null&&!Ft($)&&!n&&(N=hr(a,c.headers,e));constW=yielde(K,V);if($!=null&&W.status===206&&!W.headers.get("Content-Range")){constF=Ft($)?le(W.headers):yieldN;if(F!=null){constH=Je({start:$.start,end:(ie=$.end)!=null?ie:F-1,totalSize:F});W.headers.set("Content-Range",H)}}returnW}))(d,u);if(g.body==null)thrownewError("Body expected for initial response");if(g.status!==206)returng;constx=Ze(g.headers);if(x==null)thrownewError("Header Content-Range expected for 206 response");constm=(()=>{varie;constK=le(g.headers);if(K!=null&&K<t)returng.body;constV=newHeaders(c.headers),N=T({start:null,end:null},h);if(N.start=((ie=N.start)!=null?ie:0)+t,N.end!=null&&N.end<N.start)returng.body;P("doWithInitialOptimization followingRange",N),V.set("Range",be(N));const$=newce(a,j(T({},c),{headers:V})),W=newTransformStream;returng.body.pipeTo(W.writable,{preventClose:!0}).then(()=>b(this,null,function*(){P("doWithInitialOptimization initialBody transfered");letF;try{constH=yields(i,$);if(H.body==null)thrownewError(`Body expected for following response of ${a}`);if(H.status===200)F=st(H.body,[N.start,N.end==null?null:N.end+1]);elseif(H.status===206)F=H.body;elsethrownewat(H)}catch(H){if(dr(H))P("use fallback fetch for doWithInitialOptimization followingBody",H),F=(yielde(i,$)).body;else{P("doWithInitialOptimization get followingBody failed",H),W.writable.abort(H);return}}F.pipeTo(W.writable).then(()=>P("doWithInitialOptimization followingBody transfered"),H=>P("doWithInitialOptimization followingBody transfer failed",H))}),F=>b(this,null,function*(){P("doWithInitialOptimization initialBody transfer failed",F)})),W.readable})(),v=x.totalSize,y=newHeaders(g.headers);if(y.delete("Content-Range"),y.delete("Content-Length"),h==null)returnv!=null&&y.set("Content-Length",v+""),newne(m,{status:200,statusText:"OK",headers:y,underlayer:g.underlayer});constS=(U=h.start)!=null?U:0,A=h.end!=null?h.end:v!=null?v-1:null;returnA!=null&&y.set("Content-Length",A-S+1+""),y.set("Content-Range",Je({start:S,end:A,totalSize:v})),newne(m,{status:206,statusText:"Partial Content",headers:y,underlayer:g.underlayer})})}}functionhr(s,e,t){returnb(this,null,function*(){constn=newHeaders(e);n.delete("Range");constr=yieldt(newJ,newce(s,{method:"HEAD",headers:n}));returnle(r.headers)})}functiondr(s){return[ct,re,Zt,ut,ge,he].some(e=>sinstanceofe)}classfr{constructor(){R(this,"locked",!1);R(this,"waitings",[]);this.unlock=this.unlock.bind(this)}lock(){returnb(this,null,function*(){returnthis.locked?(yieldnewPromise(e=>{this.waitings.push(e)}),this.unlock):(this.locked=!0,this.unlock)})}unlock(){if(this.waitings.length===0){this.locked=!1;return}this.waitings.shift()()}runExclusive(e){returnb(this,null,function*(){constt=yieldthis.lock();try{returnyielde()}catch(n){thrown}finally{t()}})}}functionwr(){varr,i;const{os:s,device:e,browser:t}=Xt(navigator.userAgent);letn;returntypeofwindow!="undefined"?n=window.location:typeofself!==void0&&(n=self.location),{os:`${s.name}_${s.version}`,browser:`${t.name}_${t.version}`,app:(r=n==null?void0:n.host)!=null?r:"",sdk:`Web SDK v${sn}`,dev_model:(i=e.model)!=null?i:"",dev_id:""}}constwt=200,pt=Q("log"),pr=te("log");classmr{constructor(e,t,n,r,i){R(this,"env",Fe(wr()));R(this,"flushMutex",newfr);R(this,"buffer",[]);this.schemaName=e,this.fetch=t,this.flushNum=n,this.flushWait=r,this.app=i}callApiLog(e){returnb(this,null,function*(){constt=this.fetch;try{constn=Qe({appID:this.app.appID,appSalt:this.app.appSalt,path:`${Lt}/v1/log/${this.schemaName}`}),r=yieldt(newRequest(`${Lt}/v1/log/${this.schemaName}`,{method:"POST",headers:{Authorization:n,"Content-Type":"text/csv","X-Env":this.env},body:br(e)}));if(!r.ok)thrownewError(`Unexpected response status: ${r.status}${r.statusText}`)}catch(n){pr("Call log API failed:",n)}})}flush(){returnb(this,null,function*(){returnthis.flushMutex.runExclusive(()=>b(this,null,function*(){conste=this.buffer.splice(0);if(e.length===0)return;constt=Math.ceil(e.length/wt);returnPromise.all(Array.from({length:t}).map((n,r)=>this.callApiLog(e.slice(r*wt,(r+1)*wt))))}))})}tryFlush(){returnb(this,null,function*(){conste=yieldthis.flushMutex.runExclusive(()=>{constt=this.buffer;if(t.length===0)return!1;if(t.length>=this.flushNum)returnpt("buffer.length >= this.flushNum"),!0;constn=Date.now()-t[0].ts;returnn>=this.flushWait*1e3?(pt("waited >= this.flushWait"),!0):this.flushWait*1e3-n});if(e===!0)returnthis.flush();typeofe=="number"&&setTimeout(()=>this.tryFlush(),e)})}log(e){this.buffer.push(T({ts:Date.now()},e)),this.tryFlush()}}classgr{constructor(e,t=self.fetch,n=100,r=3){R(this,"schemaLoggers",newMap);this.appInfo=e,this.fetch=t,this.flushNum=n,this.flushWait=r}log(e,t){pt("log",e,t);letn=this.schemaLoggers.get(e);n==null&&(n=newmr(e,this.fetch,this.flushNum,this.flushWait,this.appInfo),this.schemaLoggers.set(e,n)),n.log(t)}}functionbr(s){conste=Object.keys(s[0]),t=["ts",...e.filter(i=>i!=="ts")],n=t.map(wn).join(","),r=s.map(i=>t.map(o=>i[o]).map(o=>o!=null?o+"":"").map(wn).join(","));return[n,...r].join(`
`)}functionwn(s){lete=s.replace(/"/g,'""');return/("|,|\n)/.test(e)&&(e='"'+e+'"'),e}classvr{constructor(e){this.logger=e}log(e){returnthis.logger.log("LiveScheduleLog",e)}}constyr=newURL(We).hostname;functionRr(s,e,t,n){returnb(this,null,function*(){varl,f;constr=newvr(n),i={url:e,cip:""},o=Qe(j(T({},t),{path:We})),a=Date.now();letc,h=null,d=null,p=null;try{if(h=yieldfetch(We,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json",Authorization:o}}),d=Date.now(),!h.ok)thrownewError(`Call Schedule API failed, status: ${h.status}${h.statusText}`);returnp=yieldh.json()}catch(u){throwc=u}finally{constu=z(Date.now(),a),w=p==null?ae(c):{err_msg:"",err_desc:""};r.log(j(T({r_id:(l=h==null?void0:h.headers.get("x-reqid"))!=null?l:"",ip:"",domain:yr,status_code:(f=h==null?void0:h.status)!=null?f:-1},w),{t_conn:z(d,a),t_total:u,type:1}))}})}constRe=Q("dns"),mt=te("dns"),Sr=60,Cr=60*1e3;classEr{constructor(e,t,n=Rr,r=xe){R(this,"scheduling",newMap);R(this,"cache",newMap);R(this,"m3u8SegmentCache",newMap);this.logger=e,this.app=t,this.scheduler=n,this.cacheUrl=r}getScheduleResult(e,t){returnb(this,null,function*(){varo;constn=Date.now();letr;try{r=yieldthis.scheduler(e,t,this.app,this.logger)}catch(a){throwmt("Live schedule failed:",a),newct(a)}finally{e.set("dnsResolveTotalTime",z(Date.now(),n))}if(r.code===1)thrownewre(`Local DNS for ${t}`);if(r.code!==0)thrownewError(`Unexpected schedule code: ${r.code}`);consti=(o=r.ttl)!=null?o:Sr;return{nodes:r.hosts.map(a=>{const[c,h]=Hn(a,0),[d,p]=["",0];return{addr:{ip:d,host:c,http:h+80,https:h+443,how:p},after:0}}),expireAt:Date.now()+i*1e3,ttl:i}})}saveM3u8SegmentResult(e,t){returnb(this,null,function*(){constn=this.cacheUrl(e),r=this.cache.get(n);if(r==null){mt("No schedule result for m3u8:",e);return}consti=t.map(this.cacheUrl);i.forEach(o=>{this.m3u8SegmentCache.set(o,r)}),setTimeout(()=>{i.forEach(o=>{this.m3u8SegmentCache.delete(o)})},6e4)})}schedule(e,t){returnb(this,null,function*(){constn=this.cacheUrl(t);if(!_e(t)&&!Ot(t)){consta=this.m3u8SegmentCache.get(n);if(a==null)thrownewre("Neither m3u8 / flv URL, or m3u8 segment URL");returna}constr=this.cache.get(n);if(r!=null&>(r))returne.set("dnsResolveFromCache",!0),r;consti=this.scheduling.get(n);if(i!=null){leta;try{a=yieldi}catch(c){if(cinstanceofre)throwc}if(a!=null&>(a))returne.set("dnsResolveFromCache",!0),a;this.scheduling.delete(n)}consto=this.getScheduleResult(e,t);returnRe("save scheduling for",t),this.scheduling.set(n,o),o.then(a=>{Re("save cache for",t),this.cache.set(n,a)},()=>{}),o})}hasResult(e){constt=this.cacheUrl(e),n=_e(e)||Ot(e)?this.cache.get(t):this.m3u8SegmentCache.get(t);returnn!=null&>(n)}do(e,t,n,r){returnb(this,null,function*(){leti;Re("schedule for",t);consto=yieldthis.schedule(e,t);Re("scheduled for",t);for(leta=0;a<n;a++){constc=xr(o.nodes);if(c==null)break;try{Re("do job with",c,t),yieldr(c.addr),o.expireAt=Date.now()+o.ttl*1e3;return}catch(h){if(mt("do job with",c.addr,"failed:",h,t),i=h,se(h))break;ke(h)&&(c.after=Date.now()+Cr)}}throwi=se(i)?i:newut(i),i})}}functionpn(s,e=Date.now()){returns.after<e}functionxr(s){for(consteofs)if(pn(e))returne;returnnull}functiongt(s){conste=Date.now();returns.expireAt<=e?!1:s.nodes.some(t=>pn(t,e))}constfe=Q("utils/fetch");functionmn(s){returnb(this,null,function*(){varf,u;conste=yieldfetch(s),t=tt(s.headers);if(t==null||e.status!==206||e.body==null)returne;const{body:n,status:r,statusText:i,headers:o}=e,a=(f=Ze(o))==null?void0:f.end,c=100;leth=(u=t.start)!=null?u:0,d=n.getReader(),p=null;constl=newReadableStream({pull:w=>b(this,null,function*(){p!=null&&(clearTimeout(p),p=null),d==null&&(fe("resume on pull"),s.headers.set("range",be(j(T({},t),{start:h}))),d=(yieldfetch(s)).body.getReader());const{value:g,done:x}=yieldd.read();if(x){fe("read done"),w.close();return}try{w.enqueue(g)}catch(m){fe("enqueue failed:",m),d==null||d.cancel("target stream enqueue failed");return}if(h+=g.byteLength,a!=null&&h>a){fe("all enqueued"),d.cancel("all enqueued"),w.close();return}p=setTimeout(()=>b(this,null,function*(){p=null,d!=null&&(fe("cancel after long time no pull"),d.cancel("long time no read"),d=null)}),c)}),cancel:w=>{fe("cancel",w),d==null||d.cancel(w)}});returnnewResponse(l,{status:r,statusText:i,headers:o})})}classgn{constructor(e){this.logger=e}start(e,t){letn;constr=Date.now(),i=c=>{varf,u,w,g,x,m,v,y,S,A,M;consth=t.headers.get("Range"),d=h==null?null:jt(h),p=n==null?void0:n.headers.get("X-M-Reqid"),l=p?p.split(", ").pop():"";this.log(T({ip:(f=e.get("downloadReqIP"))!=null?f:"",domain:(u=e.get("taskDomain"))!=null?u:"",range_st:(w=d==null?void0:d.start)!=null?w:-1,range_end:(g=d==null?void0:d.end)!=null?g:-1,retry:(x=e.get("downloadRetryCount"))!=null?x:0,ftask_id:(m=e.get("downloadFileTaskID"))!=null?m:"",task_id:(v=e.get("taskID"))!=null?v:"",d_id:(y=e.get("doID"))!=null?y:"",ts_st:r,r_id:l,elt_id:(S=e.get("downloadEltID"))!=null?S:"",status_code:(A=n==null?void0:n.status)!=null?A:-1,t_req_msg:z(e.get("downloadReqMessageAt"),r),t_conn:z(e.get("downloadConnectionAt"),(M=e.get("downloadReqMessageAt"))!=null?M:r),t_tls:-1,t_st_trans:z(e.get("downloadStartTransferAt"),e.get("downloadConnectionAt")),t_resp_msg:z(e.get("downloadRespMessageAt"),e.get("downloadStartTransferAt")),err_msg:"",err_desc:"",t_content_trans:-1,t_total:-1,resp_size:-1},c))};return{onError:c=>{consth=Date.now();i(T({t_total:z(h,r)},ae(c)))},onResponse:c=>{n=c,n.bodyReadResult.then(h=>{varl;constd=Date.now(),p=h.success?null:ae(h.error);i(T({t_content_trans:z(d,(l=e.get("downloadRespMessageAt"))!=null?l:e.get("downloadStartTransferAt")),t_total:z(d,r),resp_size:h.size},p))})}}}wrap(e,t,n){returnb(this,null,function*(){constr=this.start(e,t);try{consti=yieldn();returnr.onResponse(i),i}catch(i){throwr.onError(i),i}})}log(e){returnthis.logger.log("DownloadLog",e)}}class_r{constructor(e){R(this,"downloadLogger");this.downloadLogger=newgn(e)}fetch(e,t,n=!0){returnb(this,null,function*(){returnthis.downloadLogger.wrap(e,t,()=>b(this,null,function*(){consth=t,{url:r}=h,i=Tt(h,["url"]),o=newRequest(r,T(T({},n?bn:null),i)),a=yieldmn(o),c=Date.now();returne.set("downloadConnectionAt",c),e.set("downloadStartTransferAt",c),De(a)}))})}}constbn={mode:"cors",credentials:"omit"};classvn{constructor(e,t=!0,n=mn){R(this,"downloadLogger");this.https=t,this.nativeFetch=n,this.downloadLogger=newgn(e)}fetch(e,t,n){returnb(this,null,function*(){returnthis.downloadLogger.wrap(e,t,()=>b(this,null,function*(){e.set("downloadReqIP",n.host);constr=this.nativeFetch,i=Tr(t,n,this.https),o=yieldr(i),a=Date.now();returne.set("downloadConnectionAt",a),e.set("downloadStartTransferAt",a),De(o)}))})}dispose(){}}functionTr(s,e,t=!0){const{url:n,headers:r,method:i,signal:o}=s,a=newURL(n),c=a.host,h=newHeaders(r);a.protocol=t?"https:":"http:",a.host=`${e.host}:${t?e.https:e.http}`,a.pathname=`/${c}${a.pathname}`;letd=a.toString();if(h.has("X-Miku-Agent")){constp=h.get("X-Miku-Agent");h.delete("X-Miku-Agent");constl=d.includes("?")?"&":"?",f=["X-Miku-Agent",p].map(encodeURIComponent).join("=");d=d+l+f}returnnewRequest(d,j(T({},bn),{headers:h,method:i,signal:o}))}functionAr(s){conste=[],t=s.split(`
`).map(r=>r.trim()).filter(r=>r.length>0);if(t[0]!=="#EXTM3U")thrownewError("Invalid Extended M3U Playlist");letn=null;for(constroft){if(r.startsWith("#")){r.startsWith("#EXTINF:")&&(n=r);continue}n!=null&&(e.push({uri:r}),n=null)}returne}constyn=Q("client"),bt=te("client");classDr{constructor(e,t){R(this,"fileTasks",newMap);R(this,"cache");R(this,"cdnResolver");R(this,"liveResolver");R(this,"nativeHttpClient");R(this,"http");R(this,"liveHttp");R(this,"patterns");R(this,"logger");varo,a,c,h,d;this.config=t,t!=null&&t.debug&&kt(),this.cache=new$s(t==null?void0:t.cache),this.logger=(o=t==null?void0:t.logger)!=null?o:newgr(e),this.cdnResolver=(a=t==null?void0:t.resolver)!=null?a:newTs(this.logger,e,t==null?void0:t.dnsResolver,t==null?void0:t.cacheUrl),this.liveResolver=(c=t==null?void0:t.liveResolver)!=null?c:newEr(this.logger,e,t==null?void0:t.scheduler),this.nativeHttpClient=new_r(this.logger);constn=(h=t==null?void0:t.httpClient)!=null?h:newvn(this.logger),r=(d=t==null?void0:t.liveHttpClient)!=null?d:newvn(this.logger);this.patterns=T(T({},Mt),t==null?void0:t.patterns),this.http=newon(this.logger,n,this.cdnResolver,6e3);consti=2e3;this.liveHttp=newon(this.logger,r,this.liveResolver,i)}prepare(e){returnb(this,null,function*(){returnPromise.all(e.map(t=>this.cdnResolver.resolveDomain(newJ,t))).catch(t=>{bt("prepare failed:",t)})})}createTask(e,t){constn=e.indexOf("#");returnn>=0&&(e=e.slice(0,n)),newan(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",1),this.startTask(r,i)))}createLiveTask(e,t){constn=e.indexOf("#");returnn>=0&&(e=e.slice(0,n)),newan(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",2),this.startLiveTask(r,i)))}startTask(e,t){returnb(this,null,function*(){constn=newURL(t.url).hostname,r=yieldthis.cdnResolver.getCacheKey(t.url,n);leti=this.fileTasks.get(r);if(i==null){consto=()=>b(this,null,function*(){varc;consta=yieldthis.cdnResolver.getMediaOptimization(n);returnT(T(T({},lr),a),(c=this.config)==null?void0:c.mediaOptimization)});i=newcr(this.cache,this.nativeHttpClient,this.http,r,t.url,this.patterns,o),this.fileTasks.set(r,i)}returni.startTask(e,t)})}saveM3u8SegmentResult(e,t){returnb(this,null,function*(){constn=yieldas(t),i=Ar(n).map(o=>Un(o.uri,e));yn("saveM3u8SegmentResult",xe(e),i.map(xe)),yieldthis.liveResolver.saveM3u8SegmentResult(e,i)})}startLiveTask(e,t){returnb(this,null,function*(){varh,d;constn={};t.range!=null&&(n.Range=be({start:t.range.start,end:t.range.end==null?null:t.range.end-1}));constr=newce(t.url,{method:"GET",headers:n,signal:t.signal});leti,a=((d=(h=this.config)==null?void0:h.liveOptimization)!=null?d:!0)&&_e(t.url)&&!this.liveResolver.hasResult(t.url);if(a){yn("use nativeClient for",t.url);constp=this.nativeHttpClient.fetch(e,r);this.liveHttp.do(newJ(e),r).catch(l=>{bt("do failed when prefetch for liveOptimization:",l)}),i=yieldp}elsei=yieldthis.liveHttp.do(e,r);if(i.body==null)thrownewError("Body expected");if(i.status!==200&&i.status!==206)thrownewError(`Invalid response, status: ${i.status}`);letc=i.body;if(!a&&it()&&_e(t.url)){const[p,l]=i.body.tee();this.saveM3u8SegmentResult(t.url,l).catch(f=>{bt("Save M3u8 segment cache failed:",t.url,f)}),c=p}returnnewln(c,le(i.headers),nt(i.headers),i.headers.get("Content-Type"),i)})}dispose(){this.cache.dispose()}}functionkr(s){returns&&s.mikuDeliveryProxy===!0}constLr="MIKU_DELIVERY_PROXY_CONFIG";functionBr(s,e){constt=r=>r==null?void0:r.map(i=>({source:i.source,flags:i.flags})),n=j(T({},e),{patterns:e.patterns==null?void0:On(e.patterns,r=>t(r))});returnIn(s,{[Lr]:JSON.stringify(n)})}functionPr(s){returnArray.isArray(s)?{cdn:s,live:[]}:T({cdn:[],live:[]},s)}functionMr(s){conste={},t=[];for(const{url:n,ecdn:r,fallback:i}ofs){consto=newURL(n),a=o.hostname,c=It(o.pathname);if(a!=="localhost"&&a.indexOf(".")<0||/\.qnqcdn\.net$/.test(a))continue;leth=e[a];h==null&&(e[a]=h={exts:[],total:0,ecdn:0,fallback:0}),h.exts.includes(c)||h.exts.push(c),h.total++,r&&h.ecdn++,i&&h.fallback++,Nn(o,Mt)&&!t.includes(a)&&t.push(a)}returne}functionIr(s,e){constt={};for(const{url:n,ecdn:r,size:i}ofe){consto=newURL(n),a=o.hostname,c=It(o.pathname);if(!(!s.includes(a)&&!s.includes("*")))for(consthof[`${a}/*`,`${a}/*.${c||"<none>"}`]){letd=t[h];d==null&&(t[h]=d={total:0,totalSize:0,ecdn:0,ecdnSize:0}),d.total++,d.totalSize+=i!=null?i:0,r&&(d.ecdn++,d.ecdnSize+=i!=null?i:0)}}returnt}functionOr(s,e,t){returnb(this,null,function*(){s=Br(s,e),yieldnavigator.serviceWorker.register(s,t)})}functionzr(){returnb(this,null,function*(){Nr()})}functionNr(){functions(e){varn;constt={mikuDeliveryProxy:!0,type:`window-${e}`};(n=navigator.serviceWorker.controller)==null||n.postMessage(t)}s("available"),window.addEventListener("pageshow",()=>s("available")),window.addEventListener("pagehide",()=>s("unavailable")),window.addEventListener("beforeunload",()=>s("unavailable"))}functionHr(s,e){navigator.serviceWorker.addEventListener("message",({data:t})=>{if(!kr(t)||t.type!=="window-fetch-items")return;constn=Mr(t.items),r=Pr(s.domains),i=Ir([...r.cdn,...r.live],t.items);e(n,i)}),window.addEventListener("load",()=>{setTimeout(()=>{varn;constt={mikuDeliveryProxy:!0,type:"get-window-fetch-items"};(n=navigator.serviceWorker.controller)==null||n.postMessage(t)},1e3)})}functionUr(s,e,t){returnb(this,null,function*(){constn=qr();if(n!=null){console.warn("Ability not OK for Miku Delivery Proxy API:",n);return}e.debug&&kt(),yieldPromise.all([zr(),Or(s,e,t),Ns(),xs()])})}functionqr(){return"serviceWorker"innavigator?null:"navigator.serviceWorker not available"}returnk.Client=Dr,k.initProxy=Ur,k.listenStatistics=Hr,Object.defineProperties(k,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),k}({});
`)}functionQt(s){lete=s.replace(/"/g,'""');return/("|,|\n)/.test(e)&&(e='"'+e+'"'),e}classXt{constructor(){R(this,"map",newMap)}on(e,t){vari;constr=[...(i=this.map.get(e))!=null?i:[],t];returnthis.map.set(e,r),()=>this.off(e,t)}once(e,t){constn=this.on(e,r=>{n(),t(r)});returnn}off(e,t){vari;constr=((i=this.map.get(e))!=null?i:[]).filter(o=>o!==t);this.map.set(e,r)}emit(...e){vari;const[t,n]=e;((i=this.map.get(t))!=null?i:[]).forEach(o=>{o(n)})}dispose(){this.map.clear()}}constis=self,lt=E("utils/sw/clients");classos{constructor(e=is){R(this,"clientIds",[]);R(this,"removed",newSet);R(this,"emitter",newXt);this.swScope=e}add(e){this.clientIds.includes(e)||this.removed.has(e)||(this.clientIds.push(e),lt("add",e,this.clientIds))}remove(e){constt=this.clientIds.indexOf(e);t<0||(this.clientIds.splice(t,1),this.removed.add(e),this.emitter.emit("remove",e),lt("remove",e,this.clientIds))}set(e){constt=this.clientIds,n=[],r=[];t.forEach(i=>{consto=e.indexOf(i);o>=0?(n.push(i),e.splice(o,1)):r.push(i)}),this.clientIds=[...n,...e],r.forEach(i=>{this.emitter.emit("remove",i)}),(r.length>0||e.length>0)&<("set",this.clientIds)}getAllIds(){returnthis.clientIds}getAll(){returnb(this,null,function*(){conste=(yieldthis.swScope.clients.matchAll({type:"window"})).slice();returne.reverse(),this.set(e.map(t=>t.id)),this.clientIds.map(t=>e.find(n=>n.id===t))})}get(e){returnb(this,null,function*(){constt=yieldthis.swScope.clients.get(e);returnt!=null?this.add(e):this.remove(e),t})}onRemove(e){returnthis.emitter.on("remove",e)}whenRemoved(e,t){if(!this.clientIds.includes(e))return;constn=this.emitter.on("remove",r=>{r===e&&(n(),t())})}}consthe=newos;classG{constructor(e){R(this,"value");this.value=e!=null?S({},e.value):{}}set(e,t){this.value[e]=t}get(e){returnthis.value[e]}}tt(navigator.userAgent);letye;functionHe(){if(ye!=null)returnye;try{newResponse(newReadableStream),ye=!0}catch(s){ye=!1}returnye}functionRe(){return!(typeofTransformStream=="undefined"||!He())}functionas(s){conste=[],t=s.length;for(letn=0;n<t;n++){letr=s.charCodeAt(n);if(r>=55296&&r<=56319&&t>n+1){consti=s.charCodeAt(n+1);i>=56320&&i<=57343&&(r=(r-55296)*1024+i-56320+65536,n+=1)}if(r<128){e.push(r);continue}if(r<2048){e.push(r>>6|192),e.push(r&63|128);continue}if(r<55296||r>=57344&&r<65536){e.push(r>>12|224),e.push(r>>6&63|128),e.push(r&63|128);continue}if(r>=65536&&r<=1114111){e.push(r>>18|240),e.push(r>>12&63|128),e.push(r>>6&63|128),e.push(r&63|128);continue}e.push(239,191,189)}returnnewUint8Array(e).buffer}functionls(s){returns^=s>>>16,s=Math.imul(s,2246822507),s^=s>>>13,s=Math.imul(s,3266489909),s^=s>>>16,s>>>0}constNe=newUint32Array([3432918353,461845907]);functionct(s,e){returns<<e|s>>>32-e}functioncs(s,e){constt=s.byteLength/4|0,n=newUint32Array(s,0,t);for(letr=0;r<t;r++)n[r]=Math.imul(n[r],Ne[0]),n[r]=ct(n[r],15),n[r]=Math.imul(n[r],Ne[1]),e[0]=e[0]^n[r],e[0]=ct(e[0],13),e[0]=Math.imul(e[0],5)+3864292196}functionus(s,e){constt=s.byteLength/4|0,n=s.byteLength%4;letr=0;consti=newUint8Array(s,t*4,n);switch(n){case3:r=r^i[2]<<16;case2:r=r^i[1]<<8;case1:r=r^i[0]<<0,r=Math.imul(r,Ne[0]),r=ct(r,15),r=Math.imul(r,Ne[1]),e[0]=e[0]^r}}functionhs(s,e){e[0]=e[0]^s.byteLength,e[0]=ls(e[0])}functionds(s,e){if(e=e?e|0:0,typeofs=="string"&&(s=as(s)),!(sinstanceofArrayBuffer))thrownewTypeError("Expected key to be ArrayBuffer or string");constt=newUint32Array([e]);returncs(s,t),us(s,t),hs(s,t),t.buffer}classfs{constructor(e=ws){R(this,"circle",newMap);R(this,"members",newSet);R(this,"membersReplicas",newMap);R(this,"sortedHashes",[]);this.hasher=e}updateSortedHashes(){this.sortedHashes=[...this.circle.keys()].sort((e,t)=>e-t)}_add({key:e,replicas:t}){for(letn=0;n<t;n++){constr=this.hasher(Yt(e,n));this.circle.set(r,e)}this.members.add(e),this.membersReplicas.set(e,t)}_remove({key:e,replicas:t}){for(letn=0;n<t;n++){constr=this.hasher(Yt(e,n));this.circle.delete(r)}this.members.delete(e),this.membersReplicas.delete(e)}search(e){constt=this.sortedHashes.findIndex(n=>n>e);returnt<0?0:t}get(e){if(this.members.size===0)returnnull;constt=this.hasher(e),n=this.search(t),r=this.sortedHashes[n];returnthis.circle.get(r)}getN(e,t,n){constr=n?n.size:this.members.size;if(r===0||t===0)return[];t>r&&(t=r);consti=this.hasher(e),o=this.search(i),a=[];for(letc=o;;c++){c>=this.sortedHashes.length&&(c=0);consth=this.sortedHashes[c],d=this.circle.get(h);if(!a.includes(d)&&(!n||n.has(d))&&(a.push(d),a.length>=t))returna}}add(e,t){returnthis.members.has(e)?!1:(this._add({key:e,replicas:t}),this.updateSortedHashes(),!0)}remove(e){if(!this.members.has(e))return!1;constt=this.membersReplicas.get(e);returnthis._remove({key:e,replicas:t}),this.updateSortedHashes(),!0}set(e){this.circle.clear(),this.members.clear(),this.membersReplicas.clear(),e.forEach(t=>{this._add(t)}),this.updateSortedHashes()}}functionYt(s,e){returne+s}constws=ps;functionps(s){conste=ds(s);returnnewUint32Array(e)[0]}classms{constructor(e){this.logger=e}log(e){returnthis.logger.log("DnsResolveLog",e)}}functiongs(s){conste="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",t=e.length;letn="";for(letr=0;r<s;r++)n+=e[Math.floor(Math.random()*t)];returnn}constbs=newURL(ce).hostname,vs=O("dns/httpdns");functionys(s,e,t,n){returnb(this,null,function*(){varp,l;constr=newms(n),i=V({name:e,type:"A",rid:gs(10)}),o=`${ce}?${i}`,a=it(j(S({},t),{path:ce,query:i}));letc,h=null,d=null;try{if(h=yieldfetch(o,{headers:{Authorization:a}}),!h.ok){constu=yieldSs(h);if(u==null)thrownewError(`Resolve failed, unexpected HTTP status: ${h.status}`);if(u.code==="NotSupportedArea")return{reason:"NotSupportedArea",ttl:300};thrownewError(`Resolve failed, code: ${u.code}, error: ${u.error}`)}returnd=yieldh.json()}catch(f){throwc=f}finally{constu=performance.getEntriesByName(o,"resource").pop();if(u==null)vs("Corresponding performance entry not found for",o);else{constw=d==null?ue(c):{err_msg:"",err_desc:""};r.log(j(S({r_id:(p=h==null?void0:h.headers.get("x-reqid"))!=null?p:"",ip:"",domain:bs,status_code:(l=h==null?void0:h.status)!=null?l:-1},w),{t_conn:(u.requestStart-u.connectStart)/1e3,t_total:(u.responseEnd-u.fetchStart)/1e3,type:1}))}}})}functionut(s){returns.groups!=null}functionRs(s,e){returns.find(t=>newRegExp(t.pattern).test(e))}functionCs(s){returnMath.random()<s.servicerate}functionSs(s){returnb(this,null,function*(){try{conste=yields.json();if(e&&typeofe.code=="string"&&typeofe.error=="string")returne}catch(e){}returnnull})}classZt{constructor(e,t){R(this,"db");this.dbName=e,this.storeConfigs=t}getDB(){returnb(this,null,function*(){returnthis.db!=null?this.db:(this.db=yieldnewPromise(e=>{constt=indexedDB.open(this.dbName);t.addEventListener("upgradeneeded",()=>{for(constnofthis.storeConfigs){constr=t.result.createObjectStore(n.name);for(constiofn.indexes)r.createIndex(i.name,i.keyPath)}}),e(ze(t))}),this.db)})}get(e,t){returnb(this,null,function*(){constr=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).get(t);returnze(r)})}getAll(e){returnb(this,null,function*(){constn=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).getAll();returnze(n)})}count(e){returnb(this,null,function*(){constn=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).count();returnze(n)})}set(e,t,n){returnb(this,null,function*(){consti=(yieldthis.getDB()).transaction(e,"readwrite");returni.objectStore(e).put(n,t),ht(i)})}remove(e,t){returnb(this,null,function*(){constr=(yieldthis.getDB()).transaction(e,"readwrite");returnr.objectStore(e).delete(t),ht(r)})}clear(){returnb(this,null,function*(){conste=yieldthis.getDB();yieldPromise.all(this.storeConfigs.map(({name:t})=>{constn=e.transaction(t,"readwrite");returnn.objectStore(t).clear(),ht(n)}))})}walkBy(e,t,n){returnb(this,null,function*(){consti=(yieldthis.getDB()).transaction(e,"readonly").objectStore(e).index(t).openCursor(void0,"next");returnnewPromise((o,a)=>{i.addEventListener("error",()=>a(newCe(i.error))),i.addEventListener("success",()=>{constc=i.result;if(c==null){o();return}n(c.value,c.primaryKey),c.continue()})})})}dispose(){vare;(e=this.db)==null||e.close()}}classCeextendsError{constructor(t){super(t+"");R(this,"name","IndexedDBError");this.cause=t}}functionze(s){returnnewPromise((e,t)=>{s.addEventListener("success",()=>e(s.result)),s.addEventListener("error",()=>t(newCe(s.error)))})}functionht(s){returnnewPromise((e,t)=>{s.addEventListener("complete",()=>e()),s.addEventListener("error",()=>t(newCe(s.error))),s.addEventListener("abort",()=>t(newCe(s.error)))})}functionre(s){conste=s.get("Content-Length");returne?parseInt(e,10):null}functiondt(s){conste=s.get("Content-Range");returne==null?null:xs(e)}functionxs(s){conste=s.trim().toLowerCase(),[t,n]=e.split(/\s+/);if(t!=="bytes")thrownewError(`Unit must be bytes: ${s}`);const[r,i]=n.split("/"),o=i==="*"?null:ft(i),[a,c]=(r.includes("-")?r.split("-"):[null,null]).map(h=>ft(h));return{totalSize:o,start:a,end:c}}functionSe(s){conste=s.start!=null&&s.end!=null?`${s.start}-${s.end}`:"*",t=s.totalSize==null?"*":s.totalSize+"";return`bytes ${e}/${t}`}functionft(s){returns?Number(s):null}functionxe(s){conste=s.get("Range");returne==null?null:en(e)}functionJt(s){returns.start===0&&s.end==null}functionen(s){conste=s.trim().toLowerCase();if(!e.startsWith("bytes="))thrownewError(`Unit must be bytes: ${s}`);if(e.includes(","))thrownewError(`Multiple range: ${s}`);const[,t,n]=/(\d*)-(\d*)/.exec(e)||[];if(!t&&!n)thrownewError(`Invalid range values: ${s}`);if(!t)thrownewError("Suffix range not supported");const[r,i]=[t,n].map(o=>ft(o));return{start:r,end:i}}functionEe(s){vare,t;return`bytes=${(e=s.start)!=null?e:0}-${(t=s.end)!=null?t:""}`}constEs=/[^\u0000-\u00ff]/;functiontn(s){returnEs.test(s)?"REPLACED_BY_Miku_Delivery_SEE_utils_http_encodeHeaderValue":s}functionnn(s){if(sinstanceofHeaders){conste={};s.forEach((t,n)=>{e[n]=tn(t)}),s=e}if(Array.isArray(s)){conste={};s.forEach(([t,n])=>{e[n]=tn(t)}),s=e}returnnewHeaders(s)}functionwt(s){vart;conste=dt(s);returne!=null?(t=e.totalSize)!=null?t:null:re(s)}constsn=E("utils/stream"),rn=O("utils/stream");function_s(s){returnb(this,null,function*(){conste=s.getReader();lett=newUint8Array;for(;;){const{done:r,value:i}=yielde.read();if(r)break;t=newUint8Array([...t,...i])}returnnewTextDecoder().decode(t)})}functionpt(s,e){vara;constt=s.getReader(),n=(a=e[0])!=null?a:0,r=e[1];leti=0;returnnewReadableStream({pull:c=>b(this,null,function*(){leth,d;for(;;){constu=yieldt.read();if(u.done){c.close();return}if(h=u.value,d=i+h.byteLength,d>n)break;i=d}letp=h;constl=n>i?n-i:0,f=r!=null&&r<d?r-i:void0;(l!==0||f!==void0)&&(p=h.slice(l,f)),c.enqueue(p),r!=null&&d>=r&&(t.cancel("Cancelled by slice for target range met"),c.close()),i=d}),cancel:c=>t.cancel(c)})}functionTs(s){lete=0;constt=newTransformStream({transform:(r,i)=>{e+=r.byteLength,i.enqueue(r)}}),n=s.pipeTo(t.writable).then(()=>({size:e,success:!0}),r=>({size:e,success:!1,error:r}));return[t.readable,n]}classonextendsError{constructor(){super(...arguments);R(this,"name","SaveSlicedPieceError")}}functionAs(s,e,t,n){returnb(this,null,function*(){constr=[];leti=e,o=[],a=0;functionc(){returnb(this,null,function*(){consth=i+a;sn(`saveSlicedPiece [${i}, ${h}]`);try{yieldn(newBlob(o),i,h)}catch(d){throwrn(`saveSlicedPiece [${i}, ${h}] failed`,d),newon(`saveSlicedPiece [${i}, ${h}] failed`)}r.push([i,h]),sn(`saveSlicedPiece [${i}, ${h}] finish`,r),i=h})}try{consth=s.getReader();for(;;){const{value:d,done:p}=yieldh.read();if(p)break;o.push(d),a+=d.byteLength,a>=t&&(yieldc(),o=[],a=0)}a>0&&(yieldc())}catch(h){if(!(hinstanceofon)&&(rn("exception occurred while reading stream and save by pieces",h),a>0))try{yieldc()}catch(d){}}returnr})}functionDs(s){lete,t=!1;constn=newReadableStream({start:a=>{e=a},cancel:()=>{t=!0}}),r=s.getReader();leti=!1;return{main:newReadableStream({pull:a=>b(this,null,function*(){try{const{value:c,done:h}=yieldr.read();if(i)return;if(h){a.close(),t||e.close();return}a.enqueue(c),t||e.enqueue(c)}catch(c){a.error(c),t||e.error(c)}}),cancel:a=>b(this,null,function*(){i=!0,yieldr.cancel(a),e.error(a)})}),minor:n}}classie{constructor(e,{method:t,headers:n,signal:r,body:i}){R(this,"url");R(this,"method");R(this,"headers");R(this,"body");R(this,"signal");this.url=e,this.method=t!=null?t:"GET",this.headers=newHeaders(n),this.body=i!=null?i:null,this.signal=r!=null?r:newAbortController().signal}}classte{constructor(e,{status:t,statusText:n,headers:r,underlayer:i}){R(this,"status");R(this,"statusText");R(this,"headers");R(this,"body");R(this,"bodyReadResult");R(this,"underlayer");if(this.status=t!=null?t:200,this.statusText=n!=null?n:"",this.headers=nn(r),this.underlayer=i,e==null||!Re())this.body=e,this.bodyReadResult=Promise.resolve({success:!0,size:0});else{const[o,a]=Ts(e);this.body=o,this.bodyReadResult=a}}}functionIs(s){const{url:e,headers:t,body:n,signal:r}=s;returnnewie(e,{headers:t,body:n,signal:r})}functionUe(s){const{status:e,statusText:t,headers:n,body:r}=s;returnnewte(r,{status:e,statusText:t,headers:n,underlayer:s})}class$eextendsError{constructor(t){super(`Unexpected HTTP status: ${t.status}${t.statusText}`);R(this,"name","UnexpectedHttpStatusError");this.response=t}}constks=newXt;letan;typeofself!="undefined"&&(an=self,an.addEventListener("message",s=>ks.emit("message",s)));classLsextendsError{constructor(){super(...arguments);R(this,"name","WindowClientError")}}classMsextendsError{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannelCloseError")}}classBsextendsError{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannel1stMessageError")}}functionmt(s,e=()=>1){if(s.length===0)returnnull;constt=s.map(e),n=t.reduce((i,o)=>i+o,0);letr=Math.random()*n;for(leti=0;i<t.length;i++){consto=t[i];if(r<o)returns[i];r-=o}returns[0]}functionoe(s){returns&&s.name==="AbortError"}constPs=newMs().name,Os=newBs().name;functionFe(s){return!(s&&[Ps,Os].includes(s.name)||oe(s)||sinstanceofLs)}classgtextendsError{constructor(t){super(t+"");R(this,"name","ResolveError");this.cause=t}}classlnextendsError{constructor(){super(...arguments);R(this,"name","NoAvailableNodeError")}}classbtextendsError{constructor(t){super(t+"");R(this,"name","DoWithNodeError");this.cause=t}}classaeextendsError{constructor(){super(...arguments);R(this,"name","LocalDNSError")}}functionHs(s,e,t){constn=t||newURL(s).hostname;letr,i;s=s.replace(/^\w+:\/\//,"").split("#")[0];consto=s.indexOf("?");o>=0?(i=s.slice(o+1),s=s.slice(0,o)):i="";consta=s.indexOf("/");r=a>=0?s.slice(a):"",r=Ns(e.rewrites,r),i=Fs(e.queryString,i);letc=n+r;returni!==""&&(c=c+"?"+i),c}functionNs(s,e){for(consttofs){constn=zs(t,e);if(n!=null){e=$s(t,n);break}}returne}functionzs(s,e){returnnewRegExp(s.pattern).exec(e)}constUs=/\${(\d+)}/g;function$s(s,e){returns.repl.replace(Us,(t,n)=>{vari;constr=parseInt(n,10);returnr>=e.length?t:(i=e[r])!=null?i:""})}functionFs({type:s,values:e},t){if(s==="none")return"";if(s==="all")returnt;constn=ve(t),r=e!=null?e:[],i={};returnObject.keys(n).forEach(o=>{s==="include"&&!r.includes(o)||s==="exclude"&&r.includes(o)||(i[o]=n[o])}),V(i)}functioncn(s,e){constt=newMap;returnfunction(...r){consti=e(...r),o=t.get(i);if(o!=null)returno;consta=s(...r);returnt.set(i,a),a.finally(()=>{t.delete(i)}),a}}constde=E("dns"),We=O("dns"),Ws="miku-delivery/dns/cdn/v1",vt="result",qs={name:vt,indexes:[{name:"domain",keyPath:"domain"}]};classjs{constructor(e,t,n=ys,r,i=2e3,o=5e3){R(this,"fingerprints",newMap);R(this,"disabledElts",newMap);R(this,"storage",newZt(Ws,[qs]));R(this,"getResolveResultFromStorage",cn(e=>this.storage.get(vt,e),e=>e));R(this,"refreshResolveResultInStorage",cn((e,t)=>b(this,null,function*(){constn=yieldthis.dnsResolver(e,t,this.app,this.logger),r=Date.now()+n.ttl*1e3,i=j(S({},n),{domain:t,expireAt:r});returnthis.saveResolveResultToStorage(t,i),i}),(e,t)=>t));this.logger=e,this.app=t,this.dnsResolver=n,this.cacheKeyFn=r,this.resolveTimeout=i,this.initialDisableDuration=o}getFingerprint(e){constt=this.fingerprints.get(e);if(t==null)thrownewError(`No fingerprint for ${e}`);returnt}isEltDisabled(e){constt=this.disabledElts.get(e);returnt==null?!1:t.after>Date.now()}setEltDisabled(e){constt=this.disabledElts.get(e),n=t==null?this.initialDisableDuration:t.duration,r=Date.now()+n;this.disabledElts.set(e,{duration:n*2,after:r})}removeEltDisabled(e){this.disabledElts.has(e)&&this.disabledElts.delete(e)}getCacheKey(e,t){returnb(this,null,function*(){if(this.cacheKeyFn!=null)returnthis.cacheKeyFn(e);constn=yieldthis.resolveDomain(newG,t);returnut(n)?Hs(e,n.cacheKey,n.bucket):e})}getMediaOptimization(e){returnb(this,null,function*(){constt=yieldthis.resolveDomain(newG,e);returnut(t)?t.mediaOptimization:null})}saveResolveResultToStorage(e,t){returnb(this,null,function*(){returnthis.storage.set(vt,e,t)})}resolveDomain(e,t){returnb(this,null,function*(){constn=Date.now(),r=(()=>b(this,null,function*(){consti=yieldthis.getResolveResultFromStorage(t);returni==null?this.refreshResolveResultInStorage(e,t):(Gs(i)&&(de("result from storage cache expired",t),this.refreshResolveResultInStorage(e,t)),e.set("dnsResolveFromCache",!0),i)}))().then(i=>(e.set("dnsResolveTotalTime",N(Date.now(),n)),i));returnPromise.race([r,Ht(this.resolveTimeout,"Resolve domain")]).catch(i=>{throwWe("DNS resolve failed:",i),newgt(i)})})}resolve(e,t){returnb(this,null,function*(){letn=null;returnyieldthis.do(e,t,1,r=>{n=r}),n})}do(e,t,n,r){returnb(this,null,function*(){leti;de("Resolve for",t);consto=newURL(t).hostname,[a,c]=yieldPromise.all([this.getCacheKey(t,o),this.resolveDomain(e,o)]);if(!ut(c))thrownewae(`Non-ECDN resolve result: ${o}`);const{groups:h,rules:d}=c;if(h.length===0)thrownewln(`No available group for ${o}`);de("Resolved for",t);constp=Rs(d,a);if(p==null)thrownewae("No matched rule found");if(!Cs(p))thrownewae("Do not serve with given rule");letl=p.groups.map(({groupidx:f,weight:u,splitn:w})=>{constg=h[f];if(g==null)thrownewError(`Unexpected groupidx: ${f}`);return{group:g,weight:u,splitn:w}});for(letf=0;f<n;f++){constu=mt(l,w=>w.weight);if(u==null)break;try{de("doWithGroup",f,a),yieldthis.doWithGroup(e,u.group,a,u.splitn,r);return}catch(w){if(We("doWithGroup (weight:",u.weight,") failed:",w,a),i=w,oe(w))break;Fe(w)&&(l=l.filter(g=>g!==u))}}throwi=oe(i)?i:newbt(i),i})}doWithGroup(e,t,n,r,i){returnb(this,null,function*(){consto=t.elts.filter(l=>!this.isEltDisabled(l.id));if(o.length===0)thrownewError("No available elt");consta=Ks(t),c=newSet(o.map(l=>l.id)),h=r===1?2:r;letd=a.getN(n,h,c).map(l=>o.find(f=>f.id===l)),p;for(letl=0;l<2;l++){constf=mt(d.slice(0,r),u=>u.replicas);if(f==null)break;try{de("doWithElt",f.id,n),e.set("downloadEltID",f.id),yieldVs(f,n,i),this.removeEltDisabled(f.id);return}catch(u){if(We("doWithElt",f.id,"failed:",u,n),p=u,oe(u))break;Fe(u)&&(d=d.filter(w=>w!==f),this.setEltDisabled(f.id))}}throwp})}}constun=newMap;functionKs({elts:s}){conste=s.map(({id:r,replicas:i})=>`${r}:${i}`).join(","),t=un.get(e);if(t!=null)returnt;constn=newfs;returnn.set(s.map(r=>({key:r.id,replicas:r.replicas}))),un.set(e,n),n}functionVs(s,e,t){returnb(this,null,function*(){letn=s.addrs;if(n.length===0)thrownewError("Empty addr list");letr;for(leti=0;i<2;i++){consto=mt(n);if(o==null)break;try{de("do job with",o,e),yieldt(o);return}catch(a){if(We("do job with",o,"failed:",a,e),r=a,oe(a))break;Fe(a)&&(n=n.filter(c=>c!==o))}}throwr})}functionGs(s){returns.expireAt<Date.now()}classQs{constructor(){R(this,"front",null);R(this,"back",null)}insertElementBefore(e,t){constn=t.prev;n!=null?(n.next=e,e.prev=n):this.front=e,t.prev=e,e.next=t}insertElementAfter(e,t){constn=t.next;n!=null?(n.prev=e,e.next=n):this.back=e,t.next=e,e.prev=t}pushElementFront(e){constt=this.front;t!=null?(t.prev=e,e.next=t):this.back=e,this.front=e}pushElementBack(e){constt=this.back;t!=null?(t.next=e,e.prev=t):this.front=e,this.back=e}moveBefore(e,t){e!==t&&(this.remove(e),this.insertElementBefore(e,t))}moveAfter(e,t){e!==t&&(this.remove(e),this.insertElementAfter(e,t))}moveToFront(e){this.remove(e),this.pushElementFront(e)}moveToBack(e){this.remove(e),this.pushElementBack(e)}insertBefore(e,t){constn={value:e,prev:null,next:null};returnthis.insertElementBefore(n,t),n}insertAfter(e,t){constn={value:e,prev:null,next:null};returnthis.insertElementAfter(n,t),n}pushFront(e){constt={value:e,prev:null,next:null};returnthis.pushElementFront(t),t}pushBack(e){constt={value:e,prev:null,next:null};returnthis.pushElementBack(t),t}remove(e){constt=e.prev,n=e.next;returnt!=null?(t.next=n,e.prev=null):this.front=n,n!=null?(n.prev=t,e.next=null):this.back=t,e.value}walk(e){lett=this.front;for(;t!=null;){if(e(t.value,t)===!1)return;t=t.next}}reverseWalk(e){lett=this.back;for(;t!=null;){if(e(t.value,t)===!1)return;t=t.prev}}}constqe=E("dc/cr"),Xs=O("dc/cr"),Ys={reservedQuota:5*1024*1024};classZs{constructor(e,t=Ys){R(this,"inited");R(this,"itemElementMap",newMap);R(this,"itemList",newQs);this.dc=e,this.config=t,this.inited=this.resume()}resume(){returnb(this,null,function*(){conste=[];yieldthis.dc.walkItems((t,n)=>{constr={key:n,usedTime:t.usedTime,size:yt(t)},i=this.itemList.pushBack(r);this.itemElementMap.set(n,i),e.push(...ir(t,n))});try{constt=yieldthis.dc.getBrowserCacheKeys();for(letnoft)e.includes(n)||(qe("clear inaccessible cache:",n),yieldthis.dc.browserCacheDelete(n))}catch(t){Xs("failed to clear inaccessible caches:",t)}})}addItem(e,t){constn={key:e,usedTime:t.usedTime,size:yt(t)};letr=null;returnthis.itemList.reverseWalk((i,o)=>{if(i.usedTime<=t.usedTime)returnr=this.itemList.insertAfter(n,o),!1}),r==null&&(r=this.itemList.pushFront(n)),this.itemElementMap.set(e,r),r}removeItem(e){constt=this.itemElementMap.get(e);t!=null&&(this.itemElementMap.delete(e),this.itemList.remove(t))}onItemSet(e,t){returnb(this,null,function*(){yieldthis.inited;letn=this.itemElementMap.get(e);if(n==null){this.addItem(e,t);return}n.value.size=yt(t),t.usedTime!==n.value.usedTime&&(n.value.usedTime=t.usedTime,this.itemList.moveToBack(n))})}getLeftSpace(){returnb(this,null,function*(){if(typeofnavigator.storage.estimate=="undefined")returnnull;const{quota:e,usage:t}=yieldnavigator.storage.estimate();returne!=null&&t!=null?e-t:null})}freeUpSpace(e){returnb(this,null,function*(){yieldthis.inited;lett=0;constn=[];this.itemList.walk(({key:r,size:i})=>{if(i!==0&&(n.push(r),t+=i,t>=e))return!1}),qe("to free up space, remove",n),yieldPromise.all(n.map(r=>b(this,null,function*(){yieldthis.dc.removeItemWithContent(r),this.removeItem(r)})))})}beforeContentSet(e,t,n){returnb(this,null,function*(){if(n==null)return;yieldthis.inited;constr=yieldthis.getLeftSpace(),i=this.config.reservedQuota;if(r!=null&&r-i<n){consto=n-r+i;qe("freeUpSpace for",e,t,o),yieldthis.freeUpSpace(o)}})}onQuotaExceeded(e,t,n){returnb(this,null,function*(){qe("quota exceeded",e,t,n);constr=this.config.reservedQuota;yieldthis.freeUpSpace(n?n+r:r)})}}functionJs([s,e],t){returne=e!=null?e:t,e!=null?e-s:0}functionyt(s){returns.pieces.reduce((e,t)=>{varn,r;returne+Js(t,(r=(n=s.meta)==null?void0:n.fsize)!=null?r:null)},0)}conster=E("dc"),tr="miku-delivery/dc/v1",_e="item",hn="usedTimeIndex",nr={name:_e,indexes:[{name:hn,keyPath:"usedTime"}]},sr=32*1024*1024;classrr{constructor(e={},t=tr){R(this,"db");R(this,"cr");R(this,"browserCache",null);R(this,"browserCachePromise",null);this.config=e,this.ns=t,this.db=newZt(this.ns,[nr]),this.cr=newZs(this)}openBrowserCache(){returnb(this,null,function*(){returnthis.browserCachePromise!=null?this.browserCachePromise:(this.browserCachePromise=caches.open(this.ns).catch(e=>{thrownewfe(e)}),this.browserCachePromise.then(e=>{this.browserCache=e}),this.browserCachePromise)})}getItem(e){returnb(this,null,function*(){returnthis.db.get(_e,e)})}setItem(e,t){returnb(this,null,function*(){er("setItem",e,t),yieldthis.db.set(_e,e,t),yieldthis.cr.onItemSet(e,t)})}walkItems(e){returnb(this,null,function*(){returnthis.db.walkBy(_e,hn,e)})}removeItemWithContent(e){returnb(this,null,function*(){constt=yieldthis.getItem(e);t!=null&&(yieldPromise.all(t.pieces.map(n=>this.removeContent(e,n))),yieldthis.db.remove(_e,e))})}browserCacheMatch(e){returnb(this,null,function*(){lett=this.browserCache;returnt==null&&(t=yieldthis.openBrowserCache()),t.match(e).catch(n=>{thrownewfe(n)})})}browserCachePut(e,t){returnb(this,null,function*(){letn=this.browserCache;n==null&&(n=yieldthis.openBrowserCache()),yieldn.put(e,t).catch(r=>{thrownewfe(r)})})}browserCacheDelete(e){returnb(this,null,function*(){lett=this.browserCache;t==null&&(t=yieldthis.openBrowserCache()),yieldt.delete(e).catch(n=>{thrownewfe(n)})})}getBrowserCacheKeys(){returnb(this,null,function*(){lete=this.browserCache;returne==null&&(e=yieldthis.openBrowserCache()),yielde.keys().then(t=>t.map(n=>n.url))})}getContent(e,t){returnb(this,null,function*(){constn=yieldthis.browserCacheMatch(je(e,t));if(n!=null){if(n.body==null)thrownewError("Body expected for cached response");returnUe(n)}})}setContent(e,t,n){returnb(this,null,function*(){if(!He())returnyieldthis.cacheResponse(e,t,n.underlayer),[t];const{headers:r,body:i}=n,o=wt(r);returnyieldAs(i,t[0],sr,(a,c,h)=>b(this,null,function*(){r.set("Content-Range",Se({start:c,end:h-1,totalSize:o})),r.set("Content-Length",h-c+"");constd=newResponse(a,{status:200,statusText:"OK",headers:r});yieldthis.cacheResponse(e,[c,h],d)}))})}cacheResponse(e,t,n){returnb(this,null,function*(){constr=je(e,t),i=re(n.headers);yieldthis.cr.beforeContentSet(e,t,i);try{yieldthis.browserCachePut(r,n)}catch(o){throwoinstanceoffe&&o.causeinstanceofError&&o.cause.name==="QuotaExceededError"&&this.cr.onQuotaExceeded(e,t,i),o}})}removeContent(e,t){returnb(this,null,function*(){constn=je(e,t);returnthis.browserCacheDelete(n)})}dispose(){this.db.dispose()}}functionje(s,e){vart;return/^https?:\/\//.test(s)||(s="https://miku-cache.com/"+s),`${s}_with_range_${e[0]}_${(t=e[1])!=null?t:""}`}functionir(s,e){returns.pieces.map(t=>je(e,t))}classfeextendsError{constructor(t){super(t+"");R(this,"name","BrowserCacheError");this.cause=t}}classor{constructor(e){this.logger=e}log(e){returnthis.logger.log("DoLog",e)}}constar=3,dn=E("http");classfn{constructor(e,t,n,r=0){R(this,"doLogger");this.client=t,this.resolver=n,this.clientResponseTimeout=r,this.doLogger=newor(e)}doWithResolved(e,t,n){returnb(this,null,function*(){dn("fetch",t.url,"with resolved",n);constr=newAbortController;Nt(r,t.signal);consti=newie(t.url,j(S({},t),{signal:r.signal}));i.headers.set("X-Miku-Agent",`miku-delivery-web/v${Ft}`);leto=this.client.fetch(e,i,n);this.clientResponseTimeout>0&&(o=Promise.race([o,Ht(this.clientResponseTimeout,"HTTPClient get response")]),o.catch(c=>{cinstanceofOt&&r.abort(c)}));consta=yieldo;if(dn("fetch",t.url,"succeeded with status",a.status),a.status===429||a.status>=500)thrownew$e(a);returna})}originalDo(e,t){returnb(this,null,function*(){if(t.signal.aborted)throwt.signal.reason;letn=-1,r;if(yieldthis.resolver.do(e,t.url,ar,i=>b(this,null,function*(){consto=newG(e);n++,o.set("downloadRetryCount",n),r=yieldthis.doWithResolved(o,t,i)})),r==null)thrownewError(`Http do failed: resolver do finished with no finalResp, url: ${t.url}`);returnr})}do(e,t){returnb(this,null,function*(){constn=Date.now(),r=se();e.set("doID",r);leti,o=null;try{returni=yieldthis.originalDo(e,t),i}catch(a){throwo=a,a}finally{const{onDoError:a,onDoResponsed:c}=this.getDoLog(e,r,n);i==null?a(o):c(i.status)}})}getDoLog(e,t,n){constr=a=>{varc;returnthis.doLogger.log(S({lookup_type:!0,t_lookup:(c=e.get("dnsResolveFromCache")===!0?0:e.get("dnsResolveTotalTime"))!=null?c:-1,t_total:-1,ts_st:n,err_desc:"",err_msg:"",status_code:-1,task_id:e.get("taskID"),id:t},a))};return{onDoError:a=>{constc=Date.now();r(S({t_total:N(c,n)},ue(a)))},onDoResponsed:a=>{constc=Date.now();r({t_total:N(c,n),status_code:a})}}}}classlr{constructor(e){this.logger=e}log(e){returnthis.logger.log("TaskLog",e)}}classwn{constructor(e,t,n,r){R(this,"id",se());R(this,"priority",0);R(this,"signal");R(this,"started",!1);R(this,"taskLogger");this.url=e,this.range=t,this.startByClient=r,this.taskLogger=newlr(n)}setPriority(e){this.priority=e}start(e){returnb(this,null,function*(){if(this.started)thrownewError("Task already started");if(this.started=!0,this.signal=e,e&&e.aborted)throwe.reason;constt=Date.now(),n=newG;n.set("taskID",this.id),n.set("taskDomain",newURL(this.url).hostname);letr,i=null;try{returnr=yieldthis.startByClient(n,this),r}catch(o){throwi=o,o}finally{const{logOnError:o,logOnTransferred:a}=this.log(n,t);r==null?o(i):r.underlayer.bodyReadResult.then(c=>{c.success?a():o(c.error)})}})}log(e,t){constn=e.get("taskCacheMatchAt"),r=e.get("task1stHttpDoAt"),i=e.get("taskResultStreamAt"),o=Date.now(),a=d=>{varp,l,f,u,w;returnthis.taskLogger.log(S({type:(p=e.get("taskType"))!=null?p:1,id:this.id,url:this.url,err_msg:"",err_desc:"",range_st:(f=(l=this.range)==null?void0:l.start)!=null?f:-1,range_end:(w=(u=this.range)==null?void0:u.end)!=null?w:-1,ts_st:t,t_cc_match:N(n,t),t_http_do:N(r,n),t_res_stream:N(i,n),t_res:N(o,i),t_trans:-1,t_total:-1},d))};return{logOnError:d=>{constp=Date.now();a(S({t_total:N(p,t)},ue(d)))},logOnTransferred:()=>{constd=Date.now();a({t_trans:N(d,o),t_total:N(d,t)})}}}}classpn{constructor(e,t,n,r,i){this.stream=e,this.size=t,this.fileSize=n,this.contentType=r,this.underlayer=i}blob(){returnb(this,null,function*(){conste=this.stream.getReader(),t=[];for(;;){const{done:n,value:r}=yielde.read();if(n)break;consti=r;t.push(i)}returnnewBlob(t)})}}functionRt(s,e,t){returns!=null&&t!=null&&t>=s&&(t=null),(e==null||e<0)&&(e=0),[e,t]}functionmn(s,e){varr;constt=((r=e[0])!=null?r:0)===0,n=e[1]==null||s!=null&&e[1]===s;returnt&&n}functioncr(s,e){varr,i;constt=(r=e[0])!=null?r:0,n=(i=e[1])!=null?i:s;returnn==null?null:n-t}functionur(s,e,t){varc,h;if(e===0)return[];constn=(d,p)=>bn(d,p,e!=null?e:Number.POSITIVE_INFINITY),r=(c=s==null?void0:s[0])!=null?c:0,i=(h=s==null?void0:s[1])!=null?h:e,o=[];leta=r;for(constdoft){if(a==null||e!=null&&d[1]!=null&&d[1]>e)break;if(!(d[1]!=null&&a>=d[1])){if(i==null||i>d[0]){d[0]>a&&o.push({cached:!1,range:Rt(e,a,d[0])});constp=n(d[0],a)?d[0]:a,l=n(d[1],i)?i:d[1];n(l,p)&&(o.push({cached:!0,range:Rt(e,p,l)}),a=l);continue}break}}returnn(i,a)&&o.push({cached:!1,range:Rt(e,a,i)}),o}functionhr(s,e){varr;constt=(r=e[0])!=null?r:0,n=e[1];for(constiofs){if(i[1]!=null&&i[1]<=t)continue;if(i[0]>t)break;consto=t-i[0],a=fr(n!=null?n:i[1],i[0]);return{piece:i,start:o,end:a}}thrownewError("Piece not found")}functiondr(s,e){constt=s.filter(o=>!e.some(a=>o[0]===a[0]&&o[1]===a[1])),n=[e[0][0],e[e.length-1][1]];for(letooft)if(gn(o,n))return{toSave:t,toRemove:e};constr=[],i=[];for(letooft)gn(n,o)?i.push(o):r.push(o);return{toSave:[...r,...e].sort((o,a)=>o[0]-a[0]),toRemove:i}}functiongn(s,e){returns[0]<=e[0]&&!bn(e[1],s[1],Number.POSITIVE_INFINITY)}functionbn(s,e,t){constn=s!=null?s:t,r=e!=null?e:t;returnn>r}functionfr(s,e){returns==null||e==null?null:s-e}functionvn(s){conste={},t=s.split(",").map(n=>{let[r,i]=n.split("=").map(o=>o.trim());return[r.toLowerCase(),i]});for(const[n,r]oft)if(n==="max-age"){if(r!=null){consti=parseInt(r,10);Number.isNaN(i)||(e["max-age"]=i)}}else(n==="no-cache"||n==="no-store")&&(e[n]=!0);returne}functionKe(s){returnMath.floor(s/1e3)}functionyn(s,e){constt=s.get("Date");if(t==null)returne;constn=Date.parse(t);returnNumber.isNaN(n)?e:n}functionwr(s,e,t){if(s!=null)returns;constn=e.get("Expires");if(n!=null){letr=Date.parse(n);Number.isNaN(r)&&(r=0);consti=yn(e,t);returnKe(r-i)}return60*60}functionpr(s){conste=s.get("Age");if(e==null)return0;constt=parseInt(e,10);returnNumber.isNaN(t)?0:t}functionmr(s,e,t,n){constr=pr(s),i=yn(s,t),o=Math.max(0,Ke(t-i)),a=Ke(t-e),c=r+a,h=Math.max(o,c),d=Ke(n-t);returnh+d}functiongr(s,e,t,n,r){varc;consti=(c=s==null?void0:s["max-age"])!=null?c:null,o=wr(i,e,n),a=mr(e,t,n,r);returno>a}functionbr(s,e,t,n){constr=s.get("Cache-Control"),i=r!=null?vn(r):null;return(i==null?void0:i["no-cache"])===!0?!0:!gr(i,s,e,t,n)}functionvr(s){conste=s.get("Cache-Control"),t=e!=null?vn(e):null;return!(t!=null&&t["no-store"]===!0)}functionyr(s){conste=s.get("ETag");returne==null?null:e.startsWith("W/")?e.slice(2):e}functionRr(s,e){constt=newHeaders(s),n=yr(e);n!=null&&t.set("If-None-Match",n);constr=e.get("Last-Modified");returnr!=null&&t.set("If-Modified-Since",r),t}functionCr(s,e){return!(s.get("Last-Modified")===e.get("Last-Modified")&&s.get("ETag")===e.get("ETag"))}functionSr(s,e){constt=newHeaders(s);returne.forEach((n,r)=>{r=r.toLowerCase(),!(r==="content-length"||r==="content-encoding"||r==="content-range")&&t.set(r,n)}),t}constxr={threshold:0,contentRangeExposed:!0},B=E("ftask"),we=O("ftask");classEr{constructor(e,t,n,r,i,o,a){R(this,"id",se());R(this,"inited");R(this,"meta",null);R(this,"cachePieces",[]);R(this,"usedTime",0);this.cache=e,this.nativeHttpClient=t,this.http=n,this.key=r,this.url=i,this.patterns=o,this.getMediaOptimization=a,this.inited=this.resume()}fileSize(){vare,t;return(t=(e=this.meta)==null?void0:e.fsize)!=null?t:null}cacheValidationRequired(){if(this.meta==null)return!1;const{requestTime:e,responseTime:t,headers:n}=this.meta;returne==null||t==null||n==null?!1:br(n,e,t,Date.now())}isMedia(e){constt=Be(e.url);returnthis.patterns.media.some(n=>n.test(t))}isRangeStartFirstRequested(e){varn;constt=(n=e[0])!=null?n:0;return!this.cachePieces.some(r=>{vari;returnr[0]<=t&&t<=((i=r[1])!=null?i:Number.POSITIVE_INFINITY)})}startTask(e,t){returnb(this,null,function*(){B("startTask",t.url,t.id,t.range);letn;constr=t.range!=null?[t.range.start,t.range.end]:[0,null];yieldthis.inited,this.usedTime=Date.now(),this.save().catch(a=>we("save failed when startTask:",a)),Re()?n=yieldthis.readRangeWithStream(e,t,r):(B("supportStreamOperation: false",t.url,t.id),n=yieldthis.readRangeWithoutStream(e,t,r));consti=this.meta;if(i==null)thrownewError("Missing meta in fileTask");B("startTask resolved",t.url,t.id);consto=cr(i.fsize,r);returnnewpn(n.body,o,i.fsize,i.headers.get("Content-Type"),n)})}readRangeWithoutStream(e,t,n){returnb(this,null,function*(){vara,c;letr;consti=[(a=n[0])!=null?a:0,n[1]],o=(c=yieldthis.cache.getContent(this.key,i))!=null?c:null;if(e.set("taskCacheMatchAt",Date.now()),o!=null&&!this.cacheValidationRequired())B("use cache",t.url,t.id),r=o;elseif(B("doRequestAndSaveCache",t.url,t.id,o!=null),r=yieldthis.doRequestAndSaveCache(e,t,n,o!=null,!1),r.status===304){if(o==null)thrownewError("Unexpected 304 with no cached response");r=o}returne.set("taskResultStreamAt",Date.now()),r})}readRangeWithStream(e,t,n){returnb(this,null,function*(){constr=this.isMedia(t),i=this.cacheValidationRequired();B("cacheValidationRequired",i);consto=ur(n,this.fileSize(),this.cachePieces);if(B("applyRange",n,this.fileSize(),this.cachePieces,o),i){consth=o.some(l=>l.cached),d=r?yieldthis.getMediaOptimization():!1,p=yieldthis.doRequestAndSaveCache(e,t,n,h,d);if(p.status===200||p.status===206)returnp}e.set("taskCacheMatchAt",Date.now());consta=newTransformStream(void0),c=yieldnewPromise((h,d)=>b(this,null,function*(){try{for(letp=0;p<o.length;p++){constl=p===0,{cached:f,range:u}=o[p];letw=null;if(f&&(w=yieldthis.readPieceFromLocal(e,t,u)),w==null){constx=r&&l&&this.isRangeStartFirstRequested(u)?yieldthis.getMediaOptimization():!1;w=yieldthis.readPieceFromRemote(e,t,u,x)}l&&h(w);constg=p===o.length-1;yieldw.body.pipeTo(a.writable,{preventClose:!g})}}catch(p){p!=null&&we("readRange stream error for",this.url,p),a.writable.abort(p),d(p)}}));returne.set("taskResultStreamAt",Date.now()),newte(a.readable,c)})}readPieceFromLocal(e,t,n){returnb(this,null,function*(){B("readPieceFromLocal",t.url,n);const{piece:r,start:i,end:o}=hr(this.cachePieces,n),a=yieldthis.cache.getContent(this.key,r);returna==null?(we(`Missing cache item: ${this.key} [${r})`),null):newte(pt(a.body,[i,o]),a)})}readPieceFromRemote(e,t,n,r){returnb(this,null,function*(){B("readPieceFromRemote",t.url,n);consti=yieldthis.doRequestAndSaveCache(e,t,n,!1,r);return!mn(this.fileSize(),n)&&i.status===200?(we("Range request not supported for",this.url),newte(pt(i.body,n),i)):i})}doRequest(e,t,n,r,i){returnb(this,null,function*(){varu;e.get("task1stHttpDoAt")==null&&e.set("task1stHttpDoAt",Date.now());consto=newG(e);o.set("downloadFileTaskID",this.id);leta=newHeaders({"Accept-Encoding":"identity;q=1, *;q=0"});n!=null&&(t.range==null&&mn(this.fileSize(),n)||a.set("Range",Ee({start:n[0],end:n[1]==null?null:n[1]-1})));constc=(u=this.meta)==null?void0:u.headers;r&&c!=null&&(a=Rr(a,c));consth=newie(t.url,{method:"GET",headers:a,signal:t.signal}),d=Date.now();letp;i===!1||i.threshold<=0?p=yieldthis.http.do(o,h):p=yield_r((...w)=>this.http.do(...w),(...w)=>this.nativeHttpClient.fetch(...w),i)(o,h);constl=Date.now();if(p.body==null)thrownewError("Body expected");letf=p.headers;if(r&&c!=null&&p.status===304)B(`updateStoredHeaders for ${this.url}`),f=Sr(c,p.headers);elseif(p.status!==200&&p.status!==206)thrownew$e(p);returnyieldthis.onResponse(f,d,l),p.bodyReadResult.then(w=>{B(`bodyReadResult for ${this.url}:`,w)}),p})}doRequestAndSaveCache(e,t,n,r,i){returnb(this,null,function*(){consto=yieldthis.doRequest(e,t,n,r,i);return(o.status===200||o.status===206)&&vr(o.headers)?this.saveCachePiece(t,n,o):o})}saveCachePiece(e,t,n){returnb(this,null,function*(){varo,a;letr=n,i;if(Re()){const{main:c,minor:h}=Ds(n.body);r=newte(c,n),i=newte(h,n)}elseif(!e.range){constc=n.underlayer.clone();i=Ue(c)}if(i!=null){constc=[(o=t==null?void0:t[0])!=null?o:0,(a=t==null?void0:t[1])!=null?a:null];B("saveCachePiece",this.url,c),this.cache.setContent(this.key,c,i).then(h=>b(this,null,function*(){if(h.length===0)return;const{toSave:d,toRemove:p}=dr(this.cachePieces,h);if(this.cachePieces=d,p.length>0){B("remove duplicated cache pieces",p);try{yieldPromise.all(p.map(l=>this.cache.removeContent(this.key,l)))}catch(l){B("exception occurred while removing duplicated cache pieces",l)}}returnthis.save()})).then(()=>B("saveCachePiece finish",this.url,c,this.cachePieces),h=>we("saveCachePiece failed",this.url,c,h))}returnr})}onResponse(e,t,n){returnb(this,null,function*(){constr=this.meta;this.meta={fsize:wt(e),requestTime:t,responseTime:n,headers:e},(r==null?void0:r.headers)!=null&&Cr(r.headers,e)&&(B(`${this.url} modified, clear local cache`),yieldPromise.all(this.cachePieces.map(i=>this.cache.removeContent(this.key,i))),this.cachePieces=[]),this.save().catch(i=>we("save failed when onResponse:",i))})}resume(){returnb(this,null,function*(){conste=yieldthis.cache.getItem(this.key);e==null||e.meta==null||(this.meta=j(S({},e.meta),{headers:e.meta.headers!=null?newHeaders(e.meta.headers):null}),this.cachePieces=e.pieces)})}save(){returnb(this,null,function*(){varr,i;conste=((r=this.meta)==null?void0:r.headers)!=null?[...((i=this.meta)==null?void0:i.headers).entries()]:null,n={meta:this.meta!=null?j(S({},this.meta),{headers:e}):null,pieces:this.cachePieces,usedTime:this.usedTime};yieldthis.cache.setItem(this.key,n)})}}function_r(s,e,{threshold:t,contentRangeExposed:n}){returnfunction(i,o){returnb(this,null,function*(){varZ,$;constP=o,{url:a}=P,c=Pt(P,["url"]),h=xe(o.headers);B("doWithInitialOptimization",a);constd=newG(i),p=newHeaders(c.headers),l=S({start:null,end:null},h);l.start=(Z=l.start)!=null?Z:0;constf=l.start+t-1;(l.end==null||l.end>f)&&(l.end=f),p.set("Range",Ee(l));constu=newie(a,j(S({},c),{headers:p})),g=yield((K,X)=>b(this,null,function*(){varle;letz=null;constF=xe(X.headers);F!=null&&!Jt(F)&&!n&&(z=Tr(a,c.headers,e));constW=yielde(K,X);if(F!=null&&W.status===206&&!W.headers.get("Content-Range")){constq=Jt(F)?re(W.headers):yieldz;if(q!=null){constU=Se({start:F.start,end:(le=F.end)!=null?le:q-1,totalSize:q});W.headers.set("Content-Range",U)}}returnW}))(d,u);if(g.body==null)thrownewError("Body expected for initial response");if(g.status!==206)returng;constx=dt(g.headers);if(x==null)thrownewError("Header Content-Range expected for 206 response");constm=(()=>{varle;constK=re(g.headers);if(K!=null&&K<t)returng.body;constX=newHeaders(c.headers),z=S({start:null,end:null},h);if(z.start=((le=z.start)!=null?le:0)+t,z.end!=null&&z.end<z.start)returng.body;B("doWithInitialOptimization followingRange",z),X.set("Range",Ee(z));constF=newie(a,j(S({},c),{headers:X})),W=newTransformStream;returng.body.pipeTo(W.writable,{preventClose:!0}).then(()=>b(this,null,function*(){B("doWithInitialOptimization initialBody transfered");letq;try{constU=yields(i,F);if(U.body==null)thrownewError(`Body expected for following response of ${a}`);if(U.status===200)q=pt(U.body,[z.start,z.end==null?null:z.end+1]);elseif(U.status===206)q=U.body;elsethrownew$e(U)}catch(U){if(Ct(U))B("use fallback fetch for doWithInitialOptimization followingBody",U),q=(yielde(i,F)).body;else{B("doWithInitialOptimization get followingBody failed",U),W.writable.abort(U);return}}q.pipeTo(W.writable).then(()=>B("doWithInitialOptimization followingBody transfered"),U=>B("doWithInitialOptimization followingBody transfer failed",U))}),q=>b(this,null,function*(){B("doWithInitialOptimization initialBody transfer failed",q)})),W.readable})(),v=x.totalSize,y=newHeaders(g.headers);if(y.delete("Content-Range"),y.delete("Content-Length"),h==null)returnv!=null&&y.set("Content-Length",v+""),newte(m,{status:200,statusText:"OK",headers:y,underlayer:g.underlayer});constC=($=h.start)!=null?$:0,D=h.end!=null?h.end:v!=null?v-1:null;returnD!=null&&y.set("Content-Length",D-C+1+""),y.set("Content-Range",Se({start:C,end:D,totalSize:v})),newte(m,{status:206,statusText:"Partial Content",headers:y,underlayer:g.underlayer})})}}functionTr(s,e,t){returnb(this,null,function*(){constn=newHeaders(e);n.delete("Range");constr=yieldt(newG,newie(s,{method:"HEAD",headers:n}));returnre(r.headers)})}functionCt(s){return[gt,ae,ln,bt,Ce,fe].some(e=>sinstanceofe)}classAr{constructor(e){this.logger=e}log(e){returnthis.logger.log("LiveScheduleLog",e)}}constDr=newURL(be).hostname;functionIr(s,e,t,n){returnb(this,null,function*(){varl,f;constr=newAr(n),i={url:e,cip:""},o=it(j(S({},t),{path:be})),a=Date.now();letc,h=null,d=null,p=null;try{if(h=yieldfetch(be,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json",Authorization:o}}),d=Date.now(),!h.ok)thrownewError(`Call Schedule API failed, status: ${h.status}${h.statusText}`);returnp=yieldh.json()}catch(u){throwc=u}finally{constu=N(Date.now(),a),w=p==null?ue(c):{err_msg:"",err_desc:""};r.log(j(S({r_id:(l=h==null?void0:h.headers.get("x-reqid"))!=null?l:"",ip:"",domain:Dr,status_code:(f=h==null?void0:h.status)!=null?f:-1},w),{t_conn:N(d,a),t_total:u,type:1}))}})}constTe=E("dns"),St=O("dns"),kr=60,Lr=60*1e3;classMr{constructor(e,t,n=Ir,r=Be){R(this,"scheduling",newMap);R(this,"cache",newMap);R(this,"m3u8SegmentCache",newMap);this.logger=e,this.app=t,this.scheduler=n,this.cacheUrl=r}getScheduleResult(e,t){returnb(this,null,function*(){varo;constn=Date.now();letr;try{r=yieldthis.scheduler(e,t,this.app,this.logger)}catch(a){throwSt("Live schedule failed:",a),newgt(a)}finally{e.set("dnsResolveTotalTime",N(Date.now(),n))}if(r.code===1)thrownewae(`Local DNS for ${t}`);if(r.code!==0)thrownewError(`Unexpected schedule code: ${r.code}`);consti=(o=r.ttl)!=null?o:kr;return{nodes:r.hosts.map(a=>{const[c,h]=qn(a,0),[d,p]=["",0];return{addr:{ip:d,host:c,http:h+80,https:h+443,how:p},after:0}}),expireAt:Date.now()+i*1e3,ttl:i}})}saveM3u8SegmentResult(e,t){returnb(this,null,function*(){constn=this.cacheUrl(e),r=this.cache.get(n);if(r==null){St("No schedule result for m3u8:",e);return}consti=t.map(this.cacheUrl);i.forEach(o=>{this.m3u8SegmentCache.set(o,r)}),setTimeout(()=>{i.forEach(o=>{this.m3u8SegmentCache.delete(o)})},60*1e3)})}schedule(e,t){returnb(this,null,function*(){constn=this.cacheUrl(t);if(!Pe(t)&&!$t(t)){consta=this.m3u8SegmentCache.get(n);if(a==null)thrownewae("Neither m3u8 / flv URL, or m3u8 segment URL");returna}constr=this.cache.get(n);if(r!=null&&xt(r))returne.set("dnsResolveFromCache",!0),r;consti=this.scheduling.get(n);if(i!=null){leta;try{a=yieldi}catch(c){if(cinstanceofae)throwc}if(a!=null&&xt(a))returne.set("dnsResolveFromCache",!0),a;this.scheduling.delete(n)}consto=this.getScheduleResult(e,t);returnTe("save scheduling for",t),this.scheduling.set(n,o),o.then(a=>{Te("save cache for",t),this.cache.set(n,a)},()=>{}),o})}hasResult(e){constt=this.cacheUrl(e),n=Pe(e)||$t(e)?this.cache.get(t):this.m3u8SegmentCache.get(t);returnn!=null&&xt(n)}do(e,t,n,r){returnb(this,null,function*(){leti;Te("schedule for",t);consto=yieldthis.schedule(e,t);Te("scheduled for",t);for(leta=0;a<n;a++){constc=Br(o.nodes);if(c==null)break;try{Te("do job with",c,t),yieldr(c.addr),o.expireAt=Date.now()+o.ttl*1e3;return}catch(h){if(St("do job with",c.addr,"failed:",h,t),i=h,oe(h))break;Fe(h)&&(c.after=Date.now()+Lr)}}throwi=oe(i)?i:newbt(i),i})}}functionRn(s,e=Date.now()){returns.after<e}functionBr(s){for(consteofs)if(Rn(e))returne;returnnull}functionxt(s){conste=Date.now();returns.expireAt<=e?!1:s.nodes.some(t=>Rn(t,e))}constpe=E("utils/fetch");functionCn(s){returnb(this,null,function*(){varf,u;conste=yieldfetch(s),t=xe(s.headers);if(t==null||e.status!==206||e.body==null)returne;const{body:n,status:r,statusText:i,headers:o}=e,a=(f=dt(o))==null?void0:f.end,c=100;leth=(u=t.start)!=null?u:0,d=n.getReader(),p=null;constl=newReadableStream({pull:w=>b(this,null,function*(){p!=null&&(clearTimeout(p),p=null),d==null&&(pe("resume on pull"),s.headers.set("range",Ee(j(S({},t),{start:h}))),d=(yieldfetch(s)).body.getReader());const{value:g,done:x}=yieldd.read();if(x){pe("read done"),w.close();return}try{w.enqueue(g)}catch(m){pe("enqueue failed:",m),d==null||d.cancel("target stream enqueue failed");return}if(h+=g.byteLength,a!=null&&h>a){pe("all enqueued"),d.cancel("all enqueued"),w.close();return}p=setTimeout(()=>b(this,null,function*(){p=null,d!=null&&(pe("cancel after long time no pull"),d.cancel("long time no read"),d=null)}),c)}),cancel:w=>{pe("cancel",w),d==null||d.cancel(w)}});returnnewResponse(l,{status:r,statusText:i,headers:o})})}classSn{constructor(e){this.logger=e}start(e,t){letn;constr=Date.now(),i=c=>{varf,u,w,g,x,m,v,y,C,D,P;consth=t.headers.get("Range"),d=h==null?null:en(h),p=n==null?void0:n.headers.get("X-M-Reqid"),l=p?p.split(", ").pop():"";this.log(S({ip:(f=e.get("downloadReqIP"))!=null?f:"",domain:(u=e.get("taskDomain"))!=null?u:"",range_st:(w=d==null?void0:d.start)!=null?w:-1,range_end:(g=d==null?void0:d.end)!=null?g:-1,retry:(x=e.get("downloadRetryCount"))!=null?x:0,ftask_id:(m=e.get("downloadFileTaskID"))!=null?m:"",task_id:(v=e.get("taskID"))!=null?v:"",d_id:(y=e.get("doID"))!=null?y:"",ts_st:r,r_id:l,elt_id:(C=e.get("downloadEltID"))!=null?C:"",status_code:(D=n==null?void0:n.status)!=null?D:-1,t_req_msg:N(e.get("downloadReqMessageAt"),r),t_conn:N(e.get("downloadConnectionAt"),(P=e.get("downloadReqMessageAt"))!=null?P:r),t_tls:-1,t_st_trans:N(e.get("downloadStartTransferAt"),e.get("downloadConnectionAt")),t_resp_msg:N(e.get("downloadRespMessageAt"),e.get("downloadStartTransferAt")),err_msg:"",err_desc:"",t_content_trans:-1,t_total:-1,resp_size:-1},c))};return{onError:c=>{consth=Date.now();i(S({t_total:N(h,r)},ue(c)))},onResponse:c=>{n=c,n.bodyReadResult.then(h=>{varl;constd=Date.now(),p=h.success?null:ue(h.error);i(S({t_content_trans:N(d,(l=e.get("downloadRespMessageAt"))!=null?l:e.get("downloadStartTransferAt")),t_total:N(d,r),resp_size:h.size},p))})}}}wrap(e,t,n){returnb(this,null,function*(){constr=this.start(e,t);try{consti=yieldn();returnr.onResponse(i),i}catch(i){throwr.onError(i),i}})}log(e){returnthis.logger.log("DownloadLog",e)}}classPr{constructor(e){R(this,"downloadLogger");this.downloadLogger=newSn(e)}fetch(e,t,n=!0){returnb(this,null,function*(){returnthis.downloadLogger.wrap(e,t,()=>b(this,null,function*(){consth=t,{url:r}=h,i=Pt(h,["url"]),o=newRequest(r,S(S({},n?xn:null),i)),a=yieldCn(o),c=Date.now();returne.set("downloadConnectionAt",c),e.set("downloadStartTransferAt",c),Ue(a)}))})}}constxn={mode:"cors",credentials:"omit"};classEn{constructor(e,t=!0,n=Cn){R(this,"downloadLogger");this.https=t,this.nativeFetch=n,this.downloadLogger=newSn(e)}fetch(e,t,n){returnb(this,null,function*(){returnthis.downloadLogger.wrap(e,t,()=>b(this,null,function*(){e.set("downloadReqIP",n.host);constr=this.nativeFetch,i=_n(t,n,this.https),o=yieldr(i),a=Date.now();returne.set("downloadConnectionAt",a),e.set("downloadStartTransferAt",a),Ue(o)}))})}dispose(){}}function_n(s,e,t=!0){const{url:n,headers:r,method:i,signal:o}=s,a=newURL(n),c=a.host,h=newHeaders(r);a.protocol=t?"https:":"http:",a.host=`${e.host}:${t?e.https:e.http}`,a.pathname=`/${c}${a.pathname}`;letd=a.toString();if(h.has("X-Miku-Agent")){constp=h.get("X-Miku-Agent");h.delete("X-Miku-Agent");constl=d.includes("?")?"&":"?",f=["X-Miku-Agent",p].map(encodeURIComponent).join("=");d=d+l+f}returnnewRequest(d,j(S({},xn),{headers:h,method:i,signal:o}))}functionOr(s){conste=[],t=s.split(`
`).map(r=>r.trim()).filter(r=>r.length>0);if(t[0]!=="#EXTM3U")thrownewError("Invalid Extended M3U Playlist");letn=null;for(constroft){if(r.startsWith("#")){r.startsWith("#EXTINF:")&&(n=r);continue}n!=null&&(e.push({uri:r}),n=null)}returne}constTn=E("client"),Et=O("client");classHr{constructor(e,t){R(this,"fileTasks",newMap);R(this,"cache");R(this,"cdnResolver");R(this,"liveResolver");R(this,"nativeHttpClient");R(this,"http");R(this,"liveHttp");R(this,"patterns");R(this,"logger");varo,a,c,h,d;this.config=t,t!=null&&t.debug&&M(),this.cache=newrr(t==null?void0:t.cache),this.logger=(o=t==null?void0:t.logger)!=null?o:newGt(e),this.cdnResolver=(a=t==null?void0:t.resolver)!=null?a:newjs(this.logger,e,t==null?void0:t.dnsResolver,t==null?void0:t.cacheUrl),this.liveResolver=(c=t==null?void0:t.liveResolver)!=null?c:newMr(this.logger,e,t==null?void0:t.scheduler),this.nativeHttpClient=newPr(this.logger);constn=(h=t==null?void0:t.httpClient)!=null?h:newEn(this.logger),r=(d=t==null?void0:t.liveHttpClient)!=null?d:newEn(this.logger);this.patterns=S(S({},zt),t==null?void0:t.patterns),this.http=newfn(this.logger,n,this.cdnResolver,6e3);consti=2e3;this.liveHttp=newfn(this.logger,r,this.liveResolver,i)}prepare(e){returnb(this,null,function*(){returnPromise.all(e.map(t=>this.cdnResolver.resolveDomain(newG,t))).catch(t=>{Et("prepare failed:",t)})})}createTask(e,t){constn=e.indexOf("#");returnn>=0&&(e=e.slice(0,n)),newwn(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",1),this.startTask(r,i)))}createLiveTask(e,t){constn=e.indexOf("#");returnn>=0&&(e=e.slice(0,n)),newwn(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",2),this.startLiveTask(r,i)))}startTask(e,t){returnb(this,null,function*(){constn=newURL(t.url).hostname,r=yieldthis.cdnResolver.getCacheKey(t.url,n);leti=this.fileTasks.get(r);if(i==null){consto=()=>b(this,null,function*(){varc;consta=yieldthis.cdnResolver.getMediaOptimization(n);returnS(S(S({},xr),a),(c=this.config)==null?void0:c.mediaOptimization)});i=newEr(this.cache,this.nativeHttpClient,this.http,r,t.url,this.patterns,o),this.fileTasks.set(r,i)}returni.startTask(e,t)})}saveM3u8SegmentResult(e,t){returnb(this,null,function*(){constn=yield_s(t),i=Or(n).map(o=>jn(o.uri,e));Tn("saveM3u8SegmentResult",Be(e),i.map(Be)),yieldthis.liveResolver.saveM3u8SegmentResult(e,i)})}startLiveTask(e,t){returnb(this,null,function*(){varh,d;constn={};t.range!=null&&(n.Range=Ee({start:t.range.start,end:t.range.end==null?null:t.range.end-1}));constr=newie(t.url,{method:"GET",headers:n,signal:t.signal});leti,a=((d=(h=this.config)==null?void0:h.liveOptimization)!=null?d:!0)&&Pe(t.url)&&!this.liveResolver.hasResult(t.url);if(a){Tn("use nativeClient for",t.url);constp=this.nativeHttpClient.fetch(e,r);this.liveHttp.do(newG(e),r).catch(l=>{Et("do failed when prefetch for liveOptimization:",l)}),i=yieldp}elsei=yieldthis.liveHttp.do(e,r);if(i.body==null)thrownewError("Body expected");if(i.status!==200&&i.status!==206)thrownewError(`Invalid response, status: ${i.status}`);letc=i.body;if(!a&&He()&&Pe(t.url)){const[p,l]=i.body.tee();this.saveM3u8SegmentResult(t.url,l).catch(f=>{Et("Save M3u8 segment cache failed:",t.url,f)}),c=p}returnnewpn(c,re(i.headers),wt(i.headers),i.headers.get("Content-Type"),i)})}dispose(){this.cache.dispose()}}functionNr(s){returns&&s.mikuDeliveryProxy===!0}constzr=E("proxy/common");functionUr(s,e){returnb(this,null,function*(){varu;const{browser:t}=tt(navigator.userAgent);if(t.name==="Firefox"&&e.headers.get("Range")){zr("Short circuit for Firefox:",e.url);constw=yields.cdnResolver.resolve(newG,e.url),g=_n(e,w);returnResponse.redirect(g.url)}constn=xe(e.headers),r=n==null?void0:{start:n.start,end:n.end==null?null:n.end+1},i=s.createTask(e.url,r!=null?r:void0);leto;try{o=yieldi.start(e.signal)}catch(w){if(winstanceof$e){const{status:g,statusText:x,headers:m,body:v,underlayer:y}=w.response;returny!=null?y:newResponse(v,{status:g,statusText:x,headers:m})}throww}let{stream:a,contentType:c,size:h,fileSize:d,underlayer:p}=o;if(!Re())returnp.underlayer;letl=nn(p==null?void0:p.headers);returnl.set("Accept-Ranges","bytes"),l.set("Access-Control-Allow-Origin","*"),l.set("Content-Type",c!=null?c:""),l.set("Content-Length",(h!=null?h:"")+""),l.set("Content-Transfer-Encoding","binary"),r!=null&&l.set("Content-Range",Se({start:(u=r.start)!=null?u:0,end:r.end!=null?r.end-1:d!=null?d-1:null,totalSize:d})),newResponse(a,{status:r==null?200:206,statusText:r==null?"OK":"Partial Content",headers:l})})}function$r(s,e){returnb(this,null,function*(){varl;constt=xe(e.headers),n=t==null?void0:{start:t.start,end:t.end==null?null:t.end+1},r=s.createLiveTask(e.url,n!=null?n:void0);let{stream:i,contentType:o,size:a,fileSize:c,underlayer:h}=yieldr.start(e.signal);if(!He())returnh.underlayer;letd=newHeaders(h==null?void0:h.headers);returnd.set("Accept-Ranges","bytes"),d.set("Access-Control-Allow-Origin","*"),d.set("Content-Type",o!=null?o:""),d.set("Content-Length",(a!=null?a:"")+""),n!=null&&d.set("Content-Range",Se({start:(l=n.start)!=null?l:0,end:n.end!=null?n.end-1:c!=null?c-1:null,totalSize:c})),newResponse(i,{status:n==null?200:206,statusText:n==null?"OK":"Partial Content",headers:d})})}constFr="MIKU_DELIVERY_PROXY_CONFIG";functionWr(s){conste=s.split("?")[1];if(!e)thrownewError("Invalid script url");constn=newURLSearchParams(e).get(Fr);if(n==null)thrownewError("Invalid script url: no config info");constr=JSON.parse(n),i=o=>o==null?void0:o.map(({source:a,flags:c})=>newRegExp(a,c));returnj(S({},r),{patterns:r.patterns==null?void0:Fn(r.patterns,o=>i(o))})}functionqr(s){returnArray.isArray(s)?{cdn:s,live:[]}:S({cdn:[],live:[]},s)}functionAn(s,e){constt=s.hostname;returne.includes("*")||e.includes(t)}constjr=O("proxy/statistics");classKr{constructor(){R(this,"windowFetchItemsMap",newMap)}onFetchItem(e,t,n,r,i){consto={url:t,ecdn:r,fallback:i!=null?i:!1,size:re(n.headers)};leta=this.windowFetchItemsMap.get(e);a==null&&(a=[],this.windowFetchItemsMap.set(e,a)),a.push(o)}onWindowClose(e){this.windowFetchItemsMap.delete(e)}getFetchItems(e){returnthis.windowFetchItemsMap.get(e)||[]}}functionDn(t){returnb(this,arguments,function*(s,e={}){const{url:n,headers:r,method:i,redirect:o,signal:a}=s,c=self.location.host,h=newURL(n).host;if(c===h)returnfetch(s,e);constd=newRequest(n,S({mode:"cors",credentials:"omit",headers:r,method:i,redirect:o,signal:a},e));try{returnyieldfetch(d)}catch(p){returnjr("Request with CORS failed:",n,p),fetch(s)}})}classVr{constructor(e){this.logger=e}log(e){returnthis.logger.log("PageStatusLog",e)}}constVe=E("proxy/sw"),ne=newMap,Ae=self,Q=Wr(Ae.location.href),_t=qr(Q.domains),In=S(S({},zt),Q.patterns),Ge=newHr(Q.app,S({debug:Q.debug,patterns:Q.patterns},Q.client));Ge.prepare(_t.cdn);constGr=Ge.nativeHttpClient,De=newKr,Qr=newGt(Q.app),me=newVr(Qr);Ae.addEventListener("activate",s=>{s.waitUntil(Ae.clients.claim()),he.onRemove(e=>{De.onWindowClose(e)})}),Ae.addEventListener("fetch",s=>b(this,null,function*(){s.clientId!==""&&he.add(s.clientId);conste=s.request;if(e.method==="GET"){constt=newURL(e.url),n=newAbortController;if(Nt(n,s.request.signal),Object.defineProperty(e,"signal",{value:n.signal}),he.whenRemoved(s.clientId,()=>n.abort(newWn(`Source client ${s.clientId} closed`))),An(t,_t.cdn)&&Ut(t,In))returnXr(s,e);if(An(t,_t.live)&&Ut(t,In,["live"]))returnYr(s,e)}e.method==="GET"&&Q.statistics&&s.respondWith(Dn(e).then(t=>{varn;returnDe.onFetchItem(s.clientId,e.url,t,!1),me.log({r_id:(n=ne.get(s.clientId))!=null?n:"",text:t.statusText,code:t.status,url:e.url}),t}).catch(t=>{varn;returnme.log({r_id:(n=ne.get(s.clientId))!=null?n:"",text:tinstanceofError?t.message:"",code:-1,url:e.url}),t}))})),Ae.addEventListener("message",s=>b(this,null,function*(){if(s.sourceinstanceofWindowClient&&!!Nr(s.data))switch(Ve("got proxy message",s.data,"from",s.source.id),s.data.type){case"window-available":he.add(s.source.id);break;case"window-unavailable":he.remove(s.source.id),ne.delete(s.source.id);break;case"get-window-fetch-items":conste=s.source.id,t=De.getFetchItems(e),n=yieldhe.get(e);if(n==null)thrownewError(`Invalid window client ID: ${e}`);constr={mikuDeliveryProxy:!0,type:"window-fetch-items",items:t};n.postMessage(r);break;case"get-perf-rid":ne.set(s.source.id,s.data.rid)}}));functionXr(s,e){Ve("use cdn",e.url),s.respondWith(Ur(Ge,e).then(t=>{varn;returnQ.statistics&&(De.onFetchItem(s.clientId,e.url,t,!0,!1),me.log({r_id:(n=ne.get(s.clientId))!=null?n:"",text:t.statusText,code:t.status,url:e.url})),t},t=>b(this,null,function*(){varn,r,i;if(Ct(t))if(Ve("Use fallback fetch for request",e.url,", error:",t),Q.statistics)try{consto=yieldDn(e);returnDe.onFetchItem(s.clientId,e.url,o,!0,!0),me.log({r_id:(n=ne.get(s.clientId))!=null?n:"",text:o.statusText,code:o.status,url:e.url}),o}catch(o){throwme.log({r_id:(r=ne.get(s.clientId))!=null?r:"",text:oinstanceofError?o.message:"",code:-1,url:e.url}),o}else{consto=newG;o.set("taskDomain",newURL(e.url).hostname);const{body:a,status:c,statusText:h,headers:d,underlayer:p}=yieldGr.fetch(o,Is(e),!1);returnRe()?newResponse(a,{status:c,statusText:h,headers:d}):p}throwQ.statistics&&me.log({r_id:(i=ne.get(s.clientId))!=null?i:"",text:tinstanceofError?t.message:"",code:-1,url:e.url}),t})))}functionYr(s,e){s.respondWith($r(Ge,e).then(void0,t=>b(this,null,function*(){if(Ct(t))returnVe("Use fallback fetch for request",e.url,", error:",t),fetch(e);throwt})))}})();