UNPKG

@discoveryjs/discovery

Version:

Frontend framework for rapid data (JSON) analysis, shareable serverless reports and dashboards

2 lines (1 loc) 29.9 kB
var{toString:Qt,hasOwnProperty:Ee}=Object.prototype;var O=Object.hasOwn||((e,t)=>Ee.call(e,t));function G(){return[performance.timeOrigin.toString(16),(1e4*performance.now()).toString(16),Math.random().toString(16).slice(2)].join("-")}var E=class{subscriber;value;constructor(t,r){this.subscriber=null,this.value=t,this.shouldUpdate=typeof r=="function"?r:this.shouldUpdate}get readonly(){let t=this;return{subscribe:this.subscribe.bind(this),subscribeSync:this.subscribeSync.bind(this),unsubscribe:this.unsubscribe.bind(this),get value(){return t.value}}}subscribe(t){return this.subscriber={callback:t,subscriber:this.subscriber},()=>this.unsubscribe(t)}subscribeSync(t){let r=this.subscribe(t);return t(this.value,r),r}unsubscribe(t){let r=this,n=this.subscriber;for(;n!==null;){if(n.callback===t){n.callback=null,r.subscriber=n.subscriber;break}r=n,n=n.subscriber}}shouldUpdate(t,r){return t!==r}set(t){return this.#r(t)!==!1}asyncSet(t){let r=this.#r(t);return r===!1?Promise.resolve(!1):Promise.all(r).then(()=>!0)}#r(t){if(!this.shouldUpdate(t,this.value))return!1;let r=[],n=this.subscriber;for(this.value=t;n!==null;){let{callback:a}=n;a!==null&&r.push(a(t,()=>this.unsubscribe(a))),n=n.subscriber}return r}};var X=Ae("localStorage");function Ae(e){let t=Ce(e);return function(n){return t?.getItem(n)??null}}function Ce(e){let t="__storage_test__"+Math.random(),r;try{r=window[e]}catch{return null}try{r.setItem(t,t),r.removeItem(t)}catch(n){if(!(n instanceof DOMException&&(n.code===22||n.code===1014||n.name==="QuotaExceededError"||n.name==="NS_ERROR_DOM_QUOTA_REACHED")&&r.length!==0))return null}return r}var De="discoveryjs:color-scheme",Le=Object.freeze(["auto","light","dark"]);function Pe(e){return Le.includes(e)}function Oe(){return matchMedia("(prefers-color-scheme:dark)")}function Ne(e,t){let r=e;switch(e){case!0:e="dark";break;case!1:e="light";break;case"disabled":case"disable":case"off":e="light-only";break;case"only":e="dark-only";break}if(r!==e&&console.warn(`Used legacy value "${r}" for ColorSheme, value replaced for "${e}"`),e!=="light-only"&&e!=="dark-only"&&t){let n=X(De);Pe(n)&&(e=n)}return e}function Ue(e){let t=je(e);return t==="auto"?Oe().matches?"dark":"light":t}function je(e){switch(e){case"auto":return"auto";case"dark":case"dark-only":return"dark";case"light":case"light-only":default:return"light"}}function N(e="auto",t=!1){return Ue(Ne(e,t))}var Y=new WeakMap,Ie={"font-family":"Tahoma, Verdana, Arial, sans-serif","font-size":"14px","line-height":"1.6","-webkit-text-size-adjust":"none","text-size-adjust":"none","background-color":"var(--discovery-background-color, white)",color:"var(--discovery-color, black)"},Me={"--discovery-background-color":"#242424","--discovery-color":"#cccccc"};function Z(e,t,r){t in r||(r[t]=[e.style.getPropertyValue(t),e.style.getPropertyPriority(t)])}function ee(e,t){let r=Y.get(e)||Object.create(null),n=N(t)==="dark";for(let[a,s]of Object.entries(Ie))Z(e,a,r),e.style.setProperty(a,s);for(let[a,s]of Object.entries(Me))Z(e,a,r),n?e.style.setProperty(a,s):e.style.removeProperty(a);return Y.set(e,r),n}function T(e,t,r){let n=document.createElement(e);typeof t=="string"&&(t={class:t});for(let a in t)if(O(t,a)){let s=t[a];if(typeof s>"u")continue;typeof s=="function"?n.addEventListener(a.slice(2),s):n.setAttribute(a,s)}return Array.isArray(r)?n.append(...r):typeof r=="string"&&(n.innerHTML=r),n}async function te(e,t){let r=T("style",null,":host{display:none}"),n=new Set;Array.isArray(t)&&(e.append(...t.map(a=>{switch(typeof a=="string"&&(a={type:"style",content:a}),a.type){case"style":case"inline":return T("style",{media:a.media},a.content);case"link":case"external":{let s,i,l=new Promise((o,u)=>{s=o,i=u});return n.add(l),T("link",{rel:"stylesheet",href:a.href,media:a.media,onerror(o){n.delete(l),i(o)},onload(){n.delete(l),s()}})}default:throw new Error(`Unknown type "${a.type}" for a style descriptor`)}})),n.size&&(e.append(r),await Promise.all(n),r.remove()))}function Re(e){if(!e||typeof e!="object")return"value is not an object";let{name:t,test:r,decode:n}=e;return typeof t!="string"?"missed name":typeof r!="function"?"missed test function":typeof n!="function"?"missed decode function":!1}function Ve(e){let t=Re(e);if(t)throw new Error(`Bad encoding config${e?.name?` "${e.name}"`:""}: ${t}`);let{name:r,test:n,streaming:a,decode:s}=e;return Object.freeze(a?{name:r||"unknown",test:n,streaming:!0,decode:s}:{name:r||"unknown",test:n,streaming:!1,decode:s})}function re(e){if(!e)return[];if(!Array.isArray(e))throw new Error("Encodings must be an array");return e.map(Ve)}function q(e){return typeof e=="object"&&e!==null&&(typeof e[Symbol.iterator]=="function"||typeof e[Symbol.asyncIterator]=="function")}var C=1,ze=2,Fe=new TextDecoder;function Be(e,t){return e.name==="SyntaxError"&&t.jsonParseOffset&&(e.message=e.message.replace(/at position (\d+)/,(r,n)=>"at position "+(Number(n)+t.jsonParseOffset))),e}function He(e,t){let r=e.length;e.length+=t.length;for(let n=0;n<t.length;n++)e[r+n]=t[n]}async function U(e){let t=typeof e=="function"?e():e;if(q(t)){let r=new _;try{for await(let n of t){if(typeof n!="string"&&!ArrayBuffer.isView(n))throw new TypeError("Invalid chunk: Expected string, TypedArray or Buffer");r.push(n)}return r.finish()}catch(n){throw Be(n,r)}}throw new TypeError("Invalid chunk emitter: Expected an Iterable, AsyncIterable, generator, async generator, or a function returning an Iterable or AsyncIterable")}var _=class{constructor(){this.value=void 0,this.valueStack=null,this.stack=new Array(100),this.lastFlushDepth=0,this.flushDepth=0,this.stateString=!1,this.stateStringEscape=!1,this.pendingByteSeq=null,this.pendingChunk=null,this.chunkOffset=0,this.jsonParseOffset=0}parseAndAppend(t,r){this.stack[this.lastFlushDepth-1]===C?(r&&(this.jsonParseOffset--,t="{"+t+"}"),Object.assign(this.valueStack.value,JSON.parse(t))):(r&&(this.jsonParseOffset--,t="["+t+"]"),He(this.valueStack.value,JSON.parse(t)))}prepareAddition(t){let{value:r}=this.valueStack;if(Array.isArray(r)?r.length!==0:Object.keys(r).length!==0){if(t[0]===",")return this.jsonParseOffset++,t.slice(1);if(t[0]!=="}"&&t[0]!=="]")return this.jsonParseOffset-=3,"[[]"+t}return t}flush(t,r,n){let a=t.slice(r,n);if(this.jsonParseOffset=this.chunkOffset+r,this.pendingChunk!==null&&(a=this.pendingChunk+a,this.jsonParseOffset-=this.pendingChunk.length,this.pendingChunk=null),this.flushDepth===this.lastFlushDepth)this.flushDepth>0?this.parseAndAppend(this.prepareAddition(a),!0):(this.value=JSON.parse(a),this.valueStack={value:this.value,prev:null});else if(this.flushDepth>this.lastFlushDepth){for(let s=this.flushDepth-1;s>=this.lastFlushDepth;s--)a+=this.stack[s]===C?"}":"]";this.lastFlushDepth===0?(this.value=JSON.parse(a),this.valueStack={value:this.value,prev:null}):this.parseAndAppend(this.prepareAddition(a),!0);for(let s=this.lastFlushDepth||1;s<this.flushDepth;s++){let i=this.valueStack.value;if(this.stack[s-1]===C){let l;for(l in i);i=i[l]}else i=i[i.length-1];this.valueStack={value:i,prev:this.valueStack}}}else{a=this.prepareAddition(a);for(let s=this.lastFlushDepth-1;s>=this.flushDepth;s--)this.jsonParseOffset--,a=(this.stack[s]===C?"{":"[")+a;this.parseAndAppend(a,!1);for(let s=this.lastFlushDepth-1;s>=this.flushDepth;s--)this.valueStack=this.valueStack.prev}this.lastFlushDepth=this.flushDepth}push(t){if(typeof t!="string"){if(this.pendingByteSeq!==null){let s=t;t=new Uint8Array(this.pendingByteSeq.length+s.length),t.set(this.pendingByteSeq),t.set(s,this.pendingByteSeq.length),this.pendingByteSeq=null}if(t[t.length-1]>127)for(let s=0;s<t.length;s++){let i=t[t.length-1-s];if(i>>6===3){s++,(s!==4&&i>>3===30||s!==3&&i>>4===14||s!==2&&i>>5===6)&&(this.pendingByteSeq=t.slice(t.length-s),t=t.slice(0,-s));break}}t=Fe.decode(t)}let r=t.length,n=0,a=0;e:for(let s=0;s<r;s++){if(this.stateString){for(;s<r;s++)if(this.stateStringEscape)this.stateStringEscape=!1;else switch(t.charCodeAt(s)){case 34:this.stateString=!1;continue e;case 92:this.stateStringEscape=!0}break}switch(t.charCodeAt(s)){case 34:this.stateString=!0,this.stateStringEscape=!1;break;case 44:a=s;break;case 123:a=s+1,this.stack[this.flushDepth++]=C;break;case 91:a=s+1,this.stack[this.flushDepth++]=ze;break;case 93:case 125:a=s+1,this.flushDepth--,this.flushDepth<this.lastFlushDepth&&(this.flush(t,n,a),n=a);break;case 9:case 10:case 13:case 32:n===s&&n++,a===s&&a++;break}}a>n&&this.flush(t,n,a),a<r&&(this.pendingChunk!==null?this.pendingChunk+=t:this.pendingChunk=t.slice(a,r)),this.chunkOffset+=r}finish(){return this.pendingChunk!==null&&(this.flush("",0,0),this.pendingChunk=null),this.value}};var $e=typeof Object.hasOwn=="function"?Object.hasOwn:(e,t)=>Object.hasOwnProperty.call(e,t),Ke={8:"\\b",9:"\\t",10:"\\n",12:"\\f",13:"\\r",34:'\\"',92:"\\\\"},br=Uint8Array.from({length:2048},(e,t)=>$e(Ke,t)?2:t<32?6:t<128?1:2);var $=Object.freeze({name:"json",test:()=>!0,streaming:!0,decode:U});var Je=new Uint8Array([0,0,74,83,79,78,88,76]),ie=9;var Qe=268435455;var j=2,D=4,K=8,P=16,I=32,M=64,A=128,Ge=0,Xe=1,Ye=2,Ze=3,et=4,tt=5,rt=6,nt=8,st=9,at=10,it=11,ot=12;var lt=224,ct=7936,oe=0,W=1,ut=2,ht=3,ft=4,dt=5,le=6,ce=7,gt=8;var ne=16,se=32,jr=~P,pt=j|I|M,ue=new Uint8Array(256).map((e,t)=>{for(let r=0;r<8;r++)e+=t>>r&1;return e});var he=new Uint32Array(16),Ir=he.subarray(0,8),Mr=he.subarray(8,16);var Rr=new TextEncoder;var Vr=Math.floor(Number.MAX_SAFE_INTEGER/2),mt=new Uint8Array(33);for(let e=0;e<33;e++)mt[32-e]=Math.ceil(e/7)||1;function ae(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}var fe=new Map,zr=Object.freeze({hasInlinedEntries:!1,columns:fe}),Fr=Object.freeze({hasInlinedEntries:!0,columns:fe});var Br=yt();function yt(){return new Proxy(Object.create(null),{get(e,t){return Object.hasOwn(e,t)?Reflect.get(...arguments):e[t]=0}})}var Hr=Object.hasOwnProperty;function bt(e,t,r,n=new Array(r)){let a=t&15,s=t&48,i=r,l=0,c=0;switch(s){case ne:{l=n[0]=e.readIntVar(),i--,c=1;break}case se:{l=e.readIntVar();break}}switch(a){case ut:{for(let o=0;o<i;o++)n[c+o]=e.readVlq();break}case ht:{for(let o=0;o<i;o++)n[c+o]=e.readIntVar();break}case ft:{let o=e.readBytes(Math.ceil(i/2));for(let u=0,h=0;u<i;u++)h=u&1?h>>4:o[u>>1],n[c+u]=h&8?e.readVlq()*8+(h&7):h&7;break}case dt:{let o=e.readBytes(Math.ceil(i/2));for(let u=0,h=0;u<i;u++){h=u&1?h>>4:o[u>>1];let g=h&4?-1:1;n[c+u]=h&8?g*(e.readVlq()*4+(h&3)):g*(h&3)}break}case le:{let o=t>>8,u=(1<<o)-1,h=e.readBytes(Math.ceil(i*o/8)),g=0,d=0,m=0;for(let y=0;y<i;y++){for(;d<o;)m|=h[g++]<<d,d+=8;n[c+y]=m&u,m>>=o,d-=o}break}case ce:{let o=t>>8,u=(1<<o)-1,h=e.readBytes(Math.ceil(i*o/8)),g=0,d=0,m=0;for(let y=0;y<i;y++){for(;d<o;)m|=h[g++]<<d,d+=8;n[c+y]=m&1?-((m&u)>>1):(m&u)>>1,m>>=o,d-=o}break}case gt:{let o=n[0]=e.readIntVar(),u=e.readIntVar();for(let h=1;h<r;h++)n[h]=o+=u;break}case oe:case W:{let o=a===W,u=t>>8,h=o?t&ct|u&lt:u;if(ue[u]>1){let g=e.readTypeIndex(i,h);for(let d=0;d<i;d++)n[c+d]=e.readNumber(g[d])}else{let g=31-Math.clz32(h);for(let d=0;d<i;d++)n[c+d]=e.readNumber(g)}break}default:throw new Error(`Unknown numeric array encoding method: ${a}`)}switch(s){case ne:{n[0]=l;for(let o=1;o<r;o++)n[o]+=n[o-1];break}case se:{for(let o=0;o<r;o++)n[o]+=l;break}}return n}function wt(e){let t=St(e.readBytes(e.readVlq())),r=e.readNumericArray(),n=e.readNumericArray(),a=e.readNumericArray(),s=new Array(r);for(let i=0,l=0,c=0,o="";i<r.length;i++){let u=r[i],h=t(u>>2);u&2&&(h=o.slice(0,n[l++])+h),u&1&&(h=h+o.slice(-a[c++])),s[i]=h,o=h}return s}function St(e){function t(c){if(a!==null){let o=c;c=new Uint8Array(a.length+o.length),c.set(a),c.set(o,a.length),a=null}if(c[c.length-1]>127)for(let o=0;o<c.length;o++){let u=c[c.length-1-o];if(u>>6===3){o++,(o!==4&&u>>3===30||o!==3&&u>>4===14||o!==2&&u>>5===6)&&(a=c.slice(c.length-o),c=c.subarray(0,-o));break}}return r.decode(c)}let r=new TextDecoder("utf8",{ignoreBOM:!0}),n=16*1024*1024,a=null,s=0,i="",l=0;return function(c){for(;c>i.length-l;)i=i.slice(l)+t(e.subarray(s,s+=n)),l=0;return i.slice(l,l+=c)}}var L=12;function kt(e){return e===ie}function de(e){try{let{version:t}=ge(e);if(kt(t))return!0;throw new Error(`Unsupported jsonxl version "${t}", expected "${ie}"`)}catch{return!1}}function ge(e){if(e.byteLength<L)throw new Error(`Header length must be at least ${L} bytes`);let t=new Uint8Array(e.buffer,e.byteOffset,L);if(t.subarray(0,8).some((s,i)=>s!==Je[i]))throw new Error("Bad magic number");let r=new DataView(t.buffer,t.byteOffset,L),n=r.getUint16(8,!0),a=r.getUint16(10,!0);return{version:n,flags:a,headerSize:L}}var xt=class{constructor(e,t){this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.bytes=e,this.pos=0,typeof t=="function"&&t(this),this.consumeHeader(),this.loadStrings(),this.loadArrayLengths(),this.loadArrayHeaders(),this.loadObjectEntries()}consumeHeader(){let{version:e,flags:t,headerSize:r}=ge(this.view);return this.pos+=r,{version:e,flags:t}}loadStrings(){this.strings=wt(this),this.stringRefs=this.readNumericArray(),this.stringRefsCursor=0}loadArrayHeaders(){this.arrayHeaders=this.readNumericArray(),this.arrayHeaderRefs=this.readNumericArray(),this.arrayHeaderRefsCursor=0}loadArrayLengths(){this.arrayLengths=this.readNumericArray(),this.arrayLengthsCursor=0}loadObjectEntries(){let e=this.readVlq(),t=this.readVlq();this.objectEntries=new Array(e),this.objectKeys=t?this.stringRefs.slice(-t).map(r=>this.strings[r]):[];for(let r=0;r<e;r++)this.objectEntries[r]={dict:this.readNumericArray(),refs:this.readNumericArray(),cursor:0}}readString(){return this.strings[this.stringRefs[this.stringRefsCursor++]]}readArrayHeader(){return this.arrayHeaders[this.arrayHeaderRefs[this.arrayHeaderRefsCursor++]]}readArrayLength(){return this.arrayLengths[this.arrayLengthsCursor++]}readObjectEntry(e){let t=this.objectEntries[e],r=t.refs[t.cursor++],n=t.dict[r];return n===0?null:{key:this.objectKeys[n>>8],type:n&255}}readBytes(e){return this.bytes.subarray(this.pos,this.pos+=e)}readTypeIndex(e,t,r){let n=0,a=0,s=0;for(;t>0;)t&1&&(n|=s<<(a++<<2)),s++,t>>=1;let i=new Uint8Array(e),l=32-Math.clz32(a-1),c=(1<<l)-1,o=this.readBytes(Math.ceil(l*e/8)),u=0,h=0,g=0;for(let d=0;d<e;d++){g<l&&(h|=o[u++]<<g,g+=8);let m=n>>((h&c)<<2)&15;i[d]=r?1<<m:m,h>>=l,g-=l}return i}readVlq(){let e=this.view.getUint8(this.pos);if((e&1)===0)e=e>>1,this.pos+=1;else if((e&2)===0)e=this.view.getUint8(this.pos+1)<<6|e>>2,this.pos+=2;else if((e&4)===0)e=this.view.getUint16(this.pos+1,!0)<<5|e>>3,this.pos+=3;else{let t=this.view.getUint32(this.pos,!0);e=t>>>3&Qe,this.pos+=4,t>>>31&&(e+=this.readUintVar()*(1<<28))}return e}readUintVar(){let e=this.view.getUint8(this.pos++),t=e&127,r=128;for(;e&128;)e=this.view.getUint8(this.pos++),t+=(e&127)*r,r*=128;return t}readIntVar(){let e=this.view.getUint8(this.pos++),t=e&128?this.readUintVar()*64:0,r=(e&127)>>1;return e&1?-(r+t):r+t}readUint8(){let e=this.view.getUint8(this.pos);return this.pos++,e}readInt8(){let e=this.view.getInt8(this.pos);return this.pos++,e}readUint16(){let e=this.view.getUint16(this.pos,!0);return this.pos+=2,e}readInt16(){let e=this.view.getInt16(this.pos,!0);return this.pos+=2,e}readUint24(){let e=this.view.getUint16(this.pos,!0)|this.view.getUint8(this.pos+2)<<16;return this.pos+=3,e}readInt24(){let e=this.view.getUint16(this.pos,!0),t=this.view.getUint8(this.pos+2),r=t&128?(t<<16|e)-16777216:t<<16|e;return this.pos+=3,r}readUint32(){let e=this.view.getUint32(this.pos,!0);return this.pos+=4,e}readInt32(){let e=this.view.getInt32(this.pos,!0);return this.pos+=4,e}readFloat32(){let e=this.view.getFloat32(this.pos,!0);return this.pos+=4,e}readFloat64(){let e=this.view.getFloat64(this.pos,!0);return this.pos+=8,e}readNumber(e){switch(e){case Ge:return this.readUint8();case Xe:return this.readUint16();case Ye:return this.readUint24();case Ze:return this.readUint32();case et:return this.readUintVar();case nt:return this.readInt8();case st:return this.readInt16();case at:return this.readInt24();case it:return this.readInt32();case ot:return this.readIntVar();case tt:return this.readFloat32();case rt:return this.readFloat64()}}readNumericArrayEncoding(){let e=this.readUint8();switch(e&15){case oe:case W:case le:case ce:e|=this.readUint8()<<8;break}return e}readNumericArray(e=this.readVlq()){if(e===0)return[];let t=this.readNumericArrayEncoding();return this.readNumbers(t,e)}readNumbers(e,t,r){return bt(this,e,t,r)}};function pe(e,t){function r(l={}){let c=0,o;for(;o=s.readObjectEntry(c++);)l[o.key]=a(o.type);return l}function n(l=s.readArrayLength()){if(l===0)return[];let c=s.readArrayHeader(),o=c>>16,u=c&65535,h=o&1,g=o>>5&1,d=o>>9&1,m=o>>1&255|(o&1)<<4,y=new Array(l),p=ue[m]>1?s.readTypeIndex(l,m,!0):null;if(m&pt)if(p===null)switch(m){case j:y.fill(null);break;case I:y.fill(!0);break;case M:y.fill(!1);break}else for(let f=0;f<l;f++)switch(p[f]){case j:y[f]=null;break;case I:y[f]=!0;break;case M:y[f]=!1;break}if(m&K)for(let f=0;f<l;f++)(p===null||p[f]===K)&&(y[f]=s.readString());if(m&D)if(m===D)s.readNumbers(u,l,y);else{let f=ae(p,D),b=s.readNumbers(u,f);for(let S=0,w=0;S<l;S++)p[S]===D&&(y[S]=b[w++])}if(m&A)if(d){let f=m===A?l:ae(p,A),b=s.readNumericArray(f),S=n();for(let w=0,v=0,k=0;w<l;w++)(p===null||p[w]===A)&&(y[w]=S.slice(k,k+=b[v++]))}else for(let f=0;f<l;f++)(p===null||p[f]===A)&&(y[f]=n());if(m&P){let f=m===P?y:[];for(let b=0,S=0;b<l;b++)(p===null||p[b]===P)&&(y[b]=f[S++]={});if(g){let b=s.readVlq(),S=new Array(b);for(let w=0;w<b;w++)S[w]=s.readString();for(let w=0;w<b;w++){let v=S[w],k=n(f.length);for(let x=0;x<f.length;x++)k[x]!==void 0&&(f[x][v]=k[x])}}if(h)for(let b=0;b<f.length;b++)r(f[b])}return y}function a(l){switch(1<<(l&7)){case j:return null;case K:return s.readString();case D:return s.readNumber(l>>3);case P:return r();case I:return!0;case M:return!1;case A:return n()}}let s=new xt(e,t),i=a(s.readUint8());if(s.pos!==e.byteLength)throw new Error("End of input is not reached");return i}var J=Object.freeze({name:"jsonxl/snapshot9",test:de,streaming:!1,decode:pe});var me=[{name:"gzip",test:e=>e[0]===31&&e[1]===139&&e[2]===8,createTransformStream:()=>new DecompressionStream("gzip")},{name:"zlib",test:e=>(e[0]&15)===8&&e[0]>>4<=7&&(e[0]<<8|e[1])%31===0,createTransformStream:()=>new DecompressionStream("deflate")}];function vt(e){return e.reduce((t,r)=>t+r.byteLength,0)}function Et(e,t){switch(e.length){case 0:return;case 1:return e[0];default:{let r=new Uint8Array(t||vt(e)),n=0;for(let a of e)r.set(a,n),n+=a.length;return r}}}async function ye(e){let t=[],r=0;for await(let n of e)t.push(n),r+=n.byteLength;return Et(t,r)}function At(e,t){if(typeof e!="string"){for(let r of t)if(r.test(e))return r}return null}var R=class{#r;#e;#t;#n;constructor(t,r){this.#r=t,this.#e=r,this.#t=null,this.#n=null}transform(t,r){if(this.#n===null){let n=At(t,this.#r);if(n===null)this.#n=Promise.resolve();else{let{readable:a,writable:s}=n.createTransformStream();this.#t=s.getWriter(),this.#n=a.pipeTo(new WritableStream({write(i){r.enqueue(i)},close(){r.terminate()},abort(i){r.error(i)}})),typeof this.#e=="function"&&this.#e(n.name)}}if(this.#t!==null)return this.#t.write(t);r.enqueue(t)}async flush(){this.#t!==null&&(this.#t.close(),this.#t=null),this.#n!==null&&(await this.#n,this.#n=null)}},Ct=1024*1024/4,V=class{#r;#e;#t;constructor(t,r=Ct){this.#r=t,this.#e="",this.#t=r}async transform(t,r){if(typeof this.#e!="string"&&await this.#s(r),typeof t=="string"){if(this.#e+=t,this.#n>=this.#t)return this.#s(r)}else this.#e=t,await this.#s(r)}async flush(t){await this.#s(t),await this.#r(!0)}get#n(){return this.#e.length}async#s(t){let r=this.#e;if(this.#n!==0){this.#e="";for(let n=0;n<r.length;){let a=n===0&&r.length-n<this.#t*1.5?r:r.slice(n,n+this.#t);t.enqueue(a),n+=a.length,await this.#r(!1,a.length)}}}};var z={stream:Rt,event:Vt,file:be,url:zt,push:Ft};function Dt(e){try{return new URL(e,location.origin).origin===location.origin}catch{return!1}}function Lt(e){return e.ok}function Pt(e){return e.headers.get("x-file-encoded-size")||e.headers.get("content-length")}function Ot(e){return e.headers.get("x-file-size")||(Dt(e.url)&&!e.headers.get("content-encoding")?e.headers.get("content-length"):void 0)}function Nt(e){return e.headers.get("x-file-created-at")||e.headers.get("last-modified")||void 0}function Ut(e){let t=e?Object.keys(e):[],r=["name","createdAt","elapsedTime","data"];return!(t.length!==4||t.some(n=>!r.includes(n)))}function jt(e,t,{size:r,compression:n,encoding:a}){let s=null;if(Ut(e)){let{data:p,...f}=e;e=p,t={...t,createdAt:p.createdAt},s=f}let i=e,l=s||{},{type:c,name:o,encoding:u,size:h,encodedSize:g,createdAt:d,...m}=t||{};return{resource:{type:c||"unknown",name:o||"unknown",compression:n,encoding:a,...Number.isFinite(r)?{size:r}:null,...Number.isFinite(g)?{encodedSize:g}:null,createdAt:new Date((typeof d=="string"?Date.parse(d):d)||Date.now()),...m},meta:l,data:i}}async function It(e,t,r,n){let a=Date.now(),s=[...re(t),J,$],i=0,l=!1,c="unknown",o=0;await n("receiving",g(!1));let h=e.pipeThrough(new TransformStream(new V(d))).pipeThrough(new TransformStream(new R(me,p=>l=p))).getReader();try{let p=await h.read(),{value:f,done:b}=p;if(b)throw new Error("Empty payload");for(let{name:S,test:w,streaming:v,decode:k}of s)if(w(f)){c=S;let x=m(h,p);return{data:await(v?k(x):ye(x).then(y(k))),compression:l,encoding:c,size:o,decodingTime:i}}throw new Error("No matched encoding found for the payload")}finally{h.releaseLock()}function g(p){return{done:p,elapsed:Date.now()-a,units:"bytes",completed:o,total:r}}async function d(p,f=0){o+=f,await n("receiving",g(p))}async function*m(p,f){for(;;){let{value:b,done:S}=f||await p.read();if(f=void 0,S)break;let w=performance.now();yield b,i+=performance.now()-w}}function y(p){return async f=>{await n("decoding",void 0,c);let b=performance.now();try{return await p(f)}finally{i=performance.now()-b}}}}async function Mt(e,t){try{await t.asyncSet({stage:"request"});let r=new Date,{method:n,stream:a,resource:s,options:i,data:l}=await e(),c=new Date,o=s?.size,{encodings:u}=i||{},{data:h,compression:g=!1,encoding:d="unknown",size:m=void 0,decodingTime:y=0}=l?{data:l}:await It(a,u,Number(o)||0,(k,x,Q)=>t.asyncSet({stage:k,progress:x,step:Q}));await t.asyncSet({stage:"received"});let{data:p,resource:f,meta:b}=jt(h,s,{size:m,compression:g,encoding:d}),S=new Date,w=Number(S)-Number(r),v=Math.round(y||0);return{loadMethod:n,resource:f,meta:b,data:p,timings:{time:w,start:r,end:S,loadingTime:w-v,decodingTime:v,requestTime:Number(c)-Number(r),requestStart:r,requestEnd:c,responseTime:Number(S)-Number(c),responseStart:c,responseEnd:S}}}catch(r){throw console.error("[Discovery] Error loading data:",r),await t.asyncSet({stage:"error",error:r}),r}}function F(e,t){let r=new E({stage:"inited"});return{state:r,dataset:e(r),...t}}function B(e){return t=>Mt(e,t)}function Rt(e,t){return F(B(()=>({method:"stream",stream:e,resource:t?.resource,options:t})))}function be(e,t){let r=Se(e);return F(B(()=>({method:"file",stream:e.stream(),resource:t?.resource||r,options:t})),{title:"Load data from file: "+(r?.name||"unknown")})}function Vt(e,t){let n=(e.dataTransfer||e.clipboardData||e.target)?.files?.[0];if(e.stopPropagation(),e.preventDefault(),!n)throw new Error("Can't extract a file from an event object");return be(n,t)}function zt(e,t){return t=t||{},F(B(async()=>{let r=await fetch(e,t.fetch),n=Se(r,t);if(n&&r.body)return{method:"fetch",stream:r.body,resource:t.resource||n,options:t};let a=r.headers.get("content-type")||"",s=await r.text();if(a.toLowerCase().startsWith("application/json"))try{let i=JSON.parse(s);s=i.error||i}catch{}throw s=new Error(s),s.isFetchError=!0,s.status=r.status,s.statusText=r.statusText,s.stack=null,s}),{title:`Load data from url: ${e}`})}function Ft(e){let t,r=new ReadableStream({start(i){t=i},cancel(){t=null}}),n,a=null,s=new Promise(i=>{n=l=>i({method:"push",stream:r,resource:l?a=l:e?.resource,options:e})});return e=e||{},F(B(()=>s),{start(i){n(i)},push(i){n(),t?.enqueue(i)},finish(i){t?.close(),t=null,i!==void 0&&isFinite(i)&&a!==null&&(a.encodedSize=Number(i)),a=null}})}function we({dataset:e,state:t},r){return new Promise((n,a)=>t.subscribeSync(async(s,i)=>{if(s.stage==="error"){i(),a(s.error);return}let{stage:l,progress:c,step:o}=s;await r.setState({stage:l,progress:c},o),l==="received"&&(i(),n(e))}))}function Se(e,t){if(e instanceof Response){let r=t?.isResponseOk||Lt,n=t?.getContentSize||Ot,a=t?.getContentEncodedSize||Pt,s=t?.getContentCreatedAt||Nt;if(r(e))return{type:"url",name:e.url,size:Number(n(e))||null,encodedSize:Number(a(e)),createdAt:s(e)}}if(e instanceof File)return{type:"file",name:e.name,size:e.size,createdAt:e.lastModified};if(e instanceof Blob)return{size:e.size};if(ArrayBuffer.isView(e))return{size:e.byteLength};if(typeof e=="string")return{size:e.length}}var ve={inited:{value:0,duration:0,title:"Init"},request:{value:0,duration:.1,title:"Awaiting data"},receiving:{value:.1,duration:.8,title:"Receiving data"},decoding:{value:.9,duration:.015,title:"Decoding data"},received:{value:.915,duration:.01,title:"Await app ready"},prepare:{value:.925,duration:.055,title:"Processing data (prepare)"},initui:{value:.98,duration:.02,title:"Rendering UI"},done:{value:1,duration:0,title:"Done!"},error:{value:1,duration:0,title:"Error"}},Bt=e=>e|0,ke=e=>typeof e=="function"?e:()=>{},xe=e=>new Promise(t=>setTimeout(t,e)),Ht=async()=>{if(!document.hidden)return Promise.race([new Promise(requestAnimationFrame).then(()=>xe(0)),xe(12)])};function Te(e,t,r){let{value:n,title:a,duration:s}=ve[e],i=0,l=null;if(t){let{done:c,elapsed:o,units:u,completed:h,total:g}=t;g?(i=c?1:h/g,l=u==="bytes"?Math.round(i*100)+"%":`${h}/${g}`):(i=c?1:.1+Math.min(.9,o/2e4),l=u==="bytes"?(h/(1024*1024)).toFixed(1)+"MB":String(h))}return{stageTitle:a,progressValue:n+i*s,progressText:l,stepText:r||"",title:l?`${a} (${l})${r?":":"..."}`:e!=="done"?`${a}${r?":":"..."}`:a}}var H=class extends E{startTime;lastStageStartTime;awaitRepaintPenaltyTime;finished;awaitRepaint;timings;onTiming;onFinish;appearanceDelay;domReady;el;#r;#e;constructor({onTiming:t,onFinish:r,domReady:n}){super({stage:"inited",progress:null,error:null}),this.startTime=null,this.lastStageStartTime=null,this.awaitRepaintPenaltyTime=0,this.finished=!1,this.awaitRepaint=null,this.timings=[],this.onTiming=ke(t),this.onFinish=ke(r),this.domReady=n||Promise.resolve(),this.el=T("div","view-progress skip-fast-track",[T("div","content main-secondary",[this.#r=T("span","main"),this.#e=T("span","secondary")]),T("div","progress")])}recordTiming(t,r,n=performance.now()){let a={stage:t,title:ve[t].title,duration:Bt(n-r)};this.lastStageStartTime=n,this.timings.push(a),this.onTiming(a)}async#t(t=!1,r=performance.now()){let n=r-(this.awaitRepaint||0),a=r-(this.lastStageStartTime||0);if(t||n>65&&a>200){let s=performance.now();await Ht(),this.awaitRepaintPenaltyTime+=performance.now()-s,this.awaitRepaint=performance.now()}}async setState(t,r){let n=this.value.stage,{stage:a=n,progress:s=null,error:i=null}=t;if(this.finished)return;if(i){this.set("stage"in t?{stage:a,progress:s,error:i}:{...this.value,error:i}),this.finish(i);return}this.set({stage:a,progress:s,error:i});let l=a!==n,c=performance.now();n==="inited"&&(this.startTime=c),l&&(this.lastStageStartTime!==null&&this.recordTiming(n,this.lastStageStartTime,c),this.lastStageStartTime=c,this.awaitRepaint=c);let{title:o,stepText:u,progressValue:h}=Te(a,s,r);this.el.style.setProperty("--progress",String(h)),this.#r.textContent=o,this.#e.textContent=u,this.el.offsetWidth,await this.#t(l,c)}async setStateStep(t){let{title:r,stepText:n}=Te(this.value.stage,this.value.progress,t);this.#r.textContent=r,this.#e.textContent=n,this.el.offsetWidth,await this.#t(!0)}finish(t){this.finished||(this.finished=!0,this.lastStageStartTime!==null&&this.recordTiming(this.value.stage,this.lastStageStartTime),this.recordTiming(t?"error":"done",this.startTime||this.lastStageStartTime||performance.now()),this.set({stage:"done",progress:null,error:t||null}),this.onFinish(Object.assign([...this.timings],{awaitRepaintPenaltyTime:Math.round(this.awaitRepaintPenaltyTime)})),this.el.classList.add("done"),this.el.classList.toggle("error",!!t))}dispose(){this.finish(),this.el.remove()}};function qt(e){return new H({domReady:e,onTiming:({title:t,duration:r})=>console.log(`[Discovery/preloader] ${t} \u2013 ${r}ms`)})}function _t(e){if(e&&!O(z,e))throw new Error(`dataSource "${e}" is not supported`)}function $t(e,t,r){let{darkmode:n,darkmodePersistent:a,colorScheme:s=n,colorSchemePersistent:i=a}=r,l=N(s,i);ee(t,l)&&e.setAttribute("darkmode","")}Kt.colorScheme=!0;function Kt(e){e=e||{};let t=e.container||document.body,r=document.createElement("div"),n=r.attachShadow({mode:"open"}),a=e.dataSource;_t(a),$t(r,t,e);let s=e.data,i=s?a==="push"?z.push(e.loadDataOptions):z[a||"url"](e.data,e.loadDataOptions):{dataset:Promise.resolve(),state:void 0};if(s&&a==="push"){let{start:u,push:h,finish:g}=i;globalThis.discoveryLoader={start:u,push:h,finish(...d){delete globalThis.discoveryLoader,g(...d)}}}let l=te(n,e.styles),c=e.progressbar||qt(l),o=e.embed?Wt(i.state):()=>{};return i.state&&we(i,c).catch(()=>{}),n.append(c.el),t.append(r),Object.assign(i.dataset,{el:r,shadowRoot:n,progressbar:c,disposeEmbed:o})}function Wt(e){let t=G(),r=window.parent,n=[],a=(c,o)=>{let u={from:"discoveryjs-app",id:t,type:c,payload:o};r.postMessage(u,"*")},s=()=>a("destroy",null),i=c=>{let{id:o,type:u}=c.data||{};if(o===t)switch(u){case"defineAction":case"setPageHash":case"setRouterPreventLocationUpdate":{n.push(c.data);break}default:console.error(`[Discovery/preloader] Unknown preload message type "${u}"`)}};if(r===window)return;addEventListener("message",i,!1),addEventListener("unload",s,!1),a("preinit",{page:{hash:location.hash||"#"}});let l=e?e.subscribeSync(c=>{let{stage:o}=c;return(o==="error"||o==="received")&&l(),a("loadingState",c)}):()=>{};return()=>(removeEventListener("message",i,!1),removeEventListener("unload",s,!1),l(),s(),{hostId:t,postponeMessages:n})}export{Kt as preloader};