UNPKG

@discoveryjs/discovery

Version:

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

2 lines (1 loc) 27.2 kB
var{toString:Vt,hasOwnProperty:be}=Object.prototype;var O=Object.hasOwn||((e,t)=>be.call(e,t));function W(){return[performance.timeOrigin.toString(16),(1e4*performance.now()).toString(16),Math.random().toString(16).slice(2)].join("-")}var T=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,s=this.subscriber;for(;s!==null;){if(s.callback===t){s.callback=null,r.subscriber=s.subscriber;break}r=s,s=s.subscriber}}shouldUpdate(t,r){return t!==r}set(t){return this.#e(t)!==!1}asyncSet(t){let r=this.#e(t);return r===!1?Promise.resolve(!1):Promise.all(r).then(()=>!0)}#e(t){if(!this.shouldUpdate(t,this.value))return!1;let r=[],s=this.subscriber;for(this.value=t;s!==null;){let{callback:a}=s;a!==null&&r.push(a(t,()=>this.unsubscribe(a))),s=s.subscriber}return r}};var J=Se("localStorage");function Se(e){let t=we(e);return function(s){return t?.getItem(s)??null}}function we(e){let t="__storage_test__"+Math.random(),r;try{r=window[e]}catch{return null}try{r.setItem(t,t),r.removeItem(t)}catch(s){if(!(s instanceof DOMException&&(s.code===22||s.code===1014||s.name==="QuotaExceededError"||s.name==="NS_ERROR_DOM_QUOTA_REACHED")&&r.length!==0))return null}return r}var xe="discoveryjs:color-scheme",ke=Object.freeze(["auto","light","dark"]);function ve(e){return ke.includes(e)}function Te(){return matchMedia("(prefers-color-scheme:dark)")}function Ee(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 s=J(xe);ve(s)&&(e=s)}return e}function Ce(e){let t=De(e);return t==="auto"?Te().matches?"dark":"light":t}function De(e){switch(e){case"auto":return"auto";case"dark":case"dark-only":return"dark";case"light":case"light-only":default:return"light"}}function R(e="auto",t=!1){return Ce(Ee(e,t))}var Q=new WeakMap,Ae={"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)"},Le={"--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 G(e,t){let r=Q.get(e)||Object.create(null),s=R(t)==="dark";for(let[a,n]of Object.entries(Ae))Z(e,a,r),e.style.setProperty(a,n);for(let[a,n]of Object.entries(Le))Z(e,a,r),s?e.style.setProperty(a,n):e.style.removeProperty(a);return Q.set(e,r),s}function x(e,t,r){let s=document.createElement(e);typeof t=="string"&&(t={class:t});for(let a in t)if(O(t,a)){let n=t[a];if(typeof n>"u")continue;typeof n=="function"?s.addEventListener(a.slice(2),n):s.setAttribute(a,n)}return Array.isArray(r)?s.append(...r):typeof r=="string"&&(s.innerHTML=r),s}async function Y(e,t){let r=x("style",null,":host{display:none}"),s=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 x("style",{media:a.media},a.content);case"link":case"external":{let n,i,l=new Promise((o,u)=>{n=o,i=u});return s.add(l),x("link",{rel:"stylesheet",href:a.href,media:a.media,onerror(o){s.delete(l),i(o)},onload(){s.delete(l),n()}})}default:throw new Error(`Unknown type "${a.type}" for a style descriptor`)}})),s.size&&(e.append(r),await Promise.all(s),r.remove()))}function Pe(e){if(!e||typeof e!="object")return"value is not an object";let{name:t,test:r,decode:s}=e;return typeof t!="string"?"missed name":typeof r!="function"?"missed test function":typeof s!="function"?"missed decode function":!1}function Oe(e){let t=Pe(e);if(t)throw new Error(`Bad encoding config${e?.name?` "${e.name}"`:""}: ${t}`);let{name:r,test:s,streaming:a,decode:n}=e;return Object.freeze(a?{name:r||"unknown",test:s,streaming:!0,decode:n}:{name:r||"unknown",test:s,streaming:!1,decode:n})}function X(e){if(!e)return[];if(!Array.isArray(e))throw new Error("Encodings must be an array");return e.map(Oe)}function H(e){return typeof e=="object"&&e!==null&&(typeof e[Symbol.iterator]=="function"||typeof e[Symbol.asyncIterator]=="function")}var D=1,Re=2,je=new TextDecoder;function Me(e,t){return e.name==="SyntaxError"&&t.jsonParseOffset&&(e.message=e.message.replace(/at position (\d+)/,(r,s)=>"at position "+(Number(s)+t.jsonParseOffset))),e}function Ne(e,t){let r=e.length;e.length+=t.length;for(let s=0;s<t.length;s++)e[r+s]=t[s]}async function j(e){let t=typeof e=="function"?e():e;if(H(t)){let r=new B;try{for await(let s of t){if(typeof s!="string"&&!ArrayBuffer.isView(s))throw new TypeError("Invalid chunk: Expected string, TypedArray or Buffer");r.push(s)}return r.finish()}catch(s){throw Me(s,r)}}throw new TypeError("Invalid chunk emitter: Expected an Iterable, AsyncIterable, generator, async generator, or a function returning an Iterable or AsyncIterable")}var B=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]===D?(r&&(this.jsonParseOffset--,t="{"+t+"}"),Object.assign(this.valueStack.value,JSON.parse(t))):(r&&(this.jsonParseOffset--,t="["+t+"]"),Ne(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,s){let a=t.slice(r,s);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 n=this.flushDepth-1;n>=this.lastFlushDepth;n--)a+=this.stack[n]===D?"}":"]";this.lastFlushDepth===0?(this.value=JSON.parse(a),this.valueStack={value:this.value,prev:null}):this.parseAndAppend(this.prepareAddition(a),!0);for(let n=this.lastFlushDepth||1;n<this.flushDepth;n++){let i=this.valueStack.value;if(this.stack[n-1]===D){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 n=this.lastFlushDepth-1;n>=this.flushDepth;n--)this.jsonParseOffset--,a=(this.stack[n]===D?"{":"[")+a;this.parseAndAppend(a,!1);for(let n=this.lastFlushDepth-1;n>=this.flushDepth;n--)this.valueStack=this.valueStack.prev}this.lastFlushDepth=this.flushDepth}push(t){if(typeof t!="string"){if(this.pendingByteSeq!==null){let n=t;t=new Uint8Array(this.pendingByteSeq.length+n.length),t.set(this.pendingByteSeq),t.set(n,this.pendingByteSeq.length),this.pendingByteSeq=null}if(t[t.length-1]>127)for(let n=0;n<t.length;n++){let i=t[t.length-1-n];if(i>>6===3){n++,(n!==4&&i>>3===30||n!==3&&i>>4===14||n!==2&&i>>5===6)&&(this.pendingByteSeq=t.slice(t.length-n),t=t.slice(0,-n));break}}t=je.decode(t)}let r=t.length,s=0,a=0;e:for(let n=0;n<r;n++){if(this.stateString){for(;n<r;n++)if(this.stateStringEscape)this.stateStringEscape=!1;else switch(t.charCodeAt(n)){case 34:this.stateString=!1;continue e;case 92:this.stateStringEscape=!0}break}switch(t.charCodeAt(n)){case 34:this.stateString=!0,this.stateStringEscape=!1;break;case 44:a=n;break;case 123:a=n+1,this.stack[this.flushDepth++]=D;break;case 91:a=n+1,this.stack[this.flushDepth++]=Re;break;case 93:case 125:a=n+1,this.flushDepth--,this.flushDepth<this.lastFlushDepth&&(this.flush(t,s,a),s=a);break;case 9:case 10:case 13:case 32:s===n&&s++,a===n&&a++;break}}a>s&&this.flush(t,s,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 Fe=typeof Object.hasOwn=="function"?Object.hasOwn:(e,t)=>Object.hasOwnProperty.call(e,t),Ue={8:"\\b",9:"\\t",10:"\\n",12:"\\f",13:"\\r",34:'\\"',92:"\\\\"},ir=Uint8Array.from({length:2048},(e,t)=>Fe(Ue,t)?2:t<32?6:t<128?1:2);var q=Object.freeze({name:"json",test:()=>!0,streaming:!0,decode:j});var He=new Uint8Array([0,0,74,83,79,78,88,76]),se=9,Be=268435455,qe=4294967295,M=2,A=4,$=8,P=16,N=32,I=64,C=128,$e=0,_e=1,Ke=2,We=3,Je=4,Qe=5,Ze=6,Ge=8,Ye=9,Xe=10,et=11,tt=12,rt=224,st=7936,ne=0,_=1,nt=2,at=3,it=4,ot=5,ae=6,ie=7,lt=8,ee=16,te=32,kr=~P,ct=M|N|I,oe=new Uint8Array(256).map((e,t)=>{for(let r=0;r<8;r++)e+=t>>r&1;return e});function ut(e,t,r,s=new Array(r)){let a=t&15,n=t&48,i=r,l=0,c=0;switch(n){case ee:{l=s[0]=e.readIntVar(),i--,c=1;break}case te:{l=e.readIntVar();break}}switch(a){case nt:{for(let o=0;o<i;o++)s[c+o]=e.readVlq();break}case at:{for(let o=0;o<i;o++)s[c+o]=e.readIntVar();break}case it:{let o=e.readBytes(Math.ceil(i/2));for(let u=0,d=0;u<i;u++)d=u&1?d>>4:o[u>>1],s[c+u]=d&8?e.readVlq()*8+(d&7):d&7;break}case ot:{let o=e.readBytes(Math.ceil(i/2));for(let u=0,d=0;u<i;u++){d=u&1?d>>4:o[u>>1];let h=d&4?-1:1;s[c+u]=d&8?h*(e.readVlq()*4+(d&3)):h*(d&3)}break}case ae:{let o=t>>8,u=(1<<o)-1,d=e.readBytes(Math.ceil(i*o/8)),h=0,m=0,f=0;for(let g=0;g<i;g++){for(;m<o;)f|=d[h++]<<m,m+=8;s[c+g]=f&u,f>>=o,m-=o}break}case ie:{let o=t>>8,u=(1<<o)-1,d=e.readBytes(Math.ceil(i*o/8)),h=0,m=0,f=0;for(let g=0;g<i;g++){for(;m<o;)f|=d[h++]<<m,m+=8;s[c+g]=f&1?-((f&u)>>1):(f&u)>>1,f>>=o,m-=o}break}case lt:{let o=s[0]=e.readIntVar(),u=e.readIntVar();for(let d=1;d<r;d++)s[d]=o+=u;break}case ne:case _:{let o=a===_,u=t>>8,d=o?t&st|u&rt:u;if(oe[u]>1){let h=e.readTypeIndex(i,d);for(let m=0;m<i;m++)s[c+m]=e.readNumber(h[m])}else{let h=31-Math.clz32(d);for(let m=0;m<i;m++)s[c+m]=e.readNumber(h)}break}default:throw new Error(`Unknown numeric array encoding method: ${a}`)}switch(n){case ee:{s[0]=l;for(let o=1;o<r;o++)s[o]+=s[o-1];break}case te:{for(let o=0;o<r;o++)s[o]+=l;break}}return s}var L=12;function dt(e){return e===se||e===9}function le(e){try{let{version:t}=ce(e);if(dt(t))return!0;throw new Error(`Unsupported jsonxl version "${t}", expected "${se}"`)}catch{return!1}}function ce(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((n,i)=>n!==He[i]))throw new Error("Bad magic number");let r=new DataView(t.buffer,t.byteOffset,L),s=r.getUint16(8,!0),a=r.getUint16(10,!0);return{version:s,flags:a,headerSize:L}}var ht=new TextDecoder("utf8",{ignoreBOM:!0});function ft(e){let t=ht.decode(e.readBytes(e.readVlq())),r=e.readNumericArray(),s=e.readNumericArray(),a=e.readNumericArray(),n=new Array(r);for(let i=0,l=0,c=0,o=0,u="";i<r.length;i++){let d=r[i],h=t.slice(l,l+=d>>2);d&2&&(h=u.slice(0,s[c++])+h),d&1&&(h=h+u.slice(-a[o++])),n[i]=h,u=h}return n}var pt=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}=ce(this.view);return this.pos+=r,{version:e,flags:t}}loadStrings(){this.strings=ft(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++],s=t.dict[r];return s===0?null:{key:this.objectKeys[s>>8],type:s&255}}readBytes(e){return this.bytes.subarray(this.pos,this.pos+=e)}readTypeIndex(e,t,r){let s=0,a=0,n=0;for(;t>0;)t&1&&(s|=n<<(a++<<2)),n++,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,d=0,h=0;for(let m=0;m<e;m++){h<l&&(d|=o[u++]<<h,h+=8);let f=s>>((d&c)<<2)&15;i[m]=r?1<<f:f,d>>=l,h-=l}return i}readVlq(){let e=this.view.getUint8(this.pos);if(!(e&1))e=e>>1,this.pos+=1;else if(!(e&2))e=this.view.getUint8(this.pos+1)<<6|e>>2,this.pos+=2;else if(!(e&4))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&Be,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.readUintVar();return e&1?-(e-1)/2:e<=qe?e>>>1:e/2}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 $e:return this.readUint8();case _e:return this.readUint16();case Ke:return this.readUint24();case We:return this.readUint32();case Je:return this.readUintVar();case Ge:return this.readInt8();case Ye:return this.readInt16();case Xe:return this.readInt24();case et:return this.readInt32();case tt:return this.readIntVar();case Qe:return this.readFloat32();case Ze:return this.readFloat64()}}readNumericArrayEncoding(){let e=this.readUint8();switch(e&15){case ne:case _:case ae:case ie: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 ut(this,e,t,r)}};function re(e,t){let r=0;for(let s=0;s<e.length;s++)e[s]===t&&r++;return r}function ue(e,t){function r(l={}){let c=0,o;for(;o=n.readObjectEntry(c++);)l[o.key]=a(o.type);return l}function s(l=n.readArrayLength()){if(l===0)return[];let c=n.readArrayHeader(),o=c>>16,u=c&65535,d=o&1,h=o>>5&1,m=o>>9&1,f=o>>1&255|(o&1)<<4,g=new Array(l),b=oe[f]>1?n.readTypeIndex(l,f,!0):null;if(f&ct)if(b===null)switch(f){case M:g.fill(null);break;case N:g.fill(!0);break;case I:g.fill(!1);break}else for(let p=0;p<l;p++)switch(b[p]){case M:g[p]=null;break;case N:g[p]=!0;break;case I:g[p]=!1;break}if(f&$)for(let p=0;p<l;p++)(b===null||b[p]===$)&&(g[p]=n.readString());if(f&A)if(f===A)n.readNumbers(u,l,g);else{let p=re(b,A),y=n.readNumbers(u,p);for(let w=0,S=0;w<l;w++)b[w]===A&&(g[w]=y[S++])}if(f&C)if(m){let p=f===C?l:re(b,C),y=n.readNumericArray(p),w=s();for(let S=0,E=0,k=0;S<l;S++)(b===null||b[S]===C)&&(g[S]=w.slice(k,k+=y[E++]))}else for(let p=0;p<l;p++)(b===null||b[p]===C)&&(g[p]=s());if(f&P){let p=f===P?g:[];for(let y=0,w=0;y<l;y++)(b===null||b[y]===P)&&(g[y]=p[w++]={});if(h){let y=n.readVlq(),w=new Array(y);for(let S=0;S<y;S++)w[S]=n.readString();for(let S=0;S<y;S++){let E=w[S],k=s(p.length);for(let v=0;v<p.length;v++)k[v]!==void 0&&(p[v][E]=k[v])}}if(d)for(let y=0;y<p.length;y++)r(p[y])}return g}function a(l){switch(1<<(l&7)){case M:return null;case $:return n.readString();case A:return n.readNumber(l>>3);case P:return r();case N:return!0;case I:return!1;case C:return s()}}let n=new pt(e,t),i=a(n.readUint8());if(n.pos!==e.byteLength)throw new Error("End of input is not reached");return i}var K=Object.freeze({name:"jsonxl/snapshot9",test:le,streaming:!1,decode:ue});var V={stream:Ct,event:Dt,file:de,url:At,push:Lt};function mt(e){try{return new URL(e,location.origin).origin===location.origin}catch{return!1}}function yt(e){return e.ok}function bt(e){return e.headers.get("x-file-encoded-size")||e.headers.get("content-length")}function St(e){return e.headers.get("x-file-size")||(mt(e.url)&&!e.headers.get("content-encoding")?e.headers.get("content-length"):void 0)}function wt(e){return e.headers.get("x-file-created-at")||e.headers.get("last-modified")||void 0}function xt(e){let t=e?Object.keys(e):[],r=["name","createdAt","elapsedTime","data"];return!(t.length!==4||t.some(s=>!r.includes(s)))}function kt(e,t,{size:r,encoding:s}){let a=null;if(xt(e)){let{data:g,...b}=e;e=g,t={...t,createdAt:g.createdAt},a=b}let n=e,i=a||{},{type:l,name:c,encoding:o,size:u,encodedSize:d,createdAt:h,...m}=t||{};return{resource:{type:l||"unknown",name:c||"unknown",encoding:s,...Number.isFinite(r)?{size:r}:null,...Number.isFinite(d)?{encodedSize:d}:null,createdAt:new Date((typeof h=="string"?Date.parse(h):h)||Date.now()),...m},meta:i,data:n}}async function vt(e){let t=[],r=0;for await(let n of e)t.push(n),r+=n.byteLength;let s=new Uint8Array(r),a=0;for(let n of t)s.set(n,a),a+=n.length;return s}async function Tt(e,t,r,s){let n=e.getReader(),i=Date.now(),l=[...X(t),K,q],c=0,o="unknown",u=0;await s("receiving",d(!1));try{let f=await n.read(),{value:g,done:b}=f;if(b)throw new Error("Empty payload");for(let{name:p,test:y,streaming:w,decode:S}of l)if(y(g))return o=p,{data:await(w?S(h(f)):vt(h(f)).then(m(S))),encoding:o,size:u,decodingTime:c};throw new Error("No matched encoding found for the payload")}finally{n.releaseLock()}function d(f){return{done:f,elapsed:Date.now()-i,units:"bytes",completed:u,total:r}}async function*h(f){for(;;){let{value:g,done:b}=f||await n.read();if(f=void 0,b)break;for(let p=0;p<g.length;p+=1048576){let y=performance.now(),w=p===0&&g.length-p<1048576?g:g.slice(p,p+1048576);yield w,c+=performance.now()-y,u+=w.length,await s("receiving",d(!1))}}await s("receiving",d(!0))}function m(f){return async g=>{await s("decoding",void 0,o);let b=performance.now();try{return await f(g)}finally{c=performance.now()-b}}}}async function Et(e,t){try{await t.asyncSet({stage:"request"});let r=new Date,{method:s,stream:a,resource:n,options:i,data:l}=await e(),c=new Date,o=n?.size,{encodings:u}=i||{},{data:d,encoding:h="unknown",size:m=void 0,decodingTime:f=0}=l?{data:l}:await Tt(a,u,Number(o)||0,(E,k,v)=>t.asyncSet({stage:E,progress:k,step:v}));await t.asyncSet({stage:"received"});let{data:g,resource:b,meta:p}=kt(d,n,{size:m,encoding:h}),y=new Date,w=Number(y)-Number(r),S=Math.round(f||0);return{loadMethod:s,resource:b,meta:p,data:g,timings:{time:w,start:r,end:y,loadingTime:w-S,decodingTime:S,requestTime:Number(c)-Number(r),requestStart:r,requestEnd:c,responseTime:Number(y)-Number(c),responseStart:c,responseEnd:y}}}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 T({stage:"inited"});return{state:r,dataset:e(r),...t}}function U(e){return t=>Et(e,t)}function Ct(e,t){return F(U(()=>({method:"stream",stream:e,resource:t?.resource,options:t})))}function de(e,t){let r=fe(e);return F(U(()=>({method:"file",stream:e.stream(),resource:t?.resource||r,options:t})),{title:"Load data from file: "+(r?.name||"unknown")})}function Dt(e,t){let s=(e.dataTransfer||e.clipboardData||e.target)?.files?.[0];if(e.stopPropagation(),e.preventDefault(),!s)throw new Error("Can't extract a file from an event object");return de(s,t)}function At(e,t){return t=t||{},F(U(async()=>{let r=await fetch(e,t.fetch),s=fe(r,t);if(s&&r.body)return{method:"fetch",stream:r.body,resource:t.resource||s,options:t};let a=r.headers.get("content-type")||"",n=await r.text();if(a.toLowerCase().startsWith("application/json"))try{let i=JSON.parse(n);n=i.error||i}catch{}throw n=new Error(n),n.isFetchError=!0,n.status=r.status,n.statusText=r.statusText,n.stack=null,n}),{title:`Load data from url: ${e}`})}function Lt(e){let t,r=new ReadableStream({start(i){t=i},cancel(){t=null}}),s,a=null,n=new Promise(i=>{s=l=>i({method:"push",stream:r,resource:l?a=l:e?.resource,options:e})});return e=e||{},F(U(()=>n),{start(i){s(i)},push(i){s(),t?.enqueue(i)},finish(i){t?.close(),t=null,i!==void 0&&isFinite(i)&&a!==null&&(a.encodedSize=Number(i)),a=null}})}function he({dataset:e,state:t},r){return new Promise((s,a)=>t.subscribeSync(async(n,i)=>{if(n.stage==="error"){i(),a(n.error);return}let{stage:l,progress:c,step:o}=n;await r.setState({stage:l,progress:c},o),l==="received"&&(i(),s(e))}))}function fe(e,t){if(e instanceof Response){let r=t?.isResponseOk||yt,s=t?.getContentSize||St,a=t?.getContentEncodedSize||bt,n=t?.getContentCreatedAt||wt;if(r(e))return{type:"url",name:e.url,size:Number(s(e))||null,encodedSize:Number(a(e)),createdAt:n(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 ye={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"}},Pt=e=>e|0,pe=e=>typeof e=="function"?e:()=>{},ge=e=>new Promise(t=>setTimeout(t,e)),Ot=async()=>{if(!document.hidden)return Promise.race([new Promise(requestAnimationFrame).then(()=>ge(0)),ge(12)])};function me(e,t,r){let{value:s,title:a,duration:n}=ye[e],i=0,l=null;if(t){let{done:c,elapsed:o,units:u,completed:d,total:h}=t;h?(i=c?1:d/h,l=u==="bytes"?Math.round(i*100)+"%":`${d}/${h}`):(i=c?1:.1+Math.min(.9,o/2e4),l=u==="bytes"?(d/(1024*1024)).toFixed(1)+"MB":String(d))}return{stageTitle:a,progressValue:s+i*n,progressText:l,stepText:r||"",title:l?`${a} (${l})${r?":":"..."}`:e!=="done"?`${a}${r?":":"..."}`:a}}var z=class extends T{startTime;lastStageStartTime;awaitRepaintPenaltyTime;finished;awaitRepaint;timings;onTiming;onFinish;appearanceDelay;domReady;el;#e;#t;constructor({onTiming:t,onFinish:r,domReady:s}){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=pe(t),this.onFinish=pe(r),this.domReady=s||Promise.resolve(),this.el=x("div","view-progress skip-fast-track",[x("div","content main-secondary",[this.#e=x("span","main"),this.#t=x("span","secondary")]),x("div","progress")])}recordTiming(t,r,s=performance.now()){let a={stage:t,title:ye[t].title,duration:Pt(s-r)};this.lastStageStartTime=s,this.timings.push(a),this.onTiming(a)}async#r(t=!1,r=performance.now()){let s=r-(this.awaitRepaint||0),a=r-(this.lastStageStartTime||0);if(t||s>65&&a>200){let n=performance.now();await Ot(),this.awaitRepaintPenaltyTime+=performance.now()-n,this.awaitRepaint=performance.now()}}async setState(t,r){let s=this.value.stage,{stage:a=s,progress:n=null,error:i=null}=t;if(this.finished)return;if(i){this.set("stage"in t?{stage:a,progress:n,error:i}:{...this.value,error:i}),this.finish(i);return}this.set({stage:a,progress:n,error:i});let l=a!==s,c=performance.now();s==="inited"&&(this.startTime=c),l&&(this.lastStageStartTime!==null&&this.recordTiming(s,this.lastStageStartTime,c),this.lastStageStartTime=c,this.awaitRepaint=c);let{title:o,stepText:u,progressValue:d}=me(a,n,r);this.el.style.setProperty("--progress",String(d)),this.#e.textContent=o,this.#t.textContent=u,this.el.offsetWidth,await this.#r(l,c)}async setStateStep(t){let{title:r,stepText:s}=me(this.value.stage,this.value.progress,t);this.#e.textContent=r,this.#t.textContent=s,this.el.offsetWidth,await this.#r(!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 Rt(e){return new z({domReady:e,onTiming:({title:t,duration:r})=>console.log(`[Discovery/preloader] ${t} \u2013 ${r}ms`)})}function jt(e){if(e&&!O(V,e))throw new Error(`dataSource "${e}" is not supported`)}function Mt(e,t,r){let{darkmode:s,darkmodePersistent:a,colorScheme:n=s,colorSchemePersistent:i=a}=r,l=R(n,i);G(t,l)&&e.setAttribute("darkmode","")}Nt.colorScheme=!0;function Nt(e){e=e||{};let t=e.container||document.body,r=document.createElement("div"),s=r.attachShadow({mode:"open"}),a=e.dataSource;jt(a),Mt(r,t,e);let n=e.data,i=n?a==="push"?V.push(e.loadDataOptions):V[a||"url"](e.data,e.loadDataOptions):{dataset:Promise.resolve(),state:void 0};if(n&&a==="push"){let{start:u,push:d,finish:h}=i;globalThis.discoveryLoader={start:u,push:d,finish(...m){delete globalThis.discoveryLoader,h(...m)}}}let l=Y(s,e.styles),c=e.progressbar||Rt(l),o=e.embed?It(i.state):()=>{};return i.state&&he(i,c).catch(()=>{}),s.append(c.el),t.append(r),Object.assign(i.dataset,{el:r,shadowRoot:s,progressbar:c,disposeEmbed:o})}function It(e){let t=W(),r=window.parent,s=[],a=(c,o)=>{let u={from:"discoveryjs-app",id:t,type:c,payload:o};r.postMessage(u,"*")},n=()=>a("destroy",null),i=c=>{let{id:o,type:u}=c.data||{};if(o===t)switch(u){case"defineAction":case"setPageHash":case"setRouterPreventLocationUpdate":{s.push(c.data);break}default:console.error(`[Discovery/preloader] Unknown preload message type "${u}"`)}};if(r===window)return;addEventListener("message",i,!1),addEventListener("unload",n,!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",n,!1),l(),n(),{hostId:t,postponeMessages:s})}export{Nt as preloader};