From 69f5c657397771f2bf25572646e1d83a065ce54d Mon Sep 17 00:00:00 2001 From: anne-lxm <1076217653@qq.com> Date: Fri, 9 Jun 2023 20:43:27 +0800 Subject: [PATCH] update img --- docs/.vuepress/config.js | 4 +- docs/.vuepress/public/js/miku.js | 10 +++++ docs/.vuepress/public/miku-delivery-1.1.0.js | 5 +++ .../public/miku-delivery-sw-1.1.0.js | 5 +++ docs/README.md | 45 ++++++++++--------- 5 files changed, 48 insertions(+), 21 deletions(-) create mode 100644 docs/.vuepress/public/js/miku.js create mode 100644 docs/.vuepress/public/miku-delivery-1.1.0.js create mode 100644 docs/.vuepress/public/miku-delivery-sw-1.1.0.js diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 996a04dd0..702128a58 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -23,7 +23,9 @@ const config = { name: 'keywords', content: 'serverless,云开发,数字天堂,前端开发,web开发,小程序开发,跨平台,跨平台开发,跨端开发,混合开发,app开发,多端开发,开发工具,HTML5,vue,react,native,rn,flutter,weex,cordova,微信小程序,阿里小程序,支付宝小程序,百度小程序,头条小程序,抖音小程序,QQ小程序,快应用,流应用,云函数' }], ['script', { src: `/js/redirect.js?${Date.now()}&v=${Date.now()}&version=${Date.now()}` }], - ['script', { src: 'https://hm.baidu.com/hm.js?fe3b7a223fc08c795f0f4b6350703e6f' }] + ['script', { src: 'https://hm.baidu.com/hm.js?fe3b7a223fc08c795f0f4b6350703e6f' }], + ['script', { src: 'miku-delivery-1.1.0.js' }], + ['script', { src: `/js/miku.js?${Date.now()}&v=${Date.now()}&version=${Date.now()}` }] ], locales: { '/': { diff --git a/docs/.vuepress/public/js/miku.js b/docs/.vuepress/public/js/miku.js new file mode 100644 index 000000000..104e0794b --- /dev/null +++ b/docs/.vuepress/public/js/miku.js @@ -0,0 +1,10 @@ +mikuDelivery.initProxy('miku-delivery-sw-1.1.0.js', { + /** appID 和 appSalt 由七牛配置提供*/ + app: { + appID: 'r5v5l8yhuips0xwv', + appSalt: 'ejhqsncr0hrwcadkfrsh07n3p6wxt9q3' + }, + /** 需要被代理的域名列表,域名需要提前在七牛创建完成,由七牛配置 ecdn 功能 */ + domains: ['qiniu-web-assets.dcloud.net.cn'], + // debug: true +}) \ No newline at end of file diff --git a/docs/.vuepress/public/miku-delivery-1.1.0.js b/docs/.vuepress/public/miku-delivery-1.1.0.js new file mode 100644 index 000000000..718763ae5 --- /dev/null +++ b/docs/.vuepress/public/miku-delivery-1.1.0.js @@ -0,0 +1,5 @@ +var mikuDelivery=function(k){"use strict";var jr=Object.defineProperty,Kr=Object.defineProperties;var Vr=Object.getOwnPropertyDescriptors;var He=Object.getOwnPropertySymbols;var kn=Object.prototype.hasOwnProperty,Ln=Object.prototype.propertyIsEnumerable;var _t=(k,I,B)=>I in k?jr(k,I,{enumerable:!0,configurable:!0,writable:!0,value:B}):k[I]=B,T=(k,I)=>{for(var B in I||(I={}))kn.call(I,B)&&_t(k,B,I[B]);if(He)for(var B of He(I))Ln.call(I,B)&&_t(k,B,I[B]);return k},j=(k,I)=>Kr(k,Vr(I));var Tt=(k,I)=>{var B={};for(var q in k)kn.call(k,q)&&I.indexOf(q)<0&&(B[q]=k[q]);if(k!=null&&He)for(var q of He(k))I.indexOf(q)<0&&Ln.call(k,q)&&(B[q]=k[q]);return B};var R=(k,I,B)=>(_t(k,typeof I!="symbol"?I+"":I,B),B);var b=(k,I,B)=>new Promise((q,oe)=>{var Ue=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())});function I(s){const e=[],t=s.length;for(let n=0;n=55296&&r<=56319&&t>n+1){const i=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)}return new Uint8Array(e).buffer}function B(s){return s^=s>>>16,s=Math.imul(s,2246822507),s^=s>>>13,s=Math.imul(s,3266489909),s^=s>>>16,s>>>0}const q=new Uint32Array([3432918353,461845907]);function oe(s,e){return s<>>32-e}function Ue(s,e){const t=s.byteLength/4|0,n=new Uint32Array(s,0,t);for(let r=0;re-t)}_add({key:e,replicas:t}){for(let n=0;nn>e);return t<0?0:t}get(e){if(this.members.size===0)return null;const t=this.hasher(e),n=this.search(t),r=this.sortedHashes[n];return this.circle.get(r)}getN(e,t,n){const r=n?n.size:this.members.size;if(r===0||t===0)return[];t>r&&(t=r);const i=this.hasher(e),o=this.search(i),a=[];for(let c=o;;c++){c>=this.sortedHashes.length&&(c=0);const h=this.sortedHashes[c],d=this.circle.get(h);if(!a.includes(d)&&(!n||n.has(d))&&(a.push(d),a.length>=t))return a}}add(e,t){return this.members.has(e)?!1:(this._add({key:e,replicas:t}),this.updateSortedHashes(),!0)}remove(e){if(!this.members.has(e))return!1;const t=this.membersReplicas.get(e);return this._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()}}function At(s,e){return e+s}const Bn=Pn;function Pn(s){const e=Z(s);return new Uint32Array(e)[0]}class J{constructor(e){R(this,"value");this.value=e!=null?T({},e.value):{}}set(e,t){this.value[e]=t}get(e){return this.value[e]}}let Dt=!1;function Q(s){return(...e)=>{Dt&&console.debug(`[${s}] [${(Date.now()/1e3).toFixed(3)}]`,...e)}}function kt(){Dt=!0}function te(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";function Mn(s){s[0]==="?"&&(s=s.slice(1));const e={};return s.split("&").forEach(t=>{const[n,r]=t.split("=");e[decodeURIComponent(n)]=r==null?null:decodeURIComponent(r)}),e}function Fe(s){return Object.keys(s).map(e=>[e,s[e]]).filter(([e,t])=>t!==void 0).map(([e,t])=>t===null?encodeURIComponent(e):[e,t].map(encodeURIComponent).join("=")).join("&")}function In(s,e){const t=new URLSearchParams(e).toString(),n=s.includes("?")?"&":"?";return s+n+t}function je(){const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",e=s.length;let t="";for(let n=0;n<20;n++)t+=s[Math.floor(Math.random()*e)];return t}function On(s,e){const t={};return Object.keys(s).forEach(n=>{t[n]=e(s[n])}),t}class Bt extends Error{constructor(){super(...arguments);R(this,"name","TimeoutError")}}function Pt(s,e){return new Promise((t,n)=>{setTimeout(()=>n(new Bt(e+" timeout")),s)})}function zn(s,e){e.aborted?s.abort(e.reason):e.addEventListener("abort",()=>{s.abort(e.reason)})}const Mt={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:[]};function Nn(s,e,t=["image","media","other"]){s.search="",s.hash="";const n=s.toString();return t.some(r=>{var i;return((i=e[r])!=null?i:[]).some(o=>o.test(n))})}function xe(s){const e=new URL(s);return e.search="",e.hash="",e.toString()}function ae(s){return s instanceof Error?{err_msg:s.name,err_desc:s.message}:{err_msg:"Unknown",err_desc:s+""}}function z(s,e){return s==null||s===-1||e==null||e===-1?-1:(s-e)/1e3}function Hn(s,e=80){const[t,n]=s.split(":"),r=n?parseInt(n,10):e;return[t,r]}function It(s){const e=s.split("/"),t=e[e.length-1],n=t.lastIndexOf(".");return n>=0?t.slice(n+1):""}function Un(s,e){return new URL(s,e).toString()}function _e(s){const[e]=s.split("?");return e.endsWith(".m3u8")}function Ot(s){const[e]=s.split("?");return e.endsWith(".flv")}var ee=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function qn(s){var e=s.default;if(typeof e=="function"){var t=function(){return e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(n){var r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return s[n]}})}),t}var zt={exports:{}};function $n(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Ke={exports:{}};const Wn=qn(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var Nt;function Te(){return Nt||(Nt=1,function(s,e){(function(t,n){s.exports=n()})(ee,function(){var t=t||function(n,r){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&typeof ee!="undefined"&&ee.crypto&&(i=ee.crypto),!i&&typeof $n=="function")try{i=Wn}catch(m){}var o=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(m){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(m){}}throw new Error("Native crypto module could not be used to get secure random number.")},a=Object.create||function(){function m(){}return function(v){var y;return m.prototype=v,y=new m,m.prototype=null,y}}(),c={},h=c.lib={},d=h.Base=function(){return{extend:function(m){var v=a(this);return m&&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(){var m=this.extend();return m.init.apply(m,arguments),m},init:function(){},mixIn:function(m){for(var v in m)m.hasOwnProperty(v)&&(this[v]=m[v]);m.hasOwnProperty("toString")&&(this.toString=m.toString)},clone:function(){return this.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){var v=this.words,y=m.words,S=this.sigBytes,A=m.sigBytes;if(this.clamp(),S%4)for(var M=0;M>>2]>>>24-M%4*8&255;v[S+M>>>2]|=X<<24-(S+M)%4*8}else for(var U=0;U>>2]=y[U>>>2];return this.sigBytes+=A,this},clamp:function(){var m=this.words,v=this.sigBytes;m[v>>>2]&=4294967295<<32-v%4*8,m.length=n.ceil(v/4)},clone:function(){var m=d.clone.call(this);return m.words=this.words.slice(0),m},random:function(m){for(var v=[],y=0;y>>2]>>>24-A%4*8&255;S.push((M>>>4).toString(16)),S.push((M&15).toString(16))}return S.join("")},parse:function(m){for(var v=m.length,y=[],S=0;S>>3]|=parseInt(m.substr(S,2),16)<<24-S%8*4;return new p.init(y,v/2)}},u=l.Latin1={stringify:function(m){for(var v=m.words,y=m.sigBytes,S=[],A=0;A>>2]>>>24-A%4*8&255;S.push(String.fromCharCode(M))}return S.join("")},parse:function(m){for(var v=m.length,y=[],S=0;S>>2]|=(m.charCodeAt(S)&255)<<24-S%4*8;return new p.init(y,v)}},w=l.Utf8={stringify:function(m){try{return decodeURIComponent(escape(u.stringify(m)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(m){return u.parse(unescape(encodeURIComponent(m)))}},g=h.BufferedBlockAlgorithm=d.extend({reset:function(){this._data=new p.init,this._nDataBytes=0},_append:function(m){typeof m=="string"&&(m=w.parse(m)),this._data.concat(m),this._nDataBytes+=m.sigBytes},_process:function(m){var v,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);var K=U*M,V=n.min(K*4,A);if(K){for(var N=0;N>>31}var y=(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(){var d=this._data,p=d.words,l=this._nDataBytes*8,f=d.sigBytes*8;return p[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(){var d=o.clone.call(this);return d._hash=this._hash.clone(),d}});n.SHA1=o._createHelper(h),n.HmacSHA1=o._createHmacHelper(h)}(),t.SHA1})}(Ve)),Ve.exports}var Ge={exports:{}},Ut;function jn(){return Ut||(Ut=1,function(s,e){(function(t,n){s.exports=n(Te())})(ee,function(t){(function(){var n=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=new h.init,typeof d=="string"&&(d=a.parse(d));var p=h.blockSize,l=p*4;d.sigBytes>l&&(d=h.finalize(d)),d.clamp();for(var f=this._oKey=d.clone(),u=this._iKey=d.clone(),w=f.words,g=u.words,x=0;x>>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>>6*(3-m)&63));var v=p.charAt(64);if(v)for(;l.length%4;)l.push(v);return l.join("")},parse:function(c){var h=c.length,d=this._map,p=this._reverseMap;if(!p){p=this._reverseMap=[];for(var l=0;l>>6-f%4*2,g=u|w;p[l>>>2]|=g<<24-l%4*8,l++}return i.create(p,l)}}(),t.enc.Base64})})(qt);const Vn=qt.exports;function Gn(s){let e=s.query?`${s.path}?${s.query} +`:`${s.path} +`;return s.body&&(e+=s.body),e}function Qe(s){let e;try{e=new URL(s.path).pathname}catch(a){e=s.path}let t=Gn(j(T({},s),{path:e}));const i=Kn(t,s.appSalt).toString(Vn).replace(/\+/g,"-").replace(/\//g,"_");let o=`QApp ${s.appID}:${i}`;return o=o.replace(/\//g,"_"),o=o.replace(/\+/g,"-"),o}class Qn{constructor(e){this.logger=e}log(e){return this.logger.log("DnsResolveLog",e)}}function Xn(s){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",t=e.length;let n="";for(let r=0;rnew RegExp(t.pattern).test(e))}function ts(s){return Math.random()indexedDB.deleteDatabase(e)))})}class Wt{constructor(e,t){R(this,"db");this.dbName=e,this.storeConfigs=t}getDB(){return b(this,null,function*(){return this.db!=null?this.db:(this.db=yield new Promise(e=>{const t=indexedDB.open(this.dbName);t.addEventListener("upgradeneeded",()=>{for(const n of this.storeConfigs){const r=t.result.createObjectStore(n.name);for(const i of n.indexes)r.createIndex(i.name,i.keyPath)}}),e(Ae(t))}),this.db)})}get(e,t){return b(this,null,function*(){const r=(yield this.getDB()).transaction(e,"readonly").objectStore(e).get(t);return Ae(r)})}getAll(e){return b(this,null,function*(){const n=(yield this.getDB()).transaction(e,"readonly").objectStore(e).getAll();return Ae(n)})}count(e){return b(this,null,function*(){const n=(yield this.getDB()).transaction(e,"readonly").objectStore(e).count();return Ae(n)})}set(e,t,n){return b(this,null,function*(){const i=(yield this.getDB()).transaction(e,"readwrite");return i.objectStore(e).put(n,t),Ye(i)})}remove(e,t){return b(this,null,function*(){const r=(yield this.getDB()).transaction(e,"readwrite");return r.objectStore(e).delete(t),Ye(r)})}clear(){return b(this,null,function*(){const e=yield this.getDB();yield Promise.all(this.storeConfigs.map(({name:t})=>{const n=e.transaction(t,"readwrite");return n.objectStore(t).clear(),Ye(n)}))})}walkBy(e,t,n){return b(this,null,function*(){const i=(yield this.getDB()).transaction(e,"readonly").objectStore(e).index(t).openCursor(void 0,"next");return new Promise((o,a)=>{i.addEventListener("error",()=>a(new ge(i.error))),i.addEventListener("success",()=>{const c=i.result;if(c==null){o();return}n(c.value,c.primaryKey),c.continue()})})})}dispose(){var e;(e=this.db)==null||e.close()}}class ge extends Error{constructor(t){super(t+"");R(this,"name","IndexedDBError");this.cause=t}}function Ae(s){return new Promise((e,t)=>{s.addEventListener("success",()=>e(s.result)),s.addEventListener("error",()=>t(new ge(s.error)))})}function Ye(s){return new Promise((e,t)=>{s.addEventListener("complete",()=>e()),s.addEventListener("error",()=>t(new ge(s.error))),s.addEventListener("abort",()=>t(new ge(s.error)))})}class ss{constructor(){R(this,"map",new Map)}on(e,t){var i;const r=[...(i=this.map.get(e))!=null?i:[],t];return this.map.set(e,r),()=>this.off(e,t)}once(e,t){const n=this.on(e,r=>{n(),t(r)});return n}off(e,t){var i;const r=((i=this.map.get(e))!=null?i:[]).filter(o=>o!==t);this.map.set(e,r)}emit(...e){var i;const[t,n]=e;((i=this.map.get(t))!=null?i:[]).forEach(o=>{o(n)})}dispose(){this.map.clear()}}function le(s){const e=s.get("Content-Length");return e?parseInt(e,10):null}function Ze(s){const e=s.get("Content-Range");return e==null?null:rs(e)}function rs(s){const e=s.trim().toLowerCase(),[t,n]=e.split(/\s+/);if(t!=="bytes")throw new Error(`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}}function Je(s){const e=s.start!=null&&s.end!=null?`${s.start}-${s.end}`:"*",t=s.totalSize==null?"*":s.totalSize+"";return`bytes ${e}/${t}`}function et(s){return s?Number(s):null}function tt(s){const e=s.get("Range");return e==null?null:jt(e)}function Ft(s){return s.start===0&&s.end==null}function jt(s){const e=s.trim().toLowerCase();if(!e.startsWith("bytes="))throw new Error(`Unit must be bytes: ${s}`);if(e.includes(","))throw new Error(`Multiple range: ${s}`);const[,t,n]=/(\d*)-(\d*)/.exec(e)||[];if(!t&&!n)throw new Error(`Invalid range values: ${s}`);if(!t)throw new Error("Suffix range not supported");const[r,i]=[t,n].map(o=>et(o));return{start:r,end:i}}function be(s){var e,t;return`bytes=${(e=s.start)!=null?e:0}-${(t=s.end)!=null?t:""}`}const is=/[^\u0000-\u00ff]/;function Kt(s){return is.test(s)?"REPLACED_BY_Miku_Delivery_SEE_utils_http_encodeHeaderValue":s}function os(s){if(s instanceof Headers){const e={};s.forEach((t,n)=>{e[n]=Kt(t)}),s=e}if(Array.isArray(s)){const e={};s.forEach(([t,n])=>{e[n]=Kt(t)}),s=e}return new Headers(s)}function nt(s){var t;const e=Ze(s);return e!=null?(t=e.totalSize)!=null?t:null:le(s)}const Vt=Q("utils/stream"),Gt=te("utils/stream");function as(s){return b(this,null,function*(){const e=s.getReader();let t=new Uint8Array;for(;;){const{done:r,value:i}=yield e.read();if(r)break;t=new Uint8Array([...t,...i])}return new TextDecoder().decode(t)})}function st(s,e){var a;const t=s.getReader(),n=(a=e[0])!=null?a:0,r=e[1];let i=0;return new ReadableStream({pull:c=>b(this,null,function*(){let h,d;for(;;){const u=yield t.read();if(u.done){c.close();return}if(h=u.value,d=i+h.byteLength,d>n)break;i=d}let p=h;const l=n>i?n-i:0,f=r!=null&&r=r&&(t.cancel("Cancelled by slice for target range met"),c.close()),i=d}),cancel:c=>t.cancel(c)})}function ls(s){let e=0;const t=new TransformStream({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]}class Qt extends Error{constructor(){super(...arguments);R(this,"name","SaveSlicedPieceError")}}function cs(s,e,t,n){return b(this,null,function*(){const r=[];let i=e,o=[],a=0;function c(){return b(this,null,function*(){const h=i+a;Vt(`saveSlicedPiece [${i}, ${h}]`);try{yield n(new Blob(o),i,h)}catch(d){throw Gt(`saveSlicedPiece [${i}, ${h}] failed`,d),new Qt(`saveSlicedPiece [${i}, ${h}] failed`)}r.push([i,h]),Vt(`saveSlicedPiece [${i}, ${h}] finish`,r),i=h})}try{const h=s.getReader();for(;;){const{value:d,done:p}=yield h.read();if(p)break;o.push(d),a+=d.byteLength,a>=t&&(yield c(),o=[],a=0)}a>0&&(yield c())}catch(h){if(!(h instanceof Qt)&&(Gt("exception occurred while reading stream and save by pieces",h),a>0))try{yield c()}catch(d){}}return r})}function us(s){let e,t=!1;const n=new ReadableStream({start:a=>{e=a},cancel:()=>{t=!0}}),r=s.getReader();let i=!1;return{main:new ReadableStream({pull:a=>b(this,null,function*(){try{const{value:c,done:h}=yield r.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,yield r.cancel(a),e.error(a)})}),minor:n}}var rt={exports:{}};(function(s,e){(function(t,n){var r="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){var E={};for(var O in C)D[O]&&D[O].length%2===0?E[O]=D[O].concat(C[O]):E[O]=C[O];return E},Oe=function(C){for(var D={},E=0;E0?L.length===2?typeof L[1]==a?this[L[0]]=L[1].call(this,Y):this[L[0]]=L[1]:L.length===3?typeof L[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(var E in D)if(typeof D[E]===h&&D[E].length>0){for(var O=0;OX?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;var we=typeof t!==c&&(t.jQuery||t.Zepto);if(we&&!we.ua){var ze=new G;we.ua=ze.getResult(),we.ua.get=function(){return ze.getUA()},we.ua.set=function(C){ze.setUA(C);var D=ze.getResult();for(var E in D)we.ua[E]=D[E]}}})(typeof window=="object"?window:ee)})(rt,rt.exports);const Xt=rt.exports;Xt(navigator.userAgent);let ve;function it(){if(ve!=null)return ve;try{new Response(new ReadableStream),ve=!0}catch(s){ve=!1}return ve}function ot(){return!(typeof TransformStream=="undefined"||!it())}class ce{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=new Headers(n),this.body=i!=null?i:null,this.signal=r!=null?r:new AbortController().signal}}class ne{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}}}function De(s){const{status:e,statusText:t,headers:n,body:r}=s;return new ne(r,{status:e,statusText:t,headers:n,underlayer:s})}class at extends Error{constructor(t){super(`Unexpected HTTP status: ${t.status} ${t.statusText}`);R(this,"name","UnexpectedHttpStatusError");this.response=t}}const hs=new ss;let Yt;typeof self!="undefined"&&(Yt=self,Yt.addEventListener("message",s=>hs.emit("message",s)));class ds extends Error{constructor(){super(...arguments);R(this,"name","WindowClientError")}}class fs extends Error{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannelCloseError")}}class ws extends Error{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannel1stMessageError")}}function lt(s,e=()=>1){if(s.length===0)return null;const t=s.map(e),n=t.reduce((i,o)=>i+o,0);let r=Math.random()*n;for(let i=0;i=0?(i=s.slice(o+1),s=s.slice(0,o)):i="";const a=s.indexOf("/");r=a>=0?s.slice(a):"",r=bs(e.rewrites,r),i=Ss(e.queryString,i);let c=n+r;return i!==""&&(c=c+"?"+i),c}function bs(s,e){for(const t of s){const n=vs(t,e);if(n!=null){e=Rs(t,n);break}}return e}function vs(s,e){return new RegExp(s.pattern).exec(e)}const ys=/\${(\d+)}/g;function Rs(s,e){return s.repl.replace(ys,(t,n)=>{var i;const r=parseInt(n,10);return r>=e.length?t:(i=e[r])!=null?i:""})}function Ss({type:s,values:e},t){if(s==="none")return"";if(s==="all")return t;const n=Mn(t),r=e!=null?e:[],i={};return Object.keys(n).forEach(o=>{s==="include"&&!r.includes(o)||s==="exclude"&&r.includes(o)||(i[o]=n[o])}),Fe(i)}function Jt(s,e){const t=new Map;return function(...r){const i=e(...r),o=t.get(i);if(o!=null)return o;const a=s(...r);return t.set(i,a),a.finally(()=>{t.delete(i)}),a}}const ue=Q("dns"),Le=te("dns"),Cs="miku-delivery/dns/cdn/v1",Es=[];function xs(){return $t(Es)}const ht="result",_s={name:ht,indexes:[{name:"domain",keyPath:"domain"}]};class Ts{constructor(e,t,n=Jn,r,i=2e3,o=5e3){R(this,"fingerprints",new Map);R(this,"disabledElts",new Map);R(this,"storage",new Wt(Cs,[_s]));R(this,"getResolveResultFromStorage",Jt(e=>this.storage.get(ht,e),e=>e));R(this,"refreshResolveResultInStorage",Jt((e,t)=>b(this,null,function*(){const n=yield this.dnsResolver(e,t,this.app,this.logger),r=Date.now()+n.ttl*1e3,i=j(T({},n),{domain:t,expireAt:r});return this.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){const t=this.fingerprints.get(e);if(t==null)throw new Error(`No fingerprint for ${e}`);return t}isEltDisabled(e){const t=this.disabledElts.get(e);return t==null?!1:t.after>Date.now()}setEltDisabled(e){const t=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){return b(this,null,function*(){if(this.cacheKeyFn!=null)return this.cacheKeyFn(e);const n=yield this.resolveDomain(new J,t);return Xe(n)?gs(e,n.cacheKey,n.bucket):e})}getMediaOptimization(e){return b(this,null,function*(){const t=yield this.resolveDomain(new J,e);return Xe(t)?t.mediaOptimization:null})}saveResolveResultToStorage(e,t){return b(this,null,function*(){return this.storage.set(ht,e,t)})}resolveDomain(e,t){return b(this,null,function*(){const n=Date.now(),r=(()=>b(this,null,function*(){const i=yield this.getResolveResultFromStorage(t);return i==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));return Promise.race([r,Pt(this.resolveTimeout,"Resolve domain")]).catch(i=>{throw Le("DNS resolve failed:",i),new ct(i)})})}resolve(e,t){return b(this,null,function*(){let n=null;return yield this.do(e,t,1,r=>{n=r}),n})}do(e,t,n,r){return b(this,null,function*(){let i;ue("Resolve for",t);const o=new URL(t).hostname,[a,c]=yield Promise.all([this.getCacheKey(t,o),this.resolveDomain(e,o)]);if(!Xe(c))throw new re(`Non-ECDN resolve result: ${o}`);const{groups:h,rules:d}=c;if(h.length===0)throw new Zt(`No available group for ${o}`);ue("Resolved for",t);const p=es(d,a);if(p==null)throw new re("No matched rule found");if(!ts(p))throw new re("Do not serve with given rule");let l=p.groups.map(({groupidx:f,weight:u,splitn:w})=>{const g=h[f];if(g==null)throw new Error(`Unexpected groupidx: ${f}`);return{group:g,weight:u,splitn:w}});for(let f=0;fw.weight);if(u==null)break;try{ue("doWithGroup",f,a),yield this.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))}}throw i=se(i)?i:new ut(i),i})}doWithGroup(e,t,n,r,i){return b(this,null,function*(){const o=t.elts.filter(l=>!this.isEltDisabled(l.id));if(o.length===0)throw new Error("No available elt");const a=As(t),c=new Set(o.map(l=>l.id)),h=r===1?2:r;let d=a.getN(n,h,c).map(l=>o.find(f=>f.id===l)),p;for(let l=0;l<2;l++){const f=lt(d.slice(0,r),u=>u.replicas);if(f==null)break;try{ue("doWithElt",f.id,n),e.set("downloadEltID",f.id),yield Ds(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))}}throw p})}}const en=new Map;function As({elts:s}){const e=s.map(({id:r,replicas:i})=>`${r}:${i}`).join(","),t=en.get(e);if(t!=null)return t;const n=new me;return n.set(s.map(r=>({key:r.id,replicas:r.replicas}))),en.set(e,n),n}function Ds(s,e,t){return b(this,null,function*(){let n=s.addrs;if(n.length===0)throw new Error("Empty addr list");let r;for(let i=0;i<2;i++){const o=lt(n);if(o==null)break;try{ue("do job with",o,e),yield t(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))}}throw r})}function ks(s){return s.expireAt{const r={key:n,usedTime:t.usedTime,size:dt(t)},i=this.itemList.pushBack(r);this.itemElementMap.set(n,i),e.push(...Ws(t,n))});try{const t=yield this.dc.getBrowserCacheKeys();for(let n of t)e.includes(n)||(Be("clear inaccessible cache:",n),yield this.dc.browserCacheDelete(n))}catch(t){Bs("failed to clear inaccessible caches:",t)}})}addItem(e,t){const n={key:e,usedTime:t.usedTime,size:dt(t)};let r=null;return this.itemList.reverseWalk((i,o)=>{if(i.usedTime<=t.usedTime)return r=this.itemList.insertAfter(n,o),!1}),r==null&&(r=this.itemList.pushFront(n)),this.itemElementMap.set(e,r),r}removeItem(e){const t=this.itemElementMap.get(e);t!=null&&(this.itemElementMap.delete(e),this.itemList.remove(t))}onItemSet(e,t){return b(this,null,function*(){yield this.inited;let n=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(){return b(this,null,function*(){if(typeof navigator.storage.estimate=="undefined")return null;const{quota:e,usage:t}=yield navigator.storage.estimate();return e!=null&&t!=null?e-t:null})}freeUpSpace(e){return b(this,null,function*(){yield this.inited;let t=0;const n=[];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),yield Promise.all(n.map(r=>b(this,null,function*(){yield this.dc.removeItemWithContent(r),this.removeItem(r)})))})}beforeContentSet(e,t,n){return b(this,null,function*(){if(n==null)return;yield this.inited;const r=yield this.getLeftSpace(),i=this.config.reservedQuota;if(r!=null&&r-i{var n,r;return e+Is(t,(r=(n=s.meta)==null?void 0:n.fsize)!=null?r:null)},0)}const Os=Q("dc"),zs="miku-delivery/dc/v1",tn=["miku/dc","miku/dc/v2","miku/dc/v3"];function Ns(){return Promise.all([Hs(tn),$t(tn)])}function Hs(s){return b(this,null,function*(){const t=(yield caches.keys()).filter(n=>s.includes(n));yield Promise.all(t.map(n=>caches.delete(n)))})}const ye="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=new Wt(this.ns,[Us]),this.cr=new Ms(this)}openBrowserCache(){return b(this,null,function*(){return this.browserCachePromise!=null?this.browserCachePromise:(this.browserCachePromise=caches.open(this.ns).catch(e=>{throw new he(e)}),this.browserCachePromise.then(e=>{this.browserCache=e}),this.browserCachePromise)})}getItem(e){return b(this,null,function*(){return this.db.get(ye,e)})}setItem(e,t){return b(this,null,function*(){Os("setItem",e,t),yield this.db.set(ye,e,t),yield this.cr.onItemSet(e,t)})}walkItems(e){return b(this,null,function*(){return this.db.walkBy(ye,nn,e)})}removeItemWithContent(e){return b(this,null,function*(){const t=yield this.getItem(e);t!=null&&(yield Promise.all(t.pieces.map(n=>this.removeContent(e,n))),yield this.db.remove(ye,e))})}browserCacheMatch(e){return b(this,null,function*(){let t=this.browserCache;return t==null&&(t=yield this.openBrowserCache()),t.match(e).catch(n=>{throw new he(n)})})}browserCachePut(e,t){return b(this,null,function*(){let n=this.browserCache;n==null&&(n=yield this.openBrowserCache()),yield n.put(e,t).catch(r=>{throw new he(r)})})}browserCacheDelete(e){return b(this,null,function*(){let t=this.browserCache;t==null&&(t=yield this.openBrowserCache()),yield t.delete(e).catch(n=>{throw new he(n)})})}getBrowserCacheKeys(){return b(this,null,function*(){let e=this.browserCache;return e==null&&(e=yield this.openBrowserCache()),yield e.keys().then(t=>t.map(n=>n.url))})}getContent(e,t){return b(this,null,function*(){const n=yield this.browserCacheMatch(Pe(e,t));if(n!=null){if(n.body==null)throw new Error("Body expected for cached response");return De(n)}})}setContent(e,t,n){return b(this,null,function*(){if(!it())return yield this.cacheResponse(e,t,n.underlayer),[t];const{headers:r,body:i}=n,o=nt(r);return yield cs(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+"");const d=new Response(a,{status:200,statusText:"OK",headers:r});yield this.cacheResponse(e,[c,h],d)}))})}cacheResponse(e,t,n){return b(this,null,function*(){const r=Pe(e,t),i=le(n.headers);yield this.cr.beforeContentSet(e,t,i);try{yield this.browserCachePut(r,n)}catch(o){throw o instanceof he&&o.cause instanceof Error&&o.cause.name==="QuotaExceededError"&&this.cr.onQuotaExceeded(e,t,i),o}})}removeContent(e,t){return b(this,null,function*(){const n=Pe(e,t);return this.browserCacheDelete(n)})}dispose(){this.db.dispose()}}function Pe(s,e){var t;return/^https?:\/\//.test(s)||(s="https://miku-cache.com/"+s),`${s}_with_range_${e[0]}_${(t=e[1])!=null?t:""}`}function Ws(s,e){return s.pieces.map(t=>Pe(e,t))}class he extends Error{constructor(t){super(t+"");R(this,"name","BrowserCacheError");this.cause=t}}class Fs{constructor(e){this.logger=e}log(e){return this.logger.log("DoLog",e)}}const sn="1.1.0",js=3,rn=Q("http");class on{constructor(e,t,n,r=0){R(this,"doLogger");this.client=t,this.resolver=n,this.clientResponseTimeout=r,this.doLogger=new Fs(e)}doWithResolved(e,t,n){return b(this,null,function*(){rn("fetch",t.url,"with resolved",n);const r=new AbortController;zn(r,t.signal);const i=new ce(t.url,j(T({},t),{signal:r.signal}));i.headers.set("X-Miku-Agent",`miku-delivery-web/v${sn}`);let o=this.client.fetch(e,i,n);this.clientResponseTimeout>0&&(o=Promise.race([o,Pt(this.clientResponseTimeout,"HTTPClient get response")]),o.catch(c=>{c instanceof Bt&&r.abort(c)}));const a=yield o;if(rn("fetch",t.url,"succeeded with status",a.status),a.status===429||a.status>=500)throw new at(a);return a})}originalDo(e,t){return b(this,null,function*(){if(t.signal.aborted)throw t.signal.reason;let n=-1,r;if(yield this.resolver.do(e,t.url,js,i=>b(this,null,function*(){const o=new J(e);n++,o.set("downloadRetryCount",n),r=yield this.doWithResolved(o,t,i)})),r==null)throw new Error(`Http do failed: resolver do finished with no finalResp, url: ${t.url}`);return r})}do(e,t){return b(this,null,function*(){const n=Date.now(),r=je();e.set("doID",r);let i,o=null;try{return i=yield this.originalDo(e,t),i}catch(a){throw o=a,a}finally{const{onDoError:a,onDoResponsed:c}=this.getDoLog(e,r,n);i==null?a(o):c(i.status)}})}getDoLog(e,t,n){const r=a=>{var c;return this.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=>{const c=Date.now();r(T({t_total:z(c,n)},ae(a)))},onDoResponsed:a=>{const c=Date.now();r({t_total:z(c,n),status_code:a})}}}}class Ks{constructor(e){this.logger=e}log(e){return this.logger.log("TaskLog",e)}}class an{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=new Ks(n)}setPriority(e){this.priority=e}start(e){return b(this,null,function*(){if(this.started)throw new Error("Task already started");if(this.started=!0,this.signal=e,e&&e.aborted)throw e.reason;const t=Date.now(),n=new J;n.set("taskID",this.id),n.set("taskDomain",new URL(this.url).hostname);let r,i=null;try{return r=yield this.startByClient(n,this),r}catch(o){throw i=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){const n=e.get("taskCacheMatchAt"),r=e.get("task1stHttpDoAt"),i=e.get("taskResultStreamAt"),o=Date.now(),a=d=>{var p,l,f,u,w;return this.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?void 0:l.start)!=null?f:-1,range_end:(w=(u=this.range)==null?void 0: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=>{const p=Date.now();a(T({t_total:z(p,t)},ae(d)))},logOnTransferred:()=>{const d=Date.now();a({t_trans:z(d,o),t_total:z(d,t)})}}}}class ln{constructor(e,t,n,r,i){this.stream=e,this.size=t,this.fileSize=n,this.contentType=r,this.underlayer=i}blob(){return b(this,null,function*(){const e=this.stream.getReader(),t=[];for(;;){const{done:n,value:r}=yield e.read();if(n)break;const i=r;t.push(i)}return new Blob(t)})}}function ft(s,e,t){return s!=null&&t!=null&&t>=s&&(t=null),(e==null||e<0)&&(e=0),[e,t]}function cn(s,e){var r;const t=((r=e[0])!=null?r:0)===0,n=e[1]==null||s!=null&&e[1]===s;return t&&n}function Vs(s,e){var r,i;const t=(r=e[0])!=null?r:0,n=(i=e[1])!=null?i:s;return n==null?null:n-t}function Gs(s,e,t){var c,h;if(e===0)return[];const n=(d,p)=>hn(d,p,e!=null?e:Number.POSITIVE_INFINITY),r=(c=s==null?void 0:s[0])!=null?c:0,i=(h=s==null?void 0:s[1])!=null?h:e,o=[];let a=r;for(const d of t){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])});const p=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}}return n(i,a)&&o.push({cached:!1,range:ft(e,a,i)}),o}function Qs(s,e){var r;const t=(r=e[0])!=null?r:0,n=e[1];for(const i of s){if(i[1]!=null&&i[1]<=t)continue;if(i[0]>t)break;const o=t-i[0],a=Ys(n!=null?n:i[1],i[0]);return{piece:i,start:o,end:a}}throw new Error("Piece not found")}function Xs(s,e){const t=s.filter(o=>!e.some(a=>o[0]===a[0]&&o[1]===a[1])),n=[e[0][0],e[e.length-1][1]];for(let o of t)if(un(o,n))return{toSave:t,toRemove:e};const r=[],i=[];for(let o of t)un(n,o)?i.push(o):r.push(o);return{toSave:[...r,...e].sort((o,a)=>o[0]-a[0]),toRemove:i}}function un(s,e){return s[0]<=e[0]&&!hn(e[1],s[1],Number.POSITIVE_INFINITY)}function hn(s,e,t){const n=s!=null?s:t,r=e!=null?e:t;return n>r}function Ys(s,e){return s==null||e==null?null:s-e}function dn(s){const e={},t=s.split(",").map(n=>{let[r,i]=n.split("=").map(o=>o.trim());return[r.toLowerCase(),i]});for(const[n,r]of t)if(n==="max-age"){if(r!=null){const i=parseInt(r,10);Number.isNaN(i)||(e["max-age"]=i)}}else(n==="no-cache"||n==="no-store")&&(e[n]=!0);return e}function Me(s){return Math.floor(s/1e3)}function fn(s,e){const t=s.get("Date");if(t==null)return e;const n=Date.parse(t);return Number.isNaN(n)?e:n}function Zs(s,e,t){if(s!=null)return s;const n=e.get("Expires");if(n!=null){let r=Date.parse(n);Number.isNaN(r)&&(r=0);const i=fn(e,t);return Me(r-i)}return 3600}function Js(s){const e=s.get("Age");if(e==null)return 0;const t=parseInt(e,10);return Number.isNaN(t)?0:t}function er(s,e,t,n){const r=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);return h+d}function tr(s,e,t,n,r){var c;const i=(c=s==null?void 0:s["max-age"])!=null?c:null,o=Zs(i,e,n),a=er(e,t,n,r);return o>a}function nr(s,e,t,n){const r=s.get("Cache-Control"),i=r!=null?dn(r):null;return(i==null?void 0:i["no-cache"])===!0?!0:!tr(i,s,e,t,n)}function sr(s){const e=s.get("Cache-Control"),t=e!=null?dn(e):null;return!(t!=null&&t["no-store"]===!0)}function rr(s){const e=s.get("ETag");return e==null?null:e.startsWith("W/")?e.slice(2):e}function ir(s,e){const t=new Headers(s),n=rr(e);n!=null&&t.set("If-None-Match",n);const r=e.get("Last-Modified");return r!=null&&t.set("If-Modified-Since",r),t}function or(s,e){return!(s.get("Last-Modified")===e.get("Last-Modified")&&s.get("ETag")===e.get("ETag"))}function ar(s,e){const t=new Headers(s);return e.forEach((n,r)=>{r=r.toLowerCase(),!(r==="content-length"||r==="content-encoding"||r==="content-range")&&t.set(r,n)}),t}const lr={threshold:0,contentRangeExposed:!0},P=Q("ftask"),de=te("ftask");class cr{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(){var e,t;return(t=(e=this.meta)==null?void 0:e.fsize)!=null?t:null}cacheValidationRequired(){if(this.meta==null)return!1;const{requestTime:e,responseTime:t,headers:n}=this.meta;return e==null||t==null||n==null?!1:nr(n,e,t,Date.now())}isMedia(e){const t=xe(e.url);return this.patterns.media.some(n=>n.test(t))}isRangeStartFirstRequested(e){var n;const t=(n=e[0])!=null?n:0;return!this.cachePieces.some(r=>{var i;return r[0]<=t&&t<=((i=r[1])!=null?i:Number.POSITIVE_INFINITY)})}startTask(e,t){return b(this,null,function*(){P("startTask",t.url,t.id,t.range);let n;const r=t.range!=null?[t.range.start,t.range.end]:[0,null];yield this.inited,this.usedTime=Date.now(),this.save().catch(a=>de("save failed when startTask:",a)),ot()?n=yield this.readRangeWithStream(e,t,r):(P("supportStreamOperation: false",t.url,t.id),n=yield this.readRangeWithoutStream(e,t,r));const i=this.meta;if(i==null)throw new Error("Missing meta in fileTask");P("startTask resolved",t.url,t.id);const o=Vs(i.fsize,r);return new ln(n.body,o,i.fsize,i.headers.get("Content-Type"),n)})}readRangeWithoutStream(e,t,n){return b(this,null,function*(){var a,c;let r;const i=[(a=n[0])!=null?a:0,n[1]],o=(c=yield this.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;else if(P("doRequestAndSaveCache",t.url,t.id,o!=null),r=yield this.doRequestAndSaveCache(e,t,n,o!=null,!1),r.status===304){if(o==null)throw new Error("Unexpected 304 with no cached response");r=o}return e.set("taskResultStreamAt",Date.now()),r})}readRangeWithStream(e,t,n){return b(this,null,function*(){const r=this.isMedia(t),i=this.cacheValidationRequired();P("cacheValidationRequired",i);const o=Gs(n,this.fileSize(),this.cachePieces);if(P("applyRange",n,this.fileSize(),this.cachePieces,o),i){const h=o.some(l=>l.cached),d=r?yield this.getMediaOptimization():!1,p=yield this.doRequestAndSaveCache(e,t,n,h,d);if(p.status===200||p.status===206)return p}e.set("taskCacheMatchAt",Date.now());const a=new TransformStream(void 0),c=yield new Promise((h,d)=>b(this,null,function*(){try{for(let p=0;pthis.http.do(...w),(...w)=>this.nativeHttpClient.fetch(...w),i)(o,h);const l=Date.now();if(p.body==null)throw new Error("Body expected");let f=p.headers;if(r&&c!=null&&p.status===304)P(`updateStoredHeaders for ${this.url}`),f=ar(c,p.headers);else if(p.status!==200&&p.status!==206)throw new at(p);return yield this.onResponse(f,d,l),p.bodyReadResult.then(w=>{P(`bodyReadResult for ${this.url}:`,w)}),p})}doRequestAndSaveCache(e,t,n,r,i){return b(this,null,function*(){const o=yield this.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){return b(this,null,function*(){var o,a;let r=n,i;if(ot()){const{main:c,minor:h}=us(n.body);r=new ne(c,n),i=new ne(h,n)}else if(!e.range){const c=n.underlayer.clone();i=De(c)}if(i!=null){const c=[(o=t==null?void 0:t[0])!=null?o:0,(a=t==null?void 0: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{yield Promise.all(p.map(l=>this.cache.removeContent(this.key,l)))}catch(l){P("exception occurred while removing duplicated cache pieces",l)}}return this.save()})).then(()=>P("saveCachePiece finish",this.url,c,this.cachePieces),h=>de("saveCachePiece failed",this.url,c,h))}return r})}onResponse(e,t,n){return b(this,null,function*(){const r=this.meta;this.meta={fsize:nt(e),requestTime:t,responseTime:n,headers:e},(r==null?void 0:r.headers)!=null&&or(r.headers,e)&&(P(`${this.url} modified, clear local cache`),yield Promise.all(this.cachePieces.map(i=>this.cache.removeContent(this.key,i))),this.cachePieces=[]),this.save().catch(i=>de("save failed when onResponse:",i))})}resume(){return b(this,null,function*(){const e=yield this.cache.getItem(this.key);e==null||e.meta==null||(this.meta=j(T({},e.meta),{headers:e.meta.headers!=null?new Headers(e.meta.headers):null}),this.cachePieces=e.pieces)})}save(){return b(this,null,function*(){var r,i;const e=((r=this.meta)==null?void 0:r.headers)!=null?[...((i=this.meta)==null?void 0:i.headers).entries()]:null,n={meta:this.meta!=null?j(T({},this.meta),{headers:e}):null,pieces:this.cachePieces,usedTime:this.usedTime};yield this.cache.setItem(this.key,n)})}}function ur(s,e,{threshold:t,contentRangeExposed:n}){return function(i,o){return b(this,null,function*(){var X,U;const M=o,{url:a}=M,c=Tt(M,["url"]),h=tt(o.headers);P("doWithInitialOptimization",a);const d=new J(i),p=new Headers(c.headers),l=T({start:null,end:null},h);l.start=(X=l.start)!=null?X:0;const f=l.start+t-1;(l.end==null||l.end>f)&&(l.end=f),p.set("Range",be(l));const u=new ce(a,j(T({},c),{headers:p})),g=yield((K,V)=>b(this,null,function*(){var ie;let N=null;const $=tt(V.headers);$!=null&&!Ft($)&&!n&&(N=hr(a,c.headers,e));const W=yield e(K,V);if($!=null&&W.status===206&&!W.headers.get("Content-Range")){const F=Ft($)?le(W.headers):yield N;if(F!=null){const H=Je({start:$.start,end:(ie=$.end)!=null?ie:F-1,totalSize:F});W.headers.set("Content-Range",H)}}return W}))(d,u);if(g.body==null)throw new Error("Body expected for initial response");if(g.status!==206)return g;const x=Ze(g.headers);if(x==null)throw new Error("Header Content-Range expected for 206 response");const m=(()=>{var ie;const K=le(g.headers);if(K!=null&&Kb(this,null,function*(){P("doWithInitialOptimization initialBody transfered");let F;try{const H=yield s(i,$);if(H.body==null)throw new Error(`Body expected for following response of ${a}`);if(H.status===200)F=st(H.body,[N.start,N.end==null?null:N.end+1]);else if(H.status===206)F=H.body;else throw new at(H)}catch(H){if(dr(H))P("use fallback fetch for doWithInitialOptimization followingBody",H),F=(yield e(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=new Headers(g.headers);if(y.delete("Content-Range"),y.delete("Content-Length"),h==null)return v!=null&&y.set("Content-Length",v+""),new ne(m,{status:200,statusText:"OK",headers:y,underlayer:g.underlayer});const S=(U=h.start)!=null?U:0,A=h.end!=null?h.end:v!=null?v-1:null;return A!=null&&y.set("Content-Length",A-S+1+""),y.set("Content-Range",Je({start:S,end:A,totalSize:v})),new ne(m,{status:206,statusText:"Partial Content",headers:y,underlayer:g.underlayer})})}}function hr(s,e,t){return b(this,null,function*(){const n=new Headers(e);n.delete("Range");const r=yield t(new J,new ce(s,{method:"HEAD",headers:n}));return le(r.headers)})}function dr(s){return[ct,re,Zt,ut,ge,he].some(e=>s instanceof e)}class fr{constructor(){R(this,"locked",!1);R(this,"waitings",[]);this.unlock=this.unlock.bind(this)}lock(){return b(this,null,function*(){return this.locked?(yield new Promise(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){return b(this,null,function*(){const t=yield this.lock();try{return yield e()}catch(n){throw n}finally{t()}})}}function wr(){var r,i;const{os:s,device:e,browser:t}=Xt(navigator.userAgent);let n;return typeof window!="undefined"?n=window.location:typeof self!==void 0&&(n=self.location),{os:`${s.name}_${s.version}`,browser:`${t.name}_${t.version}`,app:(r=n==null?void 0:n.host)!=null?r:"",sdk:`Web SDK v${sn}`,dev_model:(i=e.model)!=null?i:"",dev_id:""}}const wt=200,pt=Q("log"),pr=te("log");class mr{constructor(e,t,n,r,i){R(this,"env",Fe(wr()));R(this,"flushMutex",new fr);R(this,"buffer",[]);this.schemaName=e,this.fetch=t,this.flushNum=n,this.flushWait=r,this.app=i}callApiLog(e){return b(this,null,function*(){const t=this.fetch;try{const n=Qe({appID:this.app.appID,appSalt:this.app.appSalt,path:`${Lt}/v1/log/${this.schemaName}`}),r=yield t(new Request(`${Lt}/v1/log/${this.schemaName}`,{method:"POST",headers:{Authorization:n,"Content-Type":"text/csv","X-Env":this.env},body:br(e)}));if(!r.ok)throw new Error(`Unexpected response status: ${r.status} ${r.statusText}`)}catch(n){pr("Call log API failed:",n)}})}flush(){return b(this,null,function*(){return this.flushMutex.runExclusive(()=>b(this,null,function*(){const e=this.buffer.splice(0);if(e.length===0)return;const t=Math.ceil(e.length/wt);return Promise.all(Array.from({length:t}).map((n,r)=>this.callApiLog(e.slice(r*wt,(r+1)*wt))))}))})}tryFlush(){return b(this,null,function*(){const e=yield this.flushMutex.runExclusive(()=>{const t=this.buffer;if(t.length===0)return!1;if(t.length>=this.flushNum)return pt("buffer.length >= this.flushNum"),!0;const n=Date.now()-t[0].ts;return n>=this.flushWait*1e3?(pt("waited >= this.flushWait"),!0):this.flushWait*1e3-n});if(e===!0)return this.flush();typeof e=="number"&&setTimeout(()=>this.tryFlush(),e)})}log(e){this.buffer.push(T({ts:Date.now()},e)),this.tryFlush()}}class gr{constructor(e,t=self.fetch,n=100,r=3){R(this,"schemaLoggers",new Map);this.appInfo=e,this.fetch=t,this.flushNum=n,this.flushWait=r}log(e,t){pt("log",e,t);let n=this.schemaLoggers.get(e);n==null&&(n=new mr(e,this.fetch,this.flushNum,this.flushWait,this.appInfo),this.schemaLoggers.set(e,n)),n.log(t)}}function br(s){const e=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(` +`)}function wn(s){let e=s.replace(/"/g,'""');return/("|,|\n)/.test(e)&&(e='"'+e+'"'),e}class vr{constructor(e){this.logger=e}log(e){return this.logger.log("LiveScheduleLog",e)}}const yr=new URL(We).hostname;function Rr(s,e,t,n){return b(this,null,function*(){var l,f;const r=new vr(n),i={url:e,cip:""},o=Qe(j(T({},t),{path:We})),a=Date.now();let c,h=null,d=null,p=null;try{if(h=yield fetch(We,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json",Authorization:o}}),d=Date.now(),!h.ok)throw new Error(`Call Schedule API failed, status: ${h.status} ${h.statusText}`);return p=yield h.json()}catch(u){throw c=u}finally{const u=z(Date.now(),a),w=p==null?ae(c):{err_msg:"",err_desc:""};r.log(j(T({r_id:(l=h==null?void 0:h.headers.get("x-reqid"))!=null?l:"",ip:"",domain:yr,status_code:(f=h==null?void 0:h.status)!=null?f:-1},w),{t_conn:z(d,a),t_total:u,type:1}))}})}const Re=Q("dns"),mt=te("dns"),Sr=60,Cr=60*1e3;class Er{constructor(e,t,n=Rr,r=xe){R(this,"scheduling",new Map);R(this,"cache",new Map);R(this,"m3u8SegmentCache",new Map);this.logger=e,this.app=t,this.scheduler=n,this.cacheUrl=r}getScheduleResult(e,t){return b(this,null,function*(){var o;const n=Date.now();let r;try{r=yield this.scheduler(e,t,this.app,this.logger)}catch(a){throw mt("Live schedule failed:",a),new ct(a)}finally{e.set("dnsResolveTotalTime",z(Date.now(),n))}if(r.code===1)throw new re(`Local DNS for ${t}`);if(r.code!==0)throw new Error(`Unexpected schedule code: ${r.code}`);const i=(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){return b(this,null,function*(){const n=this.cacheUrl(e),r=this.cache.get(n);if(r==null){mt("No schedule result for m3u8:",e);return}const i=t.map(this.cacheUrl);i.forEach(o=>{this.m3u8SegmentCache.set(o,r)}),setTimeout(()=>{i.forEach(o=>{this.m3u8SegmentCache.delete(o)})},6e4)})}schedule(e,t){return b(this,null,function*(){const n=this.cacheUrl(t);if(!_e(t)&&!Ot(t)){const a=this.m3u8SegmentCache.get(n);if(a==null)throw new re("Neither m3u8 / flv URL, or m3u8 segment URL");return a}const r=this.cache.get(n);if(r!=null&>(r))return e.set("dnsResolveFromCache",!0),r;const i=this.scheduling.get(n);if(i!=null){let a;try{a=yield i}catch(c){if(c instanceof re)throw c}if(a!=null&>(a))return e.set("dnsResolveFromCache",!0),a;this.scheduling.delete(n)}const o=this.getScheduleResult(e,t);return Re("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){const t=this.cacheUrl(e),n=_e(e)||Ot(e)?this.cache.get(t):this.m3u8SegmentCache.get(t);return n!=null&>(n)}do(e,t,n,r){return b(this,null,function*(){let i;Re("schedule for",t);const o=yield this.schedule(e,t);Re("scheduled for",t);for(let a=0;apn(t,e))}const fe=Q("utils/fetch");function mn(s){return b(this,null,function*(){var f,u;const e=yield fetch(s),t=tt(s.headers);if(t==null||e.status!==206||e.body==null)return e;const{body:n,status:r,statusText:i,headers:o}=e,a=(f=Ze(o))==null?void 0:f.end,c=100;let h=(u=t.start)!=null?u:0,d=n.getReader(),p=null;const l=new ReadableStream({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=(yield fetch(s)).body.getReader());const{value:g,done:x}=yield d.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)}});return new Response(l,{status:r,statusText:i,headers:o})})}class gn{constructor(e){this.logger=e}start(e,t){let n;const r=Date.now(),i=c=>{var f,u,w,g,x,m,v,y,S,A,M;const h=t.headers.get("Range"),d=h==null?null:jt(h),p=n==null?void 0: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?void 0:d.start)!=null?w:-1,range_end:(g=d==null?void 0: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?void 0: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=>{const h=Date.now();i(T({t_total:z(h,r)},ae(c)))},onResponse:c=>{n=c,n.bodyReadResult.then(h=>{var l;const d=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){return b(this,null,function*(){const r=this.start(e,t);try{const i=yield n();return r.onResponse(i),i}catch(i){throw r.onError(i),i}})}log(e){return this.logger.log("DownloadLog",e)}}class _r{constructor(e){R(this,"downloadLogger");this.downloadLogger=new gn(e)}fetch(e,t,n=!0){return b(this,null,function*(){return this.downloadLogger.wrap(e,t,()=>b(this,null,function*(){const h=t,{url:r}=h,i=Tt(h,["url"]),o=new Request(r,T(T({},n?bn:null),i)),a=yield mn(o),c=Date.now();return e.set("downloadConnectionAt",c),e.set("downloadStartTransferAt",c),De(a)}))})}}const bn={mode:"cors",credentials:"omit"};class vn{constructor(e,t=!0,n=mn){R(this,"downloadLogger");this.https=t,this.nativeFetch=n,this.downloadLogger=new gn(e)}fetch(e,t,n){return b(this,null,function*(){return this.downloadLogger.wrap(e,t,()=>b(this,null,function*(){e.set("downloadReqIP",n.host);const r=this.nativeFetch,i=Tr(t,n,this.https),o=yield r(i),a=Date.now();return e.set("downloadConnectionAt",a),e.set("downloadStartTransferAt",a),De(o)}))})}dispose(){}}function Tr(s,e,t=!0){const{url:n,headers:r,method:i,signal:o}=s,a=new URL(n),c=a.host,h=new Headers(r);a.protocol=t?"https:":"http:",a.host=`${e.host}:${t?e.https:e.http}`,a.pathname=`/${c}${a.pathname}`;let d=a.toString();if(h.has("X-Miku-Agent")){const p=h.get("X-Miku-Agent");h.delete("X-Miku-Agent");const l=d.includes("?")?"&":"?",f=["X-Miku-Agent",p].map(encodeURIComponent).join("=");d=d+l+f}return new Request(d,j(T({},bn),{headers:h,method:i,signal:o}))}function Ar(s){const e=[],t=s.split(` +`).map(r=>r.trim()).filter(r=>r.length>0);if(t[0]!=="#EXTM3U")throw new Error("Invalid Extended M3U Playlist");let n=null;for(const r of t){if(r.startsWith("#")){r.startsWith("#EXTINF:")&&(n=r);continue}n!=null&&(e.push({uri:r}),n=null)}return e}const yn=Q("client"),bt=te("client");class Dr{constructor(e,t){R(this,"fileTasks",new Map);R(this,"cache");R(this,"cdnResolver");R(this,"liveResolver");R(this,"nativeHttpClient");R(this,"http");R(this,"liveHttp");R(this,"patterns");R(this,"logger");var o,a,c,h,d;this.config=t,t!=null&&t.debug&&kt(),this.cache=new $s(t==null?void 0:t.cache),this.logger=(o=t==null?void 0:t.logger)!=null?o:new gr(e),this.cdnResolver=(a=t==null?void 0:t.resolver)!=null?a:new Ts(this.logger,e,t==null?void 0:t.dnsResolver,t==null?void 0:t.cacheUrl),this.liveResolver=(c=t==null?void 0:t.liveResolver)!=null?c:new Er(this.logger,e,t==null?void 0:t.scheduler),this.nativeHttpClient=new _r(this.logger);const n=(h=t==null?void 0:t.httpClient)!=null?h:new vn(this.logger),r=(d=t==null?void 0:t.liveHttpClient)!=null?d:new vn(this.logger);this.patterns=T(T({},Mt),t==null?void 0:t.patterns),this.http=new on(this.logger,n,this.cdnResolver,6e3);const i=2e3;this.liveHttp=new on(this.logger,r,this.liveResolver,i)}prepare(e){return b(this,null,function*(){return Promise.all(e.map(t=>this.cdnResolver.resolveDomain(new J,t))).catch(t=>{bt("prepare failed:",t)})})}createTask(e,t){const n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),new an(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",1),this.startTask(r,i)))}createLiveTask(e,t){const n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),new an(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",2),this.startLiveTask(r,i)))}startTask(e,t){return b(this,null,function*(){const n=new URL(t.url).hostname,r=yield this.cdnResolver.getCacheKey(t.url,n);let i=this.fileTasks.get(r);if(i==null){const o=()=>b(this,null,function*(){var c;const a=yield this.cdnResolver.getMediaOptimization(n);return T(T(T({},lr),a),(c=this.config)==null?void 0:c.mediaOptimization)});i=new cr(this.cache,this.nativeHttpClient,this.http,r,t.url,this.patterns,o),this.fileTasks.set(r,i)}return i.startTask(e,t)})}saveM3u8SegmentResult(e,t){return b(this,null,function*(){const n=yield as(t),i=Ar(n).map(o=>Un(o.uri,e));yn("saveM3u8SegmentResult",xe(e),i.map(xe)),yield this.liveResolver.saveM3u8SegmentResult(e,i)})}startLiveTask(e,t){return b(this,null,function*(){var h,d;const n={};t.range!=null&&(n.Range=be({start:t.range.start,end:t.range.end==null?null:t.range.end-1}));const r=new ce(t.url,{method:"GET",headers:n,signal:t.signal});let i,a=((d=(h=this.config)==null?void 0:h.liveOptimization)!=null?d:!0)&&_e(t.url)&&!this.liveResolver.hasResult(t.url);if(a){yn("use nativeClient for",t.url);const p=this.nativeHttpClient.fetch(e,r);this.liveHttp.do(new J(e),r).catch(l=>{bt("do failed when prefetch for liveOptimization:",l)}),i=yield p}else i=yield this.liveHttp.do(e,r);if(i.body==null)throw new Error("Body expected");if(i.status!==200&&i.status!==206)throw new Error(`Invalid response, status: ${i.status}`);let c=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}return new ln(c,le(i.headers),nt(i.headers),i.headers.get("Content-Type"),i)})}dispose(){this.cache.dispose()}}function kr(s){return s&&s.mikuDeliveryProxy===!0}const Lr="MIKU_DELIVERY_PROXY_CONFIG";function Br(s,e){const t=r=>r==null?void 0:r.map(i=>({source:i.source,flags:i.flags})),n=j(T({},e),{patterns:e.patterns==null?void 0:On(e.patterns,r=>t(r))});return In(s,{[Lr]:JSON.stringify(n)})}function Pr(s){return Array.isArray(s)?{cdn:s,live:[]}:T({cdn:[],live:[]},s)}function Mr(s){const e={},t=[];for(const{url:n,ecdn:r,fallback:i}of s){const o=new URL(n),a=o.hostname,c=It(o.pathname);if(a!=="localhost"&&a.indexOf(".")<0||/\.qnqcdn\.net$/.test(a))continue;let h=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)}return e}function Ir(s,e){const t={};for(const{url:n,ecdn:r,size:i}of e){const o=new URL(n),a=o.hostname,c=It(o.pathname);if(!(!s.includes(a)&&!s.includes("*")))for(const h of[`${a}/*`,`${a}/*.${c||""}`]){let d=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)}}return t}function Or(s,e,t){return b(this,null,function*(){s=Br(s,e),yield navigator.serviceWorker.register(s,t)})}function zr(){return b(this,null,function*(){Nr()})}function Nr(){function s(e){var n;const t={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"))}function Hr(s,e){navigator.serviceWorker.addEventListener("message",({data:t})=>{if(!kr(t)||t.type!=="window-fetch-items")return;const n=Mr(t.items),r=Pr(s.domains),i=Ir([...r.cdn,...r.live],t.items);e(n,i)}),window.addEventListener("load",()=>{setTimeout(()=>{var n;const t={mikuDeliveryProxy:!0,type:"get-window-fetch-items"};(n=navigator.serviceWorker.controller)==null||n.postMessage(t)},1e3)})}function Ur(s,e,t){return b(this,null,function*(){const n=qr();if(n!=null){console.warn("Ability not OK for Miku Delivery Proxy API:",n);return}e.debug&&kt(),yield Promise.all([zr(),Or(s,e,t),Ns(),xs()])})}function qr(){return"serviceWorker"in navigator?null:"navigator.serviceWorker not available"}return k.Client=Dr,k.initProxy=Ur,k.listenStatistics=Hr,Object.defineProperties(k,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}}),k}({}); diff --git a/docs/.vuepress/public/miku-delivery-sw-1.1.0.js b/docs/.vuepress/public/miku-delivery-sw-1.1.0.js new file mode 100644 index 000000000..59c9f7494 --- /dev/null +++ b/docs/.vuepress/public/miku-delivery-sw-1.1.0.js @@ -0,0 +1,5 @@ +var ti=Object.defineProperty,ni=Object.defineProperties;var si=Object.getOwnPropertyDescriptors;var Je=Object.getOwnPropertySymbols;var Un=Object.prototype.hasOwnProperty,$n=Object.prototype.propertyIsEnumerable;var Bt=(L,E,M)=>E in L?ti(L,E,{enumerable:!0,configurable:!0,writable:!0,value:M}):L[E]=M,S=(L,E)=>{for(var M in E||(E={}))Un.call(E,M)&&Bt(L,M,E[M]);if(Je)for(var M of Je(E))$n.call(E,M)&&Bt(L,M,E[M]);return L},j=(L,E)=>ni(L,si(E));var Pt=(L,E)=>{var M={};for(var O in L)Un.call(L,O)&&E.indexOf(O)<0&&(M[O]=L[O]);if(L!=null&&Je)for(var O of Je(L))E.indexOf(O)<0&&$n.call(L,O)&&(M[O]=L[O]);return M};var R=(L,E,M)=>(Bt(L,typeof E!="symbol"?E+"":E,M),M);var b=(L,E,M)=>new Promise((O,ce)=>{var Me=V=>{try{ve(M.next(V))}catch(se){ce(se)}},be=V=>{try{ve(M.throw(V))}catch(se){ce(se)}},ve=V=>V.done?O(V.value):Promise.resolve(V.value).then(Me,be);ve((M=M.apply(L,E)).next())});(function(){"use strict";let L=!1;function E(s){return(...e)=>{L&&console.debug(`[${s}] [${(Date.now()/1e3).toFixed(3)}]`,...e)}}function M(){L=!0}function O(s){return(...e)=>{console.warn(`[${s}] [${(Date.now()/1e3).toFixed(3)}]`,...e)}}const ce="https://api.qiniudns.com/v1/resolve",Me="https://api.qiniudns.com",be="https://pili-zeus.qiniuapi.com/v1/scheduling";function ve(s){s[0]==="?"&&(s=s.slice(1));const e={};return s.split("&").forEach(t=>{const[n,r]=t.split("=");e[decodeURIComponent(n)]=r==null?null:decodeURIComponent(r)}),e}function V(s){return Object.keys(s).map(e=>[e,s[e]]).filter(([e,t])=>t!==void 0).map(([e,t])=>t===null?encodeURIComponent(e):[e,t].map(encodeURIComponent).join("=")).join("&")}function se(){const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",e=s.length;let t="";for(let n=0;n<20;n++)t+=s[Math.floor(Math.random()*e)];return t}function Fn(s,e){const t={};return Object.keys(s).forEach(n=>{t[n]=e(s[n])}),t}class Ot extends Error{constructor(){super(...arguments);R(this,"name","TimeoutError")}}function Ht(s,e){return new Promise((t,n)=>{setTimeout(()=>n(new Ot(e+" timeout")),s)})}class Wn extends Error{constructor(){super(...arguments);R(this,"name","AbortError")}}function Nt(s,e){e.aborted?s.abort(e.reason):e.addEventListener("abort",()=>{s.abort(e.reason)})}const zt={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:[]};function Ut(s,e,t=["image","media","other"]){s.search="",s.hash="";const n=s.toString();return t.some(r=>{var i;return((i=e[r])!=null?i:[]).some(o=>o.test(n))})}function Be(s){const e=new URL(s);return e.search="",e.hash="",e.toString()}function ue(s){return s instanceof Error?{err_msg:s.name,err_desc:s.message}:{err_msg:"Unknown",err_desc:s+""}}function N(s,e){return s==null||s===-1||e==null||e===-1?-1:(s-e)/1e3}function qn(s,e=80){const[t,n]=s.split(":"),r=n?parseInt(n,10):e;return[t,r]}function jn(s,e){return new URL(s,e).toString()}function Pe(s){const[e]=s.split("?");return e.endsWith(".m3u8")}function $t(s){const[e]=s.split("?");return e.endsWith(".flv")}class Kn{constructor(){R(this,"locked",!1);R(this,"waitings",[]);this.unlock=this.unlock.bind(this)}lock(){return b(this,null,function*(){return this.locked?(yield new Promise(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){return b(this,null,function*(){const t=yield this.lock();try{return yield e()}catch(n){throw n}finally{t()}})}}var ee=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Vn(s){var e=s.default;if(typeof e=="function"){var t=function(){return e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(n){var r=Object.getOwnPropertyDescriptor(s,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:function(){return s[n]}})}),t}var et={exports:{}};(function(s,e){(function(t,n){var r="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",C="smarttv",D="wearable",P="embedded",Z=255,$="Amazon",K="Apple",X="ASUS",z="BlackBerry",F="Browser",W="Chrome",le="Edge",q="Firefox",U="Google",kn="Huawei",Tt="LG",At="Microsoft",Ln="Motorola",Qe="Opera",Dt="Samsung",It="Sony",Mn="Xiaomi",kt="Zebra",Bn="Facebook",Zr=function(_,I){var T={};for(var H in _)I[H]&&I[H].length%2===0?T[H]=I[H].concat(_[H]):T[H]=_[H];return T},Xe=function(_){for(var I={},T=0;T<_.length;T++)I[_[T].toUpperCase()]=_[T];return I},Pn=function(_,I){return typeof _===d?Ie(I).indexOf(Ie(_))!==-1:!1},Ie=function(_){return _.toLowerCase()},Jr=function(_){return typeof _===d?_.replace(/[^\d\.]/g,i).split(".")[0]:n},Lt=function(_,I){if(typeof _===d)return _=_.replace(/^\s\s*/,i).replace(/\s\s*$/,i),typeof I===c?_:_.substring(0,Z)},ke=function(_,I){for(var T=0,H,A,Ze,k,Le,J;T0?k.length===2?typeof k[1]==a?this[k[0]]=k[1].call(this,J):this[k[0]]=k[1]:k.length===3?typeof k[1]===a&&!(k[1].exec&&k[1].test)?this[k[0]]=J?k[1].call(this,J,k[2]):n:this[k[0]]=J?J.replace(k[1],k[2]):n:k.length===4&&(this[k[0]]=J?k[3].call(this,J.replace(k[1],k[2])):n):this[k]=J||n;T+=2}},Mt=function(_,I){for(var T in I)if(typeof I[T]===h&&I[T].length>0){for(var H=0;HZ?Lt(A,Z):A,this},this.setUA(T),this};Y.VERSION=r,Y.BROWSER=Xe([f,g,p]),Y.CPU=Xe([x]),Y.DEVICE=Xe([l,w,u,m,v,C,y,D,P]),Y.ENGINE=Y.OS=Xe([f,g]),s.exports&&(e=s.exports=Y),e.UAParser=Y;var ge=typeof t!==c&&(t.jQuery||t.Zepto);if(ge&&!ge.ua){var Ye=new Y;ge.ua=Ye.getResult(),ge.ua.get=function(){return Ye.getUA()},ge.ua.set=function(_){Ye.setUA(_);var I=Ye.getResult();for(var T in I)ge.ua[T]=I[T]}}})(typeof window=="object"?window:ee)})(et,et.exports);const tt=et.exports,Ft="1.1.0";function Gn(){var r,i;const{os:s,device:e,browser:t}=tt(navigator.userAgent);let n;return typeof window!="undefined"?n=window.location:typeof self!==void 0&&(n=self.location),{os:`${s.name}_${s.version}`,browser:`${t.name}_${t.version}`,app:(r=n==null?void 0:n.host)!=null?r:"",sdk:`Web SDK v${Ft}`,dev_model:(i=e.model)!=null?i:"",dev_id:""}}var Wt={exports:{}};function Qn(s){throw new Error('Could not dynamically require "'+s+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var nt={exports:{}};const Xn=Vn(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var qt;function Oe(){return qt||(qt=1,function(s,e){(function(t,n){s.exports=n()})(ee,function(){var t=t||function(n,r){var i;if(typeof window!="undefined"&&window.crypto&&(i=window.crypto),typeof self!="undefined"&&self.crypto&&(i=self.crypto),typeof globalThis!="undefined"&&globalThis.crypto&&(i=globalThis.crypto),!i&&typeof window!="undefined"&&window.msCrypto&&(i=window.msCrypto),!i&&typeof ee!="undefined"&&ee.crypto&&(i=ee.crypto),!i&&typeof Qn=="function")try{i=Xn}catch(m){}var o=function(){if(i){if(typeof i.getRandomValues=="function")try{return i.getRandomValues(new Uint32Array(1))[0]}catch(m){}if(typeof i.randomBytes=="function")try{return i.randomBytes(4).readInt32LE()}catch(m){}}throw new Error("Native crypto module could not be used to get secure random number.")},a=Object.create||function(){function m(){}return function(v){var y;return m.prototype=v,y=new m,m.prototype=null,y}}(),c={},h=c.lib={},d=h.Base=function(){return{extend:function(m){var v=a(this);return m&&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(){var m=this.extend();return m.init.apply(m,arguments),m},init:function(){},mixIn:function(m){for(var v in m)m.hasOwnProperty(v)&&(this[v]=m[v]);m.hasOwnProperty("toString")&&(this.toString=m.toString)},clone:function(){return this.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){var v=this.words,y=m.words,C=this.sigBytes,D=m.sigBytes;if(this.clamp(),C%4)for(var P=0;P>>2]>>>24-P%4*8&255;v[C+P>>>2]|=Z<<24-(C+P)%4*8}else for(var $=0;$>>2]=y[$>>>2];return this.sigBytes+=D,this},clamp:function(){var m=this.words,v=this.sigBytes;m[v>>>2]&=4294967295<<32-v%4*8,m.length=n.ceil(v/4)},clone:function(){var m=d.clone.call(this);return m.words=this.words.slice(0),m},random:function(m){for(var v=[],y=0;y>>2]>>>24-D%4*8&255;C.push((P>>>4).toString(16)),C.push((P&15).toString(16))}return C.join("")},parse:function(m){for(var v=m.length,y=[],C=0;C>>3]|=parseInt(m.substr(C,2),16)<<24-C%8*4;return new p.init(y,v/2)}},u=l.Latin1={stringify:function(m){for(var v=m.words,y=m.sigBytes,C=[],D=0;D>>2]>>>24-D%4*8&255;C.push(String.fromCharCode(P))}return C.join("")},parse:function(m){for(var v=m.length,y=[],C=0;C>>2]|=(m.charCodeAt(C)&255)<<24-C%4*8;return new p.init(y,v)}},w=l.Utf8={stringify:function(m){try{return decodeURIComponent(escape(u.stringify(m)))}catch(v){throw new Error("Malformed UTF-8 data")}},parse:function(m){return u.parse(unescape(encodeURIComponent(m)))}},g=h.BufferedBlockAlgorithm=d.extend({reset:function(){this._data=new p.init,this._nDataBytes=0},_append:function(m){typeof m=="string"&&(m=w.parse(m)),this._data.concat(m),this._nDataBytes+=m.sigBytes},_process:function(m){var v,y=this._data,C=y.words,D=y.sigBytes,P=this.blockSize,Z=P*4,$=D/Z;m?$=n.ceil($):$=n.max(($|0)-this._minBufferSize,0);var K=$*P,X=n.min(K*4,D);if(K){for(var z=0;z>>31}var y=(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(){var d=this._data,p=d.words,l=this._nDataBytes*8,f=d.sigBytes*8;return p[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(){var d=o.clone.call(this);return d._hash=this._hash.clone(),d}});n.SHA1=o._createHelper(h),n.HmacSHA1=o._createHmacHelper(h)}(),t.SHA1})}(st)),st.exports}var rt={exports:{}},Kt;function Zn(){return Kt||(Kt=1,function(s,e){(function(t,n){s.exports=n(Oe())})(ee,function(t){(function(){var n=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=new h.init,typeof d=="string"&&(d=a.parse(d));var p=h.blockSize,l=p*4;d.sigBytes>l&&(d=h.finalize(d)),d.clamp();for(var f=this._oKey=d.clone(),u=this._iKey=d.clone(),w=f.words,g=u.words,x=0;x>>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>>6*(3-m)&63));var v=p.charAt(64);if(v)for(;l.length%4;)l.push(v);return l.join("")},parse:function(c){var h=c.length,d=this._map,p=this._reverseMap;if(!p){p=this._reverseMap=[];for(var l=0;l>>6-f%4*2,g=u|w;p[l>>>2]|=g<<24-l%4*8,l++}return i.create(p,l)}}(),t.enc.Base64})})(Vt);const es=Vt.exports;function ts(s){let e=s.query?`${s.path}?${s.query} +`:`${s.path} +`;return s.body&&(e+=s.body),e}function it(s){let e;try{e=new URL(s.path).pathname}catch(a){e=s.path}let t=ts(j(S({},s),{path:e}));const i=Jn(t,s.appSalt).toString(es).replace(/\+/g,"-").replace(/\//g,"_");let o=`QApp ${s.appID}:${i}`;return o=o.replace(/\//g,"_"),o=o.replace(/\+/g,"-"),o}const ot=200,at=E("log"),ns=O("log");class ss{constructor(e,t,n,r,i){R(this,"env",V(Gn()));R(this,"flushMutex",new Kn);R(this,"buffer",[]);this.schemaName=e,this.fetch=t,this.flushNum=n,this.flushWait=r,this.app=i}callApiLog(e){return b(this,null,function*(){const t=this.fetch;try{const n=it({appID:this.app.appID,appSalt:this.app.appSalt,path:`${Me}/v1/log/${this.schemaName}`}),r=yield t(new Request(`${Me}/v1/log/${this.schemaName}`,{method:"POST",headers:{Authorization:n,"Content-Type":"text/csv","X-Env":this.env},body:rs(e)}));if(!r.ok)throw new Error(`Unexpected response status: ${r.status} ${r.statusText}`)}catch(n){ns("Call log API failed:",n)}})}flush(){return b(this,null,function*(){return this.flushMutex.runExclusive(()=>b(this,null,function*(){const e=this.buffer.splice(0);if(e.length===0)return;const t=Math.ceil(e.length/ot);return Promise.all(Array.from({length:t}).map((n,r)=>this.callApiLog(e.slice(r*ot,(r+1)*ot))))}))})}tryFlush(){return b(this,null,function*(){const e=yield this.flushMutex.runExclusive(()=>{const t=this.buffer;if(t.length===0)return!1;if(t.length>=this.flushNum)return at("buffer.length >= this.flushNum"),!0;const n=Date.now()-t[0].ts;return n>=this.flushWait*1e3?(at("waited >= this.flushWait"),!0):this.flushWait*1e3-n});if(e===!0)return this.flush();typeof e=="number"&&setTimeout(()=>this.tryFlush(),e)})}log(e){this.buffer.push(S({ts:Date.now()},e)),this.tryFlush()}}class Gt{constructor(e,t=self.fetch,n=100,r=3){R(this,"schemaLoggers",new Map);this.appInfo=e,this.fetch=t,this.flushNum=n,this.flushWait=r}log(e,t){at("log",e,t);let n=this.schemaLoggers.get(e);n==null&&(n=new ss(e,this.fetch,this.flushNum,this.flushWait,this.appInfo),this.schemaLoggers.set(e,n)),n.log(t)}}function rs(s){const e=Object.keys(s[0]),t=["ts",...e.filter(i=>i!=="ts")],n=t.map(Qt).join(","),r=s.map(i=>t.map(o=>i[o]).map(o=>o!=null?o+"":"").map(Qt).join(","));return[n,...r].join(` +`)}function Qt(s){let e=s.replace(/"/g,'""');return/("|,|\n)/.test(e)&&(e='"'+e+'"'),e}class Xt{constructor(){R(this,"map",new Map)}on(e,t){var i;const r=[...(i=this.map.get(e))!=null?i:[],t];return this.map.set(e,r),()=>this.off(e,t)}once(e,t){const n=this.on(e,r=>{n(),t(r)});return n}off(e,t){var i;const r=((i=this.map.get(e))!=null?i:[]).filter(o=>o!==t);this.map.set(e,r)}emit(...e){var i;const[t,n]=e;((i=this.map.get(t))!=null?i:[]).forEach(o=>{o(n)})}dispose(){this.map.clear()}}const is=self,lt=E("utils/sw/clients");class os{constructor(e=is){R(this,"clientIds",[]);R(this,"removed",new Set);R(this,"emitter",new Xt);this.swScope=e}add(e){this.clientIds.includes(e)||this.removed.has(e)||(this.clientIds.push(e),lt("add",e,this.clientIds))}remove(e){const t=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){const t=this.clientIds,n=[],r=[];t.forEach(i=>{const o=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(){return this.clientIds}getAll(){return b(this,null,function*(){const e=(yield this.swScope.clients.matchAll({type:"window"})).slice();return e.reverse(),this.set(e.map(t=>t.id)),this.clientIds.map(t=>e.find(n=>n.id===t))})}get(e){return b(this,null,function*(){const t=yield this.swScope.clients.get(e);return t!=null?this.add(e):this.remove(e),t})}onRemove(e){return this.emitter.on("remove",e)}whenRemoved(e,t){if(!this.clientIds.includes(e))return;const n=this.emitter.on("remove",r=>{r===e&&(n(),t())})}}const he=new os;class G{constructor(e){R(this,"value");this.value=e!=null?S({},e.value):{}}set(e,t){this.value[e]=t}get(e){return this.value[e]}}tt(navigator.userAgent);let ye;function He(){if(ye!=null)return ye;try{new Response(new ReadableStream),ye=!0}catch(s){ye=!1}return ye}function Re(){return!(typeof TransformStream=="undefined"||!He())}function as(s){const e=[],t=s.length;for(let n=0;n=55296&&r<=56319&&t>n+1){const i=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)}return new Uint8Array(e).buffer}function ls(s){return s^=s>>>16,s=Math.imul(s,2246822507),s^=s>>>13,s=Math.imul(s,3266489909),s^=s>>>16,s>>>0}const Ne=new Uint32Array([3432918353,461845907]);function ct(s,e){return s<>>32-e}function cs(s,e){const t=s.byteLength/4|0,n=new Uint32Array(s,0,t);for(let r=0;re-t)}_add({key:e,replicas:t}){for(let n=0;nn>e);return t<0?0:t}get(e){if(this.members.size===0)return null;const t=this.hasher(e),n=this.search(t),r=this.sortedHashes[n];return this.circle.get(r)}getN(e,t,n){const r=n?n.size:this.members.size;if(r===0||t===0)return[];t>r&&(t=r);const i=this.hasher(e),o=this.search(i),a=[];for(let c=o;;c++){c>=this.sortedHashes.length&&(c=0);const h=this.sortedHashes[c],d=this.circle.get(h);if(!a.includes(d)&&(!n||n.has(d))&&(a.push(d),a.length>=t))return a}}add(e,t){return this.members.has(e)?!1:(this._add({key:e,replicas:t}),this.updateSortedHashes(),!0)}remove(e){if(!this.members.has(e))return!1;const t=this.membersReplicas.get(e);return this._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()}}function Yt(s,e){return e+s}const ws=ps;function ps(s){const e=ds(s);return new Uint32Array(e)[0]}class ms{constructor(e){this.logger=e}log(e){return this.logger.log("DnsResolveLog",e)}}function gs(s){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",t=e.length;let n="";for(let r=0;rnew RegExp(t.pattern).test(e))}function Cs(s){return Math.random(){const t=indexedDB.open(this.dbName);t.addEventListener("upgradeneeded",()=>{for(const n of this.storeConfigs){const r=t.result.createObjectStore(n.name);for(const i of n.indexes)r.createIndex(i.name,i.keyPath)}}),e(ze(t))}),this.db)})}get(e,t){return b(this,null,function*(){const r=(yield this.getDB()).transaction(e,"readonly").objectStore(e).get(t);return ze(r)})}getAll(e){return b(this,null,function*(){const n=(yield this.getDB()).transaction(e,"readonly").objectStore(e).getAll();return ze(n)})}count(e){return b(this,null,function*(){const n=(yield this.getDB()).transaction(e,"readonly").objectStore(e).count();return ze(n)})}set(e,t,n){return b(this,null,function*(){const i=(yield this.getDB()).transaction(e,"readwrite");return i.objectStore(e).put(n,t),ht(i)})}remove(e,t){return b(this,null,function*(){const r=(yield this.getDB()).transaction(e,"readwrite");return r.objectStore(e).delete(t),ht(r)})}clear(){return b(this,null,function*(){const e=yield this.getDB();yield Promise.all(this.storeConfigs.map(({name:t})=>{const n=e.transaction(t,"readwrite");return n.objectStore(t).clear(),ht(n)}))})}walkBy(e,t,n){return b(this,null,function*(){const i=(yield this.getDB()).transaction(e,"readonly").objectStore(e).index(t).openCursor(void 0,"next");return new Promise((o,a)=>{i.addEventListener("error",()=>a(new Ce(i.error))),i.addEventListener("success",()=>{const c=i.result;if(c==null){o();return}n(c.value,c.primaryKey),c.continue()})})})}dispose(){var e;(e=this.db)==null||e.close()}}class Ce extends Error{constructor(t){super(t+"");R(this,"name","IndexedDBError");this.cause=t}}function ze(s){return new Promise((e,t)=>{s.addEventListener("success",()=>e(s.result)),s.addEventListener("error",()=>t(new Ce(s.error)))})}function ht(s){return new Promise((e,t)=>{s.addEventListener("complete",()=>e()),s.addEventListener("error",()=>t(new Ce(s.error))),s.addEventListener("abort",()=>t(new Ce(s.error)))})}function re(s){const e=s.get("Content-Length");return e?parseInt(e,10):null}function dt(s){const e=s.get("Content-Range");return e==null?null:xs(e)}function xs(s){const e=s.trim().toLowerCase(),[t,n]=e.split(/\s+/);if(t!=="bytes")throw new Error(`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}}function Se(s){const e=s.start!=null&&s.end!=null?`${s.start}-${s.end}`:"*",t=s.totalSize==null?"*":s.totalSize+"";return`bytes ${e}/${t}`}function ft(s){return s?Number(s):null}function xe(s){const e=s.get("Range");return e==null?null:en(e)}function Jt(s){return s.start===0&&s.end==null}function en(s){const e=s.trim().toLowerCase();if(!e.startsWith("bytes="))throw new Error(`Unit must be bytes: ${s}`);if(e.includes(","))throw new Error(`Multiple range: ${s}`);const[,t,n]=/(\d*)-(\d*)/.exec(e)||[];if(!t&&!n)throw new Error(`Invalid range values: ${s}`);if(!t)throw new Error("Suffix range not supported");const[r,i]=[t,n].map(o=>ft(o));return{start:r,end:i}}function Ee(s){var e,t;return`bytes=${(e=s.start)!=null?e:0}-${(t=s.end)!=null?t:""}`}const Es=/[^\u0000-\u00ff]/;function tn(s){return Es.test(s)?"REPLACED_BY_Miku_Delivery_SEE_utils_http_encodeHeaderValue":s}function nn(s){if(s instanceof Headers){const e={};s.forEach((t,n)=>{e[n]=tn(t)}),s=e}if(Array.isArray(s)){const e={};s.forEach(([t,n])=>{e[n]=tn(t)}),s=e}return new Headers(s)}function wt(s){var t;const e=dt(s);return e!=null?(t=e.totalSize)!=null?t:null:re(s)}const sn=E("utils/stream"),rn=O("utils/stream");function _s(s){return b(this,null,function*(){const e=s.getReader();let t=new Uint8Array;for(;;){const{done:r,value:i}=yield e.read();if(r)break;t=new Uint8Array([...t,...i])}return new TextDecoder().decode(t)})}function pt(s,e){var a;const t=s.getReader(),n=(a=e[0])!=null?a:0,r=e[1];let i=0;return new ReadableStream({pull:c=>b(this,null,function*(){let h,d;for(;;){const u=yield t.read();if(u.done){c.close();return}if(h=u.value,d=i+h.byteLength,d>n)break;i=d}let p=h;const l=n>i?n-i:0,f=r!=null&&r=r&&(t.cancel("Cancelled by slice for target range met"),c.close()),i=d}),cancel:c=>t.cancel(c)})}function Ts(s){let e=0;const t=new TransformStream({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]}class on extends Error{constructor(){super(...arguments);R(this,"name","SaveSlicedPieceError")}}function As(s,e,t,n){return b(this,null,function*(){const r=[];let i=e,o=[],a=0;function c(){return b(this,null,function*(){const h=i+a;sn(`saveSlicedPiece [${i}, ${h}]`);try{yield n(new Blob(o),i,h)}catch(d){throw rn(`saveSlicedPiece [${i}, ${h}] failed`,d),new on(`saveSlicedPiece [${i}, ${h}] failed`)}r.push([i,h]),sn(`saveSlicedPiece [${i}, ${h}] finish`,r),i=h})}try{const h=s.getReader();for(;;){const{value:d,done:p}=yield h.read();if(p)break;o.push(d),a+=d.byteLength,a>=t&&(yield c(),o=[],a=0)}a>0&&(yield c())}catch(h){if(!(h instanceof on)&&(rn("exception occurred while reading stream and save by pieces",h),a>0))try{yield c()}catch(d){}}return r})}function Ds(s){let e,t=!1;const n=new ReadableStream({start:a=>{e=a},cancel:()=>{t=!0}}),r=s.getReader();let i=!1;return{main:new ReadableStream({pull:a=>b(this,null,function*(){try{const{value:c,done:h}=yield r.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,yield r.cancel(a),e.error(a)})}),minor:n}}class ie{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=new Headers(n),this.body=i!=null?i:null,this.signal=r!=null?r:new AbortController().signal}}class te{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}}}function Is(s){const{url:e,headers:t,body:n,signal:r}=s;return new ie(e,{headers:t,body:n,signal:r})}function Ue(s){const{status:e,statusText:t,headers:n,body:r}=s;return new te(r,{status:e,statusText:t,headers:n,underlayer:s})}class $e extends Error{constructor(t){super(`Unexpected HTTP status: ${t.status} ${t.statusText}`);R(this,"name","UnexpectedHttpStatusError");this.response=t}}const ks=new Xt;let an;typeof self!="undefined"&&(an=self,an.addEventListener("message",s=>ks.emit("message",s)));class Ls extends Error{constructor(){super(...arguments);R(this,"name","WindowClientError")}}class Ms extends Error{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannelCloseError")}}class Bs extends Error{constructor(){super(...arguments);R(this,"name","UnexpectedDataChannel1stMessageError")}}function mt(s,e=()=>1){if(s.length===0)return null;const t=s.map(e),n=t.reduce((i,o)=>i+o,0);let r=Math.random()*n;for(let i=0;i=0?(i=s.slice(o+1),s=s.slice(0,o)):i="";const a=s.indexOf("/");r=a>=0?s.slice(a):"",r=Ns(e.rewrites,r),i=Fs(e.queryString,i);let c=n+r;return i!==""&&(c=c+"?"+i),c}function Ns(s,e){for(const t of s){const n=zs(t,e);if(n!=null){e=$s(t,n);break}}return e}function zs(s,e){return new RegExp(s.pattern).exec(e)}const Us=/\${(\d+)}/g;function $s(s,e){return s.repl.replace(Us,(t,n)=>{var i;const r=parseInt(n,10);return r>=e.length?t:(i=e[r])!=null?i:""})}function Fs({type:s,values:e},t){if(s==="none")return"";if(s==="all")return t;const n=ve(t),r=e!=null?e:[],i={};return Object.keys(n).forEach(o=>{s==="include"&&!r.includes(o)||s==="exclude"&&r.includes(o)||(i[o]=n[o])}),V(i)}function cn(s,e){const t=new Map;return function(...r){const i=e(...r),o=t.get(i);if(o!=null)return o;const a=s(...r);return t.set(i,a),a.finally(()=>{t.delete(i)}),a}}const de=E("dns"),We=O("dns"),Ws="miku-delivery/dns/cdn/v1",vt="result",qs={name:vt,indexes:[{name:"domain",keyPath:"domain"}]};class js{constructor(e,t,n=ys,r,i=2e3,o=5e3){R(this,"fingerprints",new Map);R(this,"disabledElts",new Map);R(this,"storage",new Zt(Ws,[qs]));R(this,"getResolveResultFromStorage",cn(e=>this.storage.get(vt,e),e=>e));R(this,"refreshResolveResultInStorage",cn((e,t)=>b(this,null,function*(){const n=yield this.dnsResolver(e,t,this.app,this.logger),r=Date.now()+n.ttl*1e3,i=j(S({},n),{domain:t,expireAt:r});return this.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){const t=this.fingerprints.get(e);if(t==null)throw new Error(`No fingerprint for ${e}`);return t}isEltDisabled(e){const t=this.disabledElts.get(e);return t==null?!1:t.after>Date.now()}setEltDisabled(e){const t=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){return b(this,null,function*(){if(this.cacheKeyFn!=null)return this.cacheKeyFn(e);const n=yield this.resolveDomain(new G,t);return ut(n)?Hs(e,n.cacheKey,n.bucket):e})}getMediaOptimization(e){return b(this,null,function*(){const t=yield this.resolveDomain(new G,e);return ut(t)?t.mediaOptimization:null})}saveResolveResultToStorage(e,t){return b(this,null,function*(){return this.storage.set(vt,e,t)})}resolveDomain(e,t){return b(this,null,function*(){const n=Date.now(),r=(()=>b(this,null,function*(){const i=yield this.getResolveResultFromStorage(t);return i==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));return Promise.race([r,Ht(this.resolveTimeout,"Resolve domain")]).catch(i=>{throw We("DNS resolve failed:",i),new gt(i)})})}resolve(e,t){return b(this,null,function*(){let n=null;return yield this.do(e,t,1,r=>{n=r}),n})}do(e,t,n,r){return b(this,null,function*(){let i;de("Resolve for",t);const o=new URL(t).hostname,[a,c]=yield Promise.all([this.getCacheKey(t,o),this.resolveDomain(e,o)]);if(!ut(c))throw new ae(`Non-ECDN resolve result: ${o}`);const{groups:h,rules:d}=c;if(h.length===0)throw new ln(`No available group for ${o}`);de("Resolved for",t);const p=Rs(d,a);if(p==null)throw new ae("No matched rule found");if(!Cs(p))throw new ae("Do not serve with given rule");let l=p.groups.map(({groupidx:f,weight:u,splitn:w})=>{const g=h[f];if(g==null)throw new Error(`Unexpected groupidx: ${f}`);return{group:g,weight:u,splitn:w}});for(let f=0;fw.weight);if(u==null)break;try{de("doWithGroup",f,a),yield this.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))}}throw i=oe(i)?i:new bt(i),i})}doWithGroup(e,t,n,r,i){return b(this,null,function*(){const o=t.elts.filter(l=>!this.isEltDisabled(l.id));if(o.length===0)throw new Error("No available elt");const a=Ks(t),c=new Set(o.map(l=>l.id)),h=r===1?2:r;let d=a.getN(n,h,c).map(l=>o.find(f=>f.id===l)),p;for(let l=0;l<2;l++){const f=mt(d.slice(0,r),u=>u.replicas);if(f==null)break;try{de("doWithElt",f.id,n),e.set("downloadEltID",f.id),yield Vs(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))}}throw p})}}const un=new Map;function Ks({elts:s}){const e=s.map(({id:r,replicas:i})=>`${r}:${i}`).join(","),t=un.get(e);if(t!=null)return t;const n=new fs;return n.set(s.map(r=>({key:r.id,replicas:r.replicas}))),un.set(e,n),n}function Vs(s,e,t){return b(this,null,function*(){let n=s.addrs;if(n.length===0)throw new Error("Empty addr list");let r;for(let i=0;i<2;i++){const o=mt(n);if(o==null)break;try{de("do job with",o,e),yield t(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))}}throw r})}function Gs(s){return s.expireAt{const r={key:n,usedTime:t.usedTime,size:yt(t)},i=this.itemList.pushBack(r);this.itemElementMap.set(n,i),e.push(...ir(t,n))});try{const t=yield this.dc.getBrowserCacheKeys();for(let n of t)e.includes(n)||(qe("clear inaccessible cache:",n),yield this.dc.browserCacheDelete(n))}catch(t){Xs("failed to clear inaccessible caches:",t)}})}addItem(e,t){const n={key:e,usedTime:t.usedTime,size:yt(t)};let r=null;return this.itemList.reverseWalk((i,o)=>{if(i.usedTime<=t.usedTime)return r=this.itemList.insertAfter(n,o),!1}),r==null&&(r=this.itemList.pushFront(n)),this.itemElementMap.set(e,r),r}removeItem(e){const t=this.itemElementMap.get(e);t!=null&&(this.itemElementMap.delete(e),this.itemList.remove(t))}onItemSet(e,t){return b(this,null,function*(){yield this.inited;let n=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(){return b(this,null,function*(){if(typeof navigator.storage.estimate=="undefined")return null;const{quota:e,usage:t}=yield navigator.storage.estimate();return e!=null&&t!=null?e-t:null})}freeUpSpace(e){return b(this,null,function*(){yield this.inited;let t=0;const n=[];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),yield Promise.all(n.map(r=>b(this,null,function*(){yield this.dc.removeItemWithContent(r),this.removeItem(r)})))})}beforeContentSet(e,t,n){return b(this,null,function*(){if(n==null)return;yield this.inited;const r=yield this.getLeftSpace(),i=this.config.reservedQuota;if(r!=null&&r-i{var n,r;return e+Js(t,(r=(n=s.meta)==null?void 0:n.fsize)!=null?r:null)},0)}const er=E("dc"),tr="miku-delivery/dc/v1",_e="item",hn="usedTimeIndex",nr={name:_e,indexes:[{name:hn,keyPath:"usedTime"}]},sr=32*1024*1024;class rr{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=new Zt(this.ns,[nr]),this.cr=new Zs(this)}openBrowserCache(){return b(this,null,function*(){return this.browserCachePromise!=null?this.browserCachePromise:(this.browserCachePromise=caches.open(this.ns).catch(e=>{throw new fe(e)}),this.browserCachePromise.then(e=>{this.browserCache=e}),this.browserCachePromise)})}getItem(e){return b(this,null,function*(){return this.db.get(_e,e)})}setItem(e,t){return b(this,null,function*(){er("setItem",e,t),yield this.db.set(_e,e,t),yield this.cr.onItemSet(e,t)})}walkItems(e){return b(this,null,function*(){return this.db.walkBy(_e,hn,e)})}removeItemWithContent(e){return b(this,null,function*(){const t=yield this.getItem(e);t!=null&&(yield Promise.all(t.pieces.map(n=>this.removeContent(e,n))),yield this.db.remove(_e,e))})}browserCacheMatch(e){return b(this,null,function*(){let t=this.browserCache;return t==null&&(t=yield this.openBrowserCache()),t.match(e).catch(n=>{throw new fe(n)})})}browserCachePut(e,t){return b(this,null,function*(){let n=this.browserCache;n==null&&(n=yield this.openBrowserCache()),yield n.put(e,t).catch(r=>{throw new fe(r)})})}browserCacheDelete(e){return b(this,null,function*(){let t=this.browserCache;t==null&&(t=yield this.openBrowserCache()),yield t.delete(e).catch(n=>{throw new fe(n)})})}getBrowserCacheKeys(){return b(this,null,function*(){let e=this.browserCache;return e==null&&(e=yield this.openBrowserCache()),yield e.keys().then(t=>t.map(n=>n.url))})}getContent(e,t){return b(this,null,function*(){const n=yield this.browserCacheMatch(je(e,t));if(n!=null){if(n.body==null)throw new Error("Body expected for cached response");return Ue(n)}})}setContent(e,t,n){return b(this,null,function*(){if(!He())return yield this.cacheResponse(e,t,n.underlayer),[t];const{headers:r,body:i}=n,o=wt(r);return yield As(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+"");const d=new Response(a,{status:200,statusText:"OK",headers:r});yield this.cacheResponse(e,[c,h],d)}))})}cacheResponse(e,t,n){return b(this,null,function*(){const r=je(e,t),i=re(n.headers);yield this.cr.beforeContentSet(e,t,i);try{yield this.browserCachePut(r,n)}catch(o){throw o instanceof fe&&o.cause instanceof Error&&o.cause.name==="QuotaExceededError"&&this.cr.onQuotaExceeded(e,t,i),o}})}removeContent(e,t){return b(this,null,function*(){const n=je(e,t);return this.browserCacheDelete(n)})}dispose(){this.db.dispose()}}function je(s,e){var t;return/^https?:\/\//.test(s)||(s="https://miku-cache.com/"+s),`${s}_with_range_${e[0]}_${(t=e[1])!=null?t:""}`}function ir(s,e){return s.pieces.map(t=>je(e,t))}class fe extends Error{constructor(t){super(t+"");R(this,"name","BrowserCacheError");this.cause=t}}class or{constructor(e){this.logger=e}log(e){return this.logger.log("DoLog",e)}}const ar=3,dn=E("http");class fn{constructor(e,t,n,r=0){R(this,"doLogger");this.client=t,this.resolver=n,this.clientResponseTimeout=r,this.doLogger=new or(e)}doWithResolved(e,t,n){return b(this,null,function*(){dn("fetch",t.url,"with resolved",n);const r=new AbortController;Nt(r,t.signal);const i=new ie(t.url,j(S({},t),{signal:r.signal}));i.headers.set("X-Miku-Agent",`miku-delivery-web/v${Ft}`);let o=this.client.fetch(e,i,n);this.clientResponseTimeout>0&&(o=Promise.race([o,Ht(this.clientResponseTimeout,"HTTPClient get response")]),o.catch(c=>{c instanceof Ot&&r.abort(c)}));const a=yield o;if(dn("fetch",t.url,"succeeded with status",a.status),a.status===429||a.status>=500)throw new $e(a);return a})}originalDo(e,t){return b(this,null,function*(){if(t.signal.aborted)throw t.signal.reason;let n=-1,r;if(yield this.resolver.do(e,t.url,ar,i=>b(this,null,function*(){const o=new G(e);n++,o.set("downloadRetryCount",n),r=yield this.doWithResolved(o,t,i)})),r==null)throw new Error(`Http do failed: resolver do finished with no finalResp, url: ${t.url}`);return r})}do(e,t){return b(this,null,function*(){const n=Date.now(),r=se();e.set("doID",r);let i,o=null;try{return i=yield this.originalDo(e,t),i}catch(a){throw o=a,a}finally{const{onDoError:a,onDoResponsed:c}=this.getDoLog(e,r,n);i==null?a(o):c(i.status)}})}getDoLog(e,t,n){const r=a=>{var c;return this.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=>{const c=Date.now();r(S({t_total:N(c,n)},ue(a)))},onDoResponsed:a=>{const c=Date.now();r({t_total:N(c,n),status_code:a})}}}}class lr{constructor(e){this.logger=e}log(e){return this.logger.log("TaskLog",e)}}class wn{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=new lr(n)}setPriority(e){this.priority=e}start(e){return b(this,null,function*(){if(this.started)throw new Error("Task already started");if(this.started=!0,this.signal=e,e&&e.aborted)throw e.reason;const t=Date.now(),n=new G;n.set("taskID",this.id),n.set("taskDomain",new URL(this.url).hostname);let r,i=null;try{return r=yield this.startByClient(n,this),r}catch(o){throw i=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){const n=e.get("taskCacheMatchAt"),r=e.get("task1stHttpDoAt"),i=e.get("taskResultStreamAt"),o=Date.now(),a=d=>{var p,l,f,u,w;return this.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?void 0:l.start)!=null?f:-1,range_end:(w=(u=this.range)==null?void 0: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=>{const p=Date.now();a(S({t_total:N(p,t)},ue(d)))},logOnTransferred:()=>{const d=Date.now();a({t_trans:N(d,o),t_total:N(d,t)})}}}}class pn{constructor(e,t,n,r,i){this.stream=e,this.size=t,this.fileSize=n,this.contentType=r,this.underlayer=i}blob(){return b(this,null,function*(){const e=this.stream.getReader(),t=[];for(;;){const{done:n,value:r}=yield e.read();if(n)break;const i=r;t.push(i)}return new Blob(t)})}}function Rt(s,e,t){return s!=null&&t!=null&&t>=s&&(t=null),(e==null||e<0)&&(e=0),[e,t]}function mn(s,e){var r;const t=((r=e[0])!=null?r:0)===0,n=e[1]==null||s!=null&&e[1]===s;return t&&n}function cr(s,e){var r,i;const t=(r=e[0])!=null?r:0,n=(i=e[1])!=null?i:s;return n==null?null:n-t}function ur(s,e,t){var c,h;if(e===0)return[];const n=(d,p)=>bn(d,p,e!=null?e:Number.POSITIVE_INFINITY),r=(c=s==null?void 0:s[0])!=null?c:0,i=(h=s==null?void 0:s[1])!=null?h:e,o=[];let a=r;for(const d of t){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])});const p=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}}return n(i,a)&&o.push({cached:!1,range:Rt(e,a,i)}),o}function hr(s,e){var r;const t=(r=e[0])!=null?r:0,n=e[1];for(const i of s){if(i[1]!=null&&i[1]<=t)continue;if(i[0]>t)break;const o=t-i[0],a=fr(n!=null?n:i[1],i[0]);return{piece:i,start:o,end:a}}throw new Error("Piece not found")}function dr(s,e){const t=s.filter(o=>!e.some(a=>o[0]===a[0]&&o[1]===a[1])),n=[e[0][0],e[e.length-1][1]];for(let o of t)if(gn(o,n))return{toSave:t,toRemove:e};const r=[],i=[];for(let o of t)gn(n,o)?i.push(o):r.push(o);return{toSave:[...r,...e].sort((o,a)=>o[0]-a[0]),toRemove:i}}function gn(s,e){return s[0]<=e[0]&&!bn(e[1],s[1],Number.POSITIVE_INFINITY)}function bn(s,e,t){const n=s!=null?s:t,r=e!=null?e:t;return n>r}function fr(s,e){return s==null||e==null?null:s-e}function vn(s){const e={},t=s.split(",").map(n=>{let[r,i]=n.split("=").map(o=>o.trim());return[r.toLowerCase(),i]});for(const[n,r]of t)if(n==="max-age"){if(r!=null){const i=parseInt(r,10);Number.isNaN(i)||(e["max-age"]=i)}}else(n==="no-cache"||n==="no-store")&&(e[n]=!0);return e}function Ke(s){return Math.floor(s/1e3)}function yn(s,e){const t=s.get("Date");if(t==null)return e;const n=Date.parse(t);return Number.isNaN(n)?e:n}function wr(s,e,t){if(s!=null)return s;const n=e.get("Expires");if(n!=null){let r=Date.parse(n);Number.isNaN(r)&&(r=0);const i=yn(e,t);return Ke(r-i)}return 60*60}function pr(s){const e=s.get("Age");if(e==null)return 0;const t=parseInt(e,10);return Number.isNaN(t)?0:t}function mr(s,e,t,n){const r=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);return h+d}function gr(s,e,t,n,r){var c;const i=(c=s==null?void 0:s["max-age"])!=null?c:null,o=wr(i,e,n),a=mr(e,t,n,r);return o>a}function br(s,e,t,n){const r=s.get("Cache-Control"),i=r!=null?vn(r):null;return(i==null?void 0:i["no-cache"])===!0?!0:!gr(i,s,e,t,n)}function vr(s){const e=s.get("Cache-Control"),t=e!=null?vn(e):null;return!(t!=null&&t["no-store"]===!0)}function yr(s){const e=s.get("ETag");return e==null?null:e.startsWith("W/")?e.slice(2):e}function Rr(s,e){const t=new Headers(s),n=yr(e);n!=null&&t.set("If-None-Match",n);const r=e.get("Last-Modified");return r!=null&&t.set("If-Modified-Since",r),t}function Cr(s,e){return!(s.get("Last-Modified")===e.get("Last-Modified")&&s.get("ETag")===e.get("ETag"))}function Sr(s,e){const t=new Headers(s);return e.forEach((n,r)=>{r=r.toLowerCase(),!(r==="content-length"||r==="content-encoding"||r==="content-range")&&t.set(r,n)}),t}const xr={threshold:0,contentRangeExposed:!0},B=E("ftask"),we=O("ftask");class Er{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(){var e,t;return(t=(e=this.meta)==null?void 0:e.fsize)!=null?t:null}cacheValidationRequired(){if(this.meta==null)return!1;const{requestTime:e,responseTime:t,headers:n}=this.meta;return e==null||t==null||n==null?!1:br(n,e,t,Date.now())}isMedia(e){const t=Be(e.url);return this.patterns.media.some(n=>n.test(t))}isRangeStartFirstRequested(e){var n;const t=(n=e[0])!=null?n:0;return!this.cachePieces.some(r=>{var i;return r[0]<=t&&t<=((i=r[1])!=null?i:Number.POSITIVE_INFINITY)})}startTask(e,t){return b(this,null,function*(){B("startTask",t.url,t.id,t.range);let n;const r=t.range!=null?[t.range.start,t.range.end]:[0,null];yield this.inited,this.usedTime=Date.now(),this.save().catch(a=>we("save failed when startTask:",a)),Re()?n=yield this.readRangeWithStream(e,t,r):(B("supportStreamOperation: false",t.url,t.id),n=yield this.readRangeWithoutStream(e,t,r));const i=this.meta;if(i==null)throw new Error("Missing meta in fileTask");B("startTask resolved",t.url,t.id);const o=cr(i.fsize,r);return new pn(n.body,o,i.fsize,i.headers.get("Content-Type"),n)})}readRangeWithoutStream(e,t,n){return b(this,null,function*(){var a,c;let r;const i=[(a=n[0])!=null?a:0,n[1]],o=(c=yield this.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;else if(B("doRequestAndSaveCache",t.url,t.id,o!=null),r=yield this.doRequestAndSaveCache(e,t,n,o!=null,!1),r.status===304){if(o==null)throw new Error("Unexpected 304 with no cached response");r=o}return e.set("taskResultStreamAt",Date.now()),r})}readRangeWithStream(e,t,n){return b(this,null,function*(){const r=this.isMedia(t),i=this.cacheValidationRequired();B("cacheValidationRequired",i);const o=ur(n,this.fileSize(),this.cachePieces);if(B("applyRange",n,this.fileSize(),this.cachePieces,o),i){const h=o.some(l=>l.cached),d=r?yield this.getMediaOptimization():!1,p=yield this.doRequestAndSaveCache(e,t,n,h,d);if(p.status===200||p.status===206)return p}e.set("taskCacheMatchAt",Date.now());const a=new TransformStream(void 0),c=yield new Promise((h,d)=>b(this,null,function*(){try{for(let p=0;pthis.http.do(...w),(...w)=>this.nativeHttpClient.fetch(...w),i)(o,h);const l=Date.now();if(p.body==null)throw new Error("Body expected");let f=p.headers;if(r&&c!=null&&p.status===304)B(`updateStoredHeaders for ${this.url}`),f=Sr(c,p.headers);else if(p.status!==200&&p.status!==206)throw new $e(p);return yield this.onResponse(f,d,l),p.bodyReadResult.then(w=>{B(`bodyReadResult for ${this.url}:`,w)}),p})}doRequestAndSaveCache(e,t,n,r,i){return b(this,null,function*(){const o=yield this.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){return b(this,null,function*(){var o,a;let r=n,i;if(Re()){const{main:c,minor:h}=Ds(n.body);r=new te(c,n),i=new te(h,n)}else if(!e.range){const c=n.underlayer.clone();i=Ue(c)}if(i!=null){const c=[(o=t==null?void 0:t[0])!=null?o:0,(a=t==null?void 0: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{yield Promise.all(p.map(l=>this.cache.removeContent(this.key,l)))}catch(l){B("exception occurred while removing duplicated cache pieces",l)}}return this.save()})).then(()=>B("saveCachePiece finish",this.url,c,this.cachePieces),h=>we("saveCachePiece failed",this.url,c,h))}return r})}onResponse(e,t,n){return b(this,null,function*(){const r=this.meta;this.meta={fsize:wt(e),requestTime:t,responseTime:n,headers:e},(r==null?void 0:r.headers)!=null&&Cr(r.headers,e)&&(B(`${this.url} modified, clear local cache`),yield Promise.all(this.cachePieces.map(i=>this.cache.removeContent(this.key,i))),this.cachePieces=[]),this.save().catch(i=>we("save failed when onResponse:",i))})}resume(){return b(this,null,function*(){const e=yield this.cache.getItem(this.key);e==null||e.meta==null||(this.meta=j(S({},e.meta),{headers:e.meta.headers!=null?new Headers(e.meta.headers):null}),this.cachePieces=e.pieces)})}save(){return b(this,null,function*(){var r,i;const e=((r=this.meta)==null?void 0:r.headers)!=null?[...((i=this.meta)==null?void 0:i.headers).entries()]:null,n={meta:this.meta!=null?j(S({},this.meta),{headers:e}):null,pieces:this.cachePieces,usedTime:this.usedTime};yield this.cache.setItem(this.key,n)})}}function _r(s,e,{threshold:t,contentRangeExposed:n}){return function(i,o){return b(this,null,function*(){var Z,$;const P=o,{url:a}=P,c=Pt(P,["url"]),h=xe(o.headers);B("doWithInitialOptimization",a);const d=new G(i),p=new Headers(c.headers),l=S({start:null,end:null},h);l.start=(Z=l.start)!=null?Z:0;const f=l.start+t-1;(l.end==null||l.end>f)&&(l.end=f),p.set("Range",Ee(l));const u=new ie(a,j(S({},c),{headers:p})),g=yield((K,X)=>b(this,null,function*(){var le;let z=null;const F=xe(X.headers);F!=null&&!Jt(F)&&!n&&(z=Tr(a,c.headers,e));const W=yield e(K,X);if(F!=null&&W.status===206&&!W.headers.get("Content-Range")){const q=Jt(F)?re(W.headers):yield z;if(q!=null){const U=Se({start:F.start,end:(le=F.end)!=null?le:q-1,totalSize:q});W.headers.set("Content-Range",U)}}return W}))(d,u);if(g.body==null)throw new Error("Body expected for initial response");if(g.status!==206)return g;const x=dt(g.headers);if(x==null)throw new Error("Header Content-Range expected for 206 response");const m=(()=>{var le;const K=re(g.headers);if(K!=null&&Kb(this,null,function*(){B("doWithInitialOptimization initialBody transfered");let q;try{const U=yield s(i,F);if(U.body==null)throw new Error(`Body expected for following response of ${a}`);if(U.status===200)q=pt(U.body,[z.start,z.end==null?null:z.end+1]);else if(U.status===206)q=U.body;else throw new $e(U)}catch(U){if(Ct(U))B("use fallback fetch for doWithInitialOptimization followingBody",U),q=(yield e(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=new Headers(g.headers);if(y.delete("Content-Range"),y.delete("Content-Length"),h==null)return v!=null&&y.set("Content-Length",v+""),new te(m,{status:200,statusText:"OK",headers:y,underlayer:g.underlayer});const C=($=h.start)!=null?$:0,D=h.end!=null?h.end:v!=null?v-1:null;return D!=null&&y.set("Content-Length",D-C+1+""),y.set("Content-Range",Se({start:C,end:D,totalSize:v})),new te(m,{status:206,statusText:"Partial Content",headers:y,underlayer:g.underlayer})})}}function Tr(s,e,t){return b(this,null,function*(){const n=new Headers(e);n.delete("Range");const r=yield t(new G,new ie(s,{method:"HEAD",headers:n}));return re(r.headers)})}function Ct(s){return[gt,ae,ln,bt,Ce,fe].some(e=>s instanceof e)}class Ar{constructor(e){this.logger=e}log(e){return this.logger.log("LiveScheduleLog",e)}}const Dr=new URL(be).hostname;function Ir(s,e,t,n){return b(this,null,function*(){var l,f;const r=new Ar(n),i={url:e,cip:""},o=it(j(S({},t),{path:be})),a=Date.now();let c,h=null,d=null,p=null;try{if(h=yield fetch(be,{method:"POST",body:JSON.stringify(i),headers:{"Content-Type":"application/json",Authorization:o}}),d=Date.now(),!h.ok)throw new Error(`Call Schedule API failed, status: ${h.status} ${h.statusText}`);return p=yield h.json()}catch(u){throw c=u}finally{const u=N(Date.now(),a),w=p==null?ue(c):{err_msg:"",err_desc:""};r.log(j(S({r_id:(l=h==null?void 0:h.headers.get("x-reqid"))!=null?l:"",ip:"",domain:Dr,status_code:(f=h==null?void 0:h.status)!=null?f:-1},w),{t_conn:N(d,a),t_total:u,type:1}))}})}const Te=E("dns"),St=O("dns"),kr=60,Lr=60*1e3;class Mr{constructor(e,t,n=Ir,r=Be){R(this,"scheduling",new Map);R(this,"cache",new Map);R(this,"m3u8SegmentCache",new Map);this.logger=e,this.app=t,this.scheduler=n,this.cacheUrl=r}getScheduleResult(e,t){return b(this,null,function*(){var o;const n=Date.now();let r;try{r=yield this.scheduler(e,t,this.app,this.logger)}catch(a){throw St("Live schedule failed:",a),new gt(a)}finally{e.set("dnsResolveTotalTime",N(Date.now(),n))}if(r.code===1)throw new ae(`Local DNS for ${t}`);if(r.code!==0)throw new Error(`Unexpected schedule code: ${r.code}`);const i=(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){return b(this,null,function*(){const n=this.cacheUrl(e),r=this.cache.get(n);if(r==null){St("No schedule result for m3u8:",e);return}const i=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){return b(this,null,function*(){const n=this.cacheUrl(t);if(!Pe(t)&&!$t(t)){const a=this.m3u8SegmentCache.get(n);if(a==null)throw new ae("Neither m3u8 / flv URL, or m3u8 segment URL");return a}const r=this.cache.get(n);if(r!=null&&xt(r))return e.set("dnsResolveFromCache",!0),r;const i=this.scheduling.get(n);if(i!=null){let a;try{a=yield i}catch(c){if(c instanceof ae)throw c}if(a!=null&&xt(a))return e.set("dnsResolveFromCache",!0),a;this.scheduling.delete(n)}const o=this.getScheduleResult(e,t);return Te("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){const t=this.cacheUrl(e),n=Pe(e)||$t(e)?this.cache.get(t):this.m3u8SegmentCache.get(t);return n!=null&&xt(n)}do(e,t,n,r){return b(this,null,function*(){let i;Te("schedule for",t);const o=yield this.schedule(e,t);Te("scheduled for",t);for(let a=0;aRn(t,e))}const pe=E("utils/fetch");function Cn(s){return b(this,null,function*(){var f,u;const e=yield fetch(s),t=xe(s.headers);if(t==null||e.status!==206||e.body==null)return e;const{body:n,status:r,statusText:i,headers:o}=e,a=(f=dt(o))==null?void 0:f.end,c=100;let h=(u=t.start)!=null?u:0,d=n.getReader(),p=null;const l=new ReadableStream({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=(yield fetch(s)).body.getReader());const{value:g,done:x}=yield d.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)}});return new Response(l,{status:r,statusText:i,headers:o})})}class Sn{constructor(e){this.logger=e}start(e,t){let n;const r=Date.now(),i=c=>{var f,u,w,g,x,m,v,y,C,D,P;const h=t.headers.get("Range"),d=h==null?null:en(h),p=n==null?void 0: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?void 0:d.start)!=null?w:-1,range_end:(g=d==null?void 0: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?void 0: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=>{const h=Date.now();i(S({t_total:N(h,r)},ue(c)))},onResponse:c=>{n=c,n.bodyReadResult.then(h=>{var l;const d=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){return b(this,null,function*(){const r=this.start(e,t);try{const i=yield n();return r.onResponse(i),i}catch(i){throw r.onError(i),i}})}log(e){return this.logger.log("DownloadLog",e)}}class Pr{constructor(e){R(this,"downloadLogger");this.downloadLogger=new Sn(e)}fetch(e,t,n=!0){return b(this,null,function*(){return this.downloadLogger.wrap(e,t,()=>b(this,null,function*(){const h=t,{url:r}=h,i=Pt(h,["url"]),o=new Request(r,S(S({},n?xn:null),i)),a=yield Cn(o),c=Date.now();return e.set("downloadConnectionAt",c),e.set("downloadStartTransferAt",c),Ue(a)}))})}}const xn={mode:"cors",credentials:"omit"};class En{constructor(e,t=!0,n=Cn){R(this,"downloadLogger");this.https=t,this.nativeFetch=n,this.downloadLogger=new Sn(e)}fetch(e,t,n){return b(this,null,function*(){return this.downloadLogger.wrap(e,t,()=>b(this,null,function*(){e.set("downloadReqIP",n.host);const r=this.nativeFetch,i=_n(t,n,this.https),o=yield r(i),a=Date.now();return e.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=new URL(n),c=a.host,h=new Headers(r);a.protocol=t?"https:":"http:",a.host=`${e.host}:${t?e.https:e.http}`,a.pathname=`/${c}${a.pathname}`;let d=a.toString();if(h.has("X-Miku-Agent")){const p=h.get("X-Miku-Agent");h.delete("X-Miku-Agent");const l=d.includes("?")?"&":"?",f=["X-Miku-Agent",p].map(encodeURIComponent).join("=");d=d+l+f}return new Request(d,j(S({},xn),{headers:h,method:i,signal:o}))}function Or(s){const e=[],t=s.split(` +`).map(r=>r.trim()).filter(r=>r.length>0);if(t[0]!=="#EXTM3U")throw new Error("Invalid Extended M3U Playlist");let n=null;for(const r of t){if(r.startsWith("#")){r.startsWith("#EXTINF:")&&(n=r);continue}n!=null&&(e.push({uri:r}),n=null)}return e}const Tn=E("client"),Et=O("client");class Hr{constructor(e,t){R(this,"fileTasks",new Map);R(this,"cache");R(this,"cdnResolver");R(this,"liveResolver");R(this,"nativeHttpClient");R(this,"http");R(this,"liveHttp");R(this,"patterns");R(this,"logger");var o,a,c,h,d;this.config=t,t!=null&&t.debug&&M(),this.cache=new rr(t==null?void 0:t.cache),this.logger=(o=t==null?void 0:t.logger)!=null?o:new Gt(e),this.cdnResolver=(a=t==null?void 0:t.resolver)!=null?a:new js(this.logger,e,t==null?void 0:t.dnsResolver,t==null?void 0:t.cacheUrl),this.liveResolver=(c=t==null?void 0:t.liveResolver)!=null?c:new Mr(this.logger,e,t==null?void 0:t.scheduler),this.nativeHttpClient=new Pr(this.logger);const n=(h=t==null?void 0:t.httpClient)!=null?h:new En(this.logger),r=(d=t==null?void 0:t.liveHttpClient)!=null?d:new En(this.logger);this.patterns=S(S({},zt),t==null?void 0:t.patterns),this.http=new fn(this.logger,n,this.cdnResolver,6e3);const i=2e3;this.liveHttp=new fn(this.logger,r,this.liveResolver,i)}prepare(e){return b(this,null,function*(){return Promise.all(e.map(t=>this.cdnResolver.resolveDomain(new G,t))).catch(t=>{Et("prepare failed:",t)})})}createTask(e,t){const n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),new wn(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",1),this.startTask(r,i)))}createLiveTask(e,t){const n=e.indexOf("#");return n>=0&&(e=e.slice(0,n)),new wn(e,t!=null?t:null,this.logger,(r,i)=>(r.set("taskType",2),this.startLiveTask(r,i)))}startTask(e,t){return b(this,null,function*(){const n=new URL(t.url).hostname,r=yield this.cdnResolver.getCacheKey(t.url,n);let i=this.fileTasks.get(r);if(i==null){const o=()=>b(this,null,function*(){var c;const a=yield this.cdnResolver.getMediaOptimization(n);return S(S(S({},xr),a),(c=this.config)==null?void 0:c.mediaOptimization)});i=new Er(this.cache,this.nativeHttpClient,this.http,r,t.url,this.patterns,o),this.fileTasks.set(r,i)}return i.startTask(e,t)})}saveM3u8SegmentResult(e,t){return b(this,null,function*(){const n=yield _s(t),i=Or(n).map(o=>jn(o.uri,e));Tn("saveM3u8SegmentResult",Be(e),i.map(Be)),yield this.liveResolver.saveM3u8SegmentResult(e,i)})}startLiveTask(e,t){return b(this,null,function*(){var h,d;const n={};t.range!=null&&(n.Range=Ee({start:t.range.start,end:t.range.end==null?null:t.range.end-1}));const r=new ie(t.url,{method:"GET",headers:n,signal:t.signal});let i,a=((d=(h=this.config)==null?void 0:h.liveOptimization)!=null?d:!0)&&Pe(t.url)&&!this.liveResolver.hasResult(t.url);if(a){Tn("use nativeClient for",t.url);const p=this.nativeHttpClient.fetch(e,r);this.liveHttp.do(new G(e),r).catch(l=>{Et("do failed when prefetch for liveOptimization:",l)}),i=yield p}else i=yield this.liveHttp.do(e,r);if(i.body==null)throw new Error("Body expected");if(i.status!==200&&i.status!==206)throw new Error(`Invalid response, status: ${i.status}`);let c=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}return new pn(c,re(i.headers),wt(i.headers),i.headers.get("Content-Type"),i)})}dispose(){this.cache.dispose()}}function Nr(s){return s&&s.mikuDeliveryProxy===!0}const zr=E("proxy/common");function Ur(s,e){return b(this,null,function*(){var u;const{browser:t}=tt(navigator.userAgent);if(t.name==="Firefox"&&e.headers.get("Range")){zr("Short circuit for Firefox:",e.url);const w=yield s.cdnResolver.resolve(new G,e.url),g=_n(e,w);return Response.redirect(g.url)}const n=xe(e.headers),r=n==null?void 0:{start:n.start,end:n.end==null?null:n.end+1},i=s.createTask(e.url,r!=null?r:void 0);let o;try{o=yield i.start(e.signal)}catch(w){if(w instanceof $e){const{status:g,statusText:x,headers:m,body:v,underlayer:y}=w.response;return y!=null?y:new Response(v,{status:g,statusText:x,headers:m})}throw w}let{stream:a,contentType:c,size:h,fileSize:d,underlayer:p}=o;if(!Re())return p.underlayer;let l=nn(p==null?void 0:p.headers);return l.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})),new Response(a,{status:r==null?200:206,statusText:r==null?"OK":"Partial Content",headers:l})})}function $r(s,e){return b(this,null,function*(){var l;const t=xe(e.headers),n=t==null?void 0:{start:t.start,end:t.end==null?null:t.end+1},r=s.createLiveTask(e.url,n!=null?n:void 0);let{stream:i,contentType:o,size:a,fileSize:c,underlayer:h}=yield r.start(e.signal);if(!He())return h.underlayer;let d=new Headers(h==null?void 0:h.headers);return d.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})),new Response(i,{status:n==null?200:206,statusText:n==null?"OK":"Partial Content",headers:d})})}const Fr="MIKU_DELIVERY_PROXY_CONFIG";function Wr(s){const e=s.split("?")[1];if(!e)throw new Error("Invalid script url");const n=new URLSearchParams(e).get(Fr);if(n==null)throw new Error("Invalid script url: no config info");const r=JSON.parse(n),i=o=>o==null?void 0:o.map(({source:a,flags:c})=>new RegExp(a,c));return j(S({},r),{patterns:r.patterns==null?void 0:Fn(r.patterns,o=>i(o))})}function qr(s){return Array.isArray(s)?{cdn:s,live:[]}:S({cdn:[],live:[]},s)}function An(s,e){const t=s.hostname;return e.includes("*")||e.includes(t)}const jr=O("proxy/statistics");class Kr{constructor(){R(this,"windowFetchItemsMap",new Map)}onFetchItem(e,t,n,r,i){const o={url:t,ecdn:r,fallback:i!=null?i:!1,size:re(n.headers)};let a=this.windowFetchItemsMap.get(e);a==null&&(a=[],this.windowFetchItemsMap.set(e,a)),a.push(o)}onWindowClose(e){this.windowFetchItemsMap.delete(e)}getFetchItems(e){return this.windowFetchItemsMap.get(e)||[]}}function Dn(t){return b(this,arguments,function*(s,e={}){const{url:n,headers:r,method:i,redirect:o,signal:a}=s,c=self.location.host,h=new URL(n).host;if(c===h)return fetch(s,e);const d=new Request(n,S({mode:"cors",credentials:"omit",headers:r,method:i,redirect:o,signal:a},e));try{return yield fetch(d)}catch(p){return jr("Request with CORS failed:",n,p),fetch(s)}})}class Vr{constructor(e){this.logger=e}log(e){return this.logger.log("PageStatusLog",e)}}const Ve=E("proxy/sw"),ne=new Map,Ae=self,Q=Wr(Ae.location.href),_t=qr(Q.domains),In=S(S({},zt),Q.patterns),Ge=new Hr(Q.app,S({debug:Q.debug,patterns:Q.patterns},Q.client));Ge.prepare(_t.cdn);const Gr=Ge.nativeHttpClient,De=new Kr,Qr=new Gt(Q.app),me=new Vr(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);const e=s.request;if(e.method==="GET"){const t=new URL(e.url),n=new AbortController;if(Nt(n,s.request.signal),Object.defineProperty(e,"signal",{value:n.signal}),he.whenRemoved(s.clientId,()=>n.abort(new Wn(`Source client ${s.clientId} closed`))),An(t,_t.cdn)&&Ut(t,In))return Xr(s,e);if(An(t,_t.live)&&Ut(t,In,["live"]))return Yr(s,e)}e.method==="GET"&&Q.statistics&&s.respondWith(Dn(e).then(t=>{var n;return De.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=>{var n;return me.log({r_id:(n=ne.get(s.clientId))!=null?n:"",text:t instanceof Error?t.message:"",code:-1,url:e.url}),t}))})),Ae.addEventListener("message",s=>b(this,null,function*(){if(s.source instanceof WindowClient&&!!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":const e=s.source.id,t=De.getFetchItems(e),n=yield he.get(e);if(n==null)throw new Error(`Invalid window client ID: ${e}`);const r={mikuDeliveryProxy:!0,type:"window-fetch-items",items:t};n.postMessage(r);break;case"get-perf-rid":ne.set(s.source.id,s.data.rid)}}));function Xr(s,e){Ve("use cdn",e.url),s.respondWith(Ur(Ge,e).then(t=>{var n;return Q.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*(){var n,r,i;if(Ct(t))if(Ve("Use fallback fetch for request",e.url,", error:",t),Q.statistics)try{const o=yield Dn(e);return De.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){throw me.log({r_id:(r=ne.get(s.clientId))!=null?r:"",text:o instanceof Error?o.message:"",code:-1,url:e.url}),o}else{const o=new G;o.set("taskDomain",new URL(e.url).hostname);const{body:a,status:c,statusText:h,headers:d,underlayer:p}=yield Gr.fetch(o,Is(e),!1);return Re()?new Response(a,{status:c,statusText:h,headers:d}):p}throw Q.statistics&&me.log({r_id:(i=ne.get(s.clientId))!=null?i:"",text:t instanceof Error?t.message:"",code:-1,url:e.url}),t})))}function Yr(s,e){s.respondWith($r(Ge,e).then(void 0,t=>b(this,null,function*(){if(Ct(t))return Ve("Use fallback fetch for request",e.url,", error:",t),fetch(e);throw t})))}})(); diff --git a/docs/README.md b/docs/README.md index afd702aa2..8bec6fbdc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -17,13 +17,13 @@ pageClass: custom-page-class
- +
Android版
- +
iOS版
@@ -40,11 +40,11 @@ pageClass: custom-page-class
- +
钉钉小程序版
- +
京东小程序版
- +
- +
@@ -121,7 +121,12 @@ pageClass: custom-page-class - + + + + + + ## 为什么要选择uni-app? @@ -130,7 +135,7 @@ pageClass: custom-page-class
- +
开发者/案例数量更多
@@ -140,7 +145,7 @@ pageClass: custom-page-class
- +
平台能力不受限
@@ -150,7 +155,7 @@ pageClass: custom-page-class
- +
性能体验优秀
@@ -161,7 +166,7 @@ pageClass: custom-page-class
- +
周边生态丰富
@@ -172,7 +177,7 @@ pageClass: custom-page-class
- +
学习成本低
@@ -181,7 +186,7 @@ pageClass: custom-page-class
- +
开发成本低
@@ -210,14 +215,14 @@ pageClass: custom-page-class 从下面`uni-app`功能框架图可看出,`uni-app`在跨平台的过程中,不牺牲平台特色,可优雅的调用平台专有能力,真正做到海纳百川、各取所长。 -![](https://web-assets.dcloud.net.cn/unidoc/zh/uni-function-diagram.png) +![](https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uni-function-diagram.png) ## 一套代码,运行到多个平台 `uni-app`实现了一套代码,同时运行到多个平台;如下图所示,一套代码,同时运行到iOS模拟器、Android模拟器、web、微信开发者工具、支付宝小程序Studio、百度开发者工具、字节跳动开发者工具、QQ开发者工具(底部每个终端选项卡,代表1个终端模拟器): -![](https://web-assets.dcloud.net.cn/unidoc/zh/dev1x8.jpg) +![](https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/dev1x8.jpg) 实际运行效果如下(点击图片可放大): -![](https://web-assets.dcloud.net.cn/unidoc/zh/uni-app-multiport.jpg) +![](https://qiniu-web-assets.dcloud.net.cn/unidoc/zh/uni-app-multiport.jpg) -- GitLab