@synnaxlabs/client 0.42.1 → 0.42.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.cjs CHANGED
@@ -1,6 +1,6 @@
1
- "use strict";var ul=Object.defineProperty;var dl=(r,e,t)=>e in r?ul(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var l=(r,e,t)=>dl(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),b=r=>Array.isArray(r)?r:[r],Es="policy",zs="allow_all";var fl=Object.defineProperty,yl=(r,e,t)=>e in r?fl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,G=(r,e,t)=>yl(r,typeof e!="symbol"?e+"":e,t);const gl=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Na=r=>{const e=(t,n=Yn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!wn(t))return t;n=wl(n);const s={},a=t;return Object.keys(a).forEach(o=>{let c=a[o];const h=r(o);n.recursive&&(wn(c)?wi(c,n.keepTypesOnRecursion)||(c=e(c,n)):n.recursiveInArray&&pi(c)&&(c=[...c].map(d=>{let f=d;return wn(d)?wi(f,n.keepTypesOnRecursion)||(f=e(d,n)):pi(d)&&(f=e({key:d},n).key),f}))),s[h]=c}),s};return e},Ns=Na(gl),pl=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Ia=Na(pl),Yn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},wl=(r=Yn)=>(r.recursive==null?r=Yn:r.recursiveInArray??(r.recursiveInArray=!1),r),pi=r=>r!=null&&Array.isArray(r),wn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),wi=(r,e)=>(e||[]).some(t=>r instanceof t),Is=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var ml=Object.defineProperty,bl=(r,e,t)=>e in r?ml(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,yt=(r,e,t)=>bl(r,typeof e!="symbol"?e+"":e,t);function vl(r){const e=r.length;let t=0,n=0;for(;n<e;){let s=r.charCodeAt(n++);if((s&4294967168)===0){t++;continue}else if((s&4294965248)===0)t+=2;else{if(s>=55296&&s<=56319&&n<e){const a=r.charCodeAt(n);(a&64512)===56320&&(++n,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?t+=3:t+=4}}return t}function Tl(r,e,t){const n=r.length;let s=t,a=0;for(;a<n;){let o=r.charCodeAt(a++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&a<n){const c=r.charCodeAt(a);(c&64512)===56320&&(++a,o=((o&1023)<<10)+(c&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const Ol=new TextEncoder,Sl=50;function El(r,e,t){Ol.encodeInto(r,e.subarray(t))}function zl(r,e,t){r.length>Sl?El(r,e,t):Tl(r,e,t)}const Nl=4096;function $a(r,e,t){let n=e;const s=n+t,a=[];let o="";for(;n<s;){const c=r[n++];if((c&128)===0)a.push(c);else if((c&224)===192){const h=r[n++]&63;a.push((c&31)<<6|h)}else if((c&240)===224){const h=r[n++]&63,d=r[n++]&63;a.push((c&31)<<12|h<<6|d)}else if((c&248)===240){const h=r[n++]&63,d=r[n++]&63,f=r[n++]&63;let u=(c&7)<<18|h<<12|d<<6|f;u>65535&&(u-=65536,a.push(u>>>10&1023|55296),u=56320|u&1023),a.push(u)}else a.push(c);a.length>=Nl&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const Il=new TextDecoder,$l=200;function xl(r,e,t){const n=r.subarray(e,e+t);return Il.decode(n)}function kl(r,e,t){return t>$l?xl(r,e,t):$a(r,e,t)}let Er=class{constructor(e,t){this.type=e,this.data=t}},we=class Wn extends Error{constructor(e){super(e);const t=Object.create(Wn.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Wn.name})}};const At=4294967295;function Al(r,e,t){const n=t/4294967296,s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function xa(r,e,t){const n=Math.floor(t/4294967296),s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function ka(r,e){const t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function Ul(r,e){const t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}const Cl=-1,Rl=4294967296-1,Bl=17179869184-1;function Pl({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Bl)if(e===0&&r<=Rl){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{const t=r/4294967296,n=r&4294967295,s=new Uint8Array(8),a=new DataView(s.buffer);return a.setUint32(0,e<<2|t&3),a.setUint32(4,n),s}else{const t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),xa(n,4,r),t}}function Dl(r){const e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,s=Math.floor(n/1e9);return{sec:t+s,nsec:n-s*1e9}}function Ml(r){if(r instanceof Date){const e=Dl(r);return Pl(e)}else return null}function jl(r){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),n=e.getUint32(4),s=(t&3)*4294967296+n,a=t>>>2;return{sec:s,nsec:a}}case 12:{const t=ka(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new we(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Ll(r){const e=jl(r);return new Date(e.sec*1e3+e.nsec/1e6)}const _l={type:Cl,encode:Ml,decode:Ll};let tr=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(_l)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){const s=this.builtInEncoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=-1-n;return new Er(o,a)}}}for(let n=0;n<this.encoders.length;n++){const s=this.encoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=n;return new Er(o,a)}}}return e instanceof Er?e:null}decode(e,t,n){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,n):new Er(t,e)}};tr.defaultCodec=new tr;function Zl(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function Vn(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Zl(r)?new Uint8Array(r):Uint8Array.from(r)}const ql=100,Fl=2048;let Yl=class Aa{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??tr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??ql,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Fl,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Aa({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),n=new Uint8Array(t),s=new DataView(t);n.set(this.bytes),this.view=s,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const t=vl(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),zl(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const n=Vn(e);this.writeU8a(n)}encodeArray(e,t){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let n=0;for(const s of t)e[s]!==void 0&&n++;return n}encodeMap(e,t){const n=Object.keys(e);this.sortKeys&&n.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const a of n){const o=e[a];this.ignoreUndefined&&o===void 0||(this.encodeString(a),this.doEncode(o,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const n=e.data(this.pos+6),s=n.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(n);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Al(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),xa(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function Bt(r,e){return new Yl(e).encodeSharedRef(r)}function mn(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}const Wl=16,Vl=16;class Gl{constructor(e=Wl,t=Vl){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){const s=this.caches[n-1];e:for(const a of s){const o=a.bytes;for(let c=0;c<n;c++)if(o[c]!==e[t+c])continue e;return a.str}return null}store(e,t){const n=this.caches[e.length-1],s={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=s:n.push(s)}decode(e,t,n){const s=this.find(e,t,n);if(s!=null)return this.hit++,s;this.miss++;const a=$a(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,a),a}}const Gn="array",Ht="map_key",Ua="map_value",Hl=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new we("The type of key must be string or number but "+typeof r)};class Kl{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=Gn,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=Ht,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Gn){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===Ht||e.type===Ua){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Ut=-1,$s=new DataView(new ArrayBuffer(0)),Jl=new Uint8Array($s.buffer);try{$s.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const mi=new RangeError("Insufficient data"),Xl=new Gl;let Ql=class Ca{constructor(e){this.totalPos=0,this.pos=0,this.view=$s,this.bytes=Jl,this.headByte=Ut,this.stack=new Kl,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??tr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??At,this.maxBinLength=(e==null?void 0:e.maxBinLength)??At,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??At,this.maxMapLength=(e==null?void 0:e.maxMapLength)??At,this.maxExtLength=(e==null?void 0:e.maxExtLength)??At,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Xl,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Hl}clone(){return new Ca({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Ut,this.stack.reset()}setBuffer(e){const t=Vn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Ut&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),n=Vn(e),s=new Uint8Array(t.length+n.length);s.set(t),s.set(n,t.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(const c of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{n=this.doDecodeSync(),t=!0}catch(h){if(!(h instanceof RangeError))throw h}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:s,pos:a,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${mn(s)} at ${o} (${a} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,s=-1;for await(const a of e){if(t&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a),n&&(s=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const s=this.lookU8();t=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();t=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();t=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===196){const s=this.lookU8();t=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();t=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();t=this.decodeBinary(s,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();t=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();t=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();t=this.decodeExtension(s,4)}else throw new we(`Unrecognized type byte: ${mn(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const s=n.top();if(s.type===Gn)if(s.array[s.position]=t,s.position++,s.position===s.size)t=s.array,n.release(s);else continue e;else if(s.type===Ht){if(t==="__proto__")throw new we("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=Ua;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)t=s.map,n.release(s);else{s.key=null,s.type=Ht;continue e}}return t}}readHeadByte(){return this.headByte===Ut&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Ut}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new we(`Unrecognized array type byte: ${mn(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new we(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new we(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var n;if(e>this.maxStrLength)throw new we(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw mi;const s=this.pos+t;let a;return this.stateIsMapKey()&&(n=this.keyDecoder)!=null&&n.canBeCached(e)?a=this.keyDecoder.decode(this.bytes,s,e):a=kl(this.bytes,s,e),this.pos+=t+e,a}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Ht:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new we(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw mi;const n=this.pos+t,s=this.bytes.subarray(n,n+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new we(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Ul(this.view,this.pos);return this.pos+=8,e}readI64(){const e=ka(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Ra(r,e){return new Ql(e).decode(r)}let eh=class{constructor(){yt(this,"contentType","application/json"),yt(this,"decoder"),yt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r))}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Ns(t);return e!=null?e.parse(n):n}encodeString(r){const e=Ia(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):Is(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},th=class{constructor(){yt(this,"contentType","text/csv")}encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e)}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!Is(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(n=>{const s=e.map(a=>JSON.stringify(n[a]??""));t.push(s.join(","))}),t.join(`
1
+ "use strict";var fl=Object.defineProperty;var yl=(r,e,t)=>e in r?fl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var l=(r,e,t)=>yl(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("zod"),b=r=>Array.isArray(r)?r:[r],Es="policy",zs="allow_all";var gl=Object.defineProperty,pl=(r,e,t)=>e in r?gl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,G=(r,e,t)=>pl(r,typeof e!="symbol"?e+"":e,t);const wl=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},$a=r=>{const e=(t,n=Yn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!wn(t))return t;n=bl(n);const s={},a=t;return Object.keys(a).forEach(o=>{let c=a[o];const h=r(o);n.recursive&&(wn(c)?bi(c,n.keepTypesOnRecursion)||(c=e(c,n)):n.recursiveInArray&&mi(c)&&(c=[...c].map(d=>{let f=d;return wn(d)?bi(f,n.keepTypesOnRecursion)||(f=e(d,n)):mi(d)&&(f=e({key:d},n).key),f}))),s[h]=c}),s};return e},Ns=$a(wl),ml=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),xa=$a(ml),Yn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},bl=(r=Yn)=>(r.recursive==null?r=Yn:r.recursiveInArray??(r.recursiveInArray=!1),r),mi=r=>r!=null&&Array.isArray(r),wn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),bi=(r,e)=>(e||[]).some(t=>r instanceof t),Is=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var vl=Object.defineProperty,Tl=(r,e,t)=>e in r?vl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,yt=(r,e,t)=>Tl(r,typeof e!="symbol"?e+"":e,t);function Ol(r){const e=r.length;let t=0,n=0;for(;n<e;){let s=r.charCodeAt(n++);if((s&4294967168)===0){t++;continue}else if((s&4294965248)===0)t+=2;else{if(s>=55296&&s<=56319&&n<e){const a=r.charCodeAt(n);(a&64512)===56320&&(++n,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?t+=3:t+=4}}return t}function Sl(r,e,t){const n=r.length;let s=t,a=0;for(;a<n;){let o=r.charCodeAt(a++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&a<n){const c=r.charCodeAt(a);(c&64512)===56320&&(++a,o=((o&1023)<<10)+(c&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const El=new TextEncoder,zl=50;function Nl(r,e,t){El.encodeInto(r,e.subarray(t))}function Il(r,e,t){r.length>zl?Nl(r,e,t):Sl(r,e,t)}const $l=4096;function ka(r,e,t){let n=e;const s=n+t,a=[];let o="";for(;n<s;){const c=r[n++];if((c&128)===0)a.push(c);else if((c&224)===192){const h=r[n++]&63;a.push((c&31)<<6|h)}else if((c&240)===224){const h=r[n++]&63,d=r[n++]&63;a.push((c&31)<<12|h<<6|d)}else if((c&248)===240){const h=r[n++]&63,d=r[n++]&63,f=r[n++]&63;let u=(c&7)<<18|h<<12|d<<6|f;u>65535&&(u-=65536,a.push(u>>>10&1023|55296),u=56320|u&1023),a.push(u)}else a.push(c);a.length>=$l&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const xl=new TextDecoder,kl=200;function Al(r,e,t){const n=r.subarray(e,e+t);return xl.decode(n)}function Ul(r,e,t){return t>kl?Al(r,e,t):ka(r,e,t)}let Er=class{constructor(e,t){this.type=e,this.data=t}},we=class Wn extends Error{constructor(e){super(e);const t=Object.create(Wn.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Wn.name})}};const At=4294967295;function Cl(r,e,t){const n=t/4294967296,s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function Aa(r,e,t){const n=Math.floor(t/4294967296),s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function Ua(r,e){const t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function Rl(r,e){const t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}const Bl=-1,Pl=4294967296-1,Dl=17179869184-1;function Ml({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Dl)if(e===0&&r<=Pl){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{const t=r/4294967296,n=r&4294967295,s=new Uint8Array(8),a=new DataView(s.buffer);return a.setUint32(0,e<<2|t&3),a.setUint32(4,n),s}else{const t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),Aa(n,4,r),t}}function jl(r){const e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,s=Math.floor(n/1e9);return{sec:t+s,nsec:n-s*1e9}}function Ll(r){if(r instanceof Date){const e=jl(r);return Ml(e)}else return null}function _l(r){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),n=e.getUint32(4),s=(t&3)*4294967296+n,a=t>>>2;return{sec:s,nsec:a}}case 12:{const t=Ua(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new we(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Zl(r){const e=_l(r);return new Date(e.sec*1e3+e.nsec/1e6)}const ql={type:Bl,encode:Ll,decode:Zl};let tr=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(ql)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){const s=this.builtInEncoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=-1-n;return new Er(o,a)}}}for(let n=0;n<this.encoders.length;n++){const s=this.encoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=n;return new Er(o,a)}}}return e instanceof Er?e:null}decode(e,t,n){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,n):new Er(t,e)}};tr.defaultCodec=new tr;function Fl(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function Vn(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Fl(r)?new Uint8Array(r):Uint8Array.from(r)}const Yl=100,Wl=2048;let Vl=class Ca{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??tr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??Yl,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Wl,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new Ca({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),n=new Uint8Array(t),s=new DataView(t);n.set(this.bytes),this.view=s,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const t=Ol(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),Il(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const n=Vn(e);this.writeU8a(n)}encodeArray(e,t){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let n=0;for(const s of t)e[s]!==void 0&&n++;return n}encodeMap(e,t){const n=Object.keys(e);this.sortKeys&&n.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const a of n){const o=e[a];this.ignoreUndefined&&o===void 0||(this.encodeString(a),this.doEncode(o,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const n=e.data(this.pos+6),s=n.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(n);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Cl(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Aa(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function Bt(r,e){return new Vl(e).encodeSharedRef(r)}function mn(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}const Gl=16,Hl=16;class Kl{constructor(e=Gl,t=Hl){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){const s=this.caches[n-1];e:for(const a of s){const o=a.bytes;for(let c=0;c<n;c++)if(o[c]!==e[t+c])continue e;return a.str}return null}store(e,t){const n=this.caches[e.length-1],s={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=s:n.push(s)}decode(e,t,n){const s=this.find(e,t,n);if(s!=null)return this.hit++,s;this.miss++;const a=ka(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,a),a}}const Gn="array",Ht="map_key",Ra="map_value",Jl=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new we("The type of key must be string or number but "+typeof r)};class Xl{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=Gn,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=Ht,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Gn){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===Ht||e.type===Ra){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Ut=-1,$s=new DataView(new ArrayBuffer(0)),Ql=new Uint8Array($s.buffer);try{$s.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const vi=new RangeError("Insufficient data"),eh=new Kl;let th=class Ba{constructor(e){this.totalPos=0,this.pos=0,this.view=$s,this.bytes=Ql,this.headByte=Ut,this.stack=new Xl,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??tr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??At,this.maxBinLength=(e==null?void 0:e.maxBinLength)??At,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??At,this.maxMapLength=(e==null?void 0:e.maxMapLength)??At,this.maxExtLength=(e==null?void 0:e.maxExtLength)??At,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:eh,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??Jl}clone(){return new Ba({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Ut,this.stack.reset()}setBuffer(e){const t=Vn(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Ut&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),n=Vn(e),s=new Uint8Array(t.length+n.length);s.set(t),s.set(n,t.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(const c of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{n=this.doDecodeSync(),t=!0}catch(h){if(!(h instanceof RangeError))throw h}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:s,pos:a,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${mn(s)} at ${o} (${a} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,s=-1;for await(const a of e){if(t&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a),n&&(s=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const s=this.lookU8();t=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();t=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();t=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===196){const s=this.lookU8();t=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();t=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();t=this.decodeBinary(s,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();t=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();t=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();t=this.decodeExtension(s,4)}else throw new we(`Unrecognized type byte: ${mn(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const s=n.top();if(s.type===Gn)if(s.array[s.position]=t,s.position++,s.position===s.size)t=s.array,n.release(s);else continue e;else if(s.type===Ht){if(t==="__proto__")throw new we("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=Ra;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)t=s.map,n.release(s);else{s.key=null,s.type=Ht;continue e}}return t}}readHeadByte(){return this.headByte===Ut&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Ut}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new we(`Unrecognized array type byte: ${mn(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new we(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new we(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var n;if(e>this.maxStrLength)throw new we(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw vi;const s=this.pos+t;let a;return this.stateIsMapKey()&&(n=this.keyDecoder)!=null&&n.canBeCached(e)?a=this.keyDecoder.decode(this.bytes,s,e):a=Ul(this.bytes,s,e),this.pos+=t+e,a}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Ht:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new we(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw vi;const n=this.pos+t,s=this.bytes.subarray(n,n+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new we(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Rl(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ua(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function Pa(r,e){return new th(e).decode(r)}let rh=class{constructor(){yt(this,"contentType","application/json"),yt(this,"decoder"),yt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r))}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Ns(t);return e!=null?e.parse(n):n}encodeString(r){const e=xa(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):Is(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},nh=class{constructor(){yt(this,"contentType","text/csv")}encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e)}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!Is(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(n=>{const s=e.map(a=>JSON.stringify(n[a]??""));t.push(s.join(","))}),t.join(`
2
2
  `)}decodeString(r,e){const[t,...n]=r.trim().split(`
3
- `).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const s=t.split(",").map(o=>o.trim()),a={};return s.forEach(o=>{a[o]=[]}),n.forEach(o=>{const c=o.split(",").map(h=>h.trim());s.forEach((h,d)=>{const f=this.parseValue(c[d]);f!=null&&a[h].push(f)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},rh=class{constructor(){yt(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r)}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const De=new tr;De.register({type:0,encode:r=>{if(ArrayBuffer.isView(r)){const e=Array.from(r);return Bt(e,{extensionCodec:De})}return Is(r)&&"encode_value"in r?typeof r.value=="bigint"?Bt(r.value.toString(),{extensionCodec:De}):Bt(r.value,{extensionCodec:De}):typeof r=="bigint"?Bt(r.toString(),{extensionCodec:De}):null},decode:r=>Ra(r,{extensionCodec:De})});let nh=class{constructor(){yt(this,"contentType","application/msgpack")}encode(r){const e=Ia(r);return Bt(e,{extensionCodec:De}).slice()}decode(r,e){const t=Ra(r,{extensionCodec:De}),n=Ns(t);return e!=null?e.parse(n):n}static registerCustomType(){}};const Rr=new eh;new th;new rh;new nh;const sh=r=>r!=null&&typeof r=="object"&&"toString"in r,ih=(r,e=!1)=>{const t=sh(r)?"stringer":typeof r;let n;switch(t){case"string":n=(s,a)=>s.localeCompare(a);break;case"stringer":n=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":n=(s,a)=>Number(s)-Number(a);break;case"bigint":n=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":n=(s,a)=>Number(s)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?ah(n):n},ah=r=>(e,t)=>r(t,e),Vr=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const Ba=i.z.object({width:i.z.number(),height:i.z.number()}),oh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),ch=["width","height"];i.z.enum(ch);const lh=["start","center","end"],hh=["signedWidth","signedHeight"];i.z.enum(hh);const jr=i.z.object({x:i.z.number(),y:i.z.number()}),uh=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),dh=["x","y"],Pa=i.z.enum(dh),Da=["top","right","bottom","left"];i.z.enum(Da);const fh=["left","right"],Ma=i.z.enum(fh),yh=["top","bottom"],ja=i.z.enum(yh),La=["center"],bi=i.z.enum(La),gh=[...Da,...La],_a=i.z.enum(gh);i.z.enum(lh);const ph=["first","last"];i.z.enum(ph);const wh=i.z.object({lower:i.z.number(),upper:i.z.number()}),mh=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([wh,Vr]);i.z.union([mh,Vr]);i.z.enum([...Pa.options,..._a.options]);i.z.union([Pa,_a,i.z.instanceof(String)]);const bh=r=>typeof r=="bigint"||r instanceof BigInt,it=(r,e)=>bh(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),Ge=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return vi(r);return vi(t)},vi=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Ti=(r,e)=>{const t=Ge(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};i.z.object({x:Ma.or(bi),y:ja.or(bi)});const vh=i.z.object({x:Ma,y:ja}),Th=Object.freeze({x:"left",y:"top"}),Oh=(r,e)=>r.x===e.x&&r.y===e.y,Oi=i.z.union([i.z.number(),jr,Vr,Ba,oh,uh]),Sh=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Si=Object.freeze({x:0,y:0}),zr=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:zr,left:zr,width:zr,height:zr});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:jr,two:jr,root:vh});const xs=(r,e,t=0,n=0,s)=>{const a={one:{...Si},two:{...Si},root:s??Th};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:s??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},bn=r=>{const e=xs(r);return{lower:e.one.x,upper:e.two.x}},vn=r=>{const e=xs(r);return{lower:e.one.y,upper:e.two.y}},Eh=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,zh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Ba,zh,jr,Vr]);var Nh=Object.defineProperty,Ih=(r,e,t)=>e in r?Nh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$e=(r,e,t)=>Ih(r,typeof e!="symbol"?e+"":e,t);const $h=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;i.z.object({offset:Oi,scale:Oi});i.z.object({offset:i.z.number(),scale:i.z.number()});const xh=r=>(e,t,n,s)=>t==="dimension"?[e,n]:[e,s?n-r:n+r],kh=r=>(e,t,n,s)=>[e,s?n/r:n*r],Ah=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:s,upper:a}=e,{lower:o,upper:c}=r,h=a-s,d=c-o;if(t==="dimension")return[r,n*(d/h)];const f=(n-s)*(d/h)+o;return[r,f]},Uh=r=>(e,t,n)=>[r,n],Ch=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:s}=r;return[r,s-(t-n)]},Rh=r=>(e,t,n)=>{const{lower:s,upper:a}=r;return n=$h(n,s,a),[e,n]},Hn=class Pt{constructor(){$e(this,"ops",[]),$e(this,"currBounds",null),$e(this,"currType",null),$e(this,"reversed",!1),this.ops=[]}static translate(e){return new Pt().translate(e)}static magnify(e){return new Pt().magnify(e)}static scale(e,t){return new Pt().scale(e,t)}translate(e){const t=this.new(),n=xh(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=kh(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Ge(e,t),s=this.new(),a=Ah(n);return a.type="scale",s.ops.push(a),s}clamp(e,t){const n=Ge(e,t),s=this.new(),a=Rh(n);return a.type="clamp",s.ops.push(a),s}reBound(e,t){const n=Ge(e,t),s=this.new(),a=Uh(n);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Ch();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Pt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,s],a)=>a(n,e,s,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,s)=>{if(n.type==="scale"||t.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&t.push([s,a])}),t.forEach(([n,s])=>{const a=e.ops.slice(n,s);a.unshift(e.ops[s]),e.ops.splice(n,s-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};$e(Hn,"IDENTITY",new Hn);let Ei=Hn;const zi=class Ne{constructor(e=new Ei,t=new Ei,n=null){$e(this,"x"),$e(this,"y"),$e(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new Ne().translate(e,t)}static translateX(e){return new Ne().translateX(e)}static translateY(e){return new Ne().translateY(e)}static clamp(e){return new Ne().clamp(e)}static magnify(e){return new Ne().magnify(e)}static scale(e){return new Ne().scale(e)}static reBound(e){return new Ne().reBound(e)}translate(e,t){const n=Sh(e,t),s=this.copy();return s.x=this.x.translate(n.x),s.y=this.y.translate(n.y),s}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Eh(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Oh(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(bn(e)),t.y=t.y.scale(vn(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(bn(e)),t.y=this.y.reBound(vn(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(bn(e)),t.y=this.y.clamp(vn(e)),t}copy(){const e=new Ne;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return xs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};$e(zi,"IDENTITY",new zi);var Bh=Object.defineProperty,Ph=(r,e,t)=>e in r?Bh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g=(r,e,t)=>Ph(r,typeof e!="symbol"?e+"":e,t);let Dh=(r,e=21)=>(t=e)=>{let n="",s=t|0;for(;s--;)n+=r[Math.random()*r.length|0];return n};const Mh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",jh=Dh(Mh,11),Lh=()=>jh(),_h=i.z.enum(["static","dynamic"]),Za=(r,e)=>{const t=new M(e);if(![k.DAY,k.HOUR,k.MINUTE,k.SECOND,k.MILLISECOND,k.MICROSECOND,k.NANOSECOND].some(s=>s.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof M?new M(n):new k(n)},C=class v{constructor(e,t="UTC"){if(g(this,"value"),g(this,"encodeValue",!0),e==null)this.value=v.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*v.MILLISECOND.valueOf();else if(typeof e=="string")this.value=v.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=v.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const s=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(s.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let h=v.hours(parseInt(n??"00")).add(v.minutes(parseInt(s??"00"))).add(v.seconds(parseInt(o??"00"))).add(v.milliseconds(parseInt(c??"00")));return t==="local"&&(h=h.add(v.utcOffset)),h.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new v(BigInt(n.getTime())*v.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(v.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new k(BigInt(new Date().getTimezoneOffset())*v.MINUTE.valueOf())}static since(e){return new v().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new v(e).valueOf()}span(e){return this.range(e).span}range(e){return new Kt(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(k.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(k.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(k.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(k.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new v(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new v(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new v(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new v(t,"UTC")}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new v(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new v(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new v(t)}toString(){return this.date().toISOString()}remainder(e){return Za(this,e)}get isToday(){return this.truncate(k.DAY).equals(v.now().truncate(k.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new v(new Date)}static max(...e){let t=v.MIN;for(const n of e){const s=new v(n);s.after(t)&&(t=s)}return t}static min(...e){let t=v.MAX;for(const n of e){const s=new v(n);s.before(t)&&(t=s)}return t}static nanoseconds(e,t="UTC"){return new v(e,t)}static microseconds(e,t="UTC"){return v.nanoseconds(e*1e3,t)}static milliseconds(e,t="UTC"){return v.microseconds(e*1e3,t)}static seconds(e,t="UTC"){return v.milliseconds(e*1e3,t)}static minutes(e,t="UTC"){return v.seconds(e*60,t)}static hours(e,t="UTC"){return v.minutes(e*60,t)}static days(e,t="UTC"){return v.hours(e*24,t)}};g(C,"NANOSECOND",C.nanoseconds(1)),g(C,"MICROSECOND",C.microseconds(1)),g(C,"MILLISECOND",C.milliseconds(1)),g(C,"SECOND",C.seconds(1)),g(C,"MINUTE",C.minutes(1)),g(C,"HOUR",C.hours(1)),g(C,"DAY",C.days(1)),g(C,"MAX",new C((1n<<63n)-1n)),g(C,"MIN",new C(0)),g(C,"ZERO",new C(0)),g(C,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new C(r.value)),i.z.string().transform(r=>new C(BigInt(r))),i.z.instanceof(Number).transform(r=>new C(r)),i.z.number().transform(r=>new C(r)),i.z.instanceof(C)]));let M=C;const R=class I{constructor(e){g(this,"value"),g(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof I?e:e instanceof Ni?e.period:e instanceof M?new I(e):["number","bigint"].includes(typeof e)?I.seconds(e):new I(e)}static fromMilliseconds(e){return e instanceof I?e:e instanceof Ni?e.period:e instanceof M?new I(e):["number","bigint"].includes(typeof e)?I.milliseconds(e):new I(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new I(e).valueOf()}greaterThan(e){return this.valueOf()>new I(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new I(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new I(e).valueOf()}remainder(e){return Za(this,e)}truncate(e){return new I(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(I.DAY),t=this.truncate(I.HOUR),n=this.truncate(I.MINUTE),s=this.truncate(I.SECOND),a=this.truncate(I.MILLISECOND),o=this.truncate(I.MICROSECOND),c=this.truncate(I.NANOSECOND),h=e,d=t.sub(e),f=n.sub(t),u=s.sub(n),N=a.sub(s),S=o.sub(a),j=c.sub(o);let U="";return h.isZero||(U+=`${h.days}d `),d.isZero||(U+=`${d.hours}h `),f.isZero||(U+=`${f.minutes}m `),u.isZero||(U+=`${u.seconds}s `),N.isZero||(U+=`${N.milliseconds}ms `),S.isZero||(U+=`${S.microseconds}µs `),j.isZero||(U+=`${j.nanoseconds}ns`),U.trim()}mult(e){return new I(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(I.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(I.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(I.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(I.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(I.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(I.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new I(e).valueOf()}add(e){return new I(this.valueOf()+new I(e).valueOf())}sub(e){return new I(this.valueOf()-new I(e).valueOf())}static nanoseconds(e=1){return new I(e)}static microseconds(e=1){return I.nanoseconds(it(e,1e3))}static milliseconds(e=1){return I.microseconds(it(e,1e3))}static seconds(e=1){return I.milliseconds(it(e,1e3))}static minutes(e=1){return I.seconds(it(e,60))}static hours(e){return I.minutes(it(e,60))}static days(e){return I.hours(it(e,24))}};g(R,"NANOSECOND",R.nanoseconds(1)),g(R,"MICROSECOND",R.microseconds(1)),g(R,"MILLISECOND",R.milliseconds(1)),g(R,"SECOND",R.seconds(1)),g(R,"MINUTE",R.minutes(1)),g(R,"HOUR",R.hours(1)),g(R,"DAY",R.days(1)),g(R,"MAX",new R((1n<<63n)-1n)),g(R,"MIN",new R(0)),g(R,"ZERO",new R(0)),g(R,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new R(r.value)),i.z.string().transform(r=>new R(BigInt(r))),i.z.instanceof(Number).transform(r=>new R(r)),i.z.number().transform(r=>new R(r)),i.z.instanceof(R)]));let k=R;const Dt=class Br extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Br(e).valueOf()}get period(){return k.seconds(1/this.valueOf())}sampleCount(e){return new k(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new se(t).valueOf()}span(e){return k.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Br(e)}static khz(e){return Br.hz(e*1e3)}};g(Dt,"z",i.z.union([i.z.number().transform(r=>new Dt(r)),i.z.instanceof(Number).transform(r=>new Dt(r)),i.z.instanceof(Dt)]));let Ni=Dt;const H=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Kn(e*this.valueOf())}};g(H,"UNKNOWN",new H(0)),g(H,"BIT128",new H(16)),g(H,"BIT64",new H(8)),g(H,"BIT32",new H(4)),g(H,"BIT16",new H(2)),g(H,"BIT8",new H(1)),g(H,"z",i.z.union([i.z.number().transform(r=>new H(r)),i.z.instanceof(Number).transform(r=>new H(r)),i.z.instanceof(H)]));let se=H;const fe=class Mt{constructor(e,t){g(this,"start"),g(this,"end"),typeof e=="object"&&"start"in e?(this.start=new M(e.start),this.end=new M(e.end)):(this.start=new M(e),this.end=new M(t))}get span(){return new k(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Mt(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=k.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return n<0&&(n=-n),s<0&&(s=-s),n<=t.valueOf()&&s<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=k.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const s=M.max(n.start,e.start),a=M.min(n.end,e.end);return a.before(s)?!1:new k(a.sub(s)).greaterThanOrEqual(t)}contains(e){return e instanceof Mt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Mt(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new Mt(M.min(...e.map(t=>t.start)),M.max(...e.map(t=>t.end)))}};g(fe,"MAX",new fe(M.MIN,M.MAX)),g(fe,"MIN",new fe(M.MAX,M.MIN)),g(fe,"ZERO",new fe(M.ZERO,M.ZERO)),g(fe,"z",i.z.union([i.z.object({start:M.z,end:M.z}).transform(r=>new fe(r.start,r.end)),i.z.instanceof(fe)]));let Kt=fe;const p=class _{constructor(e){if(g(this,"value"),g(this,"encodeValue",!0),e instanceof _||typeof e=="string"||typeof e.valueOf()=="string"){this.value=e.valueOf();return}const t=_.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){this.value=t.valueOf();return}throw this.value=_.UNKNOWN.valueOf(),new Error(`unable to find data type for ${e.toString()}`)}valueOf(){return this.value}get Array(){const e=_.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(_.JSON)||this.equals(_.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(_.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=_.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(_.UINT8)||this.equals(_.UINT16)||this.equals(_.UINT32)||this.equals(_.UINT64)}get isSigned(){return this.equals(_.INT8)||this.equals(_.INT16)||this.equals(_.INT32)||this.equals(_.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(_.INT32)&&e.equals(_.FLOAT64)||this.equals(_.INT8)&&e.equals(_.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}toJSON(){return this.toString()}get usesBigInt(){return _.BIG_INT_TYPES.some(e=>e.equals(this))}};g(p,"UNKNOWN",new p("unknown")),g(p,"FLOAT64",new p("float64")),g(p,"FLOAT32",new p("float32")),g(p,"INT64",new p("int64")),g(p,"INT32",new p("int32")),g(p,"INT16",new p("int16")),g(p,"INT8",new p("int8")),g(p,"UINT64",new p("uint64")),g(p,"UINT32",new p("uint32")),g(p,"UINT16",new p("uint16")),g(p,"UINT8",new p("uint8")),g(p,"BOOLEAN",p.UINT8),g(p,"TIMESTAMP",new p("timestamp")),g(p,"UUID",new p("uuid")),g(p,"STRING",new p("string")),g(p,"JSON",new p("json")),g(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),g(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),g(p,"DENSITIES",new Map([[p.UINT8.toString(),se.BIT8],[p.UINT16.toString(),se.BIT16],[p.UINT32.toString(),se.BIT32],[p.UINT64.toString(),se.BIT64],[p.FLOAT32.toString(),se.BIT32],[p.FLOAT64.toString(),se.BIT64],[p.INT8.toString(),se.BIT8],[p.INT16.toString(),se.BIT16],[p.INT32.toString(),se.BIT32],[p.INT64.toString(),se.BIT64],[p.TIMESTAMP.toString(),se.BIT64],[p.STRING.toString(),se.UNKNOWN],[p.JSON.toString(),se.UNKNOWN],[p.UUID.toString(),se.BIT128]])),g(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),g(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),g(p,"z",i.z.union([i.z.string().transform(r=>new p(r)),i.z.instanceof(p)]));let D=p;const te=class Y extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Y.bytes(this.valueOf()+e.valueOf())}sub(e){return Y.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Y(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Y.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Y.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Y.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Y.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Y.TERABYTE.valueOf()}toString(){const e=this.truncate(Y.TERABYTE),t=this.truncate(Y.GIGABYTE),n=this.truncate(Y.MEGABYTE),s=this.truncate(Y.KILOBYTE),a=this.truncate(Y.BYTE),o=e,c=t.sub(e),h=n.sub(t),d=s.sub(n),f=a.sub(s);let u="";return o.isZero||(u+=`${o.terabytes}TB `),c.isZero||(u+=`${c.gigabytes}GB `),h.isZero||(u+=`${h.megabytes}MB `),d.isZero||(u+=`${d.kilobytes}KB `),(!f.isZero||u==="")&&(u+=`${f.valueOf()}B`),u.trim()}static bytes(e=1){return new Y(e)}static kilobytes(e=1){return Y.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Y.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Y.megabytes(e.valueOf()*1e3)}static terabytes(e){return Y.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};g(te,"BYTE",new te(1)),g(te,"KILOBYTE",te.kilobytes(1)),g(te,"MEGABYTE",te.megabytes(1)),g(te,"GIGABYTE",te.gigabytes(1)),g(te,"TERABYTE",te.terabytes(1)),g(te,"ZERO",new te(0)),g(te,"z",i.z.union([i.z.number().transform(r=>new te(r)),i.z.instanceof(te)]));let Kn=te;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const qa=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof M||r instanceof k||r instanceof Date},Zh=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):jt(t,-n).valueOf(),jt=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),qh=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Vh?!0:qa(r),Ce=-1,Fh=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Yh=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Jn=10,Wh=(r,e)=>{if(r==="string"&&!e.isVariable)throw new Error(`cannot convert series of type ${e.toString()} to string`);if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Lt=class ye{constructor(e){g(this,"key",""),g(this,"isSynnaxSeries",!0),g(this,"dataType"),g(this,"sampleOffset"),g(this,"gl"),g(this,"_data"),g(this,"timeRange",Kt.ZERO),g(this,"alignment",0n),g(this,"_cachedMin"),g(this,"_cachedMax"),g(this,"writePos",Ce),g(this,"_refCount",0),g(this,"_cachedLength"),g(this,"_cachedIndexes"),qh(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,key:c=Lh()}=e,h=e.data??[];if(h instanceof ye||typeof h=="object"&&"isSynnaxSeries"in h&&h.isSynnaxSeries===!0){const u=h;this.key=u.key,this.dataType=u.dataType,this.sampleOffset=u.sampleOffset,this.gl=u.gl,this._data=u._data,this.timeRange=u.timeRange,this.alignment=u.alignment,this._cachedMin=u._cachedMin,this._cachedMax=u._cachedMax,this.writePos=u.writePos,this._refCount=u._refCount,this._cachedLength=u._cachedLength;return}const d=qa(h),f=Array.isArray(h);if(t!=null)this.dataType=new D(t);else{if(h instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let u=h;if(!d){if(h.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");u=h[0]}if(typeof u=="string")this.dataType=D.STRING;else if(typeof u=="number")this.dataType=D.FLOAT64;else if(typeof u=="bigint")this.dataType=D.INT64;else if(typeof u=="boolean")this.dataType=D.BOOLEAN;else if(u instanceof M||u instanceof Date||u instanceof M)this.dataType=D.TIMESTAMP;else if(typeof u=="object")this.dataType=D.JSON;else throw new Error(`cannot infer data type of ${typeof u} when constructing a Series from a JS array`)}else this.dataType=new D(h)}if(!f&&!d)this._data=h;else{let u=d?[h]:h;const N=u[0];(N instanceof M||N instanceof Date||N instanceof k)&&(u=u.map(S=>new M(S).valueOf())),this.dataType.equals(D.STRING)?(this._cachedLength=u.length,this._data=new TextEncoder().encode(`${u.join(`
3
+ `).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const s=t.split(",").map(o=>o.trim()),a={};return s.forEach(o=>{a[o]=[]}),n.forEach(o=>{const c=o.split(",").map(h=>h.trim());s.forEach((h,d)=>{const f=this.parseValue(c[d]);f!=null&&a[h].push(f)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},sh=class{constructor(){yt(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r)}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const De=new tr;De.register({type:0,encode:r=>{if(ArrayBuffer.isView(r)){const e=Array.from(r);return Bt(e,{extensionCodec:De})}return Is(r)&&"encode_value"in r?typeof r.value=="bigint"?Bt(r.value.toString(),{extensionCodec:De}):Bt(r.value,{extensionCodec:De}):typeof r=="bigint"?Bt(r.toString(),{extensionCodec:De}):null},decode:r=>Pa(r,{extensionCodec:De})});let ih=class{constructor(){yt(this,"contentType","application/msgpack")}encode(r){const e=xa(r);return Bt(e,{extensionCodec:De}).slice()}decode(r,e){const t=Pa(r,{extensionCodec:De}),n=Ns(t);return e!=null?e.parse(n):n}static registerCustomType(){}};const Rr=new rh;new nh;new sh;new ih;const ah=r=>r!=null&&typeof r=="object"&&"toString"in r,oh=(r,e=!1)=>{const t=ah(r)?"stringer":typeof r;let n;switch(t){case"string":n=(s,a)=>s.localeCompare(a);break;case"stringer":n=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":n=(s,a)=>Number(s)-Number(a);break;case"bigint":n=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":n=(s,a)=>Number(s)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?ch(n):n},ch=r=>(e,t)=>r(t,e),Vr=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const Da=i.z.object({width:i.z.number(),height:i.z.number()}),lh=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),hh=["width","height"];i.z.enum(hh);const uh=["start","center","end"],dh=["signedWidth","signedHeight"];i.z.enum(dh);const jr=i.z.object({x:i.z.number(),y:i.z.number()}),fh=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),yh=["x","y"],Ma=i.z.enum(yh),ja=["top","right","bottom","left"];i.z.enum(ja);const gh=["left","right"],La=i.z.enum(gh),ph=["top","bottom"],_a=i.z.enum(ph),Za=["center"],Ti=i.z.enum(Za),wh=[...ja,...Za],qa=i.z.enum(wh);i.z.enum(uh);const mh=["first","last"];i.z.enum(mh);const bh=i.z.object({lower:i.z.number(),upper:i.z.number()}),vh=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([bh,Vr]);i.z.union([vh,Vr]);i.z.enum([...Ma.options,...qa.options]);i.z.union([Ma,qa,i.z.instanceof(String)]);const Th=r=>typeof r=="bigint"||r instanceof BigInt,it=(r,e)=>Th(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),Ge=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Oi(r);return Oi(t)},Oi=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Si=(r,e)=>{const t=Ge(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};i.z.object({x:La.or(Ti),y:_a.or(Ti)});const Oh=i.z.object({x:La,y:_a}),Sh=Object.freeze({x:"left",y:"top"}),Eh=(r,e)=>r.x===e.x&&r.y===e.y,Ei=i.z.union([i.z.number(),jr,Vr,Da,lh,fh]),zh=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},zi=Object.freeze({x:0,y:0}),zr=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:zr,left:zr,width:zr,height:zr});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:jr,two:jr,root:Oh});const xs=(r,e,t=0,n=0,s)=>{const a={one:{...zi},two:{...zi},root:s??Sh};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:s??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},bn=r=>{const e=xs(r);return{lower:e.one.x,upper:e.two.x}},vn=r=>{const e=xs(r);return{lower:e.one.y,upper:e.two.y}},Nh=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Ih=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([Da,Ih,jr,Vr]);var $h=Object.defineProperty,xh=(r,e,t)=>e in r?$h(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,$e=(r,e,t)=>xh(r,typeof e!="symbol"?e+"":e,t);const kh=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;i.z.object({offset:Ei,scale:Ei});i.z.object({offset:i.z.number(),scale:i.z.number()});const Ah=r=>(e,t,n,s)=>t==="dimension"?[e,n]:[e,s?n-r:n+r],Uh=r=>(e,t,n,s)=>[e,s?n/r:n*r],Ch=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:s,upper:a}=e,{lower:o,upper:c}=r,h=a-s,d=c-o;if(t==="dimension")return[r,n*(d/h)];const f=(n-s)*(d/h)+o;return[r,f]},Rh=r=>(e,t,n)=>[r,n],Bh=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:s}=r;return[r,s-(t-n)]},Ph=r=>(e,t,n)=>{const{lower:s,upper:a}=r;return n=kh(n,s,a),[e,n]},Hn=class Pt{constructor(){$e(this,"ops",[]),$e(this,"currBounds",null),$e(this,"currType",null),$e(this,"reversed",!1),this.ops=[]}static translate(e){return new Pt().translate(e)}static magnify(e){return new Pt().magnify(e)}static scale(e,t){return new Pt().scale(e,t)}translate(e){const t=this.new(),n=Ah(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Uh(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Ge(e,t),s=this.new(),a=Ch(n);return a.type="scale",s.ops.push(a),s}clamp(e,t){const n=Ge(e,t),s=this.new(),a=Ph(n);return a.type="clamp",s.ops.push(a),s}reBound(e,t){const n=Ge(e,t),s=this.new(),a=Rh(n);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Bh();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Pt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,s],a)=>a(n,e,s,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,s)=>{if(n.type==="scale"||t.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&t.push([s,a])}),t.forEach(([n,s])=>{const a=e.ops.slice(n,s);a.unshift(e.ops[s]),e.ops.splice(n,s-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};$e(Hn,"IDENTITY",new Hn);let Ni=Hn;const Ii=class Ne{constructor(e=new Ni,t=new Ni,n=null){$e(this,"x"),$e(this,"y"),$e(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new Ne().translate(e,t)}static translateX(e){return new Ne().translateX(e)}static translateY(e){return new Ne().translateY(e)}static clamp(e){return new Ne().clamp(e)}static magnify(e){return new Ne().magnify(e)}static scale(e){return new Ne().scale(e)}static reBound(e){return new Ne().reBound(e)}translate(e,t){const n=zh(e,t),s=this.copy();return s.x=this.x.translate(n.x),s.y=this.y.translate(n.y),s}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Nh(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Eh(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(bn(e)),t.y=t.y.scale(vn(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(bn(e)),t.y=this.y.reBound(vn(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(bn(e)),t.y=this.y.clamp(vn(e)),t}copy(){const e=new Ne;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return xs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};$e(Ii,"IDENTITY",new Ii);var Dh=Object.defineProperty,Mh=(r,e,t)=>e in r?Dh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g=(r,e,t)=>Mh(r,typeof e!="symbol"?e+"":e,t);let jh=(r,e=21)=>(t=e)=>{let n="",s=t|0;for(;s--;)n+=r[Math.random()*r.length|0];return n};const Lh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",_h=jh(Lh,11),Zh=()=>_h(),qh=i.z.enum(["static","dynamic"]),Fa=(r,e)=>{const t=new M(e);if(![k.DAY,k.HOUR,k.MINUTE,k.SECOND,k.MILLISECOND,k.MICROSECOND,k.NANOSECOND].some(s=>s.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof M?new M(n):new k(n)},C=class v{constructor(e,t="UTC"){if(g(this,"value"),g(this,"encodeValue",!0),e==null)this.value=v.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*v.MILLISECOND.valueOf();else if(typeof e=="string")this.value=v.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=v.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const s=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(s.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let h=v.hours(parseInt(n??"00")).add(v.minutes(parseInt(s??"00"))).add(v.seconds(parseInt(o??"00"))).add(v.milliseconds(parseInt(c??"00")));return t==="local"&&(h=h.add(v.utcOffset)),h.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new v(BigInt(n.getTime())*v.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(v.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new k(BigInt(new Date().getTimezoneOffset())*v.MINUTE.valueOf())}static since(e){return new v().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new v(e).valueOf()}span(e){return this.range(e).span}range(e){return new Kt(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(k.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(k.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(k.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(k.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new v(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new v(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new v(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new v(t,"UTC")}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new v(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new v(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new v(t)}toString(){return this.date().toISOString()}remainder(e){return Fa(this,e)}get isToday(){return this.truncate(k.DAY).equals(v.now().truncate(k.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new v(new Date)}static max(...e){let t=v.MIN;for(const n of e){const s=new v(n);s.after(t)&&(t=s)}return t}static min(...e){let t=v.MAX;for(const n of e){const s=new v(n);s.before(t)&&(t=s)}return t}static nanoseconds(e,t="UTC"){return new v(e,t)}static microseconds(e,t="UTC"){return v.nanoseconds(e*1e3,t)}static milliseconds(e,t="UTC"){return v.microseconds(e*1e3,t)}static seconds(e,t="UTC"){return v.milliseconds(e*1e3,t)}static minutes(e,t="UTC"){return v.seconds(e*60,t)}static hours(e,t="UTC"){return v.minutes(e*60,t)}static days(e,t="UTC"){return v.hours(e*24,t)}};g(C,"NANOSECOND",C.nanoseconds(1)),g(C,"MICROSECOND",C.microseconds(1)),g(C,"MILLISECOND",C.milliseconds(1)),g(C,"SECOND",C.seconds(1)),g(C,"MINUTE",C.minutes(1)),g(C,"HOUR",C.hours(1)),g(C,"DAY",C.days(1)),g(C,"MAX",new C((1n<<63n)-1n)),g(C,"MIN",new C(0)),g(C,"ZERO",new C(0)),g(C,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new C(r.value)),i.z.string().transform(r=>new C(BigInt(r))),i.z.instanceof(Number).transform(r=>new C(r)),i.z.number().transform(r=>new C(r)),i.z.instanceof(C)]));let M=C;const R=class I{constructor(e){g(this,"value"),g(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof I?e:e instanceof $i?e.period:e instanceof M?new I(e):["number","bigint"].includes(typeof e)?I.seconds(e):new I(e)}static fromMilliseconds(e){return e instanceof I?e:e instanceof $i?e.period:e instanceof M?new I(e):["number","bigint"].includes(typeof e)?I.milliseconds(e):new I(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new I(e).valueOf()}greaterThan(e){return this.valueOf()>new I(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new I(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new I(e).valueOf()}remainder(e){return Fa(this,e)}truncate(e){return new I(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(I.DAY),t=this.truncate(I.HOUR),n=this.truncate(I.MINUTE),s=this.truncate(I.SECOND),a=this.truncate(I.MILLISECOND),o=this.truncate(I.MICROSECOND),c=this.truncate(I.NANOSECOND),h=e,d=t.sub(e),f=n.sub(t),u=s.sub(n),N=a.sub(s),S=o.sub(a),j=c.sub(o);let U="";return h.isZero||(U+=`${h.days}d `),d.isZero||(U+=`${d.hours}h `),f.isZero||(U+=`${f.minutes}m `),u.isZero||(U+=`${u.seconds}s `),N.isZero||(U+=`${N.milliseconds}ms `),S.isZero||(U+=`${S.microseconds}µs `),j.isZero||(U+=`${j.nanoseconds}ns`),U.trim()}mult(e){return new I(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(I.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(I.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(I.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(I.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(I.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(I.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new I(e).valueOf()}add(e){return new I(this.valueOf()+new I(e).valueOf())}sub(e){return new I(this.valueOf()-new I(e).valueOf())}static nanoseconds(e=1){return new I(e)}static microseconds(e=1){return I.nanoseconds(it(e,1e3))}static milliseconds(e=1){return I.microseconds(it(e,1e3))}static seconds(e=1){return I.milliseconds(it(e,1e3))}static minutes(e=1){return I.seconds(it(e,60))}static hours(e){return I.minutes(it(e,60))}static days(e){return I.hours(it(e,24))}};g(R,"NANOSECOND",R.nanoseconds(1)),g(R,"MICROSECOND",R.microseconds(1)),g(R,"MILLISECOND",R.milliseconds(1)),g(R,"SECOND",R.seconds(1)),g(R,"MINUTE",R.minutes(1)),g(R,"HOUR",R.hours(1)),g(R,"DAY",R.days(1)),g(R,"MAX",new R((1n<<63n)-1n)),g(R,"MIN",new R(0)),g(R,"ZERO",new R(0)),g(R,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new R(r.value)),i.z.string().transform(r=>new R(BigInt(r))),i.z.instanceof(Number).transform(r=>new R(r)),i.z.number().transform(r=>new R(r)),i.z.instanceof(R)]));let k=R;const Dt=class Br extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Br(e).valueOf()}get period(){return k.seconds(1/this.valueOf())}sampleCount(e){return new k(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new se(t).valueOf()}span(e){return k.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Br(e)}static khz(e){return Br.hz(e*1e3)}};g(Dt,"z",i.z.union([i.z.number().transform(r=>new Dt(r)),i.z.instanceof(Number).transform(r=>new Dt(r)),i.z.instanceof(Dt)]));let $i=Dt;const H=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new Kn(e*this.valueOf())}};g(H,"UNKNOWN",new H(0)),g(H,"BIT128",new H(16)),g(H,"BIT64",new H(8)),g(H,"BIT32",new H(4)),g(H,"BIT16",new H(2)),g(H,"BIT8",new H(1)),g(H,"z",i.z.union([i.z.number().transform(r=>new H(r)),i.z.instanceof(Number).transform(r=>new H(r)),i.z.instanceof(H)]));let se=H;const fe=class Mt{constructor(e,t){g(this,"start"),g(this,"end"),typeof e=="object"&&"start"in e?(this.start=new M(e.start),this.end=new M(e.end)):(this.start=new M(e),this.end=new M(t))}get span(){return new k(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Mt(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=k.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return n<0&&(n=-n),s<0&&(s=-s),n<=t.valueOf()&&s<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=k.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const s=M.max(n.start,e.start),a=M.min(n.end,e.end);return a.before(s)?!1:new k(a.sub(s)).greaterThanOrEqual(t)}contains(e){return e instanceof Mt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Mt(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new Mt(M.min(...e.map(t=>t.start)),M.max(...e.map(t=>t.end)))}};g(fe,"MAX",new fe(M.MIN,M.MAX)),g(fe,"MIN",new fe(M.MAX,M.MIN)),g(fe,"ZERO",new fe(M.ZERO,M.ZERO)),g(fe,"z",i.z.union([i.z.object({start:M.z,end:M.z}).transform(r=>new fe(r.start,r.end)),i.z.instanceof(fe)]));let Kt=fe;const p=class _{constructor(e){if(g(this,"value"),g(this,"encodeValue",!0),e instanceof _||typeof e=="string"||typeof e.valueOf()=="string"){this.value=e.valueOf();return}const t=_.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){this.value=t.valueOf();return}throw this.value=_.UNKNOWN.valueOf(),new Error(`unable to find data type for ${e.toString()}`)}valueOf(){return this.value}get Array(){const e=_.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(_.JSON)||this.equals(_.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(_.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=_.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(_.UINT8)||this.equals(_.UINT16)||this.equals(_.UINT32)||this.equals(_.UINT64)}get isSigned(){return this.equals(_.INT8)||this.equals(_.INT16)||this.equals(_.INT32)||this.equals(_.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(_.INT32)&&e.equals(_.FLOAT64)||this.equals(_.INT8)&&e.equals(_.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}toJSON(){return this.toString()}get usesBigInt(){return _.BIG_INT_TYPES.some(e=>e.equals(this))}};g(p,"UNKNOWN",new p("unknown")),g(p,"FLOAT64",new p("float64")),g(p,"FLOAT32",new p("float32")),g(p,"INT64",new p("int64")),g(p,"INT32",new p("int32")),g(p,"INT16",new p("int16")),g(p,"INT8",new p("int8")),g(p,"UINT64",new p("uint64")),g(p,"UINT32",new p("uint32")),g(p,"UINT16",new p("uint16")),g(p,"UINT8",new p("uint8")),g(p,"BOOLEAN",p.UINT8),g(p,"TIMESTAMP",new p("timestamp")),g(p,"UUID",new p("uuid")),g(p,"STRING",new p("string")),g(p,"JSON",new p("json")),g(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),g(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),g(p,"DENSITIES",new Map([[p.UINT8.toString(),se.BIT8],[p.UINT16.toString(),se.BIT16],[p.UINT32.toString(),se.BIT32],[p.UINT64.toString(),se.BIT64],[p.FLOAT32.toString(),se.BIT32],[p.FLOAT64.toString(),se.BIT64],[p.INT8.toString(),se.BIT8],[p.INT16.toString(),se.BIT16],[p.INT32.toString(),se.BIT32],[p.INT64.toString(),se.BIT64],[p.TIMESTAMP.toString(),se.BIT64],[p.STRING.toString(),se.UNKNOWN],[p.JSON.toString(),se.UNKNOWN],[p.UUID.toString(),se.BIT128]])),g(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),g(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),g(p,"z",i.z.union([i.z.string().transform(r=>new p(r)),i.z.instanceof(p)]));let D=p;const te=class Y extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Y.bytes(this.valueOf()+e.valueOf())}sub(e){return Y.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Y(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Y.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Y.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Y.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Y.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Y.TERABYTE.valueOf()}toString(){const e=this.truncate(Y.TERABYTE),t=this.truncate(Y.GIGABYTE),n=this.truncate(Y.MEGABYTE),s=this.truncate(Y.KILOBYTE),a=this.truncate(Y.BYTE),o=e,c=t.sub(e),h=n.sub(t),d=s.sub(n),f=a.sub(s);let u="";return o.isZero||(u+=`${o.terabytes}TB `),c.isZero||(u+=`${c.gigabytes}GB `),h.isZero||(u+=`${h.megabytes}MB `),d.isZero||(u+=`${d.kilobytes}KB `),(!f.isZero||u==="")&&(u+=`${f.valueOf()}B`),u.trim()}static bytes(e=1){return new Y(e)}static kilobytes(e=1){return Y.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Y.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Y.megabytes(e.valueOf()*1e3)}static terabytes(e){return Y.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};g(te,"BYTE",new te(1)),g(te,"KILOBYTE",te.kilobytes(1)),g(te,"MEGABYTE",te.megabytes(1)),g(te,"GIGABYTE",te.gigabytes(1)),g(te,"TERABYTE",te.terabytes(1)),g(te,"ZERO",new te(0)),g(te,"z",i.z.union([i.z.number().transform(r=>new te(r)),i.z.instanceof(te)]));let Kn=te;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Ya=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof M||r instanceof k||r instanceof Date},Fh=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):jt(t,-n).valueOf(),jt=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),Yh=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Hh?!0:Ya(r),Ce=-1,Wh=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Vh=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),Jn=10,Gh=(r,e)=>{if(r==="string"&&!e.isVariable)throw new Error(`cannot convert series of type ${e.toString()} to string`);if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Lt=class ye{constructor(e){g(this,"key",""),g(this,"isSynnaxSeries",!0),g(this,"dataType"),g(this,"sampleOffset"),g(this,"gl"),g(this,"_data"),g(this,"timeRange",Kt.ZERO),g(this,"alignment",0n),g(this,"_cachedMin"),g(this,"_cachedMax"),g(this,"writePos",Ce),g(this,"_refCount",0),g(this,"_cachedLength"),g(this,"_cachedIndexes"),Yh(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,key:c=Zh()}=e,h=e.data??[];if(h instanceof ye||typeof h=="object"&&"isSynnaxSeries"in h&&h.isSynnaxSeries===!0){const u=h;this.key=u.key,this.dataType=u.dataType,this.sampleOffset=u.sampleOffset,this.gl=u.gl,this._data=u._data,this.timeRange=u.timeRange,this.alignment=u.alignment,this._cachedMin=u._cachedMin,this._cachedMax=u._cachedMax,this.writePos=u.writePos,this._refCount=u._refCount,this._cachedLength=u._cachedLength;return}const d=Ya(h),f=Array.isArray(h);if(t!=null)this.dataType=new D(t);else{if(h instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let u=h;if(!d){if(h.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");u=h[0]}if(typeof u=="string")this.dataType=D.STRING;else if(typeof u=="number")this.dataType=D.FLOAT64;else if(typeof u=="bigint")this.dataType=D.INT64;else if(typeof u=="boolean")this.dataType=D.BOOLEAN;else if(u instanceof M||u instanceof Date||u instanceof M)this.dataType=D.TIMESTAMP;else if(typeof u=="object")this.dataType=D.JSON;else throw new Error(`cannot infer data type of ${typeof u} when constructing a Series from a JS array`)}else this.dataType=new D(h)}if(!f&&!d)this._data=h;else{let u=d?[h]:h;const N=u[0];(N instanceof M||N instanceof Date||N instanceof k)&&(u=u.map(S=>new M(S).valueOf())),this.dataType.equals(D.STRING)?(this._cachedLength=u.length,this._data=new TextEncoder().encode(`${u.join(`
4
4
  `)}
5
5
  `).buffer):this.dataType.equals(D.JSON)?(this._cachedLength=u.length,this._data=new TextEncoder().encode(`${u.map(S=>Rr.encodeString(S)).join(`
6
6
  `)}
@@ -10,9 +10,9 @@
10
10
  `)}
11
11
  `);return new ye({data:n,dataType:D.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount<=0){console.warn("attempted to release a series with a negative reference count");return}this._refCount--,this._refCount===0&&this.gl.control!=null&&this.maybeGarbageCollectGLBuffer(this.gl.control)}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Ce)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===Ce)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this._cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Ce?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(D.STRING,D.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
12
12
  `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(D.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=D.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const s=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(s.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(D.JSON))throw new Error("cannot parse non-JSON series as JSON");return new TextDecoder().decode(this.underlyingData).split(`
13
- `).slice(0,-1).map(t=>e.parse(Rr.decodeString(t)))}get byteCapacity(){return new Kn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ce?this.byteCapacity:this.dataType.isVariable?new Kn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ce?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,s)=>{n===Jn&&(e++,t.push(s+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let s=0;s<this.length;s++)n[s]=Zh(this.dataType,e,this.data[s],t);return new ye({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(D.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),jt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(D.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),jt(this._cachedMin,this.sampleOffset))}get bounds(){return Ge(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return jt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return jt(n,this.sampleOffset)}atVariable(e,t){let n=0,s=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Jn){if(e===0){s=o;break}n=o+1,e--}if(s===0&&(s=this.data.length),n>=s||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,s);return this.dataType.equals(D.STRING)?new TextDecoder().decode(a):Ns(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const s=ih(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(D.FLOAT32)&&!this.dataType.equals(D.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:s}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Ce){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ce}as(e){return Wh(e,this.dataType),this}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ui(this.alignmentBounds.lower),upper:Ui(this.alignmentBounds.upper)},timeRange:(e=this.timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return Ge(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Gh(this);return this.dataType.equals(D.JSON)?new Hh(e):e}return new Kh(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Ii(this,e,t??this.length)}subAlignmentIterator(e,t){return new Ii(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ye({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let s;return e?s=this.data.subarray(t,n):s=this.data.slice(t,n),new ye({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ye({data:this.buffer,dataType:this.dataType,timeRange:Kt.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){var e,t;let n=`${this.dataType.toString()} ${this.length} [`;if(this.length<=10)n+=Array.from(this).map(s=>s.toString());else{for(let s=0;s<5;s++)n+=`${(e=this.at(s))==null?void 0:e.toString()}`,s<4&&(n+=",");n+="...";for(let s=-5;s<0;s++)n+=(t=this.at(s))==null?void 0:t.toString(),s<-1&&(n+=",")}return n+="]",n}};g(Lt,"crudeZ",i.z.object({timeRange:Kt.z.optional(),dataType:D.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Fh,Yh,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:_h.optional().default("static").optional()})),g(Lt,"z",Lt.crudeZ.transform(r=>new Lt(r)));let Vh=Lt,Ii=class{constructor(r,e,t){g(this,"series"),g(this,"end"),g(this,"index"),this.series=r;const n=Ge(0,r.length);this.end=Ti(n,t),this.index=Ti(n,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class Gh{constructor(e){if(g(this,"series"),g(this,"index"),g(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==Jn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var $i,xi;const Fa=class Ya{constructor(e){g(this,"wrapped"),g(this,$i,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Rr.decodeString(e.value,Ya.SCHEMA)}}[(xi=Symbol.iterator,$i=Symbol.toStringTag,xi)](){return this}};g(Fa,"SCHEMA",i.z.record(i.z.string(),i.z.unknown()));let Hh=Fa;var ki,Ai;class Kh{constructor(e){g(this,"series"),g(this,"index"),g(this,ki,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Ai=Symbol.iterator,ki=Symbol.toStringTag,Ai)](){return this}}const Ui=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};i.z.object({key:i.z.string(),value:i.z.string()});i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const Wa=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Jh=Wa(),Va=["macOS","Windows","Linux"],Xh=["macos","windows","linux"],Qh={macos:"macOS",windows:"Windows",linux:"Linux"},eu=i.z.enum(Va).or(i.z.enum(Xh).transform(r=>Qh[r])),tu=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"macOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"};let Tn;const ru=(r={})=>{const{force:e,default:t}=r;return e??Tn??(Tn=tu(),Tn??t)},Ga=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Va,RUNTIME:Jh,detect:Wa,getOS:ru,osZ:eu},Symbol.toStringTag,{value:"Module"}));var nu=Object.defineProperty,su=(r,e,t)=>e in r?nu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_t=(r,e,t)=>su(r,typeof e!="symbol"?e+"":e,t);const iu=(...r)=>r.map(Ha).join(""),Ha=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),au=r=>r.endsWith("/")?r.slice(0,-1):r,ou=(r,e="")=>r===null?"":`?${Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&")}`,Xn=class Qn{constructor({host:e,port:t,protocol:n="",pathPrefix:s=""}){_t(this,"protocol"),_t(this,"host"),_t(this,"port"),_t(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Ha(s)}replace(e){return new Qn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Qn({...this,pathPrefix:iu(this.path,e)})}toString(){return au(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};_t(Xn,"UNKNOWN",new Xn({host:"unknown",port:0}));let cu=Xn;const lu=-128,hu=127;i.z.number().int().min(lu).max(hu);const uu=-32768,du=32767;i.z.number().int().min(uu).max(du);const fu=-2147483648,yu=2147483647;i.z.number().int().min(fu).max(yu);const gu=-9223372036854775808n,pu=9223372036854775807n;i.z.bigint().min(gu).max(pu);const wu=255;i.z.number().int().min(0).max(wu);const mu=65535;i.z.number().int().min(0).max(mu);const bu=4294967295;i.z.number().int().min(0).max(bu);const vu=18446744073709551615n;i.z.bigint().min(0n).max(vu);var Tu=Object.defineProperty,Ou=(r,e,t)=>e in r?Tu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ve=(r,e,t)=>Ou(r,typeof e!="symbol"?e+"":e,t);const Su=async r=>await new Promise(e=>setTimeout(e,k.fromMilliseconds(r).milliseconds));class Eu{constructor(e){ve(this,"config"),ve(this,"retries"),ve(this,"interval"),this.config={baseInterval:new k((e==null?void 0:e.baseInterval)??k.seconds(1)),maxRetries:(e==null?void 0:e.maxRetries)??5,scale:(e==null?void 0:e.scale)??1,sleepFn:(e==null?void 0:e.sleepFn)??Su},this.retries=0,this.interval=new k(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const zu=i.z.object({baseInterval:k.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Nu=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Eu,breakerConfig:zu},Symbol.toStringTag,{value:"Module"})),Iu=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,ks=i.z.string().regex(Iu),gt=i.z.number().min(0).max(255),$u=i.z.number().min(0).max(1),Ka=i.z.tuple([gt,gt,gt,$u]),Ja=i.z.tuple([gt,gt,gt]),As=(r,e=1)=>{if(typeof r=="string")return ku(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}throw new Error(`Invalid color: ${JSON.stringify(r)}`)},xu=i.z.union([ks,Ka,Ja]).transform(r=>As(r)),ku=(r,e=1)=>{if(!ks.safeParse(r).success)throw new Error(`Invalid hex color: ${r}`);return r=Au(r),[Nr(r,0),Nr(r,2),Nr(r,4),r.length===8?Nr(r,6)/255:e]},Nr=(r,e)=>parseInt(r.slice(e,e+2),16),Au=r=>r.startsWith("#")?r.slice(1):r,Uu=i.z.union([ks,Ka,i.z.string(),Ja]);As("#000000");As("#ffffff");const Cu=i.z.object({key:i.z.string(),color:Uu,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Cu);const Ru=i.z.object({key:i.z.string(),name:i.z.string(),color:xu});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Ru)});const Bu=i.z.number().int().min(0).max(255),Pu=i.z.object({name:i.z.string(),key:i.z.string()}),Lr=r=>i.z.object({subject:Pu,resource:r,authority:Bu}),Du=i.z.object({from:Lr(i.z.any()),to:i.z.null()}),Mu=i.z.object({from:i.z.null(),to:Lr(i.z.any())});i.z.union([Du,Mu,i.z.object({from:Lr(i.z.any()),to:Lr(i.z.any())})]);const ju=r=>Object.getOwnPropertySymbols(globalThis).includes(r),Lu=(r,e)=>{const t=Symbol.for(r);if(!ju(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},_u=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Gr=r=>{var e;return e=class extends Error{constructor(t,n){super(t,n),ve(this,"discriminator",e.discriminator),ve(this,"type",e.TYPE),ve(this,"matches",e.matches),this.name=e.TYPE}static sub(t){return Gr(`${r}.${t}`)}},ve(e,"discriminator","FreighterError"),ve(e,"TYPE",r),ve(e,"matches",_u(r)),e},Xa=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},ot="unknown",es="nil";class Zu{constructor(){ve(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:es,data:""};if(Xa(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:ot,data:e.message};if(typeof e=="string")return{type:ot,data:e};try{return{type:ot,data:JSON.stringify(e)}}catch{return{type:ot,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===es)return null;if(e.type===ot)return new ts(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new ts(e.data)}}const Us=Lu("synnax-error-registry",()=>new Zu),qu=({encode:r,decode:e})=>Us().register({encode:r,decode:e}),Fu=r=>Us().encode(r),Yu=r=>r==null?null:Us().decode(r);class ts extends Gr("unknown"){}const Wu=i.z.object({type:i.z.string(),data:i.z.string()});class Vu extends Gr("canceled"){}const qe=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Vu,NONE:es,UNKNOWN:ot,Unknown:ts,createTyped:Gr,decode:Yu,encode:Fu,isTyped:Xa,payloadZ:Wu,register:qu},Symbol.toStringTag,{value:"Module"}));i.object({jsonrpc:i.string(),id:i.number().optional(),method:i.string().optional(),params:i.unknown().optional(),result:i.unknown().optional()});i.z.string().regex(/^\d+\.\d+\.\d+$/);const Gu=["standard","scientific","engineering"];i.z.enum(Gu);let hr=class extends qe.createTyped("freighter"){},ue=class extends hr.sub("eof"){constructor(){super("EOF")}},bt=class extends hr.sub("stream_closed"){constructor(){super("StreamClosed")}},Fe=class extends hr.sub("unreachable"){constructor(e={}){const{message:t="Unreachable",url:n=cu.UNKNOWN}=e;super(t),G(this,"url"),this.url=n}};const Hu=r=>{if(!r.type.startsWith(hr.TYPE))return null;if(ue.matches(r))return{type:ue.TYPE,data:"EOF"};if(bt.matches(r))return{type:bt.TYPE,data:"StreamClosed"};if(Fe.matches(r))return{type:Fe.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Ku=r=>{if(!r.type.startsWith(hr.TYPE))return null;switch(r.type){case ue.TYPE:return new ue;case bt.TYPE:return new bt;case Fe.TYPE:return new Fe;default:throw new qe.Unknown(`Unknown error type: ${r.data}`)}};qe.register({encode:Hu,decode:Ku});class Qa{constructor(){G(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const s=async a=>{if(n===this.middleware.length)return await t(a);const o=this.middleware[n];return n++,await o(a,s)};return await s(e)}}const eo="Content-Type",Ci=r=>{if(Ga.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(s,a)=>await e(s,{...a,agent:n})},Ju=r=>"code"in r&&r.code==="ECONNREFUSED"||r.message.toLowerCase().includes("load failed"),Xu=400;class Qu extends Qa{constructor(e,t,n=!1){return super(),G(this,"endpoint"),G(this,"encoder"),G(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=Ci(this.endpoint.protocol),new Proxy(this,{get:(s,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(s,a,o)})}get headers(){return{[eo]:this.encoder.contentType}}async send(e,t,n,s){t=n==null?void 0:n.parse(t);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(t??{});const[,h]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async d=>{const f={...d,params:{}};c.headers={...this.headers,...d.params};let u;try{u=await Ci(d.protocol)(d.target,c)}catch(S){let j=S;return Ju(j)&&(j=new Fe({url:o})),[f,j]}const N=new Uint8Array(await(await u.blob()).arrayBuffer());if(u!=null&&u.ok)return s!=null&&(a=this.encoder.decode(N,s)),[f,null];try{if(u.status!==Xu)return[f,new Error(u.statusText)];const S=this.encoder.decode(N,qe.payloadZ),j=qe.decode(S);return[f,j]}catch(S){return[f,new Error(`[freighter] - failed to decode error: ${u.statusText}: ${S.message}`)]}});return h!=null?[null,h]:[a,null]}}const ed=(r,e)=>{class t{constructor(s){G(this,"wrapped"),this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,a,o,c){const h=new Nu.Breaker(e);do{const[d,f]=await this.wrapped.send(s,a,o,c);if(f==null)return[d,null];if(!Fe.matches(f))return[null,f];if(!await h.wait())return[d,f]}while(!0)}}return new t(r)},m=async(r,e,t,n,s)=>{const[a,o]=await r.send(e,t,n,s);if(o!=null)throw o;return a},td=()=>Ga.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),rd=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(qe.payloadZ)});class nd{constructor(e,t,n,s){G(this,"codec"),G(this,"reqSchema"),G(this,"resSchema"),G(this,"ws"),G(this,"serverClosed"),G(this,"sendClosed"),G(this,"receiveDataQueue",[]),G(this,"receiveCallbacksQueue",[]),this.codec=t,this.reqSchema=n,this.resSchema=s,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return qe.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ue;if(this.sendClosed)throw new bt;return this.ws.send(this.codec.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=qe.decode(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((t,n)=>this.receiveCallbacksQueue.push({resolve:t,reject:n}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,rd))}onClose(e){this.addMessage({type:"close",error:{type:e.code===id?ue.TYPE:bt.TYPE,data:""}})}}const sd="freighterctx",id=1e3,to=class rs extends Qa{constructor(e,t,n=!1){super(),G(this,"baseUrl"),G(this,"encoder"),G(this,"secure"),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}withCodec(e){const t=new rs(this.baseUrl,e,this.secure);return t.use(...this.middleware),t}async stream(e,t,n){const s=td();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async c=>{const h=s(this.buildURL(e,c)),d={...c,params:{}};h.binaryType=rs.MESSAGE_TYPE;const f=await this.wrapSocket(h,t,n);return f instanceof Error?[d,f]:(a=f,[d,null])});if(o!=null)throw o;return a}buildURL(e,t){const n=ou({[eo]:this.encoder.contentType,...t.params},sd);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(s=>{e.onopen=()=>{const a=new nd(e,this.encoder,t,n);a.receiveOpenAck().then(o=>{o!=null?s(o):s(a)}).catch(o=>s(o))},e.onerror=a=>{const o=a;s(new Error(o.message))}})}};G(to,"MESSAGE_TYPE","arraybuffer");let ad=to;const ro="all",no="create",so="delete",io="retrieve",ao="update",_r=i.z.enum([ro,no,so,io,ao]),od=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},oo=r=>{const e=(t,n=ns)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!On(t))return t;n=ld(n);const s={},a=t;return Object.keys(a).forEach(o=>{let c=a[o];const h=r(o);n.recursive&&(On(c)?Bi(c,n.keepTypesOnRecursion)||(c=e(c,n)):n.recursiveInArray&&Ri(c)&&(c=[...c].map(d=>{let f=d;return On(d)?Bi(f,n.keepTypesOnRecursion)||(f=e(d,n)):Ri(d)&&(f=e({key:d},n).key),f}))),s[h]=c}),s};return e},Cs=oo(od),cd=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),co=oo(cd),ns={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},ld=(r=ns)=>(r.recursive==null?r=ns:r.recursiveInArray??(r.recursiveInArray=!1),r),Ri=r=>r!=null&&Array.isArray(r),On=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Bi=(r,e)=>(e||[]).some(t=>r instanceof t),Hr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var hd=Object.defineProperty,ud=(r,e,t)=>e in r?hd(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pt=(r,e,t)=>ud(r,typeof e!="symbol"?e+"":e,t);function dd(r){const e=r.length;let t=0,n=0;for(;n<e;){let s=r.charCodeAt(n++);if((s&4294967168)===0){t++;continue}else if((s&4294965248)===0)t+=2;else{if(s>=55296&&s<=56319&&n<e){const a=r.charCodeAt(n);(a&64512)===56320&&(++n,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?t+=3:t+=4}}return t}function fd(r,e,t){const n=r.length;let s=t,a=0;for(;a<n;){let o=r.charCodeAt(a++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&a<n){const c=r.charCodeAt(a);(c&64512)===56320&&(++a,o=((o&1023)<<10)+(c&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const yd=new TextEncoder,gd=50;function pd(r,e,t){yd.encodeInto(r,e.subarray(t))}function wd(r,e,t){r.length>gd?pd(r,e,t):fd(r,e,t)}const md=4096;function lo(r,e,t){let n=e;const s=n+t,a=[];let o="";for(;n<s;){const c=r[n++];if((c&128)===0)a.push(c);else if((c&224)===192){const h=r[n++]&63;a.push((c&31)<<6|h)}else if((c&240)===224){const h=r[n++]&63,d=r[n++]&63;a.push((c&31)<<12|h<<6|d)}else if((c&248)===240){const h=r[n++]&63,d=r[n++]&63,f=r[n++]&63;let u=(c&7)<<18|h<<12|d<<6|f;u>65535&&(u-=65536,a.push(u>>>10&1023|55296),u=56320|u&1023),a.push(u)}else a.push(c);a.length>=md&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const bd=new TextDecoder,vd=200;function Td(r,e,t){const n=r.subarray(e,e+t);return bd.decode(n)}function Od(r,e,t){return t>vd?Td(r,e,t):lo(r,e,t)}let Ir=class{constructor(e,t){this.type=e,this.data=t}},me=class ss extends Error{constructor(e){super(e);const t=Object.create(ss.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ss.name})}};const Ct=4294967295;function Sd(r,e,t){const n=t/4294967296,s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function ho(r,e,t){const n=Math.floor(t/4294967296),s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function uo(r,e){const t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function Ed(r,e){const t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}const zd=-1,Nd=4294967296-1,Id=17179869184-1;function $d({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=Id)if(e===0&&r<=Nd){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{const t=r/4294967296,n=r&4294967295,s=new Uint8Array(8),a=new DataView(s.buffer);return a.setUint32(0,e<<2|t&3),a.setUint32(4,n),s}else{const t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),ho(n,4,r),t}}function xd(r){const e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,s=Math.floor(n/1e9);return{sec:t+s,nsec:n-s*1e9}}function kd(r){if(r instanceof Date){const e=xd(r);return $d(e)}else return null}function Ad(r){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),n=e.getUint32(4),s=(t&3)*4294967296+n,a=t>>>2;return{sec:s,nsec:a}}case 12:{const t=uo(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new me(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Ud(r){const e=Ad(r);return new Date(e.sec*1e3+e.nsec/1e6)}const Cd={type:zd,encode:kd,decode:Ud};let rr=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Cd)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){const s=this.builtInEncoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=-1-n;return new Ir(o,a)}}}for(let n=0;n<this.encoders.length;n++){const s=this.encoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=n;return new Ir(o,a)}}}return e instanceof Ir?e:null}decode(e,t,n){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,n):new Ir(t,e)}};rr.defaultCodec=new rr;function Rd(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function is(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Rd(r)?new Uint8Array(r):Uint8Array.from(r)}const Bd=100,Pd=2048;let Dd=class fo{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??rr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??Bd,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Pd,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new fo({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),n=new Uint8Array(t),s=new DataView(t);n.set(this.bytes),this.view=s,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const t=dd(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),wd(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const n=is(e);this.writeU8a(n)}encodeArray(e,t){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let n=0;for(const s of t)e[s]!==void 0&&n++;return n}encodeMap(e,t){const n=Object.keys(e);this.sortKeys&&n.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const a of n){const o=e[a];this.ignoreUndefined&&o===void 0||(this.encodeString(a),this.doEncode(o,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const n=e.data(this.pos+6),s=n.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(n);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Sd(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),ho(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function Zt(r,e){return new Dd(e).encodeSharedRef(r)}function Sn(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}const Md=16,jd=16;class Ld{constructor(e=Md,t=jd){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){const s=this.caches[n-1];e:for(const a of s){const o=a.bytes;for(let c=0;c<n;c++)if(o[c]!==e[t+c])continue e;return a.str}return null}store(e,t){const n=this.caches[e.length-1],s={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=s:n.push(s)}decode(e,t,n){const s=this.find(e,t,n);if(s!=null)return this.hit++,s;this.miss++;const a=lo(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,a),a}}const as="array",Jt="map_key",yo="map_value",_d=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new me("The type of key must be string or number but "+typeof r)};class Zd{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=as,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=Jt,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===as){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===Jt||e.type===yo){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Rt=-1,Rs=new DataView(new ArrayBuffer(0)),qd=new Uint8Array(Rs.buffer);try{Rs.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Pi=new RangeError("Insufficient data"),Fd=new Ld;let Yd=class go{constructor(e){this.totalPos=0,this.pos=0,this.view=Rs,this.bytes=qd,this.headByte=Rt,this.stack=new Zd,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??rr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??Ct,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Ct,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Ct,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Ct,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Ct,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Fd,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??_d}clone(){return new go({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Rt,this.stack.reset()}setBuffer(e){const t=is(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Rt&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),n=is(e),s=new Uint8Array(t.length+n.length);s.set(t),s.set(n,t.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(const c of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{n=this.doDecodeSync(),t=!0}catch(h){if(!(h instanceof RangeError))throw h}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:s,pos:a,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Sn(s)} at ${o} (${a} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,s=-1;for await(const a of e){if(t&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a),n&&(s=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const s=this.lookU8();t=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();t=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();t=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===196){const s=this.lookU8();t=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();t=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();t=this.decodeBinary(s,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();t=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();t=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();t=this.decodeExtension(s,4)}else throw new me(`Unrecognized type byte: ${Sn(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const s=n.top();if(s.type===as)if(s.array[s.position]=t,s.position++,s.position===s.size)t=s.array,n.release(s);else continue e;else if(s.type===Jt){if(t==="__proto__")throw new me("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=yo;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)t=s.map,n.release(s);else{s.key=null,s.type=Jt;continue e}}return t}}readHeadByte(){return this.headByte===Rt&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Rt}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new me(`Unrecognized array type byte: ${Sn(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new me(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new me(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var n;if(e>this.maxStrLength)throw new me(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Pi;const s=this.pos+t;let a;return this.stateIsMapKey()&&(n=this.keyDecoder)!=null&&n.canBeCached(e)?a=this.keyDecoder.decode(this.bytes,s,e):a=Od(this.bytes,s,e),this.pos+=t+e,a}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Jt:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new me(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Pi;const n=this.pos+t,s=this.bytes.subarray(n,n+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new me(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Ed(this.view,this.pos);return this.pos+=8,e}readI64(){const e=uo(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function po(r,e){return new Yd(e).decode(r)}let wo=class{constructor(){pt(this,"contentType","application/json"),pt(this,"decoder"),pt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),s=Cs(n);return t!=null?t.parse(s):s}encodeString(e){const t=co(e);return JSON.stringify(t,(n,s)=>ArrayBuffer.isView(s)?Array.from(s):Hr(s)&&"encode_value"in s?typeof s.value=="bigint"?s.value.toString():s.value:typeof s=="bigint"?s.toString():s)}static registerCustomType(){}},mo=class{constructor(){pt(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t)}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Hr(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(s=>{const a=t.map(o=>JSON.stringify(s[o]??""));n.push(a.join(","))}),n.join(`
13
+ `).slice(0,-1).map(t=>e.parse(Rr.decodeString(t)))}get byteCapacity(){return new Kn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ce?this.byteCapacity:this.dataType.isVariable?new Kn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ce?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,s)=>{n===Jn&&(e++,t.push(s+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let s=0;s<this.length;s++)n[s]=Fh(this.dataType,e,this.data[s],t);return new ye({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(D.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),jt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(D.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),jt(this._cachedMin,this.sampleOffset))}get bounds(){return Ge(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return jt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return jt(n,this.sampleOffset)}atVariable(e,t){let n=0,s=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Jn){if(e===0){s=o;break}n=o+1,e--}if(s===0&&(s=this.data.length),n>=s||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,s);return this.dataType.equals(D.STRING)?new TextDecoder().decode(a):Ns(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const s=oh(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(D.FLOAT32)&&!this.dataType.equals(D.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:s}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Ce){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ce}as(e){return Gh(e,this.dataType),this}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ri(this.alignmentBounds.lower),upper:Ri(this.alignmentBounds.upper)},timeRange:(e=this.timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return Ge(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Kh(this);return this.dataType.equals(D.JSON)?new Jh(e):e}return new Xh(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new xi(this,e,t??this.length)}subAlignmentIterator(e,t){return new xi(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ye({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let s;return e?s=this.data.subarray(t,n):s=this.data.slice(t,n),new ye({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ye({data:this.buffer,dataType:this.dataType,timeRange:Kt.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){var e,t;let n=`${this.dataType.toString()} ${this.length} [`;if(this.length<=10)n+=Array.from(this).map(s=>s.toString());else{for(let s=0;s<5;s++)n+=`${(e=this.at(s))==null?void 0:e.toString()}`,s<4&&(n+=",");n+="...";for(let s=-5;s<0;s++)n+=(t=this.at(s))==null?void 0:t.toString(),s<-1&&(n+=",")}return n+="]",n}};g(Lt,"crudeZ",i.z.object({timeRange:Kt.z.optional(),dataType:D.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Wh,Vh,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:qh.optional().default("static").optional()})),g(Lt,"z",Lt.crudeZ.transform(r=>new Lt(r)));let Hh=Lt,xi=class{constructor(e,t,n){g(this,"series"),g(this,"end"),g(this,"index"),this.series=e;const s=Ge(0,e.length);this.end=Si(s,n),this.index=Si(s,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class Kh{constructor(e){if(g(this,"series"),g(this,"index"),g(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==Jn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var ki,Ai;const Wa=class Va{constructor(e){g(this,"wrapped"),g(this,ki,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Rr.decodeString(e.value,Va.SCHEMA)}}[(Ai=Symbol.iterator,ki=Symbol.toStringTag,Ai)](){return this}};g(Wa,"SCHEMA",i.z.record(i.z.string(),i.z.unknown()));let Jh=Wa;var Ui,Ci;class Xh{constructor(e){g(this,"series"),g(this,"index"),g(this,Ui,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Ci=Symbol.iterator,Ui=Symbol.toStringTag,Ci)](){return this}}const Ri=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};i.z.object({key:i.z.string(),value:i.z.string()});i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown());const Ga=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Qh=Ga(),Ha=["macOS","Windows","Linux"],eu=["macos","windows","linux"],tu={macos:"macOS",windows:"Windows",linux:"Linux"},ru=i.z.enum(Ha).or(i.z.enum(eu).transform(r=>tu[r])),nu=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"macOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"};let Tn;const su=(r={})=>{const{force:e,default:t}=r;return e??Tn??(Tn=nu(),Tn??t)},Ka=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Ha,RUNTIME:Qh,detect:Ga,getOS:su,osZ:ru},Symbol.toStringTag,{value:"Module"}));var iu=Object.defineProperty,au=(r,e,t)=>e in r?iu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_t=(r,e,t)=>au(r,typeof e!="symbol"?e+"":e,t);const ou=(...r)=>r.map(Ja).join(""),Ja=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),cu=r=>r.endsWith("/")?r.slice(0,-1):r,lu=(r,e="")=>r===null?"":`?${Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&")}`,Xn=class Qn{constructor({host:e,port:t,protocol:n="",pathPrefix:s=""}){_t(this,"protocol"),_t(this,"host"),_t(this,"port"),_t(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Ja(s)}replace(e){return new Qn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Qn({...this,pathPrefix:ou(this.path,e)})}toString(){return cu(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};_t(Xn,"UNKNOWN",new Xn({host:"unknown",port:0}));let hu=Xn;const uu=-128,du=127;i.z.number().int().min(uu).max(du);const fu=-32768,yu=32767;i.z.number().int().min(fu).max(yu);const gu=-2147483648,pu=2147483647;i.z.number().int().min(gu).max(pu);const wu=-9223372036854775808n,mu=9223372036854775807n;i.z.bigint().min(wu).max(mu);const bu=255;i.z.number().int().min(0).max(bu);const vu=65535;i.z.number().int().min(0).max(vu);const Tu=4294967295;i.z.number().int().min(0).max(Tu);const Ou=18446744073709551615n;i.z.bigint().min(0n).max(Ou);var Su=Object.defineProperty,Eu=(r,e,t)=>e in r?Su(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ve=(r,e,t)=>Eu(r,typeof e!="symbol"?e+"":e,t);const zu=async r=>await new Promise(e=>setTimeout(e,k.fromMilliseconds(r).milliseconds));class Nu{constructor(e){ve(this,"config"),ve(this,"retries"),ve(this,"interval"),this.config={baseInterval:new k((e==null?void 0:e.baseInterval)??k.seconds(1)),maxRetries:(e==null?void 0:e.maxRetries)??5,scale:(e==null?void 0:e.scale)??1,sleepFn:(e==null?void 0:e.sleepFn)??zu},this.retries=0,this.interval=new k(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Iu=i.z.object({baseInterval:k.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),$u=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Nu,breakerConfig:Iu},Symbol.toStringTag,{value:"Module"})),xu=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,ks=i.z.string().regex(xu),gt=i.z.number().min(0).max(255),ku=i.z.number().min(0).max(1),As=i.z.tuple([gt,gt,gt,ku]),Xa=i.z.tuple([gt,gt,gt]),Qa=i.z.object({rgba255:As}),Us=(r,e=1)=>{if(typeof r=="string")return Uu(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}if(typeof r=="object"&&"rgba255"in r)return r.rgba255;throw new Error(`Invalid color: ${JSON.stringify(r)}`)},Au=i.z.union([ks,As,Xa,Qa]).transform(r=>Us(r)),Uu=(r,e=1)=>{if(!ks.safeParse(r).success)throw new Error(`Invalid hex color: ${r}`);return r=Cu(r),[Nr(r,0),Nr(r,2),Nr(r,4),r.length===8?Nr(r,6)/255:e]},Nr=(r,e)=>parseInt(r.slice(e,e+2),16),Cu=r=>r.startsWith("#")?r.slice(1):r,Ru=i.z.union([ks,As,i.z.string(),Xa,Qa]);Us("#000000");Us("#ffffff");const Bu=i.z.object({key:i.z.string(),color:Ru,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Bu);const Pu=i.z.object({key:i.z.string(),name:i.z.string(),color:Au});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Pu)});const Du=i.z.number().int().min(0).max(255),Mu=i.z.object({name:i.z.string(),key:i.z.string()}),Lr=r=>i.z.object({subject:Mu,resource:r,authority:Du}),ju=i.z.object({from:Lr(i.z.any()),to:i.z.null()}),Lu=i.z.object({from:i.z.null(),to:Lr(i.z.any())});i.z.union([ju,Lu,i.z.object({from:Lr(i.z.any()),to:Lr(i.z.any())})]);const _u=r=>Object.getOwnPropertySymbols(globalThis).includes(r),Zu=(r,e)=>{const t=Symbol.for(r);if(!_u(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},qu=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Gr=r=>{var e;return e=class extends Error{constructor(t,n){super(t,n),ve(this,"discriminator",e.discriminator),ve(this,"type",e.TYPE),ve(this,"matches",e.matches),this.name=e.TYPE}static sub(t){return Gr(`${r}.${t}`)}},ve(e,"discriminator","FreighterError"),ve(e,"TYPE",r),ve(e,"matches",qu(r)),e},eo=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},ot="unknown",es="nil";class Fu{constructor(){ve(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:es,data:""};if(eo(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:ot,data:e.message};if(typeof e=="string")return{type:ot,data:e};try{return{type:ot,data:JSON.stringify(e)}}catch{return{type:ot,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===es)return null;if(e.type===ot)return new ts(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new ts(e.data)}}const Cs=Zu("synnax-error-registry",()=>new Fu),Yu=({encode:r,decode:e})=>Cs().register({encode:r,decode:e}),Wu=r=>Cs().encode(r),Vu=r=>r==null?null:Cs().decode(r);class ts extends Gr("unknown"){}const Gu=i.z.object({type:i.z.string(),data:i.z.string()});class Hu extends Gr("canceled"){}const qe=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Hu,NONE:es,UNKNOWN:ot,Unknown:ts,createTyped:Gr,decode:Vu,encode:Wu,isTyped:eo,payloadZ:Gu,register:Yu},Symbol.toStringTag,{value:"Module"}));i.object({jsonrpc:i.string(),id:i.number().optional(),method:i.string().optional(),params:i.unknown().optional(),result:i.unknown().optional()});i.z.string().regex(/^\d+\.\d+\.\d+$/);const Ku=["standard","scientific","engineering"];i.z.enum(Ku);let hr=class extends qe.createTyped("freighter"){},ue=class extends hr.sub("eof"){constructor(){super("EOF")}},bt=class extends hr.sub("stream_closed"){constructor(){super("StreamClosed")}},Fe=class extends hr.sub("unreachable"){constructor(e={}){const{message:t="Unreachable",url:n=hu.UNKNOWN}=e;super(t),G(this,"url"),this.url=n}};const Ju=r=>{if(!r.type.startsWith(hr.TYPE))return null;if(ue.matches(r))return{type:ue.TYPE,data:"EOF"};if(bt.matches(r))return{type:bt.TYPE,data:"StreamClosed"};if(Fe.matches(r))return{type:Fe.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Xu=r=>{if(!r.type.startsWith(hr.TYPE))return null;switch(r.type){case ue.TYPE:return new ue;case bt.TYPE:return new bt;case Fe.TYPE:return new Fe;default:throw new qe.Unknown(`Unknown error type: ${r.data}`)}};qe.register({encode:Ju,decode:Xu});let to=class{constructor(){G(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const s=async a=>{if(n===this.middleware.length)return await t(a);const o=this.middleware[n];return n++,await o(a,s)};return await s(e)}};const ro="Content-Type",Bi=r=>{if(Ka.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(s,a)=>await e(s,{...a,agent:n})},Qu=r=>"code"in r&&r.code==="ECONNREFUSED"||r.message.toLowerCase().includes("load failed"),ed=400;class td extends to{constructor(e,t,n=!1){return super(),G(this,"endpoint"),G(this,"encoder"),G(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=Bi(this.endpoint.protocol),new Proxy(this,{get:(s,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(s,a,o)})}get headers(){return{[ro]:this.encoder.contentType}}async send(e,t,n,s){t=n==null?void 0:n.parse(t);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(t??{});const[,h]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async d=>{const f={...d,params:{}};c.headers={...this.headers,...d.params};let u;try{u=await Bi(d.protocol)(d.target,c)}catch(S){let j=S;return Qu(j)&&(j=new Fe({url:o})),[f,j]}const N=new Uint8Array(await(await u.blob()).arrayBuffer());if(u!=null&&u.ok)return s!=null&&(a=this.encoder.decode(N,s)),[f,null];try{if(u.status!==ed)return[f,new Error(u.statusText)];const S=this.encoder.decode(N,qe.payloadZ),j=qe.decode(S);return[f,j]}catch(S){return[f,new Error(`[freighter] - failed to decode error: ${u.statusText}: ${S.message}`)]}});return h!=null?[null,h]:[a,null]}}const rd=(r,e)=>{class t{constructor(s){G(this,"wrapped"),this.wrapped=s}use(...s){this.wrapped.use(...s)}async send(s,a,o,c){const h=new $u.Breaker(e);do{const[d,f]=await this.wrapped.send(s,a,o,c);if(f==null)return[d,null];if(!Fe.matches(f))return[null,f];if(!await h.wait())return[d,f]}while(!0)}}return new t(r)},m=async(r,e,t,n,s)=>{const[a,o]=await r.send(e,t,n,s);if(o!=null)throw o;return a},nd=()=>Ka.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),sd=i.z.object({type:i.z.enum(["data","close","open"]),payload:i.z.unknown(),error:i.z.optional(qe.payloadZ)});class id{constructor(e,t,n,s){G(this,"codec"),G(this,"reqSchema"),G(this,"resSchema"),G(this,"ws"),G(this,"serverClosed"),G(this,"sendClosed"),G(this,"receiveDataQueue",[]),G(this,"receiveCallbacksQueue",[]),this.codec=t,this.reqSchema=n,this.resSchema=s,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return qe.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ue;if(this.sendClosed)throw new bt;return this.ws.send(this.codec.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=qe.decode(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((t,n)=>this.receiveCallbacksQueue.push({resolve:t,reject:n}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,sd))}onClose(e){this.addMessage({type:"close",error:{type:e.code===od?ue.TYPE:bt.TYPE,data:""}})}}const ad="freighterctx",od=1e3,no=class rs extends to{constructor(e,t,n=!1){super(),G(this,"baseUrl"),G(this,"encoder"),G(this,"secure"),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}withCodec(e){const t=new rs(this.baseUrl,e,this.secure);return t.use(...this.middleware),t}async stream(e,t,n){const s=nd();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async c=>{const h=s(this.buildURL(e,c)),d={...c,params:{}};h.binaryType=rs.MESSAGE_TYPE;const f=await this.wrapSocket(h,t,n);return f instanceof Error?[d,f]:(a=f,[d,null])});if(o!=null)throw o;return a}buildURL(e,t){const n=lu({[ro]:this.encoder.contentType,...t.params},ad);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(s=>{e.onopen=()=>{const a=new id(e,this.encoder,t,n);a.receiveOpenAck().then(o=>{o!=null?s(o):s(a)}).catch(o=>s(o))},e.onerror=a=>{const o=a;s(new Error(o.message))}})}};G(no,"MESSAGE_TYPE","arraybuffer");let cd=no;const so="all",io="create",ao="delete",oo="retrieve",co="update",_r=i.z.enum([so,io,ao,oo,co]),ld=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},lo=r=>{const e=(t,n=ns)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!On(t))return t;n=ud(n);const s={},a=t;return Object.keys(a).forEach(o=>{let c=a[o];const h=r(o);n.recursive&&(On(c)?Di(c,n.keepTypesOnRecursion)||(c=e(c,n)):n.recursiveInArray&&Pi(c)&&(c=[...c].map(d=>{let f=d;return On(d)?Di(f,n.keepTypesOnRecursion)||(f=e(d,n)):Pi(d)&&(f=e({key:d},n).key),f}))),s[h]=c}),s};return e},Rs=lo(ld),hd=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),ho=lo(hd),ns={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},ud=(r=ns)=>(r.recursive==null?r=ns:r.recursiveInArray??(r.recursiveInArray=!1),r),Pi=r=>r!=null&&Array.isArray(r),On=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Di=(r,e)=>(e||[]).some(t=>r instanceof t),Hr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var dd=Object.defineProperty,fd=(r,e,t)=>e in r?dd(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,pt=(r,e,t)=>fd(r,typeof e!="symbol"?e+"":e,t);function yd(r){const e=r.length;let t=0,n=0;for(;n<e;){let s=r.charCodeAt(n++);if((s&4294967168)===0){t++;continue}else if((s&4294965248)===0)t+=2;else{if(s>=55296&&s<=56319&&n<e){const a=r.charCodeAt(n);(a&64512)===56320&&(++n,s=((s&1023)<<10)+(a&1023)+65536)}(s&4294901760)===0?t+=3:t+=4}}return t}function gd(r,e,t){const n=r.length;let s=t,a=0;for(;a<n;){let o=r.charCodeAt(a++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&a<n){const c=r.charCodeAt(a);(c&64512)===56320&&(++a,o=((o&1023)<<10)+(c&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const pd=new TextEncoder,wd=50;function md(r,e,t){pd.encodeInto(r,e.subarray(t))}function bd(r,e,t){r.length>wd?md(r,e,t):gd(r,e,t)}const vd=4096;function uo(r,e,t){let n=e;const s=n+t,a=[];let o="";for(;n<s;){const c=r[n++];if((c&128)===0)a.push(c);else if((c&224)===192){const h=r[n++]&63;a.push((c&31)<<6|h)}else if((c&240)===224){const h=r[n++]&63,d=r[n++]&63;a.push((c&31)<<12|h<<6|d)}else if((c&248)===240){const h=r[n++]&63,d=r[n++]&63,f=r[n++]&63;let u=(c&7)<<18|h<<12|d<<6|f;u>65535&&(u-=65536,a.push(u>>>10&1023|55296),u=56320|u&1023),a.push(u)}else a.push(c);a.length>=vd&&(o+=String.fromCharCode(...a),a.length=0)}return a.length>0&&(o+=String.fromCharCode(...a)),o}const Td=new TextDecoder,Od=200;function Sd(r,e,t){const n=r.subarray(e,e+t);return Td.decode(n)}function Ed(r,e,t){return t>Od?Sd(r,e,t):uo(r,e,t)}let Ir=class{constructor(e,t){this.type=e,this.data=t}},me=class ss extends Error{constructor(e){super(e);const t=Object.create(ss.prototype);Object.setPrototypeOf(this,t),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ss.name})}};const Ct=4294967295;function zd(r,e,t){const n=t/4294967296,s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function fo(r,e,t){const n=Math.floor(t/4294967296),s=t;r.setUint32(e,n),r.setUint32(e+4,s)}function yo(r,e){const t=r.getInt32(e),n=r.getUint32(e+4);return t*4294967296+n}function Nd(r,e){const t=r.getUint32(e),n=r.getUint32(e+4);return t*4294967296+n}const Id=-1,$d=4294967296-1,xd=17179869184-1;function kd({sec:r,nsec:e}){if(r>=0&&e>=0&&r<=xd)if(e===0&&r<=$d){const t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,r),t}else{const t=r/4294967296,n=r&4294967295,s=new Uint8Array(8),a=new DataView(s.buffer);return a.setUint32(0,e<<2|t&3),a.setUint32(4,n),s}else{const t=new Uint8Array(12),n=new DataView(t.buffer);return n.setUint32(0,e),fo(n,4,r),t}}function Ad(r){const e=r.getTime(),t=Math.floor(e/1e3),n=(e-t*1e3)*1e6,s=Math.floor(n/1e9);return{sec:t+s,nsec:n-s*1e9}}function Ud(r){if(r instanceof Date){const e=Ad(r);return kd(e)}else return null}function Cd(r){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(r.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const t=e.getUint32(0),n=e.getUint32(4),s=(t&3)*4294967296+n,a=t>>>2;return{sec:s,nsec:a}}case 12:{const t=yo(e,4),n=e.getUint32(0);return{sec:t,nsec:n}}default:throw new me(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${r.length}`)}}function Rd(r){const e=Cd(r);return new Date(e.sec*1e3+e.nsec/1e6)}const Bd={type:Id,encode:Ud,decode:Rd};let rr=class{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Bd)}register({type:e,encode:t,decode:n}){if(e>=0)this.encoders[e]=t,this.decoders[e]=n;else{const s=-1-e;this.builtInEncoders[s]=t,this.builtInDecoders[s]=n}}tryToEncode(e,t){for(let n=0;n<this.builtInEncoders.length;n++){const s=this.builtInEncoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=-1-n;return new Ir(o,a)}}}for(let n=0;n<this.encoders.length;n++){const s=this.encoders[n];if(s!=null){const a=s(e,t);if(a!=null){const o=n;return new Ir(o,a)}}}return e instanceof Ir?e:null}decode(e,t,n){const s=t<0?this.builtInDecoders[-1-t]:this.decoders[t];return s?s(e,t,n):new Ir(t,e)}};rr.defaultCodec=new rr;function Pd(r){return r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer}function is(r){return r instanceof Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Pd(r)?new Uint8Array(r):Uint8Array.from(r)}const Dd=100,Md=2048;let jd=class go{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??rr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??Dd,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Md,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new go({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,t){if(t>this.maxDepth)throw new Error(`Too deep objects in depth ${t}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,t)}ensureBufferSizeToWrite(e){const t=this.pos+e;this.view.byteLength<t&&this.resizeBuffer(t*2)}resizeBuffer(e){const t=new ArrayBuffer(e),n=new Uint8Array(t),s=new DataView(t);n.set(this.bytes),this.view=s,this.bytes=n}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const t=yd(e);this.ensureBufferSizeToWrite(5+t),this.writeStringHeader(t),bd(e,this.bytes,this.pos),this.pos+=t}encodeObject(e,t){const n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,t);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,t);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const t=e.byteLength;if(t<256)this.writeU8(196),this.writeU8(t);else if(t<65536)this.writeU8(197),this.writeU16(t);else if(t<4294967296)this.writeU8(198),this.writeU32(t);else throw new Error(`Too large binary: ${t}`);const n=is(e);this.writeU8a(n)}encodeArray(e,t){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const s of e)this.doEncode(s,t+1)}countWithoutUndefined(e,t){let n=0;for(const s of t)e[s]!==void 0&&n++;return n}encodeMap(e,t){const n=Object.keys(e);this.sortKeys&&n.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const a of n){const o=e[a];this.ignoreUndefined&&o===void 0||(this.encodeString(a),this.doEncode(o,t+1))}}encodeExtension(e){if(typeof e.data=="function"){const n=e.data(this.pos+6),s=n.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(n);return}const t=e.data.length;if(t===1)this.writeU8(212);else if(t===2)this.writeU8(213);else if(t===4)this.writeU8(214);else if(t===8)this.writeU8(215);else if(t===16)this.writeU8(216);else if(t<256)this.writeU8(199),this.writeU8(t);else if(t<65536)this.writeU8(200),this.writeU16(t);else if(t<4294967296)this.writeU8(201),this.writeU32(t);else throw new Error(`Too large extension object: ${t}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const t=e.length;this.ensureBufferSizeToWrite(t),this.bytes.set(e,this.pos),this.pos+=t}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),zd(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),fo(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function Zt(r,e){return new jd(e).encodeSharedRef(r)}function Sn(r){return`${r<0?"-":""}0x${Math.abs(r).toString(16).padStart(2,"0")}`}const Ld=16,_d=16;class Zd{constructor(e=Ld,t=_d){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=t,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,t,n){const s=this.caches[n-1];e:for(const a of s){const o=a.bytes;for(let c=0;c<n;c++)if(o[c]!==e[t+c])continue e;return a.str}return null}store(e,t){const n=this.caches[e.length-1],s={bytes:e,str:t};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=s:n.push(s)}decode(e,t,n){const s=this.find(e,t,n);if(s!=null)return this.hit++,s;this.miss++;const a=uo(e,t,n),o=Uint8Array.prototype.slice.call(e,t,t+n);return this.store(o,a),a}}const as="array",Jt="map_key",po="map_value",qd=r=>{if(typeof r=="string"||typeof r=="number")return r;throw new me("The type of key must be string or number but "+typeof r)};class Fd{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const t=this.getUninitializedStateFromPool();t.type=as,t.position=0,t.size=e,t.array=new Array(e)}pushMapState(e){const t=this.getUninitializedStateFromPool();t.type=Jt,t.readCount=0,t.size=e,t.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===as){const t=e;t.size=0,t.array=void 0,t.position=0,t.type=void 0}if(e.type===Jt||e.type===po){const t=e;t.size=0,t.map=void 0,t.readCount=0,t.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Rt=-1,Bs=new DataView(new ArrayBuffer(0)),Yd=new Uint8Array(Bs.buffer);try{Bs.getInt8(0)}catch(r){if(!(r instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Mi=new RangeError("Insufficient data"),Wd=new Zd;let Vd=class wo{constructor(e){this.totalPos=0,this.pos=0,this.view=Bs,this.bytes=Yd,this.headByte=Rt,this.stack=new Fd,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??rr.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??Ct,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Ct,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Ct,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Ct,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Ct,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:Wd,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??qd}clone(){return new wo({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Rt,this.stack.reset()}setBuffer(e){const t=is(e);this.bytes=t,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Rt&&!this.hasRemaining(1))this.setBuffer(e);else{const t=this.bytes.subarray(this.pos),n=is(e),s=new Uint8Array(t.length+n.length);s.set(t),s.set(n,t.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:t,pos:n}=this;return new RangeError(`Extra ${t.byteLength-n} of ${t.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const t=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return t}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let t=!1,n;for await(const c of e){if(t)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{n=this.doDecodeSync(),t=!0}catch(h){if(!(h instanceof RangeError))throw h}this.totalPos+=this.pos}if(t){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:s,pos:a,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Sn(s)} at ${o} (${a} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,t){if(this.entered){yield*this.clone().decodeMultiAsync(e,t);return}try{this.entered=!0;let n=t,s=-1;for await(const a of e){if(t&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(a),n&&(s=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let t;if(e>=224)t=e-256;else if(e<192)if(e<128)t=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else{const s=e-160;t=this.decodeString(s,0)}else if(e===192)t=null;else if(e===194)t=!1;else if(e===195)t=!0;else if(e===202)t=this.readF32();else if(e===203)t=this.readF64();else if(e===204)t=this.readU8();else if(e===205)t=this.readU16();else if(e===206)t=this.readU32();else if(e===207)this.useBigInt64?t=this.readU64AsBigInt():t=this.readU64();else if(e===208)t=this.readI8();else if(e===209)t=this.readI16();else if(e===210)t=this.readI32();else if(e===211)this.useBigInt64?t=this.readI64AsBigInt():t=this.readI64();else if(e===217){const s=this.lookU8();t=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();t=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();t=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else t=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else t={}}else if(e===196){const s=this.lookU8();t=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();t=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();t=this.decodeBinary(s,4)}else if(e===212)t=this.decodeExtension(1,0);else if(e===213)t=this.decodeExtension(2,0);else if(e===214)t=this.decodeExtension(4,0);else if(e===215)t=this.decodeExtension(8,0);else if(e===216)t=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();t=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();t=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();t=this.decodeExtension(s,4)}else throw new me(`Unrecognized type byte: ${Sn(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const s=n.top();if(s.type===as)if(s.array[s.position]=t,s.position++,s.position===s.size)t=s.array,n.release(s);else continue e;else if(s.type===Jt){if(t==="__proto__")throw new me("The key __proto__ is not allowed");s.key=this.mapKeyConverter(t),s.type=po;continue e}else if(s.map[s.key]=t,s.readCount++,s.readCount===s.size)t=s.map,n.release(s);else{s.key=null,s.type=Jt;continue e}}return t}}readHeadByte(){return this.headByte===Rt&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Rt}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new me(`Unrecognized array type byte: ${Sn(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new me(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new me(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,t){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,t):this.decodeBinary(e,t)}decodeUtf8String(e,t){var n;if(e>this.maxStrLength)throw new me(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+t+e)throw Mi;const s=this.pos+t;let a;return this.stateIsMapKey()&&(n=this.keyDecoder)!=null&&n.canBeCached(e)?a=this.keyDecoder.decode(this.bytes,s,e):a=Ed(this.bytes,s,e),this.pos+=t+e,a}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===Jt:!1}decodeBinary(e,t){if(e>this.maxBinLength)throw new me(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+t))throw Mi;const n=this.pos+t,s=this.bytes.subarray(n,n+e);return this.pos+=t+e,s}decodeExtension(e,t){if(e>this.maxExtLength)throw new me(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+t),s=this.decodeBinary(e,t+1);return this.extensionCodec.decode(s,n,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Nd(this.view,this.pos);return this.pos+=8,e}readI64(){const e=yo(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function mo(r,e){return new Vd(e).decode(r)}let bo=class{constructor(){pt(this,"contentType","application/json"),pt(this,"decoder"),pt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e))}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),s=Rs(n);return t!=null?t.parse(s):s}encodeString(e){const t=ho(e);return JSON.stringify(t,(n,s)=>ArrayBuffer.isView(s)?Array.from(s):Hr(s)&&"encode_value"in s?typeof s.value=="bigint"?s.value.toString():s.value:typeof s=="bigint"?s.toString():s)}static registerCustomType(){}},vo=class{constructor(){pt(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t)}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Hr(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(s=>{const a=t.map(o=>JSON.stringify(s[o]??""));n.push(a.join(","))}),n.join(`
14
14
  `)}decodeString(e,t){const[n,...s]=e.trim().split(`
15
- `).map(c=>c.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),s.forEach(c=>{const h=c.split(",").map(d=>d.trim());a.forEach((d,f)=>{const u=this.parseValue(h[f]);u!=null&&o[d].push(u)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},bo=class{constructor(){pt(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e)}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const Me=new rr;Me.register({type:0,encode:r=>{if(ArrayBuffer.isView(r)){const e=Array.from(r);return Zt(e,{extensionCodec:Me})}return Hr(r)&&"encode_value"in r?typeof r.value=="bigint"?Zt(r.value.toString(),{extensionCodec:Me}):Zt(r.value,{extensionCodec:Me}):typeof r=="bigint"?Zt(r.toString(),{extensionCodec:Me}):null},decode:r=>po(r,{extensionCodec:Me})});let vo=class{constructor(){pt(this,"contentType","application/msgpack")}encode(e){const t=co(e);return Zt(t,{extensionCodec:Me}).slice()}decode(e,t){const n=po(e,{extensionCodec:Me}),s=Cs(n);return t!=null?t.parse(s):s}static registerCustomType(){}};const Xt=new wo,Wd=new mo,Vd=new bo,Gd=new vo,Qe=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:mo,CSV_CODEC:Wd,JSONCodec:wo,JSON_CODEC:Xt,MSGPACK_CODEC:Gd,MsgPackCodec:vo,TEXT_CODEC:Vd,TextCodec:bo},Symbol.toStringTag,{value:"Module"})),Hd=r=>[...new Set(r)],Kd=(r,e,t=!0)=>{const n=new Map;return r.forEach(s=>{const a=e(s);if(n.has(a)){if(t)return;n.delete(a)}n.set(a,s)}),Array.from(n.values())},Di=Object.freeze(Object.defineProperty({__proto__:null,by:Kd,unique:Hd},Symbol.toStringTag,{value:"Module"})),Jd=r=>r!=null&&typeof r=="object"&&"toString"in r,Xd=(r,e=!1)=>{const t=Jd(r)?"stringer":typeof r;let n;switch(t){case"string":n=(s,a)=>s.localeCompare(a);break;case"stringer":n=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":n=(s,a)=>Number(s)-Number(a);break;case"bigint":n=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":n=(s,a)=>Number(s)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Qd(n):n},Qd=r=>(e,t)=>r(t,e),Kr=0,En=-1,zn=1,ef=r=>r<Kr,tf=r=>r>Kr,rf=r=>r===Kr,Jr=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const To=i.z.object({width:i.z.number(),height:i.z.number()}),nf=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),sf=["width","height"];i.z.enum(sf);const af=["start","center","end"],of=["signedWidth","signedHeight"];i.z.enum(of);const Zr=i.z.object({x:i.z.number(),y:i.z.number()}),cf=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),lf=["x","y"],Oo=i.z.enum(lf),So=["top","right","bottom","left"];i.z.enum(So);const hf=["left","right"],Eo=i.z.enum(hf),uf=["top","bottom"],zo=i.z.enum(uf),No=["center"],Mi=i.z.enum(No),df=[...So,...No],Io=i.z.enum(df);i.z.enum(af);const ff=["first","last"];i.z.enum(ff);const yf=i.z.object({lower:i.z.number(),upper:i.z.number()}),gf=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([yf,Jr]);i.z.union([gf,Jr]);i.z.enum([...Oo.options,...Io.options]);i.z.union([Oo,Io,i.z.instanceof(String)]);const Et=r=>typeof r=="bigint"||r instanceof BigInt,Nn=(r,e)=>Et(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),pf=(r,e)=>Et(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),ji=(r,e)=>Et(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),wf=(r,e)=>Et(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),mf=r=>Et(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,at=(r,e)=>Et(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),J=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Li(r);return Li(t)},Li=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,_i=(r,e)=>{const t=J(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},$r=(r,e)=>{const t=J(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=J(e);return n.lower>=t.lower&&n.upper<=t.upper},bf=r=>({lower:Math.min(...r.map(e=>J(e).lower)),upper:Math.max(...r.map(e=>J(e).upper))}),vf=(r,e,t)=>{const n=r.map(c=>J(c)),s=t>0?1:t<0?-1:0;if(s===0)return e;let a=t,o=e;for(;ji(a,0)===!1;){const c=n.findIndex(h=>s>0?o>=h.lower&&o<h.upper:o>h.lower&&o<=h.upper);if(c!==-1){const h=n[c];let d;if(s>0?d=Nn(h.upper,o):d=Nn(o,h.lower),d>0){const f=wf(mf(a),d);if(o=pf(o,s>0?f:-f),a=Nn(a,s>0?f:-f),ji(a,0))return o;continue}}if(s>0){const h=n.filter(d=>d.lower>o);if(h.length>0)o=h[0].lower;else return o}else{const h=n.filter(d=>d.upper<o);if(h.length>0)o=h[h.length-1].upper;else return o}}return o},Tf=(r,e,t)=>{const n=r.map(o=>J(o));if(e===t)return typeof e=="bigint"?0n:0;const s=e<t?J([e,t]):J([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const c=o.lower>s.lower?o.lower:s.lower,h=o.upper<s.upper?o.upper:s.upper;if(c<h){const d=h-c;a=a+d}}return a};i.z.object({x:Eo.or(Mi),y:zo.or(Mi)});const Of=i.z.object({x:Eo,y:zo}),Sf=Object.freeze({x:"left",y:"top"}),Ef=(r,e)=>r.x===e.x&&r.y===e.y,Zi=i.z.union([i.z.number(),Zr,Jr,To,nf,cf]),zf=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},qi=Object.freeze({x:0,y:0}),xr=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:xr,left:xr,width:xr,height:xr});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Zr,two:Zr,root:Of});const Bs=(r,e,t=0,n=0,s)=>{const a={one:{...qi},two:{...qi},root:s??Sf};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:s??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},In=r=>{const e=Bs(r);return{lower:e.one.x,upper:e.two.x}},$n=r=>{const e=Bs(r);return{lower:e.one.y,upper:e.two.y}},Nf=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,If=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([To,If,Zr,Jr]);var $f=Object.defineProperty,xf=(r,e,t)=>e in r?$f(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xe=(r,e,t)=>xf(r,typeof e!="symbol"?e+"":e,t);const kf=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;i.z.object({offset:Zi,scale:Zi});i.z.object({offset:i.z.number(),scale:i.z.number()});const Af=r=>(e,t,n,s)=>t==="dimension"?[e,n]:[e,s?n-r:n+r],Uf=r=>(e,t,n,s)=>[e,s?n/r:n*r],Cf=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:s,upper:a}=e,{lower:o,upper:c}=r,h=a-s,d=c-o;if(t==="dimension")return[r,n*(d/h)];const f=(n-s)*(d/h)+o;return[r,f]},Rf=r=>(e,t,n)=>[r,n],Bf=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:s}=r;return[r,s-(t-n)]},Pf=r=>(e,t,n)=>{const{lower:s,upper:a}=r;return n=kf(n,s,a),[e,n]},os=class qt{constructor(){xe(this,"ops",[]),xe(this,"currBounds",null),xe(this,"currType",null),xe(this,"reversed",!1),this.ops=[]}static translate(e){return new qt().translate(e)}static magnify(e){return new qt().magnify(e)}static scale(e,t){return new qt().scale(e,t)}translate(e){const t=this.new(),n=Af(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Uf(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=J(e,t),s=this.new(),a=Cf(n);return a.type="scale",s.ops.push(a),s}clamp(e,t){const n=J(e,t),s=this.new(),a=Pf(n);return a.type="clamp",s.ops.push(a),s}reBound(e,t){const n=J(e,t),s=this.new(),a=Rf(n);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Bf();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new qt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,s],a)=>a(n,e,s,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,s)=>{if(n.type==="scale"||t.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&t.push([s,a])}),t.forEach(([n,s])=>{const a=e.ops.slice(n,s);a.unshift(e.ops[s]),e.ops.splice(n,s-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};xe(os,"IDENTITY",new os);let Fi=os;const Yi=class Ie{constructor(e=new Fi,t=new Fi,n=null){xe(this,"x"),xe(this,"y"),xe(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new Ie().translate(e,t)}static translateX(e){return new Ie().translateX(e)}static translateY(e){return new Ie().translateY(e)}static clamp(e){return new Ie().clamp(e)}static magnify(e){return new Ie().magnify(e)}static scale(e){return new Ie().scale(e)}static reBound(e){return new Ie().reBound(e)}translate(e,t){const n=zf(e,t),s=this.copy();return s.x=this.x.translate(n.x),s.y=this.y.translate(n.y),s}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Nf(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Ef(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(In(e)),t.y=t.y.scale($n(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(In(e)),t.y=this.y.reBound($n(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(In(e)),t.y=this.y.clamp($n(e)),t}copy(){const e=new Ie;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Bs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};xe(Yi,"IDENTITY",new Yi);var Df=Object.defineProperty,Mf=(r,e,t)=>e in r?Df(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e,t)=>Mf(r,typeof e!="symbol"?e+"":e,t);let jf=(r,e=21)=>(t=e)=>{let n="",s=t|0;for(;s--;)n+=r[Math.random()*r.length|0];return n};const Lf="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",_f=jf(Lf,11),$o=()=>_f(),Zf=Object.freeze(Object.defineProperty({__proto__:null,create:$o},Symbol.toStringTag,{value:"Module"})),qf=i.z.enum(["static","dynamic"]),xo=(r,e)=>{const t=new z(e);if(![O.DAY,O.HOUR,O.MINUTE,O.SECOND,O.MILLISECOND,O.MICROSECOND,O.NANOSECOND].some(s=>s.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof z?new z(n):new O(n)},B=class T{constructor(e,t="UTC"){if(y(this,"value"),y(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const s=new Date(e,t-1,n,0,0,0,0);return new T(BigInt(s.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let h=T.hours(parseInt(n??"00")).add(T.minutes(parseInt(s??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(c??"00")));return t==="local"&&(h=h.add(T.utcOffset)),h.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new T(BigInt(n.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new O(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new q(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(O.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(O.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(O.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(O.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(T.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new T(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new T(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new T(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new T(t,"UTC")}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new T(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new T(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new T(t)}toString(){return this.date().toISOString()}remainder(e){return xo(this,e)}get isToday(){return this.truncate(O.DAY).equals(T.now().truncate(O.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const n of e){const s=new T(n);s.after(t)&&(t=s)}return t}static min(...e){let t=T.MAX;for(const n of e){const s=new T(n);s.before(t)&&(t=s)}return t}static nanoseconds(e,t="UTC"){return new T(e,t)}static microseconds(e,t="UTC"){return T.nanoseconds(e*1e3,t)}static milliseconds(e,t="UTC"){return T.microseconds(e*1e3,t)}static seconds(e,t="UTC"){return T.milliseconds(e*1e3,t)}static minutes(e,t="UTC"){return T.seconds(e*60,t)}static hours(e,t="UTC"){return T.minutes(e*60,t)}static days(e,t="UTC"){return T.hours(e*24,t)}};y(B,"NANOSECOND",B.nanoseconds(1)),y(B,"MICROSECOND",B.microseconds(1)),y(B,"MILLISECOND",B.milliseconds(1)),y(B,"SECOND",B.seconds(1)),y(B,"MINUTE",B.minutes(1)),y(B,"HOUR",B.hours(1)),y(B,"DAY",B.days(1)),y(B,"MAX",new B((1n<<63n)-1n)),y(B,"MIN",new B(0)),y(B,"ZERO",new B(0)),y(B,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new B(r.value)),i.z.string().transform(r=>new B(BigInt(r))),i.z.instanceof(Number).transform(r=>new B(r)),i.z.number().transform(r=>new B(r)),i.z.instanceof(B)]));let z=B;const P=class ${constructor(e){y(this,"value"),y(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof $?e:e instanceof cs?e.period:e instanceof z?new $(e):["number","bigint"].includes(typeof e)?$.seconds(e):new $(e)}static fromMilliseconds(e){return e instanceof $?e:e instanceof cs?e.period:e instanceof z?new $(e):["number","bigint"].includes(typeof e)?$.milliseconds(e):new $(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new $(e).valueOf()}greaterThan(e){return this.valueOf()>new $(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new $(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new $(e).valueOf()}remainder(e){return xo(this,e)}truncate(e){return new $(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate($.DAY),t=this.truncate($.HOUR),n=this.truncate($.MINUTE),s=this.truncate($.SECOND),a=this.truncate($.MILLISECOND),o=this.truncate($.MICROSECOND),c=this.truncate($.NANOSECOND),h=e,d=t.sub(e),f=n.sub(t),u=s.sub(n),N=a.sub(s),S=o.sub(a),j=c.sub(o);let U="";return h.isZero||(U+=`${h.days}d `),d.isZero||(U+=`${d.hours}h `),f.isZero||(U+=`${f.minutes}m `),u.isZero||(U+=`${u.seconds}s `),N.isZero||(U+=`${N.milliseconds}ms `),S.isZero||(U+=`${S.microseconds}µs `),j.isZero||(U+=`${j.nanoseconds}ns`),U.trim()}mult(e){return new $(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number($.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number($.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number($.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number($.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number($.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number($.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new $(e).valueOf()}add(e){return new $(this.valueOf()+new $(e).valueOf())}sub(e){return new $(this.valueOf()-new $(e).valueOf())}static nanoseconds(e=1){return new $(e)}static microseconds(e=1){return $.nanoseconds(at(e,1e3))}static milliseconds(e=1){return $.microseconds(at(e,1e3))}static seconds(e=1){return $.milliseconds(at(e,1e3))}static minutes(e=1){return $.seconds(at(e,60))}static hours(e){return $.minutes(at(e,60))}static days(e){return $.hours(at(e,24))}};y(P,"NANOSECOND",P.nanoseconds(1)),y(P,"MICROSECOND",P.microseconds(1)),y(P,"MILLISECOND",P.milliseconds(1)),y(P,"SECOND",P.seconds(1)),y(P,"MINUTE",P.minutes(1)),y(P,"HOUR",P.hours(1)),y(P,"DAY",P.days(1)),y(P,"MAX",new P((1n<<63n)-1n)),y(P,"MIN",new P(0)),y(P,"ZERO",new P(0)),y(P,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new P(r.value)),i.z.string().transform(r=>new P(BigInt(r))),i.z.instanceof(Number).transform(r=>new P(r)),i.z.number().transform(r=>new P(r)),i.z.instanceof(P)]));let O=P;const Ft=class Pr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Pr(e).valueOf()}get period(){return O.seconds(1/this.valueOf())}sampleCount(e){return new O(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new ne(t).valueOf()}span(e){return O.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Pr(e)}static khz(e){return Pr.hz(e*1e3)}};y(Ft,"z",i.z.union([i.z.number().transform(r=>new Ft(r)),i.z.instanceof(Number).transform(r=>new Ft(r)),i.z.instanceof(Ft)]));let cs=Ft;const K=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new vt(e*this.valueOf())}};y(K,"UNKNOWN",new K(0)),y(K,"BIT128",new K(16)),y(K,"BIT64",new K(8)),y(K,"BIT32",new K(4)),y(K,"BIT16",new K(2)),y(K,"BIT8",new K(1)),y(K,"z",i.z.union([i.z.number().transform(r=>new K(r)),i.z.instanceof(Number).transform(r=>new K(r)),i.z.instanceof(K)]));let ne=K;const ge=class Yt{constructor(e,t){y(this,"start"),y(this,"end"),typeof e=="object"&&"start"in e?(this.start=new z(e.start),this.end=new z(e.end)):(this.start=new z(e),this.end=new z(t))}get span(){return new O(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Yt(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=O.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return n<0&&(n=-n),s<0&&(s=-s),n<=t.valueOf()&&s<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=O.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const s=z.max(n.start,e.start),a=z.min(n.end,e.end);return a.before(s)?!1:new O(a.sub(s)).greaterThanOrEqual(t)}contains(e){return e instanceof Yt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Yt(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new Yt(z.min(...e.map(t=>t.start)),z.max(...e.map(t=>t.end)))}};y(ge,"MAX",new ge(z.MIN,z.MAX)),y(ge,"MIN",new ge(z.MAX,z.MIN)),y(ge,"ZERO",new ge(z.ZERO,z.ZERO)),y(ge,"z",i.z.union([i.z.object({start:z.z,end:z.z}).transform(r=>new ge(r.start,r.end)),i.z.instanceof(ge)]));let q=ge;const Ff=(r,e)=>r.start.before(e.start)?-1:r.start.after(e.start)?1:r.end.before(e.end)?-1:r.end.after(e.end)?1:0,w=class Z{constructor(e){if(y(this,"value"),y(this,"encodeValue",!0),e instanceof Z||typeof e=="string"||typeof e.valueOf()=="string"){this.value=e.valueOf();return}const t=Z.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){this.value=t.valueOf();return}throw this.value=Z.UNKNOWN.valueOf(),new Error(`unable to find data type for ${e.toString()}`)}valueOf(){return this.value}get Array(){const e=Z.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(Z.JSON)||this.equals(Z.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Z.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Z.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(Z.UINT8)||this.equals(Z.UINT16)||this.equals(Z.UINT32)||this.equals(Z.UINT64)}get isSigned(){return this.equals(Z.INT8)||this.equals(Z.INT16)||this.equals(Z.INT32)||this.equals(Z.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(Z.INT32)&&e.equals(Z.FLOAT64)||this.equals(Z.INT8)&&e.equals(Z.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}toJSON(){return this.toString()}get usesBigInt(){return Z.BIG_INT_TYPES.some(e=>e.equals(this))}};y(w,"UNKNOWN",new w("unknown")),y(w,"FLOAT64",new w("float64")),y(w,"FLOAT32",new w("float32")),y(w,"INT64",new w("int64")),y(w,"INT32",new w("int32")),y(w,"INT16",new w("int16")),y(w,"INT8",new w("int8")),y(w,"UINT64",new w("uint64")),y(w,"UINT32",new w("uint32")),y(w,"UINT16",new w("uint16")),y(w,"UINT8",new w("uint8")),y(w,"BOOLEAN",w.UINT8),y(w,"TIMESTAMP",new w("timestamp")),y(w,"UUID",new w("uuid")),y(w,"STRING",new w("string")),y(w,"JSON",new w("json")),y(w,"ARRAY_CONSTRUCTORS",new Map([[w.UINT8.toString(),Uint8Array],[w.UINT16.toString(),Uint16Array],[w.UINT32.toString(),Uint32Array],[w.UINT64.toString(),BigUint64Array],[w.FLOAT32.toString(),Float32Array],[w.FLOAT64.toString(),Float64Array],[w.INT8.toString(),Int8Array],[w.INT16.toString(),Int16Array],[w.INT32.toString(),Int32Array],[w.INT64.toString(),BigInt64Array],[w.TIMESTAMP.toString(),BigInt64Array],[w.STRING.toString(),Uint8Array],[w.JSON.toString(),Uint8Array],[w.UUID.toString(),Uint8Array]])),y(w,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,w.UINT8],[Uint16Array.name,w.UINT16],[Uint32Array.name,w.UINT32],[BigUint64Array.name,w.UINT64],[Float32Array.name,w.FLOAT32],[Float64Array.name,w.FLOAT64],[Int8Array.name,w.INT8],[Int16Array.name,w.INT16],[Int32Array.name,w.INT32],[BigInt64Array.name,w.INT64]])),y(w,"DENSITIES",new Map([[w.UINT8.toString(),ne.BIT8],[w.UINT16.toString(),ne.BIT16],[w.UINT32.toString(),ne.BIT32],[w.UINT64.toString(),ne.BIT64],[w.FLOAT32.toString(),ne.BIT32],[w.FLOAT64.toString(),ne.BIT64],[w.INT8.toString(),ne.BIT8],[w.INT16.toString(),ne.BIT16],[w.INT32.toString(),ne.BIT32],[w.INT64.toString(),ne.BIT64],[w.TIMESTAMP.toString(),ne.BIT64],[w.STRING.toString(),ne.UNKNOWN],[w.JSON.toString(),ne.UNKNOWN],[w.UUID.toString(),ne.BIT128]])),y(w,"ALL",[w.UNKNOWN,w.FLOAT64,w.FLOAT32,w.INT64,w.INT32,w.INT16,w.INT8,w.UINT64,w.UINT32,w.UINT16,w.UINT8,w.TIMESTAMP,w.UUID,w.STRING,w.JSON]),y(w,"BIG_INT_TYPES",[w.INT64,w.UINT64,w.TIMESTAMP]),y(w,"z",i.z.union([i.z.string().transform(r=>new w(r)),i.z.instanceof(w)]));let x=w;const re=class W extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return W.bytes(this.valueOf()+e.valueOf())}sub(e){return W.bytes(this.valueOf()-e.valueOf())}truncate(e){return new W(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return W.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/W.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/W.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/W.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/W.TERABYTE.valueOf()}toString(){const e=this.truncate(W.TERABYTE),t=this.truncate(W.GIGABYTE),n=this.truncate(W.MEGABYTE),s=this.truncate(W.KILOBYTE),a=this.truncate(W.BYTE),o=e,c=t.sub(e),h=n.sub(t),d=s.sub(n),f=a.sub(s);let u="";return o.isZero||(u+=`${o.terabytes}TB `),c.isZero||(u+=`${c.gigabytes}GB `),h.isZero||(u+=`${h.megabytes}MB `),d.isZero||(u+=`${d.kilobytes}KB `),(!f.isZero||u==="")&&(u+=`${f.valueOf()}B`),u.trim()}static bytes(e=1){return new W(e)}static kilobytes(e=1){return W.bytes(e.valueOf()*1e3)}static megabytes(e=1){return W.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return W.megabytes(e.valueOf()*1e3)}static terabytes(e){return W.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};y(re,"BYTE",new re(1)),y(re,"KILOBYTE",re.kilobytes(1)),y(re,"MEGABYTE",re.megabytes(1)),y(re,"GIGABYTE",re.gigabytes(1)),y(re,"TERABYTE",re.terabytes(1)),y(re,"ZERO",new re(0)),y(re,"z",i.z.union([i.z.number().transform(r=>new re(r)),i.z.instanceof(re)]));let vt=re;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const ko=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof z||r instanceof O||r instanceof Date},Yf=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):Wt(t,-n).valueOf(),Wt=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),Wf=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof _e?!0:ko(r),Re=-1,ls={[Symbol.iterator]:()=>ls,next:()=>({done:!0,value:void 0})},Vf=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Gf=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),hs=10,Ao=(r,e)=>{if(r==="string"&&!e.isVariable)throw new Error(`cannot convert series of type ${e.toString()} to string`);if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Vt=class pe{constructor(e){y(this,"key",""),y(this,"isSynnaxSeries",!0),y(this,"dataType"),y(this,"sampleOffset"),y(this,"gl"),y(this,"_data"),y(this,"timeRange",q.ZERO),y(this,"alignment",0n),y(this,"_cachedMin"),y(this,"_cachedMax"),y(this,"writePos",Re),y(this,"_refCount",0),y(this,"_cachedLength"),y(this,"_cachedIndexes"),Wf(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,key:c=$o()}=e,h=e.data??[];if(h instanceof pe||typeof h=="object"&&"isSynnaxSeries"in h&&h.isSynnaxSeries===!0){const u=h;this.key=u.key,this.dataType=u.dataType,this.sampleOffset=u.sampleOffset,this.gl=u.gl,this._data=u._data,this.timeRange=u.timeRange,this.alignment=u.alignment,this._cachedMin=u._cachedMin,this._cachedMax=u._cachedMax,this.writePos=u.writePos,this._refCount=u._refCount,this._cachedLength=u._cachedLength;return}const d=ko(h),f=Array.isArray(h);if(t!=null)this.dataType=new x(t);else{if(h instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let u=h;if(!d){if(h.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");u=h[0]}if(typeof u=="string")this.dataType=x.STRING;else if(typeof u=="number")this.dataType=x.FLOAT64;else if(typeof u=="bigint")this.dataType=x.INT64;else if(typeof u=="boolean")this.dataType=x.BOOLEAN;else if(u instanceof z||u instanceof Date||u instanceof z)this.dataType=x.TIMESTAMP;else if(typeof u=="object")this.dataType=x.JSON;else throw new Error(`cannot infer data type of ${typeof u} when constructing a Series from a JS array`)}else this.dataType=new x(h)}if(!f&&!d)this._data=h;else{let u=d?[h]:h;const N=u[0];(N instanceof z||N instanceof Date||N instanceof O)&&(u=u.map(S=>new z(S).valueOf())),this.dataType.equals(x.STRING)?(this._cachedLength=u.length,this._data=new TextEncoder().encode(`${u.join(`
15
+ `).map(c=>c.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(c=>c.trim()),o={};return a.forEach(c=>{o[c]=[]}),s.forEach(c=>{const h=c.split(",").map(d=>d.trim());a.forEach((d,f)=>{const u=this.parseValue(h[f]);u!=null&&o[d].push(u)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},To=class{constructor(){pt(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e)}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const Me=new rr;Me.register({type:0,encode:r=>{if(ArrayBuffer.isView(r)){const e=Array.from(r);return Zt(e,{extensionCodec:Me})}return Hr(r)&&"encode_value"in r?typeof r.value=="bigint"?Zt(r.value.toString(),{extensionCodec:Me}):Zt(r.value,{extensionCodec:Me}):typeof r=="bigint"?Zt(r.toString(),{extensionCodec:Me}):null},decode:r=>mo(r,{extensionCodec:Me})});let Oo=class{constructor(){pt(this,"contentType","application/msgpack")}encode(e){const t=ho(e);return Zt(t,{extensionCodec:Me}).slice()}decode(e,t){const n=mo(e,{extensionCodec:Me}),s=Rs(n);return t!=null?t.parse(s):s}static registerCustomType(){}};const Xt=new bo,Gd=new vo,Hd=new To,Kd=new Oo,Qe=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:vo,CSV_CODEC:Gd,JSONCodec:bo,JSON_CODEC:Xt,MSGPACK_CODEC:Kd,MsgPackCodec:Oo,TEXT_CODEC:Hd,TextCodec:To},Symbol.toStringTag,{value:"Module"})),Jd=r=>[...new Set(r)],Xd=(r,e,t=!0)=>{const n=new Map;return r.forEach(s=>{const a=e(s);if(n.has(a)){if(t)return;n.delete(a)}n.set(a,s)}),Array.from(n.values())},ji=Object.freeze(Object.defineProperty({__proto__:null,by:Xd,unique:Jd},Symbol.toStringTag,{value:"Module"})),Qd=r=>r!=null&&typeof r=="object"&&"toString"in r,ef=(r,e=!1)=>{const t=Qd(r)?"stringer":typeof r;let n;switch(t){case"string":n=(s,a)=>s.localeCompare(a);break;case"stringer":n=(s,a)=>s.toString().localeCompare(a.toString());break;case"number":n=(s,a)=>Number(s)-Number(a);break;case"bigint":n=(s,a)=>BigInt(s)-BigInt(a)>0n?1:-1;break;case"boolean":n=(s,a)=>Number(s)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?tf(n):n},tf=r=>(e,t)=>r(t,e),Kr=0,En=-1,zn=1,rf=r=>r<Kr,nf=r=>r>Kr,sf=r=>r===Kr,Jr=i.z.tuple([i.z.number(),i.z.number()]);i.z.tuple([i.z.bigint(),i.z.bigint()]);const So=i.z.object({width:i.z.number(),height:i.z.number()}),af=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()}),of=["width","height"];i.z.enum(of);const cf=["start","center","end"],lf=["signedWidth","signedHeight"];i.z.enum(lf);const Zr=i.z.object({x:i.z.number(),y:i.z.number()}),hf=i.z.object({clientX:i.z.number(),clientY:i.z.number()}),uf=["x","y"],Eo=i.z.enum(uf),zo=["top","right","bottom","left"];i.z.enum(zo);const df=["left","right"],No=i.z.enum(df),ff=["top","bottom"],Io=i.z.enum(ff),$o=["center"],Li=i.z.enum($o),yf=[...zo,...$o],xo=i.z.enum(yf);i.z.enum(cf);const gf=["first","last"];i.z.enum(gf);const pf=i.z.object({lower:i.z.number(),upper:i.z.number()}),wf=i.z.object({lower:i.z.bigint(),upper:i.z.bigint()});i.z.union([pf,Jr]);i.z.union([wf,Jr]);i.z.enum([...Eo.options,...xo.options]);i.z.union([Eo,xo,i.z.instanceof(String)]);const Et=r=>typeof r=="bigint"||r instanceof BigInt,Nn=(r,e)=>Et(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),mf=(r,e)=>Et(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),_i=(r,e)=>Et(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),bf=(r,e)=>Et(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),vf=r=>Et(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,at=(r,e)=>Et(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),J=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Zi(r);return Zi(t)},Zi=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,qi=(r,e)=>{const t=J(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},$r=(r,e)=>{const t=J(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=J(e);return n.lower>=t.lower&&n.upper<=t.upper},Tf=r=>({lower:Math.min(...r.map(e=>J(e).lower)),upper:Math.max(...r.map(e=>J(e).upper))}),Of=(r,e,t)=>{const n=r.map(c=>J(c)),s=t>0?1:t<0?-1:0;if(s===0)return e;let a=t,o=e;for(;_i(a,0)===!1;){const c=n.findIndex(h=>s>0?o>=h.lower&&o<h.upper:o>h.lower&&o<=h.upper);if(c!==-1){const h=n[c];let d;if(s>0?d=Nn(h.upper,o):d=Nn(o,h.lower),d>0){const f=bf(vf(a),d);if(o=mf(o,s>0?f:-f),a=Nn(a,s>0?f:-f),_i(a,0))return o;continue}}if(s>0){const h=n.filter(d=>d.lower>o);if(h.length>0)o=h[0].lower;else return o}else{const h=n.filter(d=>d.upper<o);if(h.length>0)o=h[h.length-1].upper;else return o}}return o},Sf=(r,e,t)=>{const n=r.map(o=>J(o));if(e===t)return typeof e=="bigint"?0n:0;const s=e<t?J([e,t]):J([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const c=o.lower>s.lower?o.lower:s.lower,h=o.upper<s.upper?o.upper:s.upper;if(c<h){const d=h-c;a=a+d}}return a};i.z.object({x:No.or(Li),y:Io.or(Li)});const Ef=i.z.object({x:No,y:Io}),zf=Object.freeze({x:"left",y:"top"}),Nf=(r,e)=>r.x===e.x&&r.y===e.y,Fi=i.z.union([i.z.number(),Zr,Jr,So,af,hf]),If=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Yi=Object.freeze({x:0,y:0}),xr=i.z.union([i.z.number(),i.z.string()]);i.z.object({top:xr,left:xr,width:xr,height:xr});i.z.object({left:i.z.number(),top:i.z.number(),right:i.z.number(),bottom:i.z.number()});i.z.object({one:Zr,two:Zr,root:Ef});const Ps=(r,e,t=0,n=0,s)=>{const a={one:{...Yi},two:{...Yi},root:s??zf};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:r,y:e},a.two={x:a.one.x+t,y:a.one.y+n},a}return"one"in r&&"two"in r&&"root"in r?{...r,root:s??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(a.one={x:r.left,y:r.top},a.two={x:r.right,y:r.bottom},a):(a.one=r,e==null?a.two={x:a.one.x+t,y:a.one.y+n}:typeof e=="number"?a.two={x:a.one.x+e,y:a.one.y+t}:"width"in e?a.two={x:a.one.x+e.width,y:a.one.y+e.height}:"signedWidth"in e?a.two={x:a.one.x+e.signedWidth,y:a.one.y+e.signedHeight}:a.two=e,a))},In=r=>{const e=Ps(r);return{lower:e.one.x,upper:e.two.x}},$n=r=>{const e=Ps(r);return{lower:e.one.y,upper:e.two.y}},$f=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,xf=i.z.object({signedWidth:i.z.number(),signedHeight:i.z.number()});i.z.union([So,xf,Zr,Jr]);var kf=Object.defineProperty,Af=(r,e,t)=>e in r?kf(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,xe=(r,e,t)=>Af(r,typeof e!="symbol"?e+"":e,t);const Uf=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;i.z.object({offset:Fi,scale:Fi});i.z.object({offset:i.z.number(),scale:i.z.number()});const Cf=r=>(e,t,n,s)=>t==="dimension"?[e,n]:[e,s?n-r:n+r],Rf=r=>(e,t,n,s)=>[e,s?n/r:n*r],Bf=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:s,upper:a}=e,{lower:o,upper:c}=r,h=a-s,d=c-o;if(t==="dimension")return[r,n*(d/h)];const f=(n-s)*(d/h)+o;return[r,f]},Pf=r=>(e,t,n)=>[r,n],Df=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:s}=r;return[r,s-(t-n)]},Mf=r=>(e,t,n)=>{const{lower:s,upper:a}=r;return n=Uf(n,s,a),[e,n]},os=class qt{constructor(){xe(this,"ops",[]),xe(this,"currBounds",null),xe(this,"currType",null),xe(this,"reversed",!1),this.ops=[]}static translate(e){return new qt().translate(e)}static magnify(e){return new qt().magnify(e)}static scale(e,t){return new qt().scale(e,t)}translate(e){const t=this.new(),n=Cf(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Rf(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=J(e,t),s=this.new(),a=Bf(n);return a.type="scale",s.ops.push(a),s}clamp(e,t){const n=J(e,t),s=this.new(),a=Mf(n);return a.type="clamp",s.ops.push(a),s}reBound(e,t){const n=J(e,t),s=this.new(),a=Pf(n);return a.type="re-bound",s.ops.push(a),s}invert(){const e=Df();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new qt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,s],a)=>a(n,e,s,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,s)=>{if(n.type==="scale"||t.some(([o,c])=>s>=o&&s<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>s);a!==-1&&t.push([s,a])}),t.forEach(([n,s])=>{const a=e.ops.slice(n,s);a.unshift(e.ops[s]),e.ops.splice(n,s-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};xe(os,"IDENTITY",new os);let Wi=os;const Vi=class Ie{constructor(e=new Wi,t=new Wi,n=null){xe(this,"x"),xe(this,"y"),xe(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new Ie().translate(e,t)}static translateX(e){return new Ie().translateX(e)}static translateY(e){return new Ie().translateY(e)}static clamp(e){return new Ie().clamp(e)}static magnify(e){return new Ie().magnify(e)}static scale(e){return new Ie().scale(e)}static reBound(e){return new Ie().reBound(e)}translate(e,t){const n=If(e,t),s=this.copy();return s.x=this.x.translate(n.x),s.y=this.y.translate(n.y),s}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if($f(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Nf(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(In(e)),t.y=t.y.scale($n(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(In(e)),t.y=this.y.reBound($n(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(In(e)),t.y=this.y.clamp($n(e)),t}copy(){const e=new Ie;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Ps(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};xe(Vi,"IDENTITY",new Vi);var jf=Object.defineProperty,Lf=(r,e,t)=>e in r?jf(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e,t)=>Lf(r,typeof e!="symbol"?e+"":e,t);let _f=(r,e=21)=>(t=e)=>{let n="",s=t|0;for(;s--;)n+=r[Math.random()*r.length|0];return n};const Zf="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",qf=_f(Zf,11),ko=()=>qf(),Ff=Object.freeze(Object.defineProperty({__proto__:null,create:ko},Symbol.toStringTag,{value:"Module"})),Yf=i.z.enum(["static","dynamic"]),Ao=(r,e)=>{const t=new z(e);if(![O.DAY,O.HOUR,O.MINUTE,O.SECOND,O.MILLISECOND,O.MICROSECOND,O.NANOSECOND].some(s=>s.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof z?new z(n):new O(n)},B=class T{constructor(e,t="UTC"){if(y(this,"value"),y(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const s=new Date(e,t-1,n,0,0,0,0);return new T(BigInt(s.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,s,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let h=T.hours(parseInt(n??"00")).add(T.minutes(parseInt(s??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(c??"00")));return t==="local"&&(h=h.add(T.utcOffset)),h.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new T(BigInt(n.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new O(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new q(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(O.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(O.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(O.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(O.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(T.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new T(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new T(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new T(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new T(t,"UTC")}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new T(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new T(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new T(t)}toString(){return this.date().toISOString()}remainder(e){return Ao(this,e)}get isToday(){return this.truncate(O.DAY).equals(T.now().truncate(O.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const n of e){const s=new T(n);s.after(t)&&(t=s)}return t}static min(...e){let t=T.MAX;for(const n of e){const s=new T(n);s.before(t)&&(t=s)}return t}static nanoseconds(e,t="UTC"){return new T(e,t)}static microseconds(e,t="UTC"){return T.nanoseconds(e*1e3,t)}static milliseconds(e,t="UTC"){return T.microseconds(e*1e3,t)}static seconds(e,t="UTC"){return T.milliseconds(e*1e3,t)}static minutes(e,t="UTC"){return T.seconds(e*60,t)}static hours(e,t="UTC"){return T.minutes(e*60,t)}static days(e,t="UTC"){return T.hours(e*24,t)}};y(B,"NANOSECOND",B.nanoseconds(1)),y(B,"MICROSECOND",B.microseconds(1)),y(B,"MILLISECOND",B.milliseconds(1)),y(B,"SECOND",B.seconds(1)),y(B,"MINUTE",B.minutes(1)),y(B,"HOUR",B.hours(1)),y(B,"DAY",B.days(1)),y(B,"MAX",new B((1n<<63n)-1n)),y(B,"MIN",new B(0)),y(B,"ZERO",new B(0)),y(B,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new B(r.value)),i.z.string().transform(r=>new B(BigInt(r))),i.z.instanceof(Number).transform(r=>new B(r)),i.z.number().transform(r=>new B(r)),i.z.instanceof(B)]));let z=B;const P=class ${constructor(e){y(this,"value"),y(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof $?e:e instanceof cs?e.period:e instanceof z?new $(e):["number","bigint"].includes(typeof e)?$.seconds(e):new $(e)}static fromMilliseconds(e){return e instanceof $?e:e instanceof cs?e.period:e instanceof z?new $(e):["number","bigint"].includes(typeof e)?$.milliseconds(e):new $(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new $(e).valueOf()}greaterThan(e){return this.valueOf()>new $(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new $(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new $(e).valueOf()}remainder(e){return Ao(this,e)}truncate(e){return new $(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate($.DAY),t=this.truncate($.HOUR),n=this.truncate($.MINUTE),s=this.truncate($.SECOND),a=this.truncate($.MILLISECOND),o=this.truncate($.MICROSECOND),c=this.truncate($.NANOSECOND),h=e,d=t.sub(e),f=n.sub(t),u=s.sub(n),N=a.sub(s),S=o.sub(a),j=c.sub(o);let U="";return h.isZero||(U+=`${h.days}d `),d.isZero||(U+=`${d.hours}h `),f.isZero||(U+=`${f.minutes}m `),u.isZero||(U+=`${u.seconds}s `),N.isZero||(U+=`${N.milliseconds}ms `),S.isZero||(U+=`${S.microseconds}µs `),j.isZero||(U+=`${j.nanoseconds}ns`),U.trim()}mult(e){return new $(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number($.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number($.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number($.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number($.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number($.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number($.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new $(e).valueOf()}add(e){return new $(this.valueOf()+new $(e).valueOf())}sub(e){return new $(this.valueOf()-new $(e).valueOf())}static nanoseconds(e=1){return new $(e)}static microseconds(e=1){return $.nanoseconds(at(e,1e3))}static milliseconds(e=1){return $.microseconds(at(e,1e3))}static seconds(e=1){return $.milliseconds(at(e,1e3))}static minutes(e=1){return $.seconds(at(e,60))}static hours(e){return $.minutes(at(e,60))}static days(e){return $.hours(at(e,24))}};y(P,"NANOSECOND",P.nanoseconds(1)),y(P,"MICROSECOND",P.microseconds(1)),y(P,"MILLISECOND",P.milliseconds(1)),y(P,"SECOND",P.seconds(1)),y(P,"MINUTE",P.minutes(1)),y(P,"HOUR",P.hours(1)),y(P,"DAY",P.days(1)),y(P,"MAX",new P((1n<<63n)-1n)),y(P,"MIN",new P(0)),y(P,"ZERO",new P(0)),y(P,"z",i.z.union([i.z.object({value:i.z.bigint()}).transform(r=>new P(r.value)),i.z.string().transform(r=>new P(BigInt(r))),i.z.instanceof(Number).transform(r=>new P(r)),i.z.number().transform(r=>new P(r)),i.z.instanceof(P)]));let O=P;const Ft=class Pr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Pr(e).valueOf()}get period(){return O.seconds(1/this.valueOf())}sampleCount(e){return new O(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new ne(t).valueOf()}span(e){return O.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Pr(e)}static khz(e){return Pr.hz(e*1e3)}};y(Ft,"z",i.z.union([i.z.number().transform(r=>new Ft(r)),i.z.instanceof(Number).transform(r=>new Ft(r)),i.z.instanceof(Ft)]));let cs=Ft;const K=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new vt(e*this.valueOf())}};y(K,"UNKNOWN",new K(0)),y(K,"BIT128",new K(16)),y(K,"BIT64",new K(8)),y(K,"BIT32",new K(4)),y(K,"BIT16",new K(2)),y(K,"BIT8",new K(1)),y(K,"z",i.z.union([i.z.number().transform(r=>new K(r)),i.z.instanceof(Number).transform(r=>new K(r)),i.z.instanceof(K)]));let ne=K;const ge=class Yt{constructor(e,t){y(this,"start"),y(this,"end"),typeof e=="object"&&"start"in e?(this.start=new z(e.start),this.end=new z(e.end)):(this.start=new z(e),this.end=new z(t))}get span(){return new O(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new Yt(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=O.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),s=this.end.sub(e.end).valueOf();return n<0&&(n=-n),s<0&&(s=-s),n<=t.valueOf()&&s<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=O.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const s=z.max(n.start,e.start),a=z.min(n.end,e.end);return a.before(s)?!1:new O(a.sub(s)).greaterThanOrEqual(t)}contains(e){return e instanceof Yt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Yt(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new Yt(z.min(...e.map(t=>t.start)),z.max(...e.map(t=>t.end)))}};y(ge,"MAX",new ge(z.MIN,z.MAX)),y(ge,"MIN",new ge(z.MAX,z.MIN)),y(ge,"ZERO",new ge(z.ZERO,z.ZERO)),y(ge,"z",i.z.union([i.z.object({start:z.z,end:z.z}).transform(r=>new ge(r.start,r.end)),i.z.instanceof(ge)]));let q=ge;const Wf=(r,e)=>r.start.before(e.start)?-1:r.start.after(e.start)?1:r.end.before(e.end)?-1:r.end.after(e.end)?1:0,w=class Z{constructor(e){if(y(this,"value"),y(this,"encodeValue",!0),e instanceof Z||typeof e=="string"||typeof e.valueOf()=="string"){this.value=e.valueOf();return}const t=Z.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){this.value=t.valueOf();return}throw this.value=Z.UNKNOWN.valueOf(),new Error(`unable to find data type for ${e.toString()}`)}valueOf(){return this.value}get Array(){const e=Z.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(Z.JSON)||this.equals(Z.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Z.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Z.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(Z.UINT8)||this.equals(Z.UINT16)||this.equals(Z.UINT32)||this.equals(Z.UINT64)}get isSigned(){return this.equals(Z.INT8)||this.equals(Z.INT16)||this.equals(Z.INT32)||this.equals(Z.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(Z.INT32)&&e.equals(Z.FLOAT64)||this.equals(Z.INT8)&&e.equals(Z.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}toJSON(){return this.toString()}get usesBigInt(){return Z.BIG_INT_TYPES.some(e=>e.equals(this))}};y(w,"UNKNOWN",new w("unknown")),y(w,"FLOAT64",new w("float64")),y(w,"FLOAT32",new w("float32")),y(w,"INT64",new w("int64")),y(w,"INT32",new w("int32")),y(w,"INT16",new w("int16")),y(w,"INT8",new w("int8")),y(w,"UINT64",new w("uint64")),y(w,"UINT32",new w("uint32")),y(w,"UINT16",new w("uint16")),y(w,"UINT8",new w("uint8")),y(w,"BOOLEAN",w.UINT8),y(w,"TIMESTAMP",new w("timestamp")),y(w,"UUID",new w("uuid")),y(w,"STRING",new w("string")),y(w,"JSON",new w("json")),y(w,"ARRAY_CONSTRUCTORS",new Map([[w.UINT8.toString(),Uint8Array],[w.UINT16.toString(),Uint16Array],[w.UINT32.toString(),Uint32Array],[w.UINT64.toString(),BigUint64Array],[w.FLOAT32.toString(),Float32Array],[w.FLOAT64.toString(),Float64Array],[w.INT8.toString(),Int8Array],[w.INT16.toString(),Int16Array],[w.INT32.toString(),Int32Array],[w.INT64.toString(),BigInt64Array],[w.TIMESTAMP.toString(),BigInt64Array],[w.STRING.toString(),Uint8Array],[w.JSON.toString(),Uint8Array],[w.UUID.toString(),Uint8Array]])),y(w,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,w.UINT8],[Uint16Array.name,w.UINT16],[Uint32Array.name,w.UINT32],[BigUint64Array.name,w.UINT64],[Float32Array.name,w.FLOAT32],[Float64Array.name,w.FLOAT64],[Int8Array.name,w.INT8],[Int16Array.name,w.INT16],[Int32Array.name,w.INT32],[BigInt64Array.name,w.INT64]])),y(w,"DENSITIES",new Map([[w.UINT8.toString(),ne.BIT8],[w.UINT16.toString(),ne.BIT16],[w.UINT32.toString(),ne.BIT32],[w.UINT64.toString(),ne.BIT64],[w.FLOAT32.toString(),ne.BIT32],[w.FLOAT64.toString(),ne.BIT64],[w.INT8.toString(),ne.BIT8],[w.INT16.toString(),ne.BIT16],[w.INT32.toString(),ne.BIT32],[w.INT64.toString(),ne.BIT64],[w.TIMESTAMP.toString(),ne.BIT64],[w.STRING.toString(),ne.UNKNOWN],[w.JSON.toString(),ne.UNKNOWN],[w.UUID.toString(),ne.BIT128]])),y(w,"ALL",[w.UNKNOWN,w.FLOAT64,w.FLOAT32,w.INT64,w.INT32,w.INT16,w.INT8,w.UINT64,w.UINT32,w.UINT16,w.UINT8,w.TIMESTAMP,w.UUID,w.STRING,w.JSON]),y(w,"BIG_INT_TYPES",[w.INT64,w.UINT64,w.TIMESTAMP]),y(w,"z",i.z.union([i.z.string().transform(r=>new w(r)),i.z.instanceof(w)]));let x=w;const re=class W extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return W.bytes(this.valueOf()+e.valueOf())}sub(e){return W.bytes(this.valueOf()-e.valueOf())}truncate(e){return new W(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return W.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/W.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/W.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/W.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/W.TERABYTE.valueOf()}toString(){const e=this.truncate(W.TERABYTE),t=this.truncate(W.GIGABYTE),n=this.truncate(W.MEGABYTE),s=this.truncate(W.KILOBYTE),a=this.truncate(W.BYTE),o=e,c=t.sub(e),h=n.sub(t),d=s.sub(n),f=a.sub(s);let u="";return o.isZero||(u+=`${o.terabytes}TB `),c.isZero||(u+=`${c.gigabytes}GB `),h.isZero||(u+=`${h.megabytes}MB `),d.isZero||(u+=`${d.kilobytes}KB `),(!f.isZero||u==="")&&(u+=`${f.valueOf()}B`),u.trim()}static bytes(e=1){return new W(e)}static kilobytes(e=1){return W.bytes(e.valueOf()*1e3)}static megabytes(e=1){return W.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return W.megabytes(e.valueOf()*1e3)}static terabytes(e){return W.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};y(re,"BYTE",new re(1)),y(re,"KILOBYTE",re.kilobytes(1)),y(re,"MEGABYTE",re.megabytes(1)),y(re,"GIGABYTE",re.gigabytes(1)),y(re,"TERABYTE",re.terabytes(1)),y(re,"ZERO",new re(0)),y(re,"z",i.z.union([i.z.number().transform(r=>new re(r)),i.z.instanceof(re)]));let vt=re;i.z.union([i.z.instanceof(Uint8Array),i.z.instanceof(Uint16Array),i.z.instanceof(Uint32Array),i.z.instanceof(BigUint64Array),i.z.instanceof(Float32Array),i.z.instanceof(Float64Array),i.z.instanceof(Int8Array),i.z.instanceof(Int16Array),i.z.instanceof(Int32Array),i.z.instanceof(BigInt64Array)]);const Uo=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof z||r instanceof O||r instanceof Date},Vf=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):Wt(t,-n).valueOf(),Wt=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),Gf=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof _e?!0:Uo(r),Re=-1,ls={[Symbol.iterator]:()=>ls,next:()=>({done:!0,value:void 0})},Hf=i.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Kf=i.z.union([i.z.null(),i.z.undefined()]).transform(()=>new Uint8Array().buffer),hs=10,Co=(r,e)=>{if(r==="string"&&!e.isVariable)throw new Error(`cannot convert series of type ${e.toString()} to string`);if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Vt=class pe{constructor(e){y(this,"key",""),y(this,"isSynnaxSeries",!0),y(this,"dataType"),y(this,"sampleOffset"),y(this,"gl"),y(this,"_data"),y(this,"timeRange",q.ZERO),y(this,"alignment",0n),y(this,"_cachedMin"),y(this,"_cachedMax"),y(this,"writePos",Re),y(this,"_refCount",0),y(this,"_cachedLength"),y(this,"_cachedIndexes"),Gf(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:s=0,glBufferUsage:a="static",alignment:o=0n,key:c=ko()}=e,h=e.data??[];if(h instanceof pe||typeof h=="object"&&"isSynnaxSeries"in h&&h.isSynnaxSeries===!0){const u=h;this.key=u.key,this.dataType=u.dataType,this.sampleOffset=u.sampleOffset,this.gl=u.gl,this._data=u._data,this.timeRange=u.timeRange,this.alignment=u.alignment,this._cachedMin=u._cachedMin,this._cachedMax=u._cachedMax,this.writePos=u.writePos,this._refCount=u._refCount,this._cachedLength=u._cachedLength;return}const d=Uo(h),f=Array.isArray(h);if(t!=null)this.dataType=new x(t);else{if(h instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||d){let u=h;if(!d){if(h.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");u=h[0]}if(typeof u=="string")this.dataType=x.STRING;else if(typeof u=="number")this.dataType=x.FLOAT64;else if(typeof u=="bigint")this.dataType=x.INT64;else if(typeof u=="boolean")this.dataType=x.BOOLEAN;else if(u instanceof z||u instanceof Date||u instanceof z)this.dataType=x.TIMESTAMP;else if(typeof u=="object")this.dataType=x.JSON;else throw new Error(`cannot infer data type of ${typeof u} when constructing a Series from a JS array`)}else this.dataType=new x(h)}if(!f&&!d)this._data=h;else{let u=d?[h]:h;const N=u[0];(N instanceof z||N instanceof Date||N instanceof O)&&(u=u.map(S=>new z(S).valueOf())),this.dataType.equals(x.STRING)?(this._cachedLength=u.length,this._data=new TextEncoder().encode(`${u.join(`
16
16
  `)}
17
17
  `).buffer):this.dataType.equals(x.JSON)?(this._cachedLength=u.length,this._data=new TextEncoder().encode(`${u.map(S=>Xt.encodeString(S)).join(`
18
18
  `)}
@@ -22,25 +22,25 @@
22
22
  `)}
23
23
  `);return new pe({data:n,dataType:x.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount<=0){console.warn("attempted to release a series with a negative reference count");return}this._refCount--,this._refCount===0&&this.gl.control!=null&&this.maybeGarbageCollectGLBuffer(this.gl.control)}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Re)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===Re)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this._cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Re?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(x.STRING,x.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
24
24
  `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(x.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=x.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const s=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(s.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(x.JSON))throw new Error("cannot parse non-JSON series as JSON");return new TextDecoder().decode(this.underlyingData).split(`
25
- `).slice(0,-1).map(t=>e.parse(Xt.decodeString(t)))}get byteCapacity(){return new vt(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Re?this.byteCapacity:this.dataType.isVariable?new vt(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Re?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,s)=>{n===hs&&(e++,t.push(s+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let s=0;s<this.length;s++)n[s]=Yf(this.dataType,e,this.data[s],t);return new pe({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),Wt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),Wt(this._cachedMin,this.sampleOffset))}get bounds(){return J(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return Wt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return Wt(n,this.sampleOffset)}atVariable(e,t){let n=0,s=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===hs){if(e===0){s=o;break}n=o+1,e--}if(s===0&&(s=this.data.length),n>=s||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,s);return this.dataType.equals(x.STRING)?new TextDecoder().decode(a):Cs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const s=Xd(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(x.FLOAT32)&&!this.dataType.equals(x.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:s}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Re){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Re}as(e){return Ao(e,this.dataType),this}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Qi(this.alignmentBounds.lower),upper:Qi(this.alignmentBounds.upper)},timeRange:(e=this.timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return J(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Hf(this);return this.dataType.equals(x.JSON)?new Kf(e):e}return new Jf(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Wi(this,e,t??this.length)}subAlignmentIterator(e,t){return new Wi(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new pe({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let s;return e?s=this.data.subarray(t,n):s=this.data.slice(t,n),new pe({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new pe({data:this.buffer,dataType:this.dataType,timeRange:q.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){var e,t;let n=`${this.dataType.toString()} ${this.length} [`;if(this.length<=10)n+=Array.from(this).map(s=>s.toString());else{for(let s=0;s<5;s++)n+=`${(e=this.at(s))==null?void 0:e.toString()}`,s<4&&(n+=",");n+="...";for(let s=-5;s<0;s++)n+=(t=this.at(s))==null?void 0:t.toString(),s<-1&&(n+=",")}return n+="]",n}};y(Vt,"crudeZ",i.z.object({timeRange:q.z.optional(),dataType:x.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Vf,Gf,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:qf.optional().default("static").optional()})),y(Vt,"z",Vt.crudeZ.transform(r=>new Vt(r)));let _e=Vt,Wi=class{constructor(e,t,n){y(this,"series"),y(this,"end"),y(this,"index"),this.series=e;const s=J(0,e.length);this.end=_i(s,n),this.index=_i(s,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}},Hf=class{constructor(e){if(y(this,"series"),y(this,"index"),y(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==hs;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}};var Vi,Gi;const Uo=class Co{constructor(e){y(this,"wrapped"),y(this,Vi,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Xt.decodeString(e.value,Co.SCHEMA)}}[(Gi=Symbol.iterator,Vi=Symbol.toStringTag,Gi)](){return this}};y(Uo,"SCHEMA",i.z.record(i.z.string(),i.z.unknown()));let Kf=Uo;var Hi,Ki;class Jf{constructor(e){y(this,"series"),y(this,"index"),y(this,Hi,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Ki=Symbol.iterator,Hi=Symbol.toStringTag,Ki)](){return this}}let Ro=class{constructor(e=[]){if(y(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return Ao(e,this.dataType),this}get dataType(){return this.series.length===0?x.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?q.ZERO:new q(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?J(0n,0n):J(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){"isSynnaxSeries"in e&&e.isSynnaxSeries?this.series.push(e):this.series.push(...e.series)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const n of this.series)if($r(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new xn(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return ls;let n=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)n+=o.length;else if($r(o.alignmentBounds,e)){n+=Number(e-o.alignment);break}}let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)s+=o.length;else if($r(o.alignmentBounds,t)){s+=Number(t-o.alignment);break}}return new xn(this,n,s)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return ls;let n=0;for(let s=0;s<this.series.length;s++){const a=this.series[s];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)n+=a.length;else if($r(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new xn(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return bf(this.series.map(e=>e.bounds))}get byteLength(){return new vt(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const n=this.series.map(s=>s.alignmentBounds);return vf(n,e,t)}acquire(){this.series.forEach(e=>e.acquire())}release(){this.series.forEach(e=>e.release())}distance(e,t){const n=this.series.map(s=>s.alignmentBounds);return Tf(n,e,t)}parseJSON(e){if(!this.dataType.equals(x.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Xf(this.series)}};var Ji,Xi;class Xf{constructor(e){y(this,"series"),y(this,"seriesIndex"),y(this,"internal"),y(this,Ji,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(Xi=Symbol.iterator,Ji=Symbol.toStringTag,Xi)](){return this}}let xn=class{constructor(e,t,n){y(this,"series"),y(this,"index"),y(this,"end"),this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};const Qi=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},Qf=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},ey=(r,e,t=".")=>{const n=r.split(t);return n.map((s,a)=>{const o=e(s,a,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(s=>s!=null).join(t)},ty=(r,e,t={optional:!1,separator:"."})=>{t.separator??(t.separator=".");const{optional:n,getter:s=(c,h)=>c[h]}=t,a=e.split(t.separator);if(a.length===1&&a[0]==="")return r;let o=r;for(const c of a){const h=s(o,c);if(h==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${c} is null`)}o=h}return o};i.z.object({key:i.z.string(),value:i.z.string()});var ry=Object.defineProperty,ny=(r,e,t)=>e in r?ry(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>ny(r,typeof e!="symbol"?e+"":e,t);let sy=class{constructor(e,t){Dr(this,"handlers"),Dr(this,"transform"),Dr(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,s]=this.transform(e);if(!s)return;t=n}this.handlers.forEach((n,s)=>s(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},iy=class{constructor(e){Dr(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const He=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:iy,Observer:sy},Symbol.toStringTag,{value:"Module"})),ce=i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown()),ay=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";ay();const oy=["macOS","Windows","Linux"],cy=["macos","windows","linux"],ly={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(oy).or(i.z.enum(cy).transform(r=>ly[r]));var hy=Object.defineProperty,uy=(r,e,t)=>e in r?hy(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gt=(r,e,t)=>uy(r,typeof e!="symbol"?e+"":e,t);const dy=(...r)=>r.map(Bo).join(""),Bo=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),fy=r=>r.endsWith("/")?r.slice(0,-1):r,us=class ds{constructor({host:e,port:t,protocol:n="",pathPrefix:s=""}){Gt(this,"protocol"),Gt(this,"host"),Gt(this,"port"),Gt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Bo(s)}replace(e){return new ds({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new ds({...this,pathPrefix:dy(this.path,e)})}toString(){return fy(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Gt(us,"UNKNOWN",new us({host:"unknown",port:0}));let yy=us;const gy=-128,py=127,wy=i.z.number().int().min(gy).max(py),my=-32768,by=32767,vy=i.z.number().int().min(my).max(by),Ty=-2147483648,Oy=2147483647,Sy=i.z.number().int().min(Ty).max(Oy),Ey=-9223372036854775808n,zy=9223372036854775807n,Ny=i.z.bigint().min(Ey).max(zy),Iy=255,$y=i.z.number().int().min(0).max(Iy),xy=65535,ky=i.z.number().int().min(0).max(xy),Ay=4294967295,Uy=i.z.number().int().min(0).max(Ay),Cy=18446744073709551615n,Ry=i.z.bigint().min(0n).max(Cy),Po=r=>ey(r,(e,t,n)=>{const s=t===n.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[t+1]));return a&&(e="element"),s||o?e:[e,"shape"]}),ea=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},By=(r,e,t)=>ty(ea(r,"shape"),Po(e),{...t,getter:ea}),Py=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:By,getFieldSchemaPath:Po,int16:vy,int32:Sy,int64:Ny,int8:wy,uint16:ky,uint32:Uy,uint64:Ry,uint8:$y},Symbol.toStringTag,{value:"Module"}));var Dy=Object.defineProperty,My=(r,e,t)=>e in r?Dy(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Te=(r,e,t)=>My(r,typeof e!="symbol"?e+"":e,t);const jy=async r=>await new Promise(e=>setTimeout(e,O.fromMilliseconds(r).milliseconds));class Ly{constructor(e){Te(this,"config"),Te(this,"retries"),Te(this,"interval"),this.config={baseInterval:new O((e==null?void 0:e.baseInterval)??O.seconds(1)),maxRetries:(e==null?void 0:e.maxRetries)??5,scale:(e==null?void 0:e.scale)??1,sleepFn:(e==null?void 0:e.sleepFn)??jy},this.retries=0,this.interval=new O(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const _y=i.z.object({baseInterval:O.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),Do=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Ly,breakerConfig:_y},Symbol.toStringTag,{value:"Module"})),Zy=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Ps=i.z.string().regex(Zy),wt=i.z.number().min(0).max(255),qy=i.z.number().min(0).max(1),Mo=i.z.tuple([wt,wt,wt,qy]),jo=i.z.tuple([wt,wt,wt]),Ds=(r,e=1)=>{if(typeof r=="string")return Yy(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}throw new Error(`Invalid color: ${JSON.stringify(r)}`)},Fy=i.z.union([Ps,Mo,jo]).transform(r=>Ds(r)),Yy=(r,e=1)=>{if(!Ps.safeParse(r).success)throw new Error(`Invalid hex color: ${r}`);return r=Wy(r),[kr(r,0),kr(r,2),kr(r,4),r.length===8?kr(r,6)/255:e]},kr=(r,e)=>parseInt(r.slice(e,e+2),16),Wy=r=>r.startsWith("#")?r.slice(1):r,Vy=i.z.union([Ps,Mo,i.z.string(),jo]);Ds("#000000");Ds("#ffffff");const Gy=i.z.object({key:i.z.string(),color:Vy,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Gy);const Hy=i.z.object({key:i.z.string(),name:i.z.string(),color:Fy});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Hy)});const Lo=i.z.number().int().min(0).max(255),_o=255,Zo=0,Ky={lower:Zo,upper:_o+1},qo=i.z.object({name:i.z.string(),key:i.z.string()}),nr=r=>i.z.object({subject:qo,resource:r,authority:Lo}),Jy=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),Fo=i.z.object({from:nr(i.z.any()),to:i.z.null()}),Yo=i.z.object({from:i.z.null(),to:nr(i.z.any())}),Xy=i.z.union([Fo,Yo,i.z.object({from:nr(i.z.any()),to:nr(i.z.any())})]),Ke=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:_o,AUTHORITY_BOUNDS:Ky,ZERO_AUTHORITY:Zo,acquireZ:Yo,authorityZ:Lo,filterTransfersByChannelKey:Jy,releaseZ:Fo,stateZ:nr,subjectZ:qo,transferZ:Xy},Symbol.toStringTag,{value:"Module"})),Qy=r=>Object.getOwnPropertySymbols(globalThis).includes(r),eg=(r,e)=>{const t=Symbol.for(r);if(!Qy(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},tg=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Xr=r=>{var e;return e=class extends Error{constructor(t,n){super(t,n),Te(this,"discriminator",e.discriminator),Te(this,"type",e.TYPE),Te(this,"matches",e.matches),this.name=e.TYPE}static sub(t){return Xr(`${r}.${t}`)}},Te(e,"discriminator","FreighterError"),Te(e,"TYPE",r),Te(e,"matches",tg(r)),e},Wo=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},ct="unknown",fs="nil";class rg{constructor(){Te(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:fs,data:""};if(Wo(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:ct,data:e.message};if(typeof e=="string")return{type:ct,data:e};try{return{type:ct,data:JSON.stringify(e)}}catch{return{type:ct,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===fs)return null;if(e.type===ct)return new ys(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new ys(e.data)}}const Ms=eg("synnax-error-registry",()=>new rg),ng=({encode:r,decode:e})=>Ms().register({encode:r,decode:e}),sg=r=>Ms().encode(r),ig=r=>r==null?null:Ms().decode(r);class ys extends Xr("unknown"){}const ag=i.z.object({type:i.z.string(),data:i.z.string()});class og extends Xr("canceled"){}const Tt=Object.freeze(Object.defineProperty({__proto__:null,Canceled:og,NONE:fs,UNKNOWN:ct,Unknown:ys,createTyped:Xr,decode:ig,encode:sg,isTyped:Wo,payloadZ:ag,register:ng},Symbol.toStringTag,{value:"Module"}));i.object({jsonrpc:i.string(),id:i.number().optional(),method:i.string().optional(),params:i.unknown().optional(),result:i.unknown().optional()});const gs=i.z.string().regex(/^\d+\.\d+\.\d+$/),ur=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=gs.parse(r),s=gs.parse(e),[a,o,c]=n.split(".").map(Number),[h,d,f]=s.split(".").map(Number);if(t.checkMajor){if(a<h)return En;if(a>h)return zn}if(t.checkMinor){if(o<d)return En;if(o>d)return zn}if(t.checkPatch){if(c<f)return En;if(c>f)return zn}return Kr},cg=(r,e,t={})=>rf(ur(r,e,t)),Vo=(r,e,t={})=>tf(ur(r,e,t)),lg=(r,e,t={})=>ef(ur(r,e,t)),hg=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},ug=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:s})=>{const a=Object.keys(e).sort(ur).pop();if(a==null)return d=>{if(d.version??(d.version=n),d.version!==s.version)return console.log(`${r} version ${d.version} is newer than latest version of ${s.version}.
25
+ `).slice(0,-1).map(t=>e.parse(Xt.decodeString(t)))}get byteCapacity(){return new vt(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Re?this.byteCapacity:this.dataType.isVariable?new vt(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Re?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,s)=>{n===hs&&(e++,t.push(s+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let s=0;s<this.length;s++)n[s]=Vf(this.dataType,e,this.data[s],t);return new pe({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),Wt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),Wt(this._cachedMin,this.sampleOffset))}get bounds(){return J(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return Wt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return Wt(n,this.sampleOffset)}atVariable(e,t){let n=0,s=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],s=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===hs){if(e===0){s=o;break}n=o+1,e--}if(s===0&&(s=this.data.length),n>=s||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,s);return this.dataType.equals(x.STRING)?new TextDecoder().decode(a):Rs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const s=ef(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=s(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(x.FLOAT32)&&!this.dataType.equals(x.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:s}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==s)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Re){s===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(s).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Re}as(e){return Co(e,this.dataType),this}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:ta(this.alignmentBounds.lower),upper:ta(this.alignmentBounds.upper)},timeRange:(e=this.timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return J(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Jf(this);return this.dataType.equals(x.JSON)?new Xf(e):e}return new Qf(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Gi(this,e,t??this.length)}subAlignmentIterator(e,t){return new Gi(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new pe({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let s;return e?s=this.data.subarray(t,n):s=this.data.slice(t,n),new pe({data:s,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new pe({data:this.buffer,dataType:this.dataType,timeRange:q.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){var e,t;let n=`${this.dataType.toString()} ${this.length} [`;if(this.length<=10)n+=Array.from(this).map(s=>s.toString());else{for(let s=0;s<5;s++)n+=`${(e=this.at(s))==null?void 0:e.toString()}`,s<4&&(n+=",");n+="...";for(let s=-5;s<0;s++)n+=(t=this.at(s))==null?void 0:t.toString(),s<-1&&(n+=",")}return n+="]",n}};y(Vt,"crudeZ",i.z.object({timeRange:q.z.optional(),dataType:x.z,alignment:i.z.coerce.bigint().optional(),data:i.z.union([Hf,Kf,i.z.instanceof(ArrayBuffer),i.z.instanceof(Uint8Array)]),glBufferUsage:Yf.optional().default("static").optional()})),y(Vt,"z",Vt.crudeZ.transform(r=>new Vt(r)));let _e=Vt,Gi=class{constructor(e,t,n){y(this,"series"),y(this,"end"),y(this,"index"),this.series=e;const s=J(0,e.length);this.end=qi(s,n),this.index=qi(s,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class Jf{constructor(e){if(y(this,"series"),y(this,"index"),y(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==hs;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Hi,Ki;const Ro=class Bo{constructor(e){y(this,"wrapped"),y(this,Hi,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Xt.decodeString(e.value,Bo.SCHEMA)}}[(Ki=Symbol.iterator,Hi=Symbol.toStringTag,Ki)](){return this}};y(Ro,"SCHEMA",i.z.record(i.z.string(),i.z.unknown()));let Xf=Ro;var Ji,Xi;class Qf{constructor(e){y(this,"series"),y(this,"index"),y(this,Ji,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Xi=Symbol.iterator,Ji=Symbol.toStringTag,Xi)](){return this}}class Po{constructor(e=[]){if(y(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return Co(e,this.dataType),this}get dataType(){return this.series.length===0?x.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?q.ZERO:new q(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?J(0n,0n):J(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){"isSynnaxSeries"in e&&e.isSynnaxSeries?this.series.push(e):this.series.push(...e.series)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const n of this.series)if($r(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new xn(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return ls;let n=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)n+=o.length;else if($r(o.alignmentBounds,e)){n+=Number(e-o.alignment);break}}let s=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)s+=o.length;else if($r(o.alignmentBounds,t)){s+=Number(t-o.alignment);break}}return new xn(this,n,s)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return ls;let n=0;for(let s=0;s<this.series.length;s++){const a=this.series[s];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)n+=a.length;else if($r(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new xn(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return Tf(this.series.map(e=>e.bounds))}get byteLength(){return new vt(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const n=this.series.map(s=>s.alignmentBounds);return Of(n,e,t)}acquire(){this.series.forEach(e=>e.acquire())}release(){this.series.forEach(e=>e.release())}distance(e,t){const n=this.series.map(s=>s.alignmentBounds);return Sf(n,e,t)}parseJSON(e){if(!this.dataType.equals(x.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new ey(this.series)}}var Qi,ea;class ey{constructor(e){y(this,"series"),y(this,"seriesIndex"),y(this,"internal"),y(this,Qi,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(ea=Symbol.iterator,Qi=Symbol.toStringTag,ea)](){return this}}let xn=class{constructor(e,t,n){y(this,"series"),y(this,"index"),y(this,"end"),this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};const ta=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},ty=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},ry=(r,e,t=".")=>{const n=r.split(t);return n.map((s,a)=>{const o=e(s,a,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(s=>s!=null).join(t)},ny=(r,e,t={optional:!1,separator:"."})=>{t.separator??(t.separator=".");const{optional:n,getter:s=(c,h)=>c[h]}=t,a=e.split(t.separator);if(a.length===1&&a[0]==="")return r;let o=r;for(const c of a){const h=s(o,c);if(h==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${c} is null`)}o=h}return o};i.z.object({key:i.z.string(),value:i.z.string()});var sy=Object.defineProperty,iy=(r,e,t)=>e in r?sy(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dr=(r,e,t)=>iy(r,typeof e!="symbol"?e+"":e,t);let ay=class{constructor(e,t){Dr(this,"handlers"),Dr(this,"transform"),Dr(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,s]=this.transform(e);if(!s)return;t=n}this.handlers.forEach((n,s)=>s(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},oy=class{constructor(e){Dr(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const He=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:oy,Observer:ay},Symbol.toStringTag,{value:"Module"})),ce=i.z.record(i.z.union([i.z.number(),i.z.string(),i.z.symbol()]),i.z.unknown()),cy=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";cy();const ly=["macOS","Windows","Linux"],hy=["macos","windows","linux"],uy={macos:"macOS",windows:"Windows",linux:"Linux"};i.z.enum(ly).or(i.z.enum(hy).transform(r=>uy[r]));var dy=Object.defineProperty,fy=(r,e,t)=>e in r?dy(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Gt=(r,e,t)=>fy(r,typeof e!="symbol"?e+"":e,t);const yy=(...r)=>r.map(Do).join(""),Do=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),gy=r=>r.endsWith("/")?r.slice(0,-1):r,us=class ds{constructor({host:e,port:t,protocol:n="",pathPrefix:s=""}){Gt(this,"protocol"),Gt(this,"host"),Gt(this,"port"),Gt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Do(s)}replace(e){return new ds({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new ds({...this,pathPrefix:yy(this.path,e)})}toString(){return gy(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Gt(us,"UNKNOWN",new us({host:"unknown",port:0}));let py=us;const wy=-128,my=127,by=i.z.number().int().min(wy).max(my),vy=-32768,Ty=32767,Oy=i.z.number().int().min(vy).max(Ty),Sy=-2147483648,Ey=2147483647,zy=i.z.number().int().min(Sy).max(Ey),Ny=-9223372036854775808n,Iy=9223372036854775807n,$y=i.z.bigint().min(Ny).max(Iy),xy=255,ky=i.z.number().int().min(0).max(xy),Ay=65535,Uy=i.z.number().int().min(0).max(Ay),Cy=4294967295,Ry=i.z.number().int().min(0).max(Cy),By=18446744073709551615n,Py=i.z.bigint().min(0n).max(By),Mo=r=>ry(r,(e,t,n)=>{const s=t===n.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[t+1]));return a&&(e="element"),s||o?e:[e,"shape"]}),ra=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},Dy=(r,e,t)=>ny(ra(r,"shape"),Mo(e),{...t,getter:ra}),My=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:Dy,getFieldSchemaPath:Mo,int16:Oy,int32:zy,int64:$y,int8:by,uint16:Uy,uint32:Ry,uint64:Py,uint8:ky},Symbol.toStringTag,{value:"Module"}));var jy=Object.defineProperty,Ly=(r,e,t)=>e in r?jy(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Te=(r,e,t)=>Ly(r,typeof e!="symbol"?e+"":e,t);const _y=async r=>await new Promise(e=>setTimeout(e,O.fromMilliseconds(r).milliseconds));class Zy{constructor(e){Te(this,"config"),Te(this,"retries"),Te(this,"interval"),this.config={baseInterval:new O((e==null?void 0:e.baseInterval)??O.seconds(1)),maxRetries:(e==null?void 0:e.maxRetries)??5,scale:(e==null?void 0:e.scale)??1,sleepFn:(e==null?void 0:e.sleepFn)??_y},this.retries=0,this.interval=new O(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const qy=i.z.object({baseInterval:O.z.optional(),maxRetries:i.z.number().optional(),scale:i.z.number().optional()}),jo=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Zy,breakerConfig:qy},Symbol.toStringTag,{value:"Module"})),Fy=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Ds=i.z.string().regex(Fy),wt=i.z.number().min(0).max(255),Yy=i.z.number().min(0).max(1),Ms=i.z.tuple([wt,wt,wt,Yy]),Lo=i.z.tuple([wt,wt,wt]),_o=i.z.object({rgba255:Ms}),js=(r,e=1)=>{if(typeof r=="string")return Vy(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}if(typeof r=="object"&&"rgba255"in r)return r.rgba255;throw new Error(`Invalid color: ${JSON.stringify(r)}`)},Wy=i.z.union([Ds,Ms,Lo,_o]).transform(r=>js(r)),Vy=(r,e=1)=>{if(!Ds.safeParse(r).success)throw new Error(`Invalid hex color: ${r}`);return r=Gy(r),[kr(r,0),kr(r,2),kr(r,4),r.length===8?kr(r,6)/255:e]},kr=(r,e)=>parseInt(r.slice(e,e+2),16),Gy=r=>r.startsWith("#")?r.slice(1):r,Hy=i.z.union([Ds,Ms,i.z.string(),Lo,_o]);js("#000000");js("#ffffff");const Ky=i.z.object({key:i.z.string(),color:Hy,position:i.z.number(),switched:i.z.boolean().optional()});i.z.array(Ky);const Jy=i.z.object({key:i.z.string(),name:i.z.string(),color:Wy});i.z.object({key:i.z.string(),name:i.z.string(),swatches:i.z.array(Jy)});const Zo=i.z.number().int().min(0).max(255),qo=255,Fo=0,Xy={lower:Fo,upper:qo+1},Yo=i.z.object({name:i.z.string(),key:i.z.string()}),nr=r=>i.z.object({subject:Yo,resource:r,authority:Zo}),Qy=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),Wo=i.z.object({from:nr(i.z.any()),to:i.z.null()}),Vo=i.z.object({from:i.z.null(),to:nr(i.z.any())}),eg=i.z.union([Wo,Vo,i.z.object({from:nr(i.z.any()),to:nr(i.z.any())})]),Ke=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:qo,AUTHORITY_BOUNDS:Xy,ZERO_AUTHORITY:Fo,acquireZ:Vo,authorityZ:Zo,filterTransfersByChannelKey:Qy,releaseZ:Wo,stateZ:nr,subjectZ:Yo,transferZ:eg},Symbol.toStringTag,{value:"Module"})),tg=r=>Object.getOwnPropertySymbols(globalThis).includes(r),rg=(r,e)=>{const t=Symbol.for(r);if(!tg(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},ng=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Xr=r=>{var e;return e=class extends Error{constructor(t,n){super(t,n),Te(this,"discriminator",e.discriminator),Te(this,"type",e.TYPE),Te(this,"matches",e.matches),this.name=e.TYPE}static sub(t){return Xr(`${r}.${t}`)}},Te(e,"discriminator","FreighterError"),Te(e,"TYPE",r),Te(e,"matches",ng(r)),e},Go=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},ct="unknown",fs="nil";class sg{constructor(){Te(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:fs,data:""};if(Go(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:ct,data:e.message};if(typeof e=="string")return{type:ct,data:e};try{return{type:ct,data:JSON.stringify(e)}}catch{return{type:ct,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===fs)return null;if(e.type===ct)return new ys(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new ys(e.data)}}const Ls=rg("synnax-error-registry",()=>new sg),ig=({encode:r,decode:e})=>Ls().register({encode:r,decode:e}),ag=r=>Ls().encode(r),og=r=>r==null?null:Ls().decode(r);class ys extends Xr("unknown"){}const cg=i.z.object({type:i.z.string(),data:i.z.string()});class lg extends Xr("canceled"){}const Tt=Object.freeze(Object.defineProperty({__proto__:null,Canceled:lg,NONE:fs,UNKNOWN:ct,Unknown:ys,createTyped:Xr,decode:og,encode:ag,isTyped:Go,payloadZ:cg,register:ig},Symbol.toStringTag,{value:"Module"}));i.object({jsonrpc:i.string(),id:i.number().optional(),method:i.string().optional(),params:i.unknown().optional(),result:i.unknown().optional()});const gs=i.z.string().regex(/^\d+\.\d+\.\d+$/),ur=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=gs.parse(r),s=gs.parse(e),[a,o,c]=n.split(".").map(Number),[h,d,f]=s.split(".").map(Number);if(t.checkMajor){if(a<h)return En;if(a>h)return zn}if(t.checkMinor){if(o<d)return En;if(o>d)return zn}if(t.checkPatch){if(c<f)return En;if(c>f)return zn}return Kr},hg=(r,e,t={})=>sf(ur(r,e,t)),Ho=(r,e,t={})=>nf(ur(r,e,t)),ug=(r,e,t={})=>rf(ur(r,e,t)),dg=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},fg=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:s})=>{const a=Object.keys(e).sort(ur).pop();if(a==null)return d=>{if(d.version??(d.version=n),d.version!==s.version)return console.log(`${r} version ${d.version} is newer than latest version of ${s.version}.
26
26
  Returning default instead.
27
- `),s;try{return t!=null?t.parse(d):d}catch(f){return console.log(`${r} failed to parse default. Exiting with default`),console.error(f),s}};const o=Object.keys(e).length;let c=!1;const h=d=>{try{if(o===0||Vo(d.version,a))return console.log(c?`${r} ${d.version} now up to date`:`${r} version ${d.version} is up to date with target version ${s.version}`),d;const f=d.version,u=e[f],N=u(d);return c=!0,h(N)}catch(f){return console.log(`${r} failed to migrate from ${d.version} to ${a}`),console.error(f),s}};return d=>{try{if(d.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),d.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),s;return h(d)}catch(f){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(f),s}}},ta=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:ur,createMigration:hg,migrator:ug,semVerNewer:Vo,semVerOlder:lg,semVerZ:gs,versionsEqual:cg},Symbol.toStringTag,{value:"Module"})),dg=["standard","scientific","engineering"];i.z.enum(dg);const fg=(r,e="")=>{const t=r.length;return t===0?e:t===1?r[0]:t===2?`${r[0]} and ${r[1]}`:`${r.slice(0,-1).join(", ")}, and ${r[t-1]}`},yg=r=>{const e=r.split(" "),t=new Set,n=e.map(o=>o.charAt(0).toLowerCase()).join("");t.add(n.replace(/-/g,"_")),t.add(n.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;r.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const h=e.map((d,f)=>f!==c?d.charAt(0).toLowerCase():d).join("");t.add(h.replace(/-/g,"_")),t.add(h.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const a=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return t.add(a.join("").replace(/-/g,"_")),t.add(a.join("_").replace(/-/g,"_")),Array.from(t).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},gg=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:yg,naturalLanguageJoin:fg},Symbol.toStringTag,{value:"Module"}));class Ue extends Tt.createTyped("sy"){}class F extends Ue.sub("validation"){}class ra extends F.sub("field"){constructor(t,n){super(`${t}: ${n}`);l(this,"field");l(this,"message");this.field=t,this.message=n}}class sr extends Ue.sub("auth"){}class ps extends sr.sub("invalid-token"){}class ws extends sr.sub("expired-token"){}class mt extends Ue.sub("unexpected"){constructor(e){super(`
27
+ `),s;try{return t!=null?t.parse(d):d}catch(f){return console.log(`${r} failed to parse default. Exiting with default`),console.error(f),s}};const o=Object.keys(e).length;let c=!1;const h=d=>{try{if(o===0||Ho(d.version,a))return console.log(c?`${r} ${d.version} now up to date`:`${r} version ${d.version} is up to date with target version ${s.version}`),d;const f=d.version,u=e[f],N=u(d);return c=!0,h(N)}catch(f){return console.log(`${r} failed to migrate from ${d.version} to ${a}`),console.error(f),s}};return d=>{try{if(d.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),d.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),s;return h(d)}catch(f){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(f),s}}},na=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:ur,createMigration:dg,migrator:fg,semVerNewer:Ho,semVerOlder:ug,semVerZ:gs,versionsEqual:hg},Symbol.toStringTag,{value:"Module"})),yg=["standard","scientific","engineering"];i.z.enum(yg);const gg=(r,e="")=>{const t=r.length;return t===0?e:t===1?r[0]:t===2?`${r[0]} and ${r[1]}`:`${r.slice(0,-1).join(", ")}, and ${r[t-1]}`},pg=r=>{const e=r.split(" "),t=new Set,n=e.map(o=>o.charAt(0).toLowerCase()).join("");t.add(n.replace(/-/g,"_")),t.add(n.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const s=/\d+/g;r.match(s)&&e.forEach((o,c)=>{if(s.test(o)){const h=e.map((d,f)=>f!==c?d.charAt(0).toLowerCase():d).join("");t.add(h.replace(/-/g,"_")),t.add(h.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const a=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return t.add(a.join("").replace(/-/g,"_")),t.add(a.join("_").replace(/-/g,"_")),Array.from(t).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},wg=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:pg,naturalLanguageJoin:gg},Symbol.toStringTag,{value:"Module"}));class Ue extends Tt.createTyped("sy"){}class F extends Ue.sub("validation"){}class sa extends F.sub("field"){constructor(t,n){super(`${t}: ${n}`);l(this,"field");l(this,"message");this.field=t,this.message=n}}class sr extends Ue.sub("auth"){}class ps extends sr.sub("invalid-token"){}class ws extends sr.sub("expired-token"){}class mt extends Ue.sub("unexpected"){constructor(e){super(`
28
28
  Unexpected error encountered:
29
29
 
30
30
  ${e}
31
31
 
32
32
  Please report this to the Synnax team.
33
- `)}}class ke extends Ue.sub("query"){}class Je extends ke.sub("not_found"){}class Xe extends ke.sub("multiple_results"){}class ms extends Ue.sub("route"){constructor(t,n){super(t);l(this,"path");this.path=n}}class bs extends Ue.sub("control"){}class na extends bs.sub("unauthorized"){}class pg extends Ue.sub("contiguity"){}const wg=r=>{if(!r.type.startsWith(Ue.TYPE))return null;if(r.type.startsWith(F.TYPE)){if(r.type===ra.TYPE){const e=r.data.split(": ");return e.length<2?new F(r.data):new ra(e[0],e[1])}return new F(r.data)}return r.type.startsWith(sr.TYPE)?r.type.startsWith(ps.TYPE)?new ps(r.data):r.type.startsWith(ws.TYPE)?new ws(r.data):new sr(r.data):r.type.startsWith(mt.TYPE)?new mt(r.data):r.type.startsWith(ke.TYPE)?r.type.startsWith(Je.TYPE)?new Je(r.data):r.type.startsWith(Xe.TYPE)?new Xe(r.data):new ke(r.data):r.type.startsWith(bs.TYPE)?r.type.startsWith(na.TYPE)?new na(r.data):new bs(r.data):r.type.startsWith(ms.TYPE)?new ms(r.data,r.data):new mt(r.data)},mg=()=>{throw new Error("Not implemented")};Tt.register({encode:mg,decode:wg});const bg=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Fe?[t,new Fe({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]},zt=i.z.string().uuid(),Qr=i.z.string(),js=i.z.object({key:zt,name:Qr}),vg=r=>{const e=b(r);if(e.length===0)throw new Error("No groups specified");const t=zt.safeParse(e[0]).success;return{single:!Array.isArray(r),variant:t?"keys":"names",normalized:e,actual:r}},Ls="group",X=r=>i.z.union([i.z.union([i.z.null(),i.z.undefined()]).transform(()=>[]),r.array()]),Q=i.z.number(),dr=i.z.string(),fr=i.z.object({name:dr,key:Q,dataType:x.z,leaseholder:i.z.number(),index:Q,isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional(),expression:i.z.string().default(""),requires:X(Q)}),Go=fr.extend({key:Q.optional(),leaseholder:i.z.number().optional(),index:Q.optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional().default(!1),virtual:i.z.boolean().optional().default(!1),expression:i.z.string().optional().default(""),requires:X(Q).optional().default([])}),en="channel",_s="framer",sa=r=>{const e=b(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ia=(r,e)=>{const t=b(r);if(t.length===e.length)return;const n=sa(r);throw sa===null?new F("[Frame] - channel keys or names must be provided when constructing a frame."):new F(`[Frame] - ${n}s and series must be the same length.
34
- Got ${t.length} ${n}s and ${e.length} series.`)};class V{constructor(e=[],t=[]){l(this,"columns",[]);l(this,"series",[]);if(e instanceof V){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,a)=>this.push(a,...b(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e;s.series??(s.series=[]),s.keys??(s.keys=[]);const a=s.series.map(o=>Ho(o));ia(s.keys,a),s.keys.forEach((o,c)=>this.push(o,a[c]))}else Object.entries(e).forEach(([s,a])=>{const o=parseInt(s);if(!isNaN(o))return this.push(o,...b(a));this.push(s,...b(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=b(t),a=b(e);ia(a,s),s.forEach((o,c)=>this.push(a[c],o));return}throw new F(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
33
+ `)}}class ke extends Ue.sub("query"){}class Je extends ke.sub("not_found"){}class Xe extends ke.sub("multiple_results"){}class ms extends Ue.sub("route"){constructor(t,n){super(t);l(this,"path");this.path=n}}class bs extends Ue.sub("control"){}class ia extends bs.sub("unauthorized"){}class mg extends Ue.sub("contiguity"){}const bg=r=>{if(!r.type.startsWith(Ue.TYPE))return null;if(r.type.startsWith(F.TYPE)){if(r.type===sa.TYPE){const e=r.data.split(": ");return e.length<2?new F(r.data):new sa(e[0],e[1])}return new F(r.data)}return r.type.startsWith(sr.TYPE)?r.type.startsWith(ps.TYPE)?new ps(r.data):r.type.startsWith(ws.TYPE)?new ws(r.data):new sr(r.data):r.type.startsWith(mt.TYPE)?new mt(r.data):r.type.startsWith(ke.TYPE)?r.type.startsWith(Je.TYPE)?new Je(r.data):r.type.startsWith(Xe.TYPE)?new Xe(r.data):new ke(r.data):r.type.startsWith(bs.TYPE)?r.type.startsWith(ia.TYPE)?new ia(r.data):new bs(r.data):r.type.startsWith(ms.TYPE)?new ms(r.data,r.data):new mt(r.data)},vg=()=>{throw new Error("Not implemented")};Tt.register({encode:vg,decode:bg});const Tg=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Fe?[t,new Fe({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]},zt=i.z.string().uuid(),Qr=i.z.string(),_s=i.z.object({key:zt,name:Qr}),Og=r=>{const e=b(r);if(e.length===0)throw new Error("No groups specified");const t=zt.safeParse(e[0]).success;return{single:!Array.isArray(r),variant:t?"keys":"names",normalized:e,actual:r}},Zs="group",X=r=>i.z.union([i.z.union([i.z.null(),i.z.undefined()]).transform(()=>[]),r.array()]),Q=i.z.number(),dr=i.z.string(),fr=i.z.object({name:dr,key:Q,dataType:x.z,leaseholder:i.z.number(),index:Q,isIndex:i.z.boolean(),internal:i.z.boolean(),virtual:i.z.boolean(),alias:i.z.string().optional(),expression:i.z.string().default(""),requires:X(Q)}),Ko=fr.extend({key:Q.optional(),leaseholder:i.z.number().optional(),index:Q.optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional().default(!1),virtual:i.z.boolean().optional().default(!1),expression:i.z.string().optional().default(""),requires:X(Q).optional().default([])}),en="channel",qs="framer",aa=r=>{const e=b(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},oa=(r,e)=>{const t=b(r);if(t.length===e.length)return;const n=aa(r);throw aa===null?new F("[Frame] - channel keys or names must be provided when constructing a frame."):new F(`[Frame] - ${n}s and series must be the same length.
34
+ Got ${t.length} ${n}s and ${e.length} series.`)};class V{constructor(e=[],t=[]){l(this,"columns",[]);l(this,"series",[]);if(e instanceof V){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((s,a)=>this.push(a,...b(s)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const s=e;s.series??(s.series=[]),s.keys??(s.keys=[]);const a=s.series.map(o=>Jo(o));oa(s.keys,a),s.keys.forEach((o,c)=>this.push(o,a[c]))}else Object.entries(e).forEach(([s,a])=>{const o=parseInt(s);if(!isNaN(o))return this.push(o,...b(a));this.push(s,...b(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const s=b(t),a=b(e);oa(a,s),s.forEach((o,c)=>this.push(a[c],o));return}throw new F(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
35
35
  payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
36
- name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new mt("colType is not key");return this.columns??[]}get uniqueKeys(){return Di.unique(this.keys)}get names(){if(this.colType==="key")throw new mt("colType is not name");return this.columns??[]}get uniqueNames(){return Di.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Ko(e)),keys:[...this.keys]}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return q.ZERO;const n=z.min(...this.series.map(a=>a.timeRange.start)),s=z.max(...this.series.map(a=>a.timeRange.end));return new q(n,s)}const t=this.get(e);return t==null?q.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new Ro(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof V){if(this.colType!==null&&e.colType!==this.colType)throw new F("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new F("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new F("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new V([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new V;return this.forEach((n,s,a)=>t.push(...e(n,s,a))),t}forEach(e){this.columns.forEach((t,n)=>{const s=this.series[n];e(t,s,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(s=>{n[s]=this.get(s).at(e,t)}),n}filter(e){const t=new V;return this.columns.forEach((n,s)=>{const a=this.series[s];e(n,a,s)&&t.push(n,a)}),t}get byteLength(){return new vt(this.series.reduce((e,t)=>e.add(t.byteLength),vt.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const s=this.series[n].digest;t in e?e[t].push(s):e[t]=[s]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}toString(){let e=`Frame{
36
+ name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new mt("colType is not key");return this.columns??[]}get uniqueKeys(){return ji.unique(this.keys)}get names(){if(this.colType==="key")throw new mt("colType is not name");return this.columns??[]}get uniqueNames(){return ji.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Xo(e)),keys:[...this.keys]}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return q.ZERO;const n=z.min(...this.series.map(a=>a.timeRange.start)),s=z.max(...this.series.map(a=>a.timeRange.end));return new q(n,s)}const t=this.get(e);return t==null?q.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new Po(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof V){if(this.colType!==null&&e.colType!==this.colType)throw new F("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new F("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new F("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new V([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new V;return this.forEach((n,s,a)=>t.push(...e(n,s,a))),t}forEach(e){this.columns.forEach((t,n)=>{const s=this.series[n];e(t,s,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(s=>{n[s]=this.get(s).at(e,t)}),n}filter(e){const t=new V;return this.columns.forEach((n,s)=>{const a=this.series[s];e(n,a,s)&&t.push(n,a)}),t}get byteLength(){return new vt(this.series.reduce((e,t)=>e.add(t.byteLength),vt.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const s=this.series[n].digest;t in e?e[t].push(s):e[t]=[s]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}toString(){let e=`Frame{
37
37
  `;return this.uniqueColumns.forEach(t=>{e+=` ${t}: ${this.get(t).series.map(n=>n.toString()).join(",")}
38
- `}),e+="}",e}}const tn=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().optional().default([])]),series:i.z.union([i.z.null().transform(()=>[]),_e.crudeZ.array().optional().default([])])}),Ho=r=>{const{dataType:e,data:t,timeRange:n,alignment:s}=r;return new _e({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:s})},Ko=r=>({timeRange:r.timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment}),Ye=Py.uint32,Zs=i.z.object({key:Ye,variant:i.z.string(),message:i.z.string(),lastReceived:z.z.optional()}),rn=i.z.object({key:Ye,name:i.z.string(),state:Zs.optional()}),Jo=rn.partial({key:!0}),nn="rack",qs=r=>r?Qe.JSON_CODEC.decodeString(r,ce):{},yr=i.z.string(),Fs=i.z.object({key:yr,variant:i.z.string(),details:ce.or(i.z.string().transform(qs))}),gr=i.z.object({key:yr,rack:Ye,name:i.z.string(),make:i.z.string(),model:i.z.string(),location:i.z.string(),configured:i.z.boolean().optional(),properties:ce.or(i.z.string().transform(qs)),state:Fs.optional()}),Xo=gr.extend({properties:i.z.unknown().transform(r=>Qe.JSON_CODEC.encodeString(r))}),sn="device",Se=r=>r?JSON.parse(r):{},We=i.z.union([i.z.string(),i.z.bigint().transform(r=>r.toString()),i.z.number().transform(r=>r.toString())]),Qo=i.z.enum(["info","success","error","warning"]),ir=i.z.object({task:We,variant:Qo,key:i.z.string().optional(),details:ce.or(i.z.string().transform(Se)).or(i.z.array(i.z.unknown())).or(i.z.null())}),pr=i.z.object({key:We,name:i.z.string(),type:i.z.string(),internal:i.z.boolean().optional(),config:ce.or(i.z.string().transform(qs)),state:ir.optional().nullable(),snapshot:i.z.boolean().optional()}),ec=pr.omit({key:!0}).extend({key:We.transform(r=>r.toString()).optional(),config:i.z.unknown().transform(r=>Qe.JSON_CODEC.encodeString(r))}),Ys=i.z.object({task:We,type:i.z.string(),key:i.z.string(),args:ce.or(i.z.string().transform(Se)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),an="task",Tg=r=>Number(BigInt(r)>>32n),et=i.z.string().uuid(),wr=i.z.object({key:et,name:i.z.string().min(1),color:i.z.string()}),Ws="label",ae=i.z.string().uuid(),Vs=i.z.string().min(1),mr=i.z.object({key:ae,name:Vs,timeRange:q.z,color:i.z.string().optional()}),tc=mr.partial({key:!0}),rc=r=>{const e=b(r),t=e.length===0;let n=!1;return t||(n=ae.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},Gs="range",Hs="range-alias",tt=i.z.string().uuid(),br=i.z.object({key:tt,username:i.z.string().min(1),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!0)}),nc=br.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:i.z.string().min(1)}),Ks="user",Nt=i.z.string().uuid(),on=i.z.object({key:Nt,name:i.z.string(),data:ce.or(i.z.string().transform(Se))}),sc=on.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Js="lineplot",It=i.z.string().uuid(),cn=i.z.object({key:It,name:i.z.string(),data:ce.or(i.z.string().transform(Se))}),ic=cn.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Xs="log",Ee=i.z.string().uuid(),ln=i.z.object({key:Ee,name:i.z.string(),layout:ce.or(i.z.string().transform(Se))}),hn="workspace",ac=ln.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),oc=ln.omit({layout:!0}).extend({layout:i.z.string().transform(Se)}),rt=i.z.string().uuid(),un=i.z.object({key:rt,name:i.z.string(),data:ce.or(i.z.string().transform(Se)),snapshot:i.z.boolean()}),cc=un.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Qs=un.extend({data:i.z.string().transform(Se)}),ei="schematic",$t=i.z.string().uuid(),ti=i.z.object({key:$t,name:i.z.string(),data:ce.or(i.z.string().transform(Se))}),lc=ti.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),ri=ti.extend({data:i.z.string().transform(Se)}),ni="table",si="builtin",hc="cluster",uc="node",vr=i.z.enum([Ws,Xs,zs,si,hc,en,uc,Ls,Gs,_s,Hs,Ks,hn,ei,Js,nn,sn,an,Es,ni]),ie=i.z.object({type:vr,key:i.z.string()}),dc=i.z.string().transform(r=>{const[e,t]=r.split(":");return{type:vr.parse(e),key:t??""}}),ht=i.z.union([dc,ie]),dt=class dt{constructor(e){l(this,"type");l(this,"key");if(e instanceof dt){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};l(dt,"z",i.z.union([i.z.instanceof(dt),ht.transform(e=>new dt(e))]));let E=dt;const Og=new E({type:si,key:"root"}),fc=i.z.object({type:i.z.number()}),yc=i.z.object({type:vr,fields:i.z.record(i.z.string(),fc)}),gc=i.z.object({id:E.z,name:i.z.string(),schema:yc.optional().nullable(),data:ce.optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),Sg="to",Eg="from",zg=i.z.object({from:E.z,type:i.z.string(),to:E.z}),vs=r=>{const[e,t,n]=r.split("->");return{from:new E(e),type:t,to:new E(n)}};class ii{constructor(e,t){l(this,"key");l(this,"name");this.key=t,this.name=e}get ontologyID(){return pc(this.key)}}const pc=r=>new E({type:Ls,key:r}),Ng=i.z.object({group:js}),Ig=i.z.object({parent:ie,key:zt.optional(),name:Qr}),$g=i.z.object({key:zt,name:Qr}),xg=i.z.object({keys:i.z.array(zt)});var he;let kg=(he=class{constructor(e){l(this,"client");this.client=e}async create(e,t,n){return(await m(this.client,he.CREATE_ENDPOINT,{parent:e,name:t,key:n},Ig,Ng)).group}async rename(e,t){await m(this.client,he.RENAME_ENDPOINT,{key:e,name:t},$g,i.z.object({}))}async delete(e){await m(this.client,he.DELETE_ENDPOINT,{keys:e},xg,i.z.object({}))}},l(he,"CREATE_ENDPOINT","/ontology/create-group"),l(he,"RENAME_ENDPOINT","/ontology/rename-group"),l(he,"DELETE_ENDPOINT","/ontology/delete-group"),he),wc=class{constructor(e){l(this,"creator");this.creator=new kg(e)}async create(e,t,n){return this.sugar(await this.creator.create(e,t,n))}async rename(e,t){return await this.creator.rename(e,t)}async delete(...e){return await this.creator.delete(e)}sugar(e){return new ii(e.name,e.key)}};const Ag=Object.freeze(Object.defineProperty({__proto__:null,Client:wc,Group:ii,ONTOLOGY_TYPE:Ls,analyzeParams:vg,groupZ:js,keyZ:zt,nameZ:Qr,ontologyID:pc},Symbol.toStringTag,{value:"Module"})),Ug="/ontology/add-children",Cg="/ontology/remove-children",Rg="/ontology/move-children",aa=i.z.object({id:ie,children:ie.array()}),Bg=i.z.object({from:ie,to:ie,children:ie.array()}),kn=i.z.object({});let Pg=class{constructor(e){l(this,"client");this.client=e}async addChildren(e,...t){await m(this.client,Ug,{id:new E(e).payload,children:t.map(n=>new E(n).payload)},aa,kn)}async removeChildren(e,...t){await m(this.client,Cg,{id:new E(e).payload,children:t.map(n=>new E(n).payload)},aa,kn)}async moveChildren(e,t,...n){const s={from:new E(e).payload,to:new E(t).payload,children:n.map(a=>new E(a).payload)};await m(this.client,Rg,s,Bg,kn)}};const Dg="/ontology/retrieve",Mg=i.z.object({ids:ie.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),includeSchema:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),term:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),types:vr.array().optional()}),jg=i.z.object({resources:gc.array()}),Mr=r=>b(r).map(e=>new E(e).payload);let mc=class{constructor(e,t){l(this,"type","ontology");l(this,"groups");l(this,"client");l(this,"writer");l(this,"framer");this.client=e,this.writer=new Pg(e),this.groups=new wc(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:Mr(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new ke(`No resource found with ID ${gg.naturalLanguageJoin(b(e).map(s=>new E(s).toString()))}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:Mr(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:Mr(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await Tr.open(this.framer,this)}async openDependentTracker(e){return await dn.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await m(this.client,Dg,e,Mg,jg);return t}};const oa="sy_ontology_resource_set",ca="sy_ontology_resource_delete",la="sy_ontology_relationship_set",ha="sy_ontology_relationship_delete";class Tr{constructor(e,t){l(this,"relationships");l(this,"resources");l(this,"resourceObs");l(this,"relationshipObs");l(this,"streamer");l(this,"client");l(this,"closePromise");this.relationshipObs=new He.Observer,this.relationships=this.relationshipObs,this.resourceObs=new He.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(la);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:vs(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(ha);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:vs(n)}))}async parseResourceSets(e){const t=e.get(oa);if(t.length===0)return[];const n=Array.from(t.as("string")).map(s=>new E(s));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(s){if(s instanceof ke)return[];throw s}}parseResourceDeletes(e){const t=e.get(ca);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new E(n)}))}static async open(e,t){const n=await e.openStreamer([oa,ca,la,ha]);return new Tr(n,t)}}const ua=r=>r==="from"?"to":"from";class dn extends He.Observer{constructor({target:t,dependents:n,relationshipType:s="parent",relationshipDirection:a="from",resourceType:o},c,h){super();l(this,"internal");l(this,"target");l(this,"relDir");l(this,"resourceType");l(this,"dependents");l(this,"client");l(this,"relType");l(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const s=t.find(a=>a.key.toString()==n.id.toString());return s==null||s.variant==="delete"?n:s.value}),this.notify(this.dependents)});l(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[ua(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const s=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[ua(this.relDir)].type===this.resourceType));if(s.length===0)return this.notify(this.dependents);this.client.retrieve(s.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)}).catch(console.error)});this.resourceType=o,this.internal=c,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(d=>d.id.type===this.resourceType)),this.client=h,this.relType=s,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,s){const a=await Tr.open(n,s);return new dn(t,a,s)}async close(){await this.internal.close()}}const Lg=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:si,CLUSTER_TYPE:hc,ChangeTracker:Tr,Client:mc,DependentTracker:dn,FROM_RELATIONSHIP_DIRECTION:Eg,ID:E,NODE_TYPE:uc,ROOT_ID:Og,TO_RELATIONSHIP_DIRECTION:Sg,crudeIDZ:ht,idZ:ie,parseIDs:Mr,parseRelationship:vs,relationshipSchemaZ:zg,resourceTypeZ:vr,resourceZ:gc,schemaFieldZ:fc,schemaZ:yc,stringIDZ:dc},Symbol.toStringTag,{value:"Module"})),Or=i.z.string().uuid(),fn=i.z.object({key:Or,subjects:X(ie),objects:X(ie),actions:X(_r)}),bc=i.z.object({key:Or.optional(),subjects:ht.array().or(ht),objects:ht.array().or(ht),actions:_r.array().or(_r)}),_g=i.z.object({keys:Or.array().optional(),subjects:ie.array().optional()}),Zg=i.z.object({policies:X(fn)}),qg="/access/policy/retrieve";let Fg=class{constructor(e){l(this,"client");this.client=e}async retrieve(e){return(await m(this.client,qg,e,_g,Zg)).policies}};const Yg=i.z.object({policies:fn.partial({key:!0}).array()}),Wg=i.z.object({policies:fn.array()}),Vg=i.z.object({keys:Or.array()}),Gg=i.z.object({}),Hg="/access/policy/create",Kg="/access/policy/delete";let Jg=class{constructor(e){l(this,"client");this.client=e}async create(e){const n=bc.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await m(this.client,Hg,{policies:n},Yg,Wg)).policies}async delete(e){await m(this.client,Kg,{keys:b(e)},Vg,Gg)}},vc=class{constructor(e){l(this,"retriever");l(this,"writer");this.retriever=new Fg(e),this.writer=new Jg(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve({keys:b(e)});return t?n:n[0]}async retrieveFor(e){const t=b(e).map(n=>new E(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const Xg=r=>new E({type:Es,key:r}),Qg=new E({type:zs,key:""}),ep=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Qg,ALLOW_ALL_ONTOLOGY_TYPE:zs,Client:vc,ONTOLOGY_TYPE:Es,keyZ:Or,newZ:bc,ontologyID:Xg,policyZ:fn},Symbol.toStringTag,{value:"Module"}));let Tc=class{constructor(e){l(this,"policy");this.policy=new vc(e)}};const tp=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:ro,CREATE_ACTION:no,Client:Tc,DELETE_ACTION:so,RETRIEVE_ACTION:io,UPDATE_ACTION:ao,actionZ:_r},Symbol.toStringTag,{value:"Module"})),rp=new Error("request for lock canceled");var np=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(n.next(f))}catch(u){o(u)}}function h(f){try{d(n.throw(f))}catch(u){o(u)}}function d(f){f.done?a(f.value):s(f.value).then(c,h)}d((n=n.apply(r,e||[])).next())})};class sp{constructor(e,t=rp){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,s)=>{const a={resolve:n,reject:s,weight:e,priority:t},o=Oc(this._queue,c=>t<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return np(this,arguments,void 0,function*(t,n=1,s=0){const[a,o]=yield this.acquire(n,s);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),ip(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const s=n.findIndex(a=>a.priority<=e);(s===-1?n:n.splice(0,s)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function ip(r,e){const t=Oc(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Oc(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var ap=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(n.next(f))}catch(u){o(u)}}function h(f){try{d(n.throw(f))}catch(u){o(u)}}function d(f){f.done?a(f.value):s(f.value).then(c,h)}d((n=n.apply(r,e||[])).next())})};class op{constructor(e){this._semaphore=new sp(1,e)}acquire(){return ap(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const ai=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let s=b(r);const a=s[0],o=typeof a;let c;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,s=s.map(h=>parseInt(h))):c=e[o],{single:n,variant:c,normalized:s,actual:r}},yn=(r,e,t,n)=>{if(n){if(t.length===0)throw new Je(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new Xe(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},cp=i.z.object({leaseholder:i.z.number().optional(),keys:Q.array().optional(),names:i.z.string().array().optional(),search:i.z.string().optional(),rangeKey:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),dataTypes:x.z.array().optional(),notDataTypes:x.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional()}),lp=i.z.object({channels:X(fr)}),Oe=r=>(Array.isArray(r)&&r.length>0&&typeof r[0]=="object"?r=r.map(e=>e.key):typeof r=="object"&&"key"in r&&(r=[r.key]),ai(r,{number:"keys",string:"names"})),Yr=class Yr{constructor(e){l(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=Oe(e),{variant:s}=n;let{normalized:a}=n;return s==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[s]:a,...t})}async page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(Yr.ENDPOINT,e,cp,lp);if(n!=null)throw n;return t.channels}};l(Yr,"ENDPOINT","/channel/retrieve");let ar=Yr;class oi{constructor(e){l(this,"cache");l(this,"namesToKeys");l(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=Oe(e),s=[],a=[];if(n.forEach(c=>{const h=this.get(c);h!=null?s.push(...h):a.push(c)}),a.length===0)return s;const o=await this.wrapped.retrieve(a,t);return this.set(o),s.concat(o)}delete(e){const{variant:t,normalized:n}=Oe(e);t==="names"?n.forEach(s=>{const a=this.namesToKeys.get(s);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):n.forEach(s=>{const a=this.cache.get(s);a!=null&&(this.cache.delete(s),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,s)=>{const a=t[s],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(n),c.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(n,o);const h=this.namesToKeys.get(a);h==null?this.namesToKeys.set(a,new Set([n])):h.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(s=>{const a=this.cache.get(s);a!=null&&n.push(a)}),n.length!==0)return n}}class Sc{constructor(e,t){l(this,"mu",new op);l(this,"requests",new Map);l(this,"wrapped");l(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Qf(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=Oe(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(s=>e.add(s)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,s)=>n.resolve(t.filter(a=>s.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Ec=async(r,e)=>{const{normalized:t}=Oe(e),n=await r.retrieve(t),s=[];if(t.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&s.push(a)}),s.length>0)throw new ke(`Could not find channels: ${JSON.stringify(s)}`);return n};class ci{constructor({dataType:e,name:t,leaseholder:n=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:h=!1,frameClient:d,alias:f,expression:u="",requires:N=[]}){l(this,"_frameClient");l(this,"key");l(this,"name");l(this,"dataType");l(this,"leaseholder");l(this,"index");l(this,"isIndex");l(this,"internal");l(this,"alias");l(this,"virtual");l(this,"expression");l(this,"requires");this.key=s,this.name=t,this.dataType=new x(e),this.leaseholder=n,this.index=o,this.isIndex=a,this.internal=c,this.alias=f,this.virtual=h,this.expression=u,this.requires=N??[],this._frameClient=d??null}get framer(){if(this._frameClient==null)throw new F("cannot read from a channel that has not been created");return this._frameClient}get payload(){return fr.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,requires:this.requires})}get isCalculated(){return or(this.payload)}get ontologyID(){return Ic(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const hp="/channel/retrieve-group",up=i.z.object({}),dp=i.z.object({group:js});let zc=class{constructor(e,t,n,s){l(this,"type",en);l(this,"frameClient");l(this,"client");l(this,"retriever");l(this,"writer");this.frameClient=e,this.retriever=t,this.client=n,this.writer=s}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,s=!Array.isArray(e);let a=b(e),o=[];if(n){const c=await this.retriever.retrieve(a.map(d=>d.name)),h=new Set(c.map(d=>d.name));a=a.filter(d=>!h.has(d.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),s?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),s=this.sugar(await this.retriever.retrieve(e,t));return yn("channel",e,s,n),n?s[0]:s}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=Oe(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new oi(new Sc(new ar(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new ci({...n,frameClient:t}))}async retrieveGroup(){const e=await m(this.client,hp,{},up,dp);return new ii(e.group.name,e.group.key)}};const or=({virtual:r,expression:e})=>r&&e!=="",Nc=async(r,e)=>{if(!or(e))return e.index;for(const t of e.requires){const n=await r(t);if(n==null)return null;if(!n.virtual)return n.index}for(const t of e.requires){const n=await r(t);if(n==null)return null;if(or(n)){const s=await Nc(r,n);if(s!=null)return s}}return null},Ic=r=>new E({type:en,key:r.toString()}),fp=i.z.object({channels:Go.array()}),yp=i.z.object({channels:fr.array()}),gp=i.z.object({keys:Q.array().optional(),names:dr.array().optional()}),pp=i.z.object({}),wp=i.z.object({keys:Q.array(),names:dr.array()}),mp=i.z.object({}),bp="/channel/create",vp="/channel/delete",Tp="/channel/rename";let $c=class{constructor(e,t){l(this,"client");l(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await m(this.client,bp,{channels:e},fp,yp);return this.cache.set(t),t}async delete(e){await m(this.client,vp,e,gp,pp),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await m(this.client,Tp,{keys:e,names:t},wp,mp),this.cache.rename(e,t)}};const Op=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:oi,Channel:ci,Client:zc,ClusterRetriever:ar,DebouncedBatchRetriever:Sc,ONTOLOGY_TYPE:en,Writer:$c,analyzeParams:Oe,channelZ:fr,isCalculated:or,keyZ:Q,nameZ:dr,newZ:Go,ontologyID:Ic,resolveCalculatedIndex:Nc,retrieveRequired:Ec},Symbol.toStringTag,{value:"Module"})),Sp=i.z.object({keys:tt.array().optional(),usernames:i.z.string().array().optional()}),Ep=i.z.object({users:X(br)}),zp="/user/retrieve";let Np=class{constructor(e){l(this,"client");this.client=e}async retrieve(e){return(await m(this.client,zp,e,Sp,Ep)).users}};const Ip=i.z.object({users:nc.array()}),$p=i.z.object({users:br.array()}),xp=i.z.object({key:tt,username:i.z.string().min(1)}),kp=i.z.object({}),Ap=i.z.object({key:tt,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),Up=i.z.object({}),Cp=i.z.object({keys:tt.array()}),Rp=i.z.object({}),Bp="/user/create",Pp="/user/change-username",Dp="/user/rename",Mp="/user/delete";let jp=class{constructor(e){l(this,"client");this.client=e}async create(e){return(await m(this.client,Bp,{users:b(e)},Ip,$p)).users}async changeUsername(e,t){await m(this.client,Pp,{key:e,username:t},xp,kp)}async rename(e,t,n){await m(this.client,Dp,{key:e,firstName:t,lastName:n},Ap,Up)}async delete(e){await m(this.client,Mp,{keys:b(e)},Cp,Rp)}},xc=class{constructor(e){l(this,"reader");l(this,"writer");this.writer=new jp(e),this.reader=new Np(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.reader.retrieve({keys:b(e)});if(t)return n;if(n.length===0)throw new Je(`No user with key ${e} found`);if(n.length>1)throw new Xe(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:b(e)});if(t)return n;if(n.length===0)throw new Je(`No user with username ${e} found`);if(n.length>1)throw new Xe(`Multiple users found with username ${e}`);return n[0]}async rename(e,t,n){await this.writer.rename(e,t,n)}async delete(e){await this.writer.delete(e)}};const Lp=r=>new E({type:Ks,key:r}),_p=Object.freeze(Object.defineProperty({__proto__:null,Client:xc,ONTOLOGY_TYPE:Ks,keyZ:tt,newZ:nc,ontologyID:Lp,userZ:br},Symbol.toStringTag,{value:"Module"})),Zp=i.z.object({username:i.z.string(),password:i.z.string()}),qp=i.z.object({token:i.z.string(),user:br}),da="/auth/login",Fp=3,Yp="/auth/change-password",Wp=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),Vp=i.z.object({}),Gp=[ps,ws];let Hp=class{constructor(e,t){l(this,"token");l(this,"client");l(this,"credentials");l(this,"authenticating");l(this,"authenticated");l(this,"user");l(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await m(this.client,Yp,{username:this.credentials.username,password:this.credentials.password,newPassword:e},Wp,Vp),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(da)){this.authenticating??(this.authenticating=new Promise((c,h)=>{this.client.send(da,this.credentials,Zp,qp).then(([d,f])=>{if(f!=null)return c(f);this.token=d==null?void 0:d.token,this.user=d==null?void 0:d.user,this.authenticated=!0,c(null)}).catch(h)}));const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[s,a]=await n(t);return Gp.some(o=>o.matches(a))&&this.retryCount<Fp?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[s,a])};return e}};const kc=i.z.enum(["disconnected","connecting","connected","failed"]),Ac=i.z.object({status:kc,error:i.z.instanceof(Error).optional(),message:i.z.string().optional(),clusterKey:i.z.string(),clientVersion:i.z.string(),clientServerCompatible:i.z.boolean(),nodeVersion:i.z.string().optional()}),Kp=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),fa={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.42.1"},ya=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
38
+ `}),e+="}",e}}const tn=i.z.object({keys:i.z.union([i.z.null().transform(()=>[]),i.z.number().array().optional().default([])]),series:i.z.union([i.z.null().transform(()=>[]),_e.crudeZ.array().optional().default([])])}),Jo=r=>{const{dataType:e,data:t,timeRange:n,alignment:s}=r;return new _e({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:s})},Xo=r=>({timeRange:r.timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment}),Ye=My.uint32,Fs=i.z.object({key:Ye,variant:i.z.string(),message:i.z.string(),lastReceived:z.z.optional()}),rn=i.z.object({key:Ye,name:i.z.string(),state:Fs.optional()}),Qo=rn.partial({key:!0}),nn="rack",Ys=r=>r?Qe.JSON_CODEC.decodeString(r,ce):{},yr=i.z.string(),Ws=i.z.object({key:yr,variant:i.z.string(),details:ce.or(i.z.string().transform(Ys))}),gr=i.z.object({key:yr,rack:Ye,name:i.z.string(),make:i.z.string(),model:i.z.string(),location:i.z.string(),configured:i.z.boolean().optional(),properties:ce.or(i.z.string().transform(Ys)),state:Ws.optional()}),ec=gr.extend({properties:i.z.unknown().transform(r=>Qe.JSON_CODEC.encodeString(r))}),sn="device",Se=r=>r?JSON.parse(r):{},We=i.z.union([i.z.string(),i.z.bigint().transform(r=>r.toString()),i.z.number().transform(r=>r.toString())]),tc=i.z.enum(["info","success","error","warning"]),ir=i.z.object({task:We,variant:tc,key:i.z.string().optional(),details:ce.or(i.z.string().transform(Se)).or(i.z.array(i.z.unknown())).or(i.z.null())}),pr=i.z.object({key:We,name:i.z.string(),type:i.z.string(),internal:i.z.boolean().optional(),config:ce.or(i.z.string().transform(Ys)),state:ir.optional().nullable(),snapshot:i.z.boolean().optional()}),rc=pr.omit({key:!0}).extend({key:We.transform(r=>r.toString()).optional(),config:i.z.unknown().transform(r=>Qe.JSON_CODEC.encodeString(r))}),Vs=i.z.object({task:We,type:i.z.string(),key:i.z.string(),args:ce.or(i.z.string().transform(Se)).or(i.z.array(i.z.unknown())).or(i.z.null()).optional()}),an="task",Sg=r=>Number(BigInt(r)>>32n),et=i.z.string().uuid(),wr=i.z.object({key:et,name:i.z.string().min(1),color:i.z.string()}),Gs="label",ae=i.z.string().uuid(),Hs=i.z.string().min(1),mr=i.z.object({key:ae,name:Hs,timeRange:q.z,color:i.z.string().optional()}),nc=mr.partial({key:!0}),sc=r=>{const e=b(r),t=e.length===0;let n=!1;return t||(n=ae.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},Ks="range",Js="range-alias",tt=i.z.string().uuid(),br=i.z.object({key:tt,username:i.z.string().min(1),firstName:i.z.string().default(""),lastName:i.z.string().default(""),rootUser:i.z.boolean().default(!0)}),ic=br.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:i.z.string().min(1)}),Xs="user",Nt=i.z.string().uuid(),on=i.z.object({key:Nt,name:i.z.string(),data:ce.or(i.z.string().transform(Se))}),ac=on.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Qs="lineplot",It=i.z.string().uuid(),cn=i.z.object({key:It,name:i.z.string(),data:ce.or(i.z.string().transform(Se))}),oc=cn.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),ei="log",Ee=i.z.string().uuid(),ln=i.z.object({key:Ee,name:i.z.string(),layout:ce.or(i.z.string().transform(Se))}),hn="workspace",cc=ln.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),lc=ln.omit({layout:!0}).extend({layout:i.z.string().transform(Se)}),rt=i.z.string().uuid(),un=i.z.object({key:rt,name:i.z.string(),data:ce.or(i.z.string().transform(Se)),snapshot:i.z.boolean()}),hc=un.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),ti=un.extend({data:i.z.string().transform(Se)}),ri="schematic",$t=i.z.string().uuid(),ni=i.z.object({key:$t,name:i.z.string(),data:ce.or(i.z.string().transform(Se))}),uc=ni.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),si=ni.extend({data:i.z.string().transform(Se)}),ii="table",ai="builtin",dc="cluster",fc="node",vr=i.z.enum([Gs,ei,zs,ai,dc,en,fc,Zs,Ks,qs,Js,Xs,hn,ri,Qs,nn,sn,an,Es,ii]),ie=i.z.object({type:vr,key:i.z.string()}),yc=i.z.string().transform(r=>{const[e,t]=r.split(":");return{type:vr.parse(e),key:t??""}}),ht=i.z.union([yc,ie]),dt=class dt{constructor(e){l(this,"type");l(this,"key");if(e instanceof dt){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};l(dt,"z",i.z.union([i.z.instanceof(dt),ht.transform(e=>new dt(e))]));let E=dt;const Eg=new E({type:ai,key:"root"}),gc=i.z.object({type:i.z.number()}),pc=i.z.object({type:vr,fields:i.z.record(i.z.string(),gc)}),wc=i.z.object({id:E.z,name:i.z.string(),schema:pc.optional().nullable(),data:ce.optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),zg="to",Ng="from",Ig=i.z.object({from:E.z,type:i.z.string(),to:E.z}),vs=r=>{const[e,t,n]=r.split("->");return{from:new E(e),type:t,to:new E(n)}};class oi{constructor(e,t){l(this,"key");l(this,"name");this.key=t,this.name=e}get ontologyID(){return mc(this.key)}}const mc=r=>new E({type:Zs,key:r}),$g=i.z.object({group:_s}),xg=i.z.object({parent:ie,key:zt.optional(),name:Qr}),kg=i.z.object({key:zt,name:Qr}),Ag=i.z.object({keys:i.z.array(zt)});var he;let Ug=(he=class{constructor(e){l(this,"client");this.client=e}async create(e,t,n){return(await m(this.client,he.CREATE_ENDPOINT,{parent:e,name:t,key:n},xg,$g)).group}async rename(e,t){await m(this.client,he.RENAME_ENDPOINT,{key:e,name:t},kg,i.z.object({}))}async delete(e){await m(this.client,he.DELETE_ENDPOINT,{keys:e},Ag,i.z.object({}))}},l(he,"CREATE_ENDPOINT","/ontology/create-group"),l(he,"RENAME_ENDPOINT","/ontology/rename-group"),l(he,"DELETE_ENDPOINT","/ontology/delete-group"),he),bc=class{constructor(e){l(this,"creator");this.creator=new Ug(e)}async create(e,t,n){return this.sugar(await this.creator.create(e,t,n))}async rename(e,t){return await this.creator.rename(e,t)}async delete(...e){return await this.creator.delete(e)}sugar(e){return new oi(e.name,e.key)}};const Cg=Object.freeze(Object.defineProperty({__proto__:null,Client:bc,Group:oi,ONTOLOGY_TYPE:Zs,analyzeParams:Og,groupZ:_s,keyZ:zt,nameZ:Qr,ontologyID:mc},Symbol.toStringTag,{value:"Module"})),Rg="/ontology/add-children",Bg="/ontology/remove-children",Pg="/ontology/move-children",ca=i.z.object({id:ie,children:ie.array()}),Dg=i.z.object({from:ie,to:ie,children:ie.array()}),kn=i.z.object({});let Mg=class{constructor(e){l(this,"client");this.client=e}async addChildren(e,...t){await m(this.client,Rg,{id:new E(e).payload,children:t.map(n=>new E(n).payload)},ca,kn)}async removeChildren(e,...t){await m(this.client,Bg,{id:new E(e).payload,children:t.map(n=>new E(n).payload)},ca,kn)}async moveChildren(e,t,...n){const s={from:new E(e).payload,to:new E(t).payload,children:n.map(a=>new E(a).payload)};await m(this.client,Pg,s,Dg,kn)}};const jg="/ontology/retrieve",Lg=i.z.object({ids:ie.array().optional(),children:i.z.boolean().optional(),parents:i.z.boolean().optional(),includeSchema:i.z.boolean().optional(),excludeFieldData:i.z.boolean().optional(),term:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),types:vr.array().optional()}),_g=i.z.object({resources:wc.array()}),Mr=r=>b(r).map(e=>new E(e).payload);let vc=class{constructor(e,t){l(this,"type","ontology");l(this,"groups");l(this,"client");l(this,"writer");l(this,"framer");this.client=e,this.writer=new Mg(e),this.groups=new bc(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:Mr(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new ke(`No resource found with ID ${wg.naturalLanguageJoin(b(e).map(s=>new E(s).toString()))}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:Mr(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:Mr(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await Tr.open(this.framer,this)}async openDependentTracker(e){return await dn.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await m(this.client,jg,e,Lg,_g);return t}};const la="sy_ontology_resource_set",ha="sy_ontology_resource_delete",ua="sy_ontology_relationship_set",da="sy_ontology_relationship_delete";class Tr{constructor(e,t){l(this,"relationships");l(this,"resources");l(this,"resourceObs");l(this,"relationshipObs");l(this,"streamer");l(this,"client");l(this,"closePromise");this.relationshipObs=new He.Observer,this.relationships=this.relationshipObs,this.resourceObs=new He.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(ua);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:vs(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(da);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:vs(n)}))}async parseResourceSets(e){const t=e.get(la);if(t.length===0)return[];const n=Array.from(t.as("string")).map(s=>new E(s));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(s){if(s instanceof ke)return[];throw s}}parseResourceDeletes(e){const t=e.get(ha);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new E(n)}))}static async open(e,t){const n=await e.openStreamer([la,ha,ua,da]);return new Tr(n,t)}}const fa=r=>r==="from"?"to":"from";class dn extends He.Observer{constructor({target:t,dependents:n,relationshipType:s="parent",relationshipDirection:a="from",resourceType:o},c,h){super();l(this,"internal");l(this,"target");l(this,"relDir");l(this,"resourceType");l(this,"dependents");l(this,"client");l(this,"relType");l(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const s=t.find(a=>a.key.toString()==n.id.toString());return s==null||s.variant==="delete"?n:s.value}),this.notify(this.dependents)});l(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[fa(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const s=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[fa(this.relDir)].type===this.resourceType));if(s.length===0)return this.notify(this.dependents);this.client.retrieve(s.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)}).catch(console.error)});this.resourceType=o,this.internal=c,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(d=>d.id.type===this.resourceType)),this.client=h,this.relType=s,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,s){const a=await Tr.open(n,s);return new dn(t,a,s)}async close(){await this.internal.close()}}const Zg=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:ai,CLUSTER_TYPE:dc,ChangeTracker:Tr,Client:vc,DependentTracker:dn,FROM_RELATIONSHIP_DIRECTION:Ng,ID:E,NODE_TYPE:fc,ROOT_ID:Eg,TO_RELATIONSHIP_DIRECTION:zg,crudeIDZ:ht,idZ:ie,parseIDs:Mr,parseRelationship:vs,relationshipSchemaZ:Ig,resourceTypeZ:vr,resourceZ:wc,schemaFieldZ:gc,schemaZ:pc,stringIDZ:yc},Symbol.toStringTag,{value:"Module"})),Or=i.z.string().uuid(),fn=i.z.object({key:Or,subjects:X(ie),objects:X(ie),actions:X(_r)}),Tc=i.z.object({key:Or.optional(),subjects:ht.array().or(ht),objects:ht.array().or(ht),actions:_r.array().or(_r)}),qg=i.z.object({keys:Or.array().optional(),subjects:ie.array().optional()}),Fg=i.z.object({policies:X(fn)}),Yg="/access/policy/retrieve";let Wg=class{constructor(e){l(this,"client");this.client=e}async retrieve(e){return(await m(this.client,Yg,e,qg,Fg)).policies}};const Vg=i.z.object({policies:fn.partial({key:!0}).array()}),Gg=i.z.object({policies:fn.array()}),Hg=i.z.object({keys:Or.array()}),Kg=i.z.object({}),Jg="/access/policy/create",Xg="/access/policy/delete";let Qg=class{constructor(e){l(this,"client");this.client=e}async create(e){const n=Tc.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await m(this.client,Jg,{policies:n},Vg,Gg)).policies}async delete(e){await m(this.client,Xg,{keys:b(e)},Hg,Kg)}},Oc=class{constructor(e){l(this,"retriever");l(this,"writer");this.retriever=new Wg(e),this.writer=new Qg(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve({keys:b(e)});return t?n:n[0]}async retrieveFor(e){const t=b(e).map(n=>new E(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const ep=r=>new E({type:Es,key:r}),tp=new E({type:zs,key:""}),rp=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:tp,ALLOW_ALL_ONTOLOGY_TYPE:zs,Client:Oc,ONTOLOGY_TYPE:Es,keyZ:Or,newZ:Tc,ontologyID:ep,policyZ:fn},Symbol.toStringTag,{value:"Module"}));let Sc=class{constructor(e){l(this,"policy");this.policy=new Oc(e)}};const np=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:so,CREATE_ACTION:io,Client:Sc,DELETE_ACTION:ao,RETRIEVE_ACTION:oo,UPDATE_ACTION:co,actionZ:_r},Symbol.toStringTag,{value:"Module"})),sp=new Error("request for lock canceled");var ip=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(n.next(f))}catch(u){o(u)}}function h(f){try{d(n.throw(f))}catch(u){o(u)}}function d(f){f.done?a(f.value):s(f.value).then(c,h)}d((n=n.apply(r,e||[])).next())})};class ap{constructor(e,t=sp){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,s)=>{const a={resolve:n,reject:s,weight:e,priority:t},o=Ec(this._queue,c=>t<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return ip(this,arguments,void 0,function*(t,n=1,s=0){const[a,o]=yield this.acquire(n,s);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),op(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const s=n.findIndex(a=>a.priority<=e);(s===-1?n:n.splice(0,s)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function op(r,e){const t=Ec(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Ec(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var cp=function(r,e,t,n){function s(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(f){try{d(n.next(f))}catch(u){o(u)}}function h(f){try{d(n.throw(f))}catch(u){o(u)}}function d(f){f.done?a(f.value):s(f.value).then(c,h)}d((n=n.apply(r,e||[])).next())})};class lp{constructor(e){this._semaphore=new ap(1,e)}acquire(){return cp(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const ci=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let s=b(r);const a=s[0],o=typeof a;let c;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,s=s.map(h=>parseInt(h))):c=e[o],{single:n,variant:c,normalized:s,actual:r}},yn=(r,e,t,n)=>{if(n){if(t.length===0)throw new Je(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new Xe(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},hp=i.z.object({leaseholder:i.z.number().optional(),keys:Q.array().optional(),names:i.z.string().array().optional(),search:i.z.string().optional(),rangeKey:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),dataTypes:x.z.array().optional(),notDataTypes:x.z.array().optional(),virtual:i.z.boolean().optional(),isIndex:i.z.boolean().optional(),internal:i.z.boolean().optional()}),up=i.z.object({channels:X(fr)}),Oe=r=>(Array.isArray(r)&&r.length>0&&typeof r[0]=="object"?r=r.map(e=>e.key):typeof r=="object"&&"key"in r&&(r=[r.key]),ci(r,{number:"keys",string:"names"})),Yr=class Yr{constructor(e){l(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=Oe(e),{variant:s}=n;let{normalized:a}=n;return s==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[s]:a,...t})}async page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(Yr.ENDPOINT,e,hp,up);if(n!=null)throw n;return t.channels}};l(Yr,"ENDPOINT","/channel/retrieve");let ar=Yr;class li{constructor(e){l(this,"cache");l(this,"namesToKeys");l(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=Oe(e),s=[],a=[];if(n.forEach(c=>{const h=this.get(c);h!=null?s.push(...h):a.push(c)}),a.length===0)return s;const o=await this.wrapped.retrieve(a,t);return this.set(o),s.concat(o)}delete(e){const{variant:t,normalized:n}=Oe(e);t==="names"?n.forEach(s=>{const a=this.namesToKeys.get(s);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(s))}):n.forEach(s=>{const a=this.cache.get(s);a!=null&&(this.cache.delete(s),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,s)=>{const a=t[s],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const c=this.namesToKeys.get(o.name);c!=null&&(c.delete(n),c.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(n,o);const h=this.namesToKeys.get(a);h==null?this.namesToKeys.set(a,new Set([n])):h.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const s=this.cache.get(e);return s==null?void 0:[s]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(s=>{const a=this.cache.get(s);a!=null&&n.push(a)}),n.length!==0)return n}}class zc{constructor(e,t){l(this,"mu",new lp);l(this,"requests",new Map);l(this,"wrapped");l(this,"debouncedRun");this.wrapped=e,this.debouncedRun=ty(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=Oe(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(s=>e.add(s)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,s)=>n.resolve(t.filter(a=>s.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Nc=async(r,e)=>{const{normalized:t}=Oe(e),n=await r.retrieve(t),s=[];if(t.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&s.push(a)}),s.length>0)throw new ke(`Could not find channels: ${JSON.stringify(s)}`);return n};class hi{constructor({dataType:e,name:t,leaseholder:n=0,key:s=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:h=!1,frameClient:d,alias:f,expression:u="",requires:N=[]}){l(this,"_frameClient");l(this,"key");l(this,"name");l(this,"dataType");l(this,"leaseholder");l(this,"index");l(this,"isIndex");l(this,"internal");l(this,"alias");l(this,"virtual");l(this,"expression");l(this,"requires");this.key=s,this.name=t,this.dataType=new x(e),this.leaseholder=n,this.index=o,this.isIndex=a,this.internal=c,this.alias=f,this.virtual=h,this.expression=u,this.requires=N??[],this._frameClient=d??null}get framer(){if(this._frameClient==null)throw new F("cannot read from a channel that has not been created");return this._frameClient}get payload(){return fr.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,requires:this.requires})}get isCalculated(){return or(this.payload)}get ontologyID(){return xc(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const dp="/channel/retrieve-group",fp=i.z.object({}),yp=i.z.object({group:_s});let Ic=class{constructor(e,t,n,s){l(this,"type",en);l(this,"frameClient");l(this,"client");l(this,"retriever");l(this,"writer");this.frameClient=e,this.retriever=t,this.client=n,this.writer=s}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,s=!Array.isArray(e);let a=b(e),o=[];if(n){const c=await this.retriever.retrieve(a.map(d=>d.name)),h=new Set(c.map(d=>d.name));a=a.filter(d=>!h.has(d.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),s?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),s=this.sugar(await this.retriever.retrieve(e,t));return yn("channel",e,s,n),n?s[0]:s}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=Oe(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new li(new zc(new ar(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new hi({...n,frameClient:t}))}async retrieveGroup(){const e=await m(this.client,dp,{},fp,yp);return new oi(e.group.name,e.group.key)}};const or=({virtual:r,expression:e})=>r&&e!=="",$c=async(r,e)=>{if(!or(e))return e.index;for(const t of e.requires){const n=await r(t);if(n==null)return null;if(!n.virtual)return n.index}for(const t of e.requires){const n=await r(t);if(n==null)return null;if(or(n)){const s=await $c(r,n);if(s!=null)return s}}return null},xc=r=>new E({type:en,key:r.toString()}),gp=i.z.object({channels:Ko.array()}),pp=i.z.object({channels:fr.array()}),wp=i.z.object({keys:Q.array().optional(),names:dr.array().optional()}),mp=i.z.object({}),bp=i.z.object({keys:Q.array(),names:dr.array()}),vp=i.z.object({}),Tp="/channel/create",Op="/channel/delete",Sp="/channel/rename";let kc=class{constructor(e,t){l(this,"client");l(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await m(this.client,Tp,{channels:e},gp,pp);return this.cache.set(t),t}async delete(e){await m(this.client,Op,e,wp,mp),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await m(this.client,Sp,{keys:e,names:t},bp,vp),this.cache.rename(e,t)}};const Ep=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:li,Channel:hi,Client:Ic,ClusterRetriever:ar,DebouncedBatchRetriever:zc,ONTOLOGY_TYPE:en,Writer:kc,analyzeParams:Oe,channelZ:fr,isCalculated:or,keyZ:Q,nameZ:dr,newZ:Ko,ontologyID:xc,resolveCalculatedIndex:$c,retrieveRequired:Nc},Symbol.toStringTag,{value:"Module"})),zp=i.z.object({keys:tt.array().optional(),usernames:i.z.string().array().optional()}),Np=i.z.object({users:X(br)}),Ip="/user/retrieve";let $p=class{constructor(e){l(this,"client");this.client=e}async retrieve(e){return(await m(this.client,Ip,e,zp,Np)).users}};const xp=i.z.object({users:ic.array()}),kp=i.z.object({users:br.array()}),Ap=i.z.object({key:tt,username:i.z.string().min(1)}),Up=i.z.object({}),Cp=i.z.object({key:tt,firstName:i.z.string().optional(),lastName:i.z.string().optional()}),Rp=i.z.object({}),Bp=i.z.object({keys:tt.array()}),Pp=i.z.object({}),Dp="/user/create",Mp="/user/change-username",jp="/user/rename",Lp="/user/delete";let _p=class{constructor(e){l(this,"client");this.client=e}async create(e){return(await m(this.client,Dp,{users:b(e)},xp,kp)).users}async changeUsername(e,t){await m(this.client,Mp,{key:e,username:t},Ap,Up)}async rename(e,t,n){await m(this.client,jp,{key:e,firstName:t,lastName:n},Cp,Rp)}async delete(e){await m(this.client,Lp,{keys:b(e)},Bp,Pp)}},Ac=class{constructor(e){l(this,"reader");l(this,"writer");this.writer=new _p(e),this.reader=new $p(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.reader.retrieve({keys:b(e)});if(t)return n;if(n.length===0)throw new Je(`No user with key ${e} found`);if(n.length>1)throw new Xe(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:b(e)});if(t)return n;if(n.length===0)throw new Je(`No user with username ${e} found`);if(n.length>1)throw new Xe(`Multiple users found with username ${e}`);return n[0]}async rename(e,t,n){await this.writer.rename(e,t,n)}async delete(e){await this.writer.delete(e)}};const Zp=r=>new E({type:Xs,key:r}),qp=Object.freeze(Object.defineProperty({__proto__:null,Client:Ac,ONTOLOGY_TYPE:Xs,keyZ:tt,newZ:ic,ontologyID:Zp,userZ:br},Symbol.toStringTag,{value:"Module"})),Fp=i.z.object({username:i.z.string(),password:i.z.string()}),Yp=i.z.object({token:i.z.string(),user:br}),ya="/auth/login",Wp=3,Vp="/auth/change-password",Gp=i.z.object({username:i.z.string(),password:i.z.string(),newPassword:i.z.string().min(1)}),Hp=i.z.object({}),Kp=[ps,ws];let Jp=class{constructor(e,t){l(this,"token");l(this,"client");l(this,"credentials");l(this,"authenticating");l(this,"authenticated");l(this,"user");l(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await m(this.client,Vp,{username:this.credentials.username,password:this.credentials.password,newPassword:e},Gp,Hp),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(ya)){this.authenticating??(this.authenticating=new Promise((c,h)=>{this.client.send(ya,this.credentials,Fp,Yp).then(([d,f])=>{if(f!=null)return c(f);this.token=d==null?void 0:d.token,this.user=d==null?void 0:d.user,this.authenticated=!0,c(null)}).catch(h)}));const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[s,a]=await n(t);return Kp.some(o=>o.matches(a))&&this.retryCount<Wp?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[s,a])};return e}};const Uc=i.z.enum(["disconnected","connecting","connected","failed"]),Cc=i.z.object({status:Uc,error:i.z.instanceof(Error).optional(),message:i.z.string().optional(),clusterKey:i.z.string(),clientVersion:i.z.string(),clientServerCompatible:i.z.boolean(),nodeVersion:i.z.string().optional()}),Xp=i.z.object({clusterKey:i.z.string(),nodeVersion:i.z.string().optional()}),ga={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.42.3"},pa=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
39
39
  This may cause compatibility issues. We recommend updating the ${n}. For more information, see
40
- https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},ft=class ft{constructor(e,t=O.seconds(30),n,s){l(this,"_state");l(this,"pollFrequency",O.seconds(30));l(this,"client");l(this,"name");l(this,"interval");l(this,"clientVersion");l(this,"onChangeHandlers",[]);l(this,"versionWarned",!1);this._state={...fa},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=s,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,s]=await this.client.send(ft.ENDPOINT,{},i.z.object({}),Kp);if(s!=null)throw s;const a=n.nodeVersion,o=this.clientVersion,c=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,c||(console.warn(ya(null,o,!0)),this.versionWarned=!0)):ta.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,c||(console.warn(ya(a,o,ta.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};l(ft,"ENDPOINT","/connectivity/check"),l(ft,"DEFAULT",fa),l(ft,"connectionStateZ",Ac);let cr=ft;const Jp=Object.freeze(Object.defineProperty({__proto__:null,Checker:cr,stateZ:Ac,statusZ:kc},Symbol.toStringTag,{value:"Module"})),Xp=i.z.object({keys:Q.array().optional(),bounds:q.z,names:dr.array().optional()}),Qp=i.z.object({}),ew="/frame/delete";class tw{constructor(e){l(this,"client");this.client=e}async delete(e){await m(this.client,ew,e,Xp,Qp)}}var Ot=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.SetAuthority=3]="SetAuthority",r))(Ot||{}),St=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(St||{});const rw=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in St)return r;throw new Error(`invalid writer mode: ${r}`)}},nw=new O(-1);class Ts extends Ue.sub("writer_closed"){constructor(){super("WriterClosed")}}const sw=i.z.object({start:z.z.optional(),controlSubject:Ke.subjectZ.optional(),keys:Q.array().optional(),authorities:Ke.authorityZ.array().optional(),mode:i.z.enum(St).optional(),errOnUnauthorized:i.z.boolean().optional(),enableAutoCommit:i.z.boolean().optional(),autoIndexPersistInterval:O.z.optional()}),iw=i.z.object({command:i.z.enum(Ot),config:sw.optional(),frame:tn.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),aw=i.z.object({command:i.z.enum(Ot),end:z.z,err:Tt.payloadZ.optional()});var Ze;let Uc=(Ze=class{constructor(e,t){l(this,"stream");l(this,"adapter");l(this,"closeErr",null);this.stream=e,this.adapter=t}static async _open(e,t,{channels:n,start:s=z.now(),authorities:a=Ke.ABSOLUTE_AUTHORITY,controlSubject:o,mode:c=1,errOnUnauthorized:h=!1,enableAutoCommit:d=!1,autoIndexPersistInterval:f=O.SECOND,useExperimentalCodec:u=!0}){const N=await hi.open(e,n);u&&(t=t.withCodec(new dw(N.codec)));const S=await t.stream(Ze.ENDPOINT,iw,aw),j=new Ze(S,N);return await j.execute({command:0,config:{start:new z(s),keys:N.keys,controlSubject:o,authorities:b(a),mode:rw(c),errOnUnauthorized:h,enableAutoCommit:d,autoIndexPersistInterval:f}}),j}async write(e,t){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const n=await this.adapter.adapt(e,t);this.stream.send({command:1,frame:n.toPayload()})}async setAuthority(e,t){if(this.closeErr!=null)throw this.closeErr;let n;if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let s;typeof e=="string"||typeof e=="number"?s={[e]:t}:s=e,s=await this.adapter.adaptObjectKeys(s),n={keys:Object.keys(s).map(a=>Number(a)),authorities:Object.values(s)}}await this.execute({command:3,config:n})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),z.ZERO):(await this.execute({command:2})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(Ts.matches(this.closeErr))return null;throw this.closeErr}const[t,n]=await this.stream.receive();n!=null?this.closeErr=ue.matches(n)?new Ts:n:this.closeErr=Tt.decode(t==null?void 0:t.err)}}async execute(e){const t=this.stream.send(e);for(t!=null&&await this.closeInternal(t);;){const[n,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const a=Tt.decode(n==null?void 0:n.err);if(a!=null&&await this.closeInternal(a),(n==null?void 0:n.command)==e.command)return n}}},l(Ze,"ENDPOINT","/frame/write"),Ze);const ga=r=>r.data.byteLength/r.dataType.density.valueOf(),ow=r=>{const{keys:e,series:t}=r;e.forEach((n,s)=>{t[s].key=n}),t.sort((n,s)=>n.key-s.key),e.sort((n,s)=>n-s),t.forEach(n=>delete n.key)},pa=5,wa=4,ma=3,ba=2,va=1,Ta=0,de=x.TIMESTAMP.density.valueOf(),Be=8,Pe=4,An=4,Un=4,cw=1;class Cc{constructor(e=[],t=[]){l(this,"contentType","application/sy-framer");l(this,"states",new Map);l(this,"currState");l(this,"seqNum",0);(e.length>0||t.length>0)&&this.update(e,t)}update(e,t){this.seqNum++;const n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,a)=>{const o=t[a];n.keyDataTypes.set(s,o),o.isVariable&&(n.hasVariableDataTypes=!0)}),n.keys.sort(),this.states.set(this.seqNum,n),this.currState=n}throwIfNotUpdated(e){if(this.seqNum<1)throw new F(`
40
+ https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},ft=class ft{constructor(e,t=O.seconds(30),n,s){l(this,"_state");l(this,"pollFrequency",O.seconds(30));l(this,"client");l(this,"name");l(this,"interval");l(this,"clientVersion");l(this,"onChangeHandlers",[]);l(this,"versionWarned",!1);this._state={...ga},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=s,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,s]=await this.client.send(ft.ENDPOINT,{},i.z.object({}),Xp);if(s!=null)throw s;const a=n.nodeVersion,o=this.clientVersion,c=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,c||(console.warn(pa(null,o,!0)),this.versionWarned=!0)):na.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,c||(console.warn(pa(a,o,na.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};l(ft,"ENDPOINT","/connectivity/check"),l(ft,"DEFAULT",ga),l(ft,"connectionStateZ",Cc);let cr=ft;const Qp=Object.freeze(Object.defineProperty({__proto__:null,Checker:cr,stateZ:Cc,statusZ:Uc},Symbol.toStringTag,{value:"Module"})),ew=i.z.object({keys:Q.array().optional(),bounds:q.z,names:dr.array().optional()}),tw=i.z.object({}),rw="/frame/delete";class nw{constructor(e){l(this,"client");this.client=e}async delete(e){await m(this.client,rw,e,ew,tw)}}var Ot=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.SetAuthority=3]="SetAuthority",r))(Ot||{}),St=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(St||{});const sw=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in St)return r;throw new Error(`invalid writer mode: ${r}`)}},iw=new O(-1);class Ts extends Ue.sub("writer_closed"){constructor(){super("WriterClosed")}}const aw=i.z.object({start:z.z.optional(),controlSubject:Ke.subjectZ.optional(),keys:Q.array().optional(),authorities:Ke.authorityZ.array().optional(),mode:i.z.enum(St).optional(),errOnUnauthorized:i.z.boolean().optional(),enableAutoCommit:i.z.boolean().optional(),autoIndexPersistInterval:O.z.optional()}),ow=i.z.object({command:i.z.enum(Ot),config:aw.optional(),frame:tn.optional(),buffer:i.z.instanceof(Uint8Array).optional()}),cw=i.z.object({command:i.z.enum(Ot),end:z.z,err:Tt.payloadZ.optional()});var Ze;let Rc=(Ze=class{constructor(e,t){l(this,"stream");l(this,"adapter");l(this,"closeErr",null);this.stream=e,this.adapter=t}static async _open(e,t,{channels:n,start:s=z.now(),authorities:a=Ke.ABSOLUTE_AUTHORITY,controlSubject:o,mode:c=1,errOnUnauthorized:h=!1,enableAutoCommit:d=!1,autoIndexPersistInterval:f=O.SECOND,useExperimentalCodec:u=!0}){const N=await di.open(e,n);u&&(t=t.withCodec(new yw(N.codec)));const S=await t.stream(Ze.ENDPOINT,ow,cw),j=new Ze(S,N);return await j.execute({command:0,config:{start:new z(s),keys:N.keys,controlSubject:o,authorities:b(a),mode:sw(c),errOnUnauthorized:h,enableAutoCommit:d,autoIndexPersistInterval:f}}),j}async write(e,t){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const n=await this.adapter.adapt(e,t);this.stream.send({command:1,frame:n.toPayload()})}async setAuthority(e,t){if(this.closeErr!=null)throw this.closeErr;let n;if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let s;typeof e=="string"||typeof e=="number"?s={[e]:t}:s=e,s=await this.adapter.adaptObjectKeys(s),n={keys:Object.keys(s).map(a=>Number(a)),authorities:Object.values(s)}}await this.execute({command:3,config:n})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),z.ZERO):(await this.execute({command:2})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if(Ts.matches(this.closeErr))return null;throw this.closeErr}const[t,n]=await this.stream.receive();n!=null?this.closeErr=ue.matches(n)?new Ts:n:this.closeErr=Tt.decode(t==null?void 0:t.err)}}async execute(e){const t=this.stream.send(e);for(t!=null&&await this.closeInternal(t);;){const[n,s]=await this.stream.receive();s!=null&&await this.closeInternal(s);const a=Tt.decode(n==null?void 0:n.err);if(a!=null&&await this.closeInternal(a),(n==null?void 0:n.command)==e.command)return n}}},l(Ze,"ENDPOINT","/frame/write"),Ze);const wa=r=>r.data.byteLength/r.dataType.density.valueOf(),lw=r=>{const{keys:e,series:t}=r;e.forEach((n,s)=>{t[s].key=n}),t.sort((n,s)=>n.key-s.key),e.sort((n,s)=>n-s),t.forEach(n=>delete n.key)},ma=5,ba=4,va=3,Ta=2,Oa=1,Sa=0,de=x.TIMESTAMP.density.valueOf(),Be=8,Pe=4,An=4,Un=4,hw=1;class Bc{constructor(e=[],t=[]){l(this,"contentType","application/sy-framer");l(this,"states",new Map);l(this,"currState");l(this,"seqNum",0);(e.length>0||t.length>0)&&this.update(e,t)}update(e,t){this.seqNum++;const n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((s,a)=>{const o=t[a];n.keyDataTypes.set(s,o),o.isVariable&&(n.hasVariableDataTypes=!0)}),n.keys.sort(),this.states.set(this.seqNum,n),this.currState=n}throwIfNotUpdated(e){if(this.seqNum<1)throw new F(`
41
41
  The codec has not been updated with a list of channels and data types.
42
42
  Please call the update method before calling ${e}.
43
- `)}encode(e,t=0){var st,Ve;this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),ow(n);let s=-1,a,o,c,h=t+cw+Un,d=!((st=this.currState)!=null&&st.hasVariableDataTypes),f=!0,u=!0,N=!0,S=!0,j=!0;n.keys.length!==((Ve=this.currState)==null?void 0:Ve.keys.length)&&(N=!1,h+=n.keys.length*An),n.series.forEach((L,xt)=>{var kt,Sr,fi,yi,gi;const ze=ga(L),le=n.keys[xt],oe=(kt=this.currState)==null?void 0:kt.keyDataTypes.get(le);if(oe==null)throw new F(`Channel ${le} was not provided in the list of channels when opening the writer`);if(!oe.equals(L.dataType))throw new F(`Series data type of ${L.dataType.toString()} does not match the data type of ${oe.toString()} for channel ${le}`);if(h+=L.data.byteLength,s===-1){s=ze,a=(Sr=L.timeRange)==null?void 0:Sr.start,o=(fi=L.timeRange)==null?void 0:fi.end,c=BigInt(L.alignment??0n);return}s!==ze&&(d=!1),((a==null?void 0:a.valueOf())!==((yi=L.timeRange)==null?void 0:yi.start.valueOf())||(o==null?void 0:o.valueOf())!==((gi=L.timeRange)==null?void 0:gi.end.valueOf()))&&(f=!1),c!==BigInt(L.alignment??0)&&(S=!1)}),u=f&&a==null&&o==null,j=S&&(c===void 0||c===0n),d?h+=Pe:h+=n.keys.length*Pe,u||(f?h+=de*2:h+=n.keys.length*de*2),j||(S?h+=Be:h+=n.keys.length*Be);const U=new Uint8Array(h),ee=new DataView(U.buffer);let A=t;return U[A]=Number(j)<<pa|Number(S)<<wa|Number(d)<<ma|Number(f)<<ba|Number(u)<<va|Number(N)<<Ta,A++,ee.setUint32(A,this.seqNum,!0),A+=Un,d&&(ee.setUint32(A,s,!0),A+=Pe),f&&!u&&(ee.setBigUint64(A,(a==null?void 0:a.valueOf())??0n,!0),ee.setBigUint64(A,(o==null?void 0:o.valueOf())??0n,!0),A+=de*2),S&&!j&&(ee.setBigUint64(A,c??0n,!0),A+=Be),n.series.forEach((L,xt)=>{var ze,le;if(N||(ee.setUint32(A,n.keys[xt],!0),A+=An),!d){let oe=L.data.byteLength;L.dataType.isVariable||(oe=ga(L)),ee.setUint32(A,oe,!0),A+=Pe}U.set(new Uint8Array(L.data),A),A+=L.data.byteLength,!f&&!u&&(ee.setBigUint64(A,((ze=L.timeRange)==null?void 0:ze.start.valueOf())??0n,!0),ee.setBigUint64(A,((le=L.timeRange)==null?void 0:le.end.valueOf())??0n,!0),A+=de*2),!S&&!j&&(ee.setBigUint64(A,L.alignment??0n,!0),A+=Be)}),U}decode(e,t=0){this.throwIfNotUpdated("decode");const n=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let a=t,o=0,c=0,h,d,f;const u=new DataView(n.buffer,n.byteOffset,n.byteLength),N=!!(n[a]>>pa&1),S=!!(n[a]>>wa&1),j=!!(n[a]>>ma&1),U=!!(n[a]>>ba&1),ee=!!(n[a]>>va&1),A=!!(n[a]>>Ta&1);a++;const st=u.getUint32(a,!0);a+=Un;const Ve=this.states.get(st);if(Ve==null)return s;if(j){if(a+Pe>u.byteLength)return s;o=u.getUint32(a,!0),a+=Pe}if(U&&!ee){if(a+de>u.byteLength)return s;h=new z(u.getBigUint64(a,!0)),a+=de,d=new z(u.getBigUint64(a,!0)),a+=de}if(S&&!N){if(a+Be>u.byteLength)return s;f=u.getBigUint64(a,!0),a+=Be}return A&&(s.keys=[...Ve.keys]),Ve.keys.forEach((L,xt)=>{if(!A){if(a>=u.byteLength||u.getUint32(a,!0)!==L)return;a+=An,s.keys.push(L)}const ze=Ve.keyDataTypes.get(L);if(c=0,j)c=o;else{if(a+Pe>u.byteLength)return;c=u.getUint32(a,!0),a+=Pe}let le=c;if(ze.isVariable||(le*=ze.density.valueOf()),a+le>u.byteLength){s.keys.splice(xt,1);return}const oe={dataType:ze,data:n.slice(a,a+le).buffer};if(a+=le,!U&&!ee){if(a+de*2>u.byteLength)return;const kt=u.getBigUint64(a,!0);a+=de;const Sr=u.getBigUint64(a,!0);a+=de,oe.timeRange=new q({start:kt,end:Sr})}else ee?oe.timeRange=new q({start:0n,end:0n}):oe.timeRange=new q({start:(h==null?void 0:h.valueOf())??0n,end:(d==null?void 0:d.valueOf())??0n});if(!S&&!N){if(a+Be>u.byteLength)return;f=u.getBigUint64(a,!0),a+=Be,oe.alignment=f}else N?oe.alignment=0n:oe.alignment=f;s.series.push(oe)}),s}}const li=254,lw=new Uint8Array([li]),hw=255,uw=new Uint8Array([hw]),Rc="application/sy-framer";class dw{constructor(e){l(this,"contentType",Rc);l(this,"base");l(this,"lowPerfCodec");this.base=e,this.lowPerfCodec=Qe.JSON_CODEC}encode(e){var s,a;const t=e;if(t.type=="close"||((s=t.payload)==null?void 0:s.command)!=Ot.Write){const o=this.lowPerfCodec.encode(t),c=new Uint8Array({length:o.byteLength+1});return c.set(lw,0),c.set(new Uint8Array(o),1),c}const n=this.base.encode((a=t.payload)==null?void 0:a.frame,1);return n.set(uw,0),n}decode(e,t){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===li)return this.lowPerfCodec.decode(e.slice(1),t);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:Ot.Write,frame:o},a}}class fw{constructor(e){l(this,"contentType",Rc);l(this,"base");l(this,"lowPerfCodec");this.base=e,this.lowPerfCodec=Qe.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,t){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===li?this.lowPerfCodec.decode(e.slice(1),t):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class gn{constructor(e){l(this,"adapter");l(this,"retriever");l(this,"keys");l(this,"codec");this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Cc}static async open(e,t){const n=new gn(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=Oe(e),s=await this.retriever.retrieve(n);if(this.codec.update(s.map(o=>o.key),s.map(o=>o.dataType)),t==="keys"){this.adapter=null,this.keys=n;return}const a=new Map;this.adapter=a,n.forEach(o=>{const c=s.find(h=>h.name===o);if(c==null)throw new Error(`Channel ${o} not found`);a.set(c.key,c.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,s)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,s]}return[n,s]})}}class hi{constructor(e){l(this,"adapter");l(this,"retriever");l(this,"keys");l(this,"codec");this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Cc}static async open(e,t){const n=new hi(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,s]of Object.entries(e))t[await this.adaptToKey(n)]=s;return t}async update(e){const t=await Ec(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key),this.codec.update(this.keys,t.map(n=>n.dataType))}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new F(`
43
+ `)}encode(e,t=0){var st,Ve;this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),lw(n);let s=-1,a,o,c,h=t+hw+Un,d=!((st=this.currState)!=null&&st.hasVariableDataTypes),f=!0,u=!0,N=!0,S=!0,j=!0;n.keys.length!==((Ve=this.currState)==null?void 0:Ve.keys.length)&&(N=!1,h+=n.keys.length*An),n.series.forEach((L,xt)=>{var kt,Sr,gi,pi,wi;const ze=wa(L),le=n.keys[xt],oe=(kt=this.currState)==null?void 0:kt.keyDataTypes.get(le);if(oe==null)throw new F(`Channel ${le} was not provided in the list of channels when opening the writer`);if(!oe.equals(L.dataType))throw new F(`Series data type of ${L.dataType.toString()} does not match the data type of ${oe.toString()} for channel ${le}`);if(h+=L.data.byteLength,s===-1){s=ze,a=(Sr=L.timeRange)==null?void 0:Sr.start,o=(gi=L.timeRange)==null?void 0:gi.end,c=BigInt(L.alignment??0n);return}s!==ze&&(d=!1),((a==null?void 0:a.valueOf())!==((pi=L.timeRange)==null?void 0:pi.start.valueOf())||(o==null?void 0:o.valueOf())!==((wi=L.timeRange)==null?void 0:wi.end.valueOf()))&&(f=!1),c!==BigInt(L.alignment??0)&&(S=!1)}),u=f&&a==null&&o==null,j=S&&(c===void 0||c===0n),d?h+=Pe:h+=n.keys.length*Pe,u||(f?h+=de*2:h+=n.keys.length*de*2),j||(S?h+=Be:h+=n.keys.length*Be);const U=new Uint8Array(h),ee=new DataView(U.buffer);let A=t;return U[A]=Number(j)<<ma|Number(S)<<ba|Number(d)<<va|Number(f)<<Ta|Number(u)<<Oa|Number(N)<<Sa,A++,ee.setUint32(A,this.seqNum,!0),A+=Un,d&&(ee.setUint32(A,s,!0),A+=Pe),f&&!u&&(ee.setBigUint64(A,(a==null?void 0:a.valueOf())??0n,!0),ee.setBigUint64(A,(o==null?void 0:o.valueOf())??0n,!0),A+=de*2),S&&!j&&(ee.setBigUint64(A,c??0n,!0),A+=Be),n.series.forEach((L,xt)=>{var ze,le;if(N||(ee.setUint32(A,n.keys[xt],!0),A+=An),!d){let oe=L.data.byteLength;L.dataType.isVariable||(oe=wa(L)),ee.setUint32(A,oe,!0),A+=Pe}U.set(new Uint8Array(L.data),A),A+=L.data.byteLength,!f&&!u&&(ee.setBigUint64(A,((ze=L.timeRange)==null?void 0:ze.start.valueOf())??0n,!0),ee.setBigUint64(A,((le=L.timeRange)==null?void 0:le.end.valueOf())??0n,!0),A+=de*2),!S&&!j&&(ee.setBigUint64(A,L.alignment??0n,!0),A+=Be)}),U}decode(e,t=0){this.throwIfNotUpdated("decode");const n=e instanceof Uint8Array?e:new Uint8Array(e),s={keys:[],series:[]};let a=t,o=0,c=0,h,d,f;const u=new DataView(n.buffer,n.byteOffset,n.byteLength),N=!!(n[a]>>ma&1),S=!!(n[a]>>ba&1),j=!!(n[a]>>va&1),U=!!(n[a]>>Ta&1),ee=!!(n[a]>>Oa&1),A=!!(n[a]>>Sa&1);a++;const st=u.getUint32(a,!0);a+=Un;const Ve=this.states.get(st);if(Ve==null)return s;if(j){if(a+Pe>u.byteLength)return s;o=u.getUint32(a,!0),a+=Pe}if(U&&!ee){if(a+de>u.byteLength)return s;h=new z(u.getBigUint64(a,!0)),a+=de,d=new z(u.getBigUint64(a,!0)),a+=de}if(S&&!N){if(a+Be>u.byteLength)return s;f=u.getBigUint64(a,!0),a+=Be}return A&&(s.keys=[...Ve.keys]),Ve.keys.forEach((L,xt)=>{if(!A){if(a>=u.byteLength||u.getUint32(a,!0)!==L)return;a+=An,s.keys.push(L)}const ze=Ve.keyDataTypes.get(L);if(c=0,j)c=o;else{if(a+Pe>u.byteLength)return;c=u.getUint32(a,!0),a+=Pe}let le=c;if(ze.isVariable||(le*=ze.density.valueOf()),a+le>u.byteLength){s.keys.splice(xt,1);return}const oe={dataType:ze,data:n.slice(a,a+le).buffer};if(a+=le,!U&&!ee){if(a+de*2>u.byteLength)return;const kt=u.getBigUint64(a,!0);a+=de;const Sr=u.getBigUint64(a,!0);a+=de,oe.timeRange=new q({start:kt,end:Sr})}else ee?oe.timeRange=new q({start:0n,end:0n}):oe.timeRange=new q({start:(h==null?void 0:h.valueOf())??0n,end:(d==null?void 0:d.valueOf())??0n});if(!S&&!N){if(a+Be>u.byteLength)return;f=u.getBigUint64(a,!0),a+=Be,oe.alignment=f}else N?oe.alignment=0n:oe.alignment=f;s.series.push(oe)}),s}}const ui=254,uw=new Uint8Array([ui]),dw=255,fw=new Uint8Array([dw]),Pc="application/sy-framer";class yw{constructor(e){l(this,"contentType",Pc);l(this,"base");l(this,"lowPerfCodec");this.base=e,this.lowPerfCodec=Qe.JSON_CODEC}encode(e){var s,a;const t=e;if(t.type=="close"||((s=t.payload)==null?void 0:s.command)!=Ot.Write){const o=this.lowPerfCodec.encode(t),c=new Uint8Array({length:o.byteLength+1});return c.set(uw,0),c.set(new Uint8Array(o),1),c}const n=this.base.encode((a=t.payload)==null?void 0:a.frame,1);return n.set(fw,0),n}decode(e,t){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ui)return this.lowPerfCodec.decode(e.slice(1),t);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:Ot.Write,frame:o},a}}class gw{constructor(e){l(this,"contentType",Pc);l(this,"base");l(this,"lowPerfCodec");this.base=e,this.lowPerfCodec=Qe.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,t){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ui?this.lowPerfCodec.decode(e.slice(1),t):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class gn{constructor(e){l(this,"adapter");l(this,"retriever");l(this,"keys");l(this,"codec");this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Bc}static async open(e,t){const n=new gn(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=Oe(e),s=await this.retriever.retrieve(n);if(this.codec.update(s.map(o=>o.key),s.map(o=>o.dataType)),t==="keys"){this.adapter=null,this.keys=n;return}const a=new Map;this.adapter=a,n.forEach(o=>{const c=s.find(h=>h.name===o);if(c==null)throw new Error(`Channel ${o} not found`);a.set(c.key,c.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,s)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,s]}return[n,s]})}}class di{constructor(e){l(this,"adapter");l(this,"retriever");l(this,"keys");l(this,"codec");this.retriever=e,this.adapter=null,this.keys=[],this.codec=new Bc}static async open(e,t){const n=new di(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,s]of Object.entries(e))t[await this.adaptToKey(n)]=s;return t}async update(e){const t=await Nc(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key),this.codec.update(this.keys,t.map(n=>n.dataType))}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new F(`
44
44
  Received a single channel name or key but no series.
45
45
  `);if(Array.isArray(t)){if(t.some(h=>h instanceof _e||Array.isArray(h)))throw new F(`
46
46
  Received a single channel name or key but multiple series.
@@ -52,5 +52,5 @@
52
52
  Received an array of channel names or keys but not enough series.
53
53
  `);const f=new _e({data:t[h],dataType:d.dataType});o.push(d.key),c.push(f)}return new V(o,c)}if(e instanceof V||e instanceof Map){const o=new V(e);if(this.adapter==null)return o;const c=o.columns.map(h=>{var f;const d=typeof h=="string"?(f=this.adapter)==null?void 0:f.get(h):h;if(d==null)throw new F(`
54
54
  Channel ${h} was not provided in the list of channels when opening the writer
55
- `);return d});return new V(c,o.series)}const n=[],s=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,h]=a[o],d=await this.fetchChannel(c),f=new _e({data:h,dataType:d.dataType});n.push(d.key),s.push(f)}return new V(n,s)}}class Bc{constructor(e,t){l(this,"name");l(this,"stream");this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
56
- Please report this error to the Synnax team.`),t!=null){if(ue.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Os=new O(-1);var ui=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(ui||{}),Pc=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Pc||{});const yw=i.z.object({command:i.z.enum(ui),span:O.z.optional(),bounds:q.z.optional(),stamp:z.z.optional(),keys:Q.array().optional(),chunkSize:i.z.number().optional()}),gw=i.z.object({variant:i.z.enum(Pc),ack:i.z.boolean(),command:i.z.enum(ui),error:Tt.payloadZ.optional().nullable(),frame:tn.optional()}),er=class er{constructor(e,t){l(this,"stream");l(this,"adapter");l(this,"value");this.stream=new Bc("Iterator",e),this.value=new V,this.adapter=t}static async _open(e,t,n,s,a={}){const o=await gn.open(n,t),c=await s.stream(er.ENDPOINT,yw,gw),h=new er(c,o);return await h.execute({command:0,keys:o.keys,bounds:new q(e),chunkSize:a.chunkSize??1e5}),h}async next(e=Os){return await this.execute({command:1,span:new O(e)})}async prev(e=Os){return await this.execute({command:2,span:new O(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new z(e)})}async seekGE(e){return await this.execute({command:6,stamp:new z(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new pw(this)}async execute(e){for(this.stream.send(e),this.value=new V;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new V(t.frame)))}}};l(er,"ENDPOINT","/frame/iterate");let qr=er;class pw{constructor(e){l(this,"iter");l(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const ww=i.z.object({keys:i.z.number().array(),downSampleFactor:i.z.number()}),mw=i.z.object({frame:tn}),bw="/frame/stream",Dc=(r,e)=>async t=>{let n;Array.isArray(t)||typeof t!="object"?n={channels:t,downSampleFactor:1}:n=t;const s=await gn.open(r,n.channels);n.useExperimentalCodec&&(e=e.withCodec(new fw(s.codec)));const a=await e.stream(bw,ww,mw),o=new vw(a,s);a.send({keys:s.keys,downSampleFactor:n.downSampleFactor??1});const[,c]=await a.receive();if(c!=null)throw c;return o},Mc=async(r,e,t)=>await Dc(r,e)(t);class vw{constructor(e,t){l(this,"stream");l(this,"adapter");l(this,"downsampleFactor");this.stream=new Bc("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ue.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new V((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys,downSampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class pn{constructor(e,t){l(this,"wrapped_",null);l(this,"breaker");l(this,"opener");l(this,"config");this.opener=e,Array.isArray(t)||typeof t!="object"?this.config={channels:t,downSampleFactor:1}:this.config=t,this.breaker=new Do.Breaker({maxRetries:5e3,baseInterval:O.seconds(1),scale:1})}static async open(e,t){const n=new pn(e,t);return await n.runStreamer(),n}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=e;try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ue.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(ue.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class Ae extends He.Observer{constructor(t,n){super(n);l(this,"streamer");l(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}const Tw=r=>new E({type:_s,key:r.toString()}),Oa=r=>Array.isArray(r)||typeof r!="object"||typeof r=="object"&&"key"in r?{channels:r}:r;let jc=class{constructor(e,t,n){l(this,"streamClient");l(this,"retriever");l(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new tw(t)}async openIterator(e,t,n){return await qr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return await Uc._open(this.retriever,this.streamClient,Oa(e))}async openStreamer(e){return await Mc(this.retriever,this.streamClient,Oa(e))}async write(e,t,n){if(n==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:St.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:O.MAX});await o.write(a),await o.commit(),await o.close();return}const s=await this.openWriter({start:e,channels:t,mode:St.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:O.MAX});await s.write(t,n),await s.close()}async read(e,t){const{single:n}=Oe(t),s=await this.readFrame(e,t);return n?s.get(t):s}async readFrame(e,t){const n=await this.openIterator(e,t),s=new V;try{for await(const a of n)s.push(a)}finally{await n.close()}return s}async delete(e,t){const{normalized:n,variant:s}=Oe(e);return s==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Ow=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:nw,AUTO_SPAN:Os,Client:jc,Frame:V,HardenedStreamer:pn,Iterator:qr,ONTOLOGY_TYPE:_s,ObservableStreamer:Ae,Writer:Uc,WriterClosedError:Ts,WriterCommand:Ot,WriterMode:St,createStreamOpener:Dc,frameZ:tn,ontologyID:Tw,openStreamer:Mc,seriesFromPayload:Ho,seriesToPayload:Ko},Symbol.toStringTag,{value:"Module"})),Sw=Ke.ABSOLUTE_AUTHORITY,Ew=Ke.ZERO_AUTHORITY,zw=Ke.stateZ(i.z.number()),Nw=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`},Iw=i.z.object({transfers:i.z.array(Ke.transferZ)});class Lc extends Ae{constructor(t){super(t,n=>{const s=this.codec.decode(n.series[0].buffer,Iw);return this.merge(s),[s.transfers,!0]});l(this,"states");l(this,"codec");this.states=new Map,this.codec=new Qe.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Sa="sy_node_1_control";let _c=class{constructor(e){l(this,"framer");this.framer=e}async openStateTracker(){const e=await pn.open(async()=>await this.framer.openStreamer(Sa),Sa);return new Lc(e)}};const $w=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Sw,Client:_c,StateTracker:Lc,ZERO_AUTHORITY:Ew,stateZ:zw,transferString:Nw},Symbol.toStringTag,{value:"Module"}));let Zc=class{constructor(e,t,n){l(this,"tasks");l(this,"racks");l(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const xw=Object.freeze(Object.defineProperty({__proto__:null,Client:Zc},Symbol.toStringTag,{value:"Module"})),nt=async(r,e,t,n)=>{const s=await r.openStreamer([e,t]),a=o=>{const c=[];return t!=null&&c.push(...o.get(t).series.flatMap(h=>n("delete",h))),e!=null&&c.push(...o.get(e).series.flatMap(h=>n("set",h))),[c,c.length>0]};return new Ae(s,a)},kw=Object.freeze(Object.defineProperty({__proto__:null,openObservable:nt},Symbol.toStringTag,{value:"Module"})),Aw="sy_device_set",Uw="sy_device_delete",Ea="sy_device_state",Cn="/hardware/device/retrieve",Cw="/hardware/device/create",Rw="/hardware/device/delete",Bw=i.z.object({devices:Xo.array()}),Pw=i.z.object({devices:gr.array()}),Dw=i.z.object({keys:yr.array()}),Mw=i.z.object({}),Rn=i.z.object({keys:yr.array().optional(),names:i.z.string().array().optional(),makes:i.z.string().array().optional(),models:i.z.string().array().optional(),locations:i.z.string().array().optional(),racks:Ye.array().optional(),search:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),ignoreNotFound:i.z.boolean().optional(),includeState:i.z.boolean().optional()}),Bn=i.z.object({devices:X(gr)});let qc=class{constructor(e,t){l(this,"type",sn);l(this,"client");l(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),s=await m(this.client,Cn,{keys:b(e),...t},Rn,Bn);return yn("Device",e,s.devices,n),n?s.devices[0]:s.devices}async search(e,t){return(await m(this.client,Cn,{search:e,...t},Rn,Bn)).devices}async page(e,t,n){return(await m(this.client,Cn,{offset:e,limit:t,...n},Rn,Bn)).devices}async create(e){const t=!Array.isArray(e),n=await m(this.client,Cw,{devices:b(e)},Bw,Pw);return t?n.devices[0]:n.devices}async delete(e){await m(this.client,Rw,{keys:b(e)},Dw,Mw)}async openDeviceTracker(){return await nt(this.frameClient,Aw,Uw,jw)}async openStateObserver(){return new Ae(await this.frameClient.openStreamer(Ea),e=>{const t=e.get(Ea);return t.length===0?[null,!1]:[t.parseJSON(Fs),!0]})}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const jw=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(gr).map(t=>({variant:r,key:t.key,value:t})),Lw=r=>new E({type:sn,key:r}),_w=Object.freeze(Object.defineProperty({__proto__:null,Client:qc,ONTOLOGY_TYPE:sn,deviceZ:gr,keyZ:yr,newZ:Xo,ontologyID:Lw,stateZ:Fs},Symbol.toStringTag,{value:"Module"})),Pn="/hardware/rack/retrieve",Zw="/hardware/rack/create",qw="/hardware/rack/delete",za="sy_rack_state",Dn=i.z.object({keys:Ye.array().optional(),names:i.z.string().array().optional(),search:i.z.string().optional(),embedded:i.z.boolean().optional(),hostIsNode:i.z.boolean().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),includeState:i.z.boolean().optional()}),Mn=i.z.object({racks:X(rn)}),Fw=i.z.object({racks:Jo.array()}),Yw=i.z.object({racks:rn.array()}),Ww=i.z.object({keys:Ye.array()}),Vw=i.z.object({});let Fc=class{constructor(e,t,n){l(this,"type",nn);l(this,"client");l(this,"tasks");l(this,"frameClient");this.client=e,this.tasks=t,this.frameClient=n}async delete(e){await m(this.client,qw,{keys:b(e)},Ww,Vw)}async create(e){const t=!Array.isArray(e),n=await m(this.client,Zw,{racks:b(e)},Fw,Yw),s=this.sugar(n.racks);return t?s[0]:s}async search(e){const t=await m(this.client,Pn,{search:e},Dn,Mn);return this.sugar(t.racks)}async page(e,t){const n=await m(this.client,Pn,{offset:e,limit:t},Dn,Mn);return this.sugar(n.racks)}async retrieve(e,t){const{variant:n,normalized:s,single:a}=ai(e,{string:"names",number:"keys"}),o=await m(this.client,Pn,{[n]:s,includeState:t==null?void 0:t.includeState},Dn,Mn),c=this.sugar(o.racks);return yn("Rack",e,c,a),a?c[0]:c}async openStateObserver(){return new Ae(await this.frameClient.openStreamer(za),e=>{const t=e.get(za);return t.length===0?[[],!1]:[t.parseJSON(Zs),!0]})}sugar(e){return e.map(({key:t,name:n,state:s})=>new Yc(t,n,this.tasks,s))}};class Yc{constructor(e,t,n,s){l(this,"key");l(this,"name");l(this,"state");l(this,"tasks");this.key=e,this.name=t,this.tasks=n,this.state=s}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async retrieveTaskByType(e){return await this.tasks.retrieveByType(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const Gw=r=>new E({type:nn,key:r.toString()}),Hw=Object.freeze(Object.defineProperty({__proto__:null,Client:Fc,ONTOLOGY_TYPE:nn,Rack:Yc,keyZ:Ye,newZ:Jo,ontologyID:Gw,rackZ:rn,stateZ:Zs},Symbol.toStringTag,{value:"Module"})),Qt="sy_task_state",ut="sy_task_cmd",Kw="sy_task_set",Jw="sy_task_delete",lt=new Error("Task not created"),Wc=async(r,e)=>{const t=await e.retrieveParents(r);return t.length===0?null:t[0]};class Vc{constructor(e,t,n,s,a=!1,o=!1,c,h=null,d=null,f=null){l(this,"key");l(this,"name");l(this,"internal");l(this,"type");l(this,"config");l(this,"snapshot");l(this,"state");l(this,"frameClient");l(this,"ontologyClient");l(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=s,this.internal=a,this.snapshot=o,c!==null&&(this.state=c),this.frameClient=h,this.ontologyClient=d,this.rangeClient=f}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return Hc(this.key)}async executeCommand(e,t){if(this.frameClient==null)throw lt;const n=await this.frameClient.openWriter(ut),s=Zf.create();return await n.write(ut,[{task:this.key,type:e,key:s,args:t}]),await n.close(),s}async executeCommandSync(e,t,n){if(this.frameClient==null)throw lt;const s=await this.frameClient.openStreamer(Qt),a=await this.executeCommand(e,t);let o;const c=new Promise(h=>setTimeout(()=>h(!1),new O(n).milliseconds));for(;;){const h=await Promise.any([s.read(),c]);if(h===!1)throw new Error("Command timed out");const d=ir.safeParse(h.at(-1).sy_task_state);if(d.success){if(o=d.data,o.key===a)break}else throw d.error}return s.close(),o}async openStateObserver(){if(this.frameClient==null)throw lt;return new Ae(await this.frameClient.openStreamer(Qt),e=>{const t=e.get(Qt);if(t.length===0)return[null,!1];const n=ir.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const s=n.data;return s.task!==this.key?[null,!1]:[s,!0]})}async openCommandObserver(){if(this.frameClient==null)throw lt;return new Ae(await this.frameClient.openStreamer(ut),e=>{const t=e.get(ut);if(t.length===0)return[null,!1];const n=Ys.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const s=n.data;return s.task!==this.key?[null,!1]:[s,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw lt;return this.snapshot?await Wc(this.key,this.ontologyClient):null}}const Xw=i.z.object({rack:Ye.optional(),keys:We.array().optional(),names:i.z.string().array().optional(),types:i.z.string().array().optional(),includeState:i.z.boolean().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),Qw=i.z.object({tasks:X(pr)}),em="/hardware/task/retrieve",tm="/hardware/task/create",rm="/hardware/task/delete",nm="/hardware/task/copy",sm=i.z.object({tasks:ec.array()}),im=i.z.object({tasks:pr.array()}),am=i.z.object({keys:We.array()}),om=i.z.object({}),cm=i.z.object({key:We,name:i.z.string(),snapshot:i.z.boolean()}),lm=i.z.object({task:pr});let Gc=class{constructor(e,t,n,s){l(this,"type",an);l(this,"client");l(this,"frameClient");l(this,"ontologyClient");l(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=s}async create(e){const t=!Array.isArray(e),n=await m(this.client,tm,{tasks:b(e)},sm,im),s=this.sugar(n.tasks);return t?s[0]:s}async delete(e){await m(this.client,rm,{keys:b(e)},am,om)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:s,variant:a}=ai(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=s;const c=await this.execRetrieve(o),h=this.sugar(c);return n&&a!=="rack"?h[0]:h}async copy(e,t,n){const s=await m(this.client,nm,{key:e,name:t,snapshot:n},cm,lm);return this.sugar([s.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return yn("Task",e,n,!0),this.sugar(n)[0]}async retrieveByType(e,t){const n=await this.execRetrieve({types:[e],rack:t});return this.sugar(n)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw lt;return await Wc(e,this.ontologyClient)}async execRetrieve(e){return(await m(this.client,em,e,Xw,Qw)).tasks}sugar(e){const t=!Array.isArray(e),n=b(e).map(({key:s,name:a,type:o,config:c,state:h,internal:d,snapshot:f})=>new Vc(s,a,o,c,d,f,h,this.frameClient,this.ontologyClient,this.rangeClient));return t?n[0]:n}async openTracker(){return await nt(this.frameClient,Kw,Jw,(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Ae(await this.frameClient.openStreamer(Qt),e=>{const t=e.get(Qt);if(t.length===0)return[null,!1];const n=ir.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}async openCommandObserver(){return new Ae(await this.frameClient.openStreamer(ut),e=>{const t=e.get(ut);if(t.length===0)return[null,!1];const n=Ys.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}};const Hc=r=>new E({type:an,key:r}),hm=Object.freeze(Object.defineProperty({__proto__:null,Client:Gc,ONTOLOGY_TYPE:an,Task:Vc,commandZ:Ys,getRackKey:Tg,keyZ:We,newZ:ec,ontologyID:Hc,stateZ:ir,statusZ:Qo,taskZ:pr},Symbol.toStringTag,{value:"Module"})),um=i.z.object({keys:et.array().optional(),for:ie.optional(),search:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),dm=i.z.object({labels:X(wr)}),Wr=class Wr{constructor(e){l(this,"client");this.client=e}async retrieve(e){return await this.execute({keys:b(e)})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Wr.ENDPOINT,e,um,dm);if(n!=null)throw n;return t.labels}};l(Wr,"ENDPOINT","/label/retrieve");let Fr=Wr;const Kc=wr.extend({key:et.optional()}),fm=i.z.object({labels:Kc.array()}),ym=i.z.object({labels:wr.array()}),gm=i.z.object({keys:et.array()}),Jc=i.z.object({id:ie,labels:et.array(),replace:i.z.boolean().optional()}),pm=Jc.omit({replace:!0}),jn=i.z.object({}),wm="/label/create",mm="/label/delete",bm="/label/set",vm="/label/remove";let Xc=class{constructor(e){l(this,"client");this.client=e}async create(e){return(await m(this.client,wm,{labels:b(e)},fm,ym)).labels}async delete(e){await m(this.client,mm,{keys:b(e)},gm,jn)}async set(e,t,{replace:n}={}){await m(this.client,bm,{id:e,labels:t,replace:n},Jc,jn)}async remove(e,t){await m(this.client,vm,{id:e,labels:t},pm,jn)}};const Tm="sy_label_set",Om="sy_label_delete";let Qc=class{constructor(e,t,n){l(this,"type","label");l(this,"retriever");l(this,"writer");l(this,"frameClient");l(this,"ontology");this.writer=new Xc(e),this.retriever=new Fr(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new E(e))}async label(e,t,n={}){await this.writer.set(new E(e),t,n)}async removeLabels(e,t){await this.writer.remove(new E(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await nt(this.frameClient,Tm,Om,Sm)}async trackLabelsOf(e){const t=new He.Observer,n=(await this.retrieveFor(e)).map(a=>({id:el(a.key),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new E(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var c,h;return{key:o.id.key,color:(c=o.data)==null?void 0:c.color,name:(h=o.data)==null?void 0:h.name}}))),t}};const Sm=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(wr).map(t=>({variant:r,key:t.key,value:t})),el=r=>new E({type:Ws,key:r}),Em=Object.freeze(Object.defineProperty({__proto__:null,Client:Qc,ONTOLOGY_TYPE:Ws,Retriever:Fr,Writer:Xc,keyZ:et,labelZ:wr,newZ:Kc,ontologyID:el},Symbol.toStringTag,{value:"Module"})),zm="sy_range_alias_set",Nm="sy_range_alias_delete",Im=i.z.object({range:ae,aliases:i.z.string().array()}),$m=i.z.object({aliases:i.z.record(i.z.string(),Q)}),xm=i.z.object({range:ae,aliases:i.z.record(Q.or(i.z.string()),i.z.string())}),km=i.z.unknown(),Am=i.z.object({range:ae,channels:Q.array()}),Um=i.z.unknown(),Cm=i.z.object({range:ae}),Rm=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),be=class be{constructor(e,t,n){l(this,"frameClient");l(this,"cache",new Map);l(this,"client");l(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",s={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:t.push(o)});if(t.length===0)return s;const a=await m(this.client,be.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Im,$m);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),n?a.aliases[t[0]]:{...s,...a.aliases}}async set(e){await m(this.client,be.SET_ENDPOINT,{range:this.rangeKey,aliases:e},xm,km)}async list(){return(await m(this.client,be.LIST_ENDPOINT,{range:this.rangeKey},Cm,Rm)).aliases}async delete(e){await m(this.client,be.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Am,Um)}async openChangeTracker(){return await nt(this.frameClient,zm,Nm,Dm(this.rangeKey))}};l(be,"SET_ENDPOINT","/range/alias/set"),l(be,"RESOLVE_ENDPOINT","/range/alias/resolve"),l(be,"LIST_ENDPOINT","/range/alias/list"),l(be,"DELETE_ENDPOINT","/range/alias/delete");let Ss=be;const Bm=i.z.object({range:ae,channel:Q,alias:i.z.string()}),Pm="---",Dm=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(Pm)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Bm).map(n=>({variant:e,key:n.alias,value:n})),di=i.z.object({range:ae,key:i.z.string(),value:i.z.string()}),Mm=i.z.object({range:ae,keys:i.z.string().array()}),jm=i.z.object({pairs:X(di)}),Lm=i.z.object({range:ae,pairs:di.array()}),_m=i.z.object({range:ae,keys:i.z.string().array()}),Le=class Le{constructor(e,t,n){l(this,"rangeKey");l(this,"client");l(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await m(this.client,Le.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},Mm,jm);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;Hr(e)?n=Object.entries(e).map(([s,a])=>({range:this.rangeKey,key:s,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await m(this.client,Le.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Lm,i.z.unknown())}async delete(e){await m(this.client,Le.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},_m,i.z.unknown())}async openTracker(){return await nt(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[s,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:s,key:a,value:""}}}):t.parseJSON(di).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};l(Le,"GET_ENDPOINT","/range/kv/get"),l(Le,"SET_ENDPOINT","/range/kv/set"),l(Le,"DELETE_ENDPOINT","/range/kv/delete");let lr=Le;class tl{constructor(e,t=q.ZERO,n,s,a,o,c,h,d,f,u){l(this,"key");l(this,"name");l(this,"kv");l(this,"timeRange");l(this,"color");l(this,"channels");l(this,"aliaser");l(this,"frameClient");l(this,"labelClient");l(this,"ontologyClient");l(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=s,this.kv=o,this.aliaser=c,this.channels=h,this.labelClient=d,this.ontologyClient=f,this.rangeClient=u}get ontologyID(){return je(this.key)}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new ke(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(je(this.key))}async addLabel(...e){await this.labelClient.label(je(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(je(this.key),e)}async openChildRangeTracker(){const e=new He.Observer,t=(await this.retrieveChildren()).map(s=>{const a=je(s.key);return{id:a,key:a.toString(),name:s.name,data:s.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(s=>e.notify(this.rangeClient.resourcesToRanges(s))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new He.Observer,t=await this.retrieveParent();if(t==null)return null;const n=je(t.key),s={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[s],relationshipDirection:"to"});return a.onChange(o=>{const c=this.rangeClient.resourcesToRanges(o);if(c.length===0)return;const h=c[0];e.notify(h)}),e.setCloser(async()=>await a.close()),e}}const Zm=(r,e)=>Ff(r.timeRange,e.timeRange),qm=i.z.object({keys:ae.array().optional(),names:i.z.array(i.z.string()).optional(),term:i.z.string().optional(),overlapsWith:q.z.optional(),limit:i.z.number().int().optional(),offset:i.z.number().int().optional(),hasLabels:et.array().optional()}),Fm="/range/retrieve",Ym=i.z.object({ranges:X(mr)});let rl=class{constructor(e,t,n,s,a,o){l(this,"type","range");l(this,"frameClient");l(this,"writer");l(this,"unaryClient");l(this,"channels");l(this,"labelClient");l(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=s,this.labelClient=a,this.ontologyClient=o}async create(e,t){const n=!Array.isArray(e),s=this.sugarMany(await this.writer.create(b(e),t));return n?s[0]:s}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new q(e)});const{single:t,actual:n,variant:s,normalized:a,empty:o}=rc(e);if(o)return[];const c=await this.execRetrieve({[s]:a});if(!t)return c;if(c.length===0)throw new Je(`range matching ${n} not found`);if(c.length>1)throw new Xe(`multiple ranges matching ${n} found`);return c[0]}getKV(e){return new lr(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await m(this.unaryClient,Fm,e,qm,Ym);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents(je(e));if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new tl(e.name,e.timeRange,e.key,e.color,this.frameClient,new lr(e.key,this.unaryClient,this.frameClient),new Ss(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await nt(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toUUIDs().map(s=>({variant:e,key:s,value:void 0})):this.sugarMany(t.parseJSON(mr)).map(s=>({variant:e,key:s.key,value:s})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,s;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new q((n=e.data)==null?void 0:n.timeRange),color:(s=e.data)==null?void 0:s.color})}};const je=r=>new E({type:Gs,key:r}),Wm=r=>new E({type:Hs,key:r}),Vm=i.z.object({ranges:mr.array()}),Gm=i.z.object({parent:ie.optional(),ranges:tc.array()}),Hm=i.z.object({keys:ae.array()}),Km=i.z.object({}),Jm=i.z.object({key:ae,name:Vs}),Xm=i.z.object({}),Qm="/range/create",eb="/range/delete",tb="/range/rename";class nl{constructor(e){l(this,"client");this.client=e}async rename(e,t){await m(this.client,tb,{key:e,name:t},Jm,Xm)}async create(e,t){return(await m(this.client,Qm,{ranges:e,...t},Gm,Vm)).ranges}async delete(e){await m(this.client,eb,{keys:e},Hm,Km)}}const rb=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:Hs,Client:rl,KV:lr,ONTOLOGY_TYPE:Gs,Range:tl,Writer:nl,aliasOntologyID:Wm,analyzeParams:rc,keyZ:ae,nameZ:Vs,newZ:tc,ontologyID:je,payloadZ:mr,sort:Zm},Symbol.toStringTag,{value:"Module"})),nb="/api/v1/";class sb{constructor(e,t={},n=!1){l(this,"url");l(this,"unary");l(this,"stream");l(this,"secure");this.secure=n,this.url=e.child(nb);const s=new Qe.JSONCodec;this.unary=ed(new Qu(this.url,s,this.secure),t),this.stream=new ad(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const ib="/workspace/lineplot/retrieve",ab="/workspace/lineplot/create",ob="/workspace/lineplot/rename",cb="/workspace/lineplot/set-data",lb="/workspace/lineplot/delete",hb=i.z.object({keys:Nt.array()}),ub=i.z.object({workspace:Ee,linePlots:sc.array()}),db=i.z.object({key:Nt,name:i.z.string()}),fb=i.z.object({key:Nt,data:i.z.string()}),yb=i.z.object({keys:Nt.array()}),gb=i.z.object({linePlots:X(on)}),pb=i.z.object({linePlots:on.array()}),Ln=i.z.object({});let sl=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,ab,{workspace:e,linePlots:b(t)},ub,pb);return n?s.linePlots:s.linePlots[0]}async rename(e,t){await m(this.client,ob,{key:e,name:t},db,Ln)}async setData(e,t){await m(this.client,cb,{key:e,data:JSON.stringify(t)},fb,Ln)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,ib,{keys:b(e)},hb,gb);return t?n.linePlots:n.linePlots[0]}async delete(e){await m(this.client,lb,{keys:b(e)},yb,Ln)}};const wb=r=>new E({type:Js,key:r}),mb=Object.freeze(Object.defineProperty({__proto__:null,Client:sl,ONTOLOGY_TYPE:Js,keyZ:Nt,linePlotZ:on,newZ:sc,ontologyID:wb},Symbol.toStringTag,{value:"Module"})),bb="/workspace/log/retrieve",vb="/workspace/log/create",Tb="/workspace/log/rename",Ob="/workspace/log/set-data",Sb="/workspace/log/delete",Eb=i.z.object({keys:It.array()}),zb=i.z.object({workspace:Ee,logs:ic.array()}),Nb=i.z.object({key:It,name:i.z.string()}),Ib=i.z.object({key:It,data:i.z.string()}),$b=i.z.object({keys:It.array()}),xb=i.z.object({logs:cn.array()}),kb=i.z.object({logs:cn.array()}),_n=i.z.object({});let il=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,vb,{workspace:e,logs:b(t)},zb,kb);return n?s.logs:s.logs[0]}async rename(e,t){await m(this.client,Tb,{key:e,name:t},Nb,_n)}async setData(e,t){await m(this.client,Ob,{key:e,data:JSON.stringify(t)},Ib,_n)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,bb,{keys:b(e)},Eb,xb);return t?n.logs:n.logs[0]}async delete(e){await m(this.client,Sb,{keys:b(e)},$b,_n)}};const Ab=r=>new E({type:Xs,key:r}),Ub=Object.freeze(Object.defineProperty({__proto__:null,Client:il,ONTOLOGY_TYPE:Xs,keyZ:It,logZ:cn,newZ:ic,ontologyID:Ab},Symbol.toStringTag,{value:"Module"})),Cb="/workspace/schematic/retrieve",Rb="/workspace/schematic/create",Bb="/workspace/schematic/rename",Pb="/workspace/schematic/set-data",Db="/workspace/schematic/delete",Mb="/workspace/schematic/copy",jb=i.z.object({keys:rt.array()}),Lb=i.z.object({workspace:Ee,schematics:cc.array()}),_b=i.z.object({key:rt,name:i.z.string()}),Zb=i.z.object({key:rt,data:i.z.string()}),qb=i.z.object({keys:rt.array()}),Fb=i.z.object({key:rt,name:i.z.string(),snapshot:i.z.boolean()}),Yb=i.z.object({schematics:X(Qs)}),Wb=i.z.object({schematics:Qs.array()}),Vb=i.z.object({schematic:un}),Zn=i.z.object({});let al=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,Rb,{workspace:e,schematics:b(t)},Lb,Wb);return n?s.schematics:s.schematics[0]}async rename(e,t){await m(this.client,Bb,{key:e,name:t},_b,Zn)}async setData(e,t){await m(this.client,Pb,{key:e,data:JSON.stringify(t)},Zb,Zn)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Cb,{keys:b(e)},jb,Yb);return t?n.schematics:n.schematics[0]}async delete(e){await m(this.client,Db,{keys:b(e)},qb,Zn)}async copy(e,t,n){return(await m(this.client,Mb,{key:e,name:t,snapshot:n},Fb,Vb)).schematic}};const Gb=r=>new E({type:ei,key:r}),Hb=Object.freeze(Object.defineProperty({__proto__:null,Client:al,ONTOLOGY_TYPE:ei,keyZ:rt,newZ:cc,ontologyID:Gb,remoteZ:Qs,schematicZ:un},Symbol.toStringTag,{value:"Module"})),Kb="/workspace/table/retrieve",Jb="/workspace/table/create",Xb="/workspace/table/rename",Qb="/workspace/table/set-data",ev="/workspace/table/delete",tv=i.z.object({keys:$t.array()}),rv=i.z.object({workspace:Ee,tables:lc.array()}),nv=i.z.object({key:$t,name:i.z.string()}),sv=i.z.object({key:$t,data:i.z.string()}),iv=i.z.object({keys:$t.array()}),av=i.z.object({tables:ri.array()}),ov=i.z.object({tables:ri.array()}),qn=i.z.object({});let ol=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,Jb,{workspace:e,tables:b(t)},rv,ov);return n?s.tables:s.tables[0]}async rename(e,t){await m(this.client,Xb,{key:e,name:t},nv,qn)}async setData(e,t){await m(this.client,Qb,{key:e,data:JSON.stringify(t)},sv,qn)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Kb,{keys:b(e)},tv,av);return t?n.tables:n.tables[0]}async delete(e){await m(this.client,ev,{keys:b(e)},iv,qn)}};const cv=r=>new E({type:ni,key:r}),lv=Object.freeze(Object.defineProperty({__proto__:null,Client:ol,ONTOLOGY_TYPE:ni,keyZ:$t,newZ:lc,ontologyID:cv,remoteZ:ri,tableZ:ti},Symbol.toStringTag,{value:"Module"})),Ar="/workspace/retrieve",hv="/workspace/create",uv="/workspace/rename",dv="/workspace/set-layout",fv="/workspace/delete",Ur=i.z.object({keys:Ee.array().optional(),search:i.z.string().optional(),author:tt.optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),yv=i.z.object({workspaces:ac.array()}),gv=i.z.object({key:Ee,name:i.z.string()}),pv=i.z.object({key:Ee,layout:i.z.string()}),wv=i.z.object({keys:Ee.array()}),Cr=i.z.object({workspaces:X(ln)}),mv=i.z.object({workspaces:oc.array()}),Fn=i.z.object({});class cl{constructor(e){l(this,"type",hn);l(this,"schematic");l(this,"linePlot");l(this,"log");l(this,"table");l(this,"client");this.client=e,this.schematic=new al(e),this.linePlot=new sl(e),this.log=new il(e),this.table=new ol(e)}async create(e){const t=Array.isArray(e),n=await m(this.client,hv,{workspaces:b(e)},yv,mv);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await m(this.client,uv,{key:e,name:t},gv,Fn)}async setLayout(e,t){await m(this.client,dv,{key:e,layout:JSON.stringify(t)},pv,Fn)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Ar,{keys:b(e)},Ur,Cr);return t?n.workspaces:n.workspaces[0]}async retrieveByAuthor(e){return(await m(this.client,Ar,{author:e},Ur,Cr)).workspaces}async search(e){return(await m(this.client,Ar,{search:e},Ur,Cr)).workspaces}async page(e,t){return(await m(this.client,Ar,{offset:e,limit:t},Ur,Cr)).workspaces}async delete(e){await m(this.client,fv,{keys:b(e)},wv,Fn)}}const bv=r=>new E({type:hn,key:r}),vv=Object.freeze(Object.defineProperty({__proto__:null,Client:cl,ONTOLOGY_TYPE:hn,keyZ:Ee,newZ:ac,ontologyID:bv,remoteZ:oc,workspaceZ:ln},Symbol.toStringTag,{value:"Module"})),ll=i.z.object({host:i.z.string({error:"Host is required"}).min(1,"Host is required"),port:i.z.number({error:"Port is required"}).or(i.z.string({error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:O.z.default(O.seconds(30)),secure:i.z.boolean().optional().default(!1),name:i.z.string().optional(),retry:Do.breakerConfig.optional()});class hl extends jc{constructor(t){const n=ll.parse(t),{host:s,port:a,username:o,password:c,connectivityPollFrequency:h,secure:d,retry:f}=n,u=new sb(new yy({host:s,port:Number(a)}),f,d);u.use(bg);let N;o!=null&&c!=null&&(N=new Hp(u.unary,{username:o,password:c}),u.use(N.middleware()));const S=new oi(new ar(u.unary)),j=new $c(u.unary,S);super(u.stream,u.unary,S);l(this,"createdAt");l(this,"props");l(this,"ranges");l(this,"channels");l(this,"auth");l(this,"user");l(this,"access");l(this,"connectivity");l(this,"ontology");l(this,"workspaces");l(this,"labels");l(this,"hardware");l(this,"control");l(this,"transport");l(this,"clientVersion","0.42.1");this.createdAt=z.now(),this.props=n,this.auth=N,this.transport=u,this.channels=new zc(this,S,u.unary,j),this.connectivity=new cr(u.unary,h,this.clientVersion,n.name),this.control=new _c(this),this.ontology=new mc(u.unary,this);const U=new nl(this.transport.unary);this.labels=new Qc(this.transport.unary,this,this.ontology),this.ranges=new rl(this,U,this.transport.unary,S,this.labels,this.ontology),this.access=new Tc(this.transport.unary),this.user=new xc(this.transport.unary),this.workspaces=new cl(this.transport.unary);const ee=new qc(this.transport.unary,this),A=new Gc(this.transport.unary,this,this.ontology,this.ranges),st=new Fc(this.transport.unary,A,this);this.hardware=new Zc(A,st,ee)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}l(hl,"connectivity",cr);exports.AuthError=sr;exports.Channel=ci;exports.ContiguityError=pg;exports.DataType=x;exports.Density=ne;exports.Frame=V;exports.MultiSeries=Ro;exports.MultipleFoundError=Xe;exports.NotFoundError=Je;exports.QueryError=ke;exports.Rate=cs;exports.RouteError=ms;exports.Series=_e;exports.Synnax=hl;exports.TimeRange=q;exports.TimeSpan=O;exports.TimeStamp=z;exports.UnexpectedError=mt;exports.ValidationError=F;exports.access=tp;exports.channel=Op;exports.connection=Jp;exports.control=$w;exports.device=_w;exports.framer=Ow;exports.group=Ag;exports.hardware=xw;exports.isCalculated=or;exports.label=Em;exports.linePlot=mb;exports.log=Ub;exports.ontology=Lg;exports.policy=ep;exports.rack=Hw;exports.ranger=rb;exports.schematic=Hb;exports.signals=kw;exports.synnaxPropsZ=ll;exports.table=lv;exports.task=hm;exports.user=_p;exports.workspace=vv;
55
+ `);return d});return new V(c,o.series)}const n=[],s=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,h]=a[o],d=await this.fetchChannel(c),f=new _e({data:h,dataType:d.dataType});n.push(d.key),s.push(f)}return new V(n,s)}}class Dc{constructor(e,t){l(this,"name");l(this,"stream");this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
56
+ Please report this error to the Synnax team.`),t!=null){if(ue.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Os=new O(-1);var fi=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(fi||{}),Mc=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Mc||{});const pw=i.z.object({command:i.z.enum(fi),span:O.z.optional(),bounds:q.z.optional(),stamp:z.z.optional(),keys:Q.array().optional(),chunkSize:i.z.number().optional()}),ww=i.z.object({variant:i.z.enum(Mc),ack:i.z.boolean(),command:i.z.enum(fi),error:Tt.payloadZ.optional().nullable(),frame:tn.optional()}),er=class er{constructor(e,t){l(this,"stream");l(this,"adapter");l(this,"value");this.stream=new Dc("Iterator",e),this.value=new V,this.adapter=t}static async _open(e,t,n,s,a={}){const o=await gn.open(n,t),c=await s.stream(er.ENDPOINT,pw,ww),h=new er(c,o);return await h.execute({command:0,keys:o.keys,bounds:new q(e),chunkSize:a.chunkSize??1e5}),h}async next(e=Os){return await this.execute({command:1,span:new O(e)})}async prev(e=Os){return await this.execute({command:2,span:new O(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new z(e)})}async seekGE(e){return await this.execute({command:6,stamp:new z(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new mw(this)}async execute(e){for(this.stream.send(e),this.value=new V;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new V(t.frame)))}}};l(er,"ENDPOINT","/frame/iterate");let qr=er;class mw{constructor(e){l(this,"iter");l(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const bw=i.z.object({keys:i.z.number().array(),downSampleFactor:i.z.number()}),vw=i.z.object({frame:tn}),Tw="/frame/stream",jc=(r,e)=>async t=>{let n;Array.isArray(t)||typeof t!="object"?n={channels:t,downSampleFactor:1}:n=t;const s=await gn.open(r,n.channels);n.useExperimentalCodec&&(e=e.withCodec(new gw(s.codec)));const a=await e.stream(Tw,bw,vw),o=new Ow(a,s);a.send({keys:s.keys,downSampleFactor:n.downSampleFactor??1});const[,c]=await a.receive();if(c!=null)throw c;return o},Lc=async(r,e,t)=>await jc(r,e)(t);class Ow{constructor(e,t){l(this,"stream");l(this,"adapter");l(this,"downsampleFactor");this.stream=new Dc("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ue.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new V((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys,downSampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class pn{constructor(e,t){l(this,"wrapped_",null);l(this,"breaker");l(this,"opener");l(this,"config");this.opener=e,Array.isArray(t)||typeof t!="object"?this.config={channels:t,downSampleFactor:1}:this.config=t,this.breaker=new jo.Breaker({maxRetries:5e3,baseInterval:O.seconds(1),scale:1})}static async open(e,t){const n=new pn(e,t);return await n.runStreamer(),n}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=e;try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ue.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(ue.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class Ae extends He.Observer{constructor(t,n){super(n);l(this,"streamer");l(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}const Sw=r=>new E({type:qs,key:r.toString()}),Ea=r=>Array.isArray(r)||typeof r!="object"||typeof r=="object"&&"key"in r?{channels:r}:r;let _c=class{constructor(e,t,n){l(this,"streamClient");l(this,"retriever");l(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new nw(t)}async openIterator(e,t,n){return await qr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return await Rc._open(this.retriever,this.streamClient,Ea(e))}async openStreamer(e){return await Lc(this.retriever,this.streamClient,Ea(e))}async write(e,t,n){if(n==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:St.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:O.MAX});await o.write(a),await o.commit(),await o.close();return}const s=await this.openWriter({start:e,channels:t,mode:St.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:O.MAX});await s.write(t,n),await s.close()}async read(e,t){const{single:n}=Oe(t),s=await this.readFrame(e,t);return n?s.get(t):s}async readFrame(e,t){const n=await this.openIterator(e,t),s=new V;try{for await(const a of n)s.push(a)}finally{await n.close()}return s}async delete(e,t){const{normalized:n,variant:s}=Oe(e);return s==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Ew=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:iw,AUTO_SPAN:Os,Client:_c,Frame:V,HardenedStreamer:pn,Iterator:qr,ONTOLOGY_TYPE:qs,ObservableStreamer:Ae,Writer:Rc,WriterClosedError:Ts,WriterCommand:Ot,WriterMode:St,createStreamOpener:jc,frameZ:tn,ontologyID:Sw,openStreamer:Lc,seriesFromPayload:Jo,seriesToPayload:Xo},Symbol.toStringTag,{value:"Module"})),zw=Ke.ABSOLUTE_AUTHORITY,Nw=Ke.ZERO_AUTHORITY,Iw=Ke.stateZ(i.z.number()),$w=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`},xw=i.z.object({transfers:i.z.array(Ke.transferZ)});class Zc extends Ae{constructor(t){super(t,n=>{const s=this.codec.decode(n.series[0].buffer,xw);return this.merge(s),[s.transfers,!0]});l(this,"states");l(this,"codec");this.states=new Map,this.codec=new Qe.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const za="sy_node_1_control";let qc=class{constructor(e){l(this,"framer");this.framer=e}async openStateTracker(){const e=await pn.open(async()=>await this.framer.openStreamer(za),za);return new Zc(e)}};const kw=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:zw,Client:qc,StateTracker:Zc,ZERO_AUTHORITY:Nw,stateZ:Iw,transferString:$w},Symbol.toStringTag,{value:"Module"}));let Fc=class{constructor(e,t,n){l(this,"tasks");l(this,"racks");l(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const Aw=Object.freeze(Object.defineProperty({__proto__:null,Client:Fc},Symbol.toStringTag,{value:"Module"})),nt=async(r,e,t,n)=>{const s=await r.openStreamer([e,t]),a=o=>{const c=[];return t!=null&&c.push(...o.get(t).series.flatMap(h=>n("delete",h))),e!=null&&c.push(...o.get(e).series.flatMap(h=>n("set",h))),[c,c.length>0]};return new Ae(s,a)},Uw=Object.freeze(Object.defineProperty({__proto__:null,openObservable:nt},Symbol.toStringTag,{value:"Module"})),Cw="sy_device_set",Rw="sy_device_delete",Na="sy_device_state",Cn="/hardware/device/retrieve",Bw="/hardware/device/create",Pw="/hardware/device/delete",Dw=i.z.object({devices:ec.array()}),Mw=i.z.object({devices:gr.array()}),jw=i.z.object({keys:yr.array()}),Lw=i.z.object({}),Rn=i.z.object({keys:yr.array().optional(),names:i.z.string().array().optional(),makes:i.z.string().array().optional(),models:i.z.string().array().optional(),locations:i.z.string().array().optional(),racks:Ye.array().optional(),search:i.z.string().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),ignoreNotFound:i.z.boolean().optional(),includeState:i.z.boolean().optional()}),Bn=i.z.object({devices:X(gr)});let Yc=class{constructor(e,t){l(this,"type",sn);l(this,"client");l(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),s=await m(this.client,Cn,{keys:b(e),...t},Rn,Bn);return yn("Device",e,s.devices,n),n?s.devices[0]:s.devices}async search(e,t){return(await m(this.client,Cn,{search:e,...t},Rn,Bn)).devices}async page(e,t,n){return(await m(this.client,Cn,{offset:e,limit:t,...n},Rn,Bn)).devices}async create(e){const t=!Array.isArray(e),n=await m(this.client,Bw,{devices:b(e)},Dw,Mw);return t?n.devices[0]:n.devices}async delete(e){await m(this.client,Pw,{keys:b(e)},jw,Lw)}async openDeviceTracker(){return await nt(this.frameClient,Cw,Rw,_w)}async openStateObserver(){return new Ae(await this.frameClient.openStreamer(Na),e=>{const t=e.get(Na);return t.length===0?[null,!1]:[t.parseJSON(Ws),!0]})}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const _w=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(gr).map(t=>({variant:r,key:t.key,value:t})),Zw=r=>new E({type:sn,key:r}),qw=Object.freeze(Object.defineProperty({__proto__:null,Client:Yc,ONTOLOGY_TYPE:sn,deviceZ:gr,keyZ:yr,newZ:ec,ontologyID:Zw,stateZ:Ws},Symbol.toStringTag,{value:"Module"})),Pn="/hardware/rack/retrieve",Fw="/hardware/rack/create",Yw="/hardware/rack/delete",Ia="sy_rack_state",Dn=i.z.object({keys:Ye.array().optional(),names:i.z.string().array().optional(),search:i.z.string().optional(),embedded:i.z.boolean().optional(),hostIsNode:i.z.boolean().optional(),limit:i.z.number().optional(),offset:i.z.number().optional(),includeState:i.z.boolean().optional()}),Mn=i.z.object({racks:X(rn)}),Ww=i.z.object({racks:Qo.array()}),Vw=i.z.object({racks:rn.array()}),Gw=i.z.object({keys:Ye.array()}),Hw=i.z.object({});let Wc=class{constructor(e,t,n){l(this,"type",nn);l(this,"client");l(this,"tasks");l(this,"frameClient");this.client=e,this.tasks=t,this.frameClient=n}async delete(e){await m(this.client,Yw,{keys:b(e)},Gw,Hw)}async create(e){const t=!Array.isArray(e),n=await m(this.client,Fw,{racks:b(e)},Ww,Vw),s=this.sugar(n.racks);return t?s[0]:s}async search(e){const t=await m(this.client,Pn,{search:e},Dn,Mn);return this.sugar(t.racks)}async page(e,t){const n=await m(this.client,Pn,{offset:e,limit:t},Dn,Mn);return this.sugar(n.racks)}async retrieve(e,t){const{variant:n,normalized:s,single:a}=ci(e,{string:"names",number:"keys"}),o=await m(this.client,Pn,{[n]:s,includeState:t==null?void 0:t.includeState},Dn,Mn),c=this.sugar(o.racks);return yn("Rack",e,c,a),a?c[0]:c}async openStateObserver(){return new Ae(await this.frameClient.openStreamer(Ia),e=>{const t=e.get(Ia);return t.length===0?[[],!1]:[t.parseJSON(Fs),!0]})}sugar(e){return e.map(({key:t,name:n,state:s})=>new Vc(t,n,this.tasks,s))}};class Vc{constructor(e,t,n,s){l(this,"key");l(this,"name");l(this,"state");l(this,"tasks");this.key=e,this.name=t,this.tasks=n,this.state=s}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async retrieveTaskByType(e){return await this.tasks.retrieveByType(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const Kw=r=>new E({type:nn,key:r.toString()}),Jw=Object.freeze(Object.defineProperty({__proto__:null,Client:Wc,ONTOLOGY_TYPE:nn,Rack:Vc,keyZ:Ye,newZ:Qo,ontologyID:Kw,rackZ:rn,stateZ:Fs},Symbol.toStringTag,{value:"Module"})),Qt="sy_task_state",ut="sy_task_cmd",Xw="sy_task_set",Qw="sy_task_delete",lt=new Error("Task not created"),Gc=async(r,e)=>{const t=await e.retrieveParents(r);return t.length===0?null:t[0]};class Hc{constructor(e,t,n,s,a=!1,o=!1,c,h=null,d=null,f=null){l(this,"key");l(this,"name");l(this,"internal");l(this,"type");l(this,"config");l(this,"snapshot");l(this,"state");l(this,"frameClient");l(this,"ontologyClient");l(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=s,this.internal=a,this.snapshot=o,c!==null&&(this.state=c),this.frameClient=h,this.ontologyClient=d,this.rangeClient=f}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return Jc(this.key)}async executeCommand(e,t){if(this.frameClient==null)throw lt;const n=await this.frameClient.openWriter(ut),s=Ff.create();return await n.write(ut,[{task:this.key,type:e,key:s,args:t}]),await n.close(),s}async executeCommandSync(e,t,n){if(this.frameClient==null)throw lt;const s=await this.frameClient.openStreamer(Qt),a=await this.executeCommand(e,t);let o;const c=new Promise(h=>setTimeout(()=>h(!1),new O(n).milliseconds));for(;;){const h=await Promise.any([s.read(),c]);if(h===!1)throw new Error("Command timed out");const d=ir.safeParse(h.at(-1).sy_task_state);if(d.success){if(o=d.data,o.key===a)break}else throw d.error}return s.close(),o}async openStateObserver(){if(this.frameClient==null)throw lt;return new Ae(await this.frameClient.openStreamer(Qt),e=>{const t=e.get(Qt);if(t.length===0)return[null,!1];const n=ir.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const s=n.data;return s.task!==this.key?[null,!1]:[s,!0]})}async openCommandObserver(){if(this.frameClient==null)throw lt;return new Ae(await this.frameClient.openStreamer(ut),e=>{const t=e.get(ut);if(t.length===0)return[null,!1];const n=Vs.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const s=n.data;return s.task!==this.key?[null,!1]:[s,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw lt;return this.snapshot?await Gc(this.key,this.ontologyClient):null}}const em=i.z.object({rack:Ye.optional(),keys:We.array().optional(),names:i.z.string().array().optional(),types:i.z.string().array().optional(),includeState:i.z.boolean().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),tm=i.z.object({tasks:X(pr)}),rm="/hardware/task/retrieve",nm="/hardware/task/create",sm="/hardware/task/delete",im="/hardware/task/copy",am=i.z.object({tasks:rc.array()}),om=i.z.object({tasks:pr.array()}),cm=i.z.object({keys:We.array()}),lm=i.z.object({}),hm=i.z.object({key:We,name:i.z.string(),snapshot:i.z.boolean()}),um=i.z.object({task:pr});let Kc=class{constructor(e,t,n,s){l(this,"type",an);l(this,"client");l(this,"frameClient");l(this,"ontologyClient");l(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=s}async create(e){const t=!Array.isArray(e),n=await m(this.client,nm,{tasks:b(e)},am,om),s=this.sugar(n.tasks);return t?s[0]:s}async delete(e){await m(this.client,sm,{keys:b(e)},cm,lm)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:s,variant:a}=ci(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=s;const c=await this.execRetrieve(o),h=this.sugar(c);return n&&a!=="rack"?h[0]:h}async copy(e,t,n){const s=await m(this.client,im,{key:e,name:t,snapshot:n},hm,um);return this.sugar([s.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return yn("Task",e,n,!0),this.sugar(n)[0]}async retrieveByType(e,t){const n=await this.execRetrieve({types:[e],rack:t});return this.sugar(n)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw lt;return await Gc(e,this.ontologyClient)}async execRetrieve(e){return(await m(this.client,rm,e,em,tm)).tasks}sugar(e){const t=!Array.isArray(e),n=b(e).map(({key:s,name:a,type:o,config:c,state:h,internal:d,snapshot:f})=>new Hc(s,a,o,c,d,f,h,this.frameClient,this.ontologyClient,this.rangeClient));return t?n[0]:n}async openTracker(){return await nt(this.frameClient,Xw,Qw,(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Ae(await this.frameClient.openStreamer(Qt),e=>{const t=e.get(Qt);if(t.length===0)return[null,!1];const n=ir.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}async openCommandObserver(){return new Ae(await this.frameClient.openStreamer(ut),e=>{const t=e.get(ut);if(t.length===0)return[null,!1];const n=Vs.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}};const Jc=r=>new E({type:an,key:r}),dm=Object.freeze(Object.defineProperty({__proto__:null,Client:Kc,ONTOLOGY_TYPE:an,Task:Hc,commandZ:Vs,getRackKey:Sg,keyZ:We,newZ:rc,ontologyID:Jc,stateZ:ir,statusZ:tc,taskZ:pr},Symbol.toStringTag,{value:"Module"})),fm=i.z.object({keys:et.array().optional(),for:ie.optional(),search:i.z.string().optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),ym=i.z.object({labels:X(wr)}),Wr=class Wr{constructor(e){l(this,"client");this.client=e}async retrieve(e){return await this.execute({keys:b(e)})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Wr.ENDPOINT,e,fm,ym);if(n!=null)throw n;return t.labels}};l(Wr,"ENDPOINT","/label/retrieve");let Fr=Wr;const Xc=wr.extend({key:et.optional()}),gm=i.z.object({labels:Xc.array()}),pm=i.z.object({labels:wr.array()}),wm=i.z.object({keys:et.array()}),Qc=i.z.object({id:ie,labels:et.array(),replace:i.z.boolean().optional()}),mm=Qc.omit({replace:!0}),jn=i.z.object({}),bm="/label/create",vm="/label/delete",Tm="/label/set",Om="/label/remove";let el=class{constructor(e){l(this,"client");this.client=e}async create(e){return(await m(this.client,bm,{labels:b(e)},gm,pm)).labels}async delete(e){await m(this.client,vm,{keys:b(e)},wm,jn)}async set(e,t,{replace:n}={}){await m(this.client,Tm,{id:e,labels:t,replace:n},Qc,jn)}async remove(e,t){await m(this.client,Om,{id:e,labels:t},mm,jn)}};const Sm="sy_label_set",Em="sy_label_delete";let tl=class{constructor(e,t,n){l(this,"type","label");l(this,"retriever");l(this,"writer");l(this,"frameClient");l(this,"ontology");this.writer=new el(e),this.retriever=new Fr(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new E(e))}async label(e,t,n={}){await this.writer.set(new E(e),t,n)}async removeLabels(e,t){await this.writer.remove(new E(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await nt(this.frameClient,Sm,Em,zm)}async trackLabelsOf(e){const t=new He.Observer,n=(await this.retrieveFor(e)).map(a=>({id:rl(a.key),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new E(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var c,h;return{key:o.id.key,color:(c=o.data)==null?void 0:c.color,name:(h=o.data)==null?void 0:h.name}}))),t}};const zm=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(wr).map(t=>({variant:r,key:t.key,value:t})),rl=r=>new E({type:Gs,key:r}),Nm=Object.freeze(Object.defineProperty({__proto__:null,Client:tl,ONTOLOGY_TYPE:Gs,Retriever:Fr,Writer:el,keyZ:et,labelZ:wr,newZ:Xc,ontologyID:rl},Symbol.toStringTag,{value:"Module"})),Im="sy_range_alias_set",$m="sy_range_alias_delete",xm=i.z.object({range:ae,aliases:i.z.string().array()}),km=i.z.object({aliases:i.z.record(i.z.string(),Q)}),Am=i.z.object({range:ae,aliases:i.z.record(Q.or(i.z.string()),i.z.string())}),Um=i.z.unknown(),Cm=i.z.object({range:ae,channels:Q.array()}),Rm=i.z.unknown(),Bm=i.z.object({range:ae}),Pm=i.z.object({aliases:i.z.record(i.z.string(),i.z.string())}),be=class be{constructor(e,t,n){l(this,"frameClient");l(this,"cache",new Map);l(this,"client");l(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",s={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const c=this.cache.get(o);c!=null?s[o]=c:t.push(o)});if(t.length===0)return s;const a=await m(this.client,be.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},xm,km);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),n?a.aliases[t[0]]:{...s,...a.aliases}}async set(e){await m(this.client,be.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Am,Um)}async list(){return(await m(this.client,be.LIST_ENDPOINT,{range:this.rangeKey},Bm,Pm)).aliases}async delete(e){await m(this.client,be.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Cm,Rm)}async openChangeTracker(){return await nt(this.frameClient,Im,$m,jm(this.rangeKey))}};l(be,"SET_ENDPOINT","/range/alias/set"),l(be,"RESOLVE_ENDPOINT","/range/alias/resolve"),l(be,"LIST_ENDPOINT","/range/alias/list"),l(be,"DELETE_ENDPOINT","/range/alias/delete");let Ss=be;const Dm=i.z.object({range:ae,channel:Q,alias:i.z.string()}),Mm="---",jm=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(Mm)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Dm).map(n=>({variant:e,key:n.alias,value:n})),yi=i.z.object({range:ae,key:i.z.string(),value:i.z.string()}),Lm=i.z.object({range:ae,keys:i.z.string().array()}),_m=i.z.object({pairs:X(yi)}),Zm=i.z.object({range:ae,pairs:yi.array()}),qm=i.z.object({range:ae,keys:i.z.string().array()}),Le=class Le{constructor(e,t,n){l(this,"rangeKey");l(this,"client");l(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await m(this.client,Le.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},Lm,_m);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;Hr(e)?n=Object.entries(e).map(([s,a])=>({range:this.rangeKey,key:s,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await m(this.client,Le.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Zm,i.z.unknown())}async delete(e){await m(this.client,Le.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},qm,i.z.unknown())}async openTracker(){return await nt(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[s,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:s,key:a,value:""}}}):t.parseJSON(yi).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};l(Le,"GET_ENDPOINT","/range/kv/get"),l(Le,"SET_ENDPOINT","/range/kv/set"),l(Le,"DELETE_ENDPOINT","/range/kv/delete");let lr=Le;class nl{constructor(e,t=q.ZERO,n,s,a,o,c,h,d,f,u){l(this,"key");l(this,"name");l(this,"kv");l(this,"timeRange");l(this,"color");l(this,"channels");l(this,"aliaser");l(this,"frameClient");l(this,"labelClient");l(this,"ontologyClient");l(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=s,this.kv=o,this.aliaser=c,this.channels=h,this.labelClient=d,this.ontologyClient=f,this.rangeClient=u}get ontologyID(){return je(this.key)}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new ke(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(je(this.key))}async addLabel(...e){await this.labelClient.label(je(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(je(this.key),e)}async openChildRangeTracker(){const e=new He.Observer,t=(await this.retrieveChildren()).map(s=>{const a=je(s.key);return{id:a,key:a.toString(),name:s.name,data:s.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(s=>e.notify(this.rangeClient.resourcesToRanges(s))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new He.Observer,t=await this.retrieveParent();if(t==null)return null;const n=je(t.key),s={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[s],relationshipDirection:"to"});return a.onChange(o=>{const c=this.rangeClient.resourcesToRanges(o);if(c.length===0)return;const h=c[0];e.notify(h)}),e.setCloser(async()=>await a.close()),e}}const Fm=(r,e)=>Wf(r.timeRange,e.timeRange),Ym=i.z.object({keys:ae.array().optional(),names:i.z.array(i.z.string()).optional(),term:i.z.string().optional(),overlapsWith:q.z.optional(),limit:i.z.number().int().optional(),offset:i.z.number().int().optional(),hasLabels:et.array().optional()}),Wm="/range/retrieve",Vm=i.z.object({ranges:X(mr)});let sl=class{constructor(e,t,n,s,a,o){l(this,"type","range");l(this,"frameClient");l(this,"writer");l(this,"unaryClient");l(this,"channels");l(this,"labelClient");l(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=s,this.labelClient=a,this.ontologyClient=o}async create(e,t){const n=!Array.isArray(e),s=this.sugarMany(await this.writer.create(b(e),t));return n?s[0]:s}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new q(e)});const{single:t,actual:n,variant:s,normalized:a,empty:o}=sc(e);if(o)return[];const c=await this.execRetrieve({[s]:a});if(!t)return c;if(c.length===0)throw new Je(`range matching ${n} not found`);if(c.length>1)throw new Xe(`multiple ranges matching ${n} found`);return c[0]}getKV(e){return new lr(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await m(this.unaryClient,Wm,e,Ym,Vm);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents(je(e));if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new nl(e.name,e.timeRange,e.key,e.color,this.frameClient,new lr(e.key,this.unaryClient,this.frameClient),new Ss(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await nt(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toUUIDs().map(s=>({variant:e,key:s,value:void 0})):this.sugarMany(t.parseJSON(mr)).map(s=>({variant:e,key:s.key,value:s})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,s;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new q((n=e.data)==null?void 0:n.timeRange),color:(s=e.data)==null?void 0:s.color})}};const je=r=>new E({type:Ks,key:r}),Gm=r=>new E({type:Js,key:r}),Hm=i.z.object({ranges:mr.array()}),Km=i.z.object({parent:ie.optional(),ranges:nc.array()}),Jm=i.z.object({keys:ae.array()}),Xm=i.z.object({}),Qm=i.z.object({key:ae,name:Hs}),eb=i.z.object({}),tb="/range/create",rb="/range/delete",nb="/range/rename";class il{constructor(e){l(this,"client");this.client=e}async rename(e,t){await m(this.client,nb,{key:e,name:t},Qm,eb)}async create(e,t){return(await m(this.client,tb,{ranges:e,...t},Km,Hm)).ranges}async delete(e){await m(this.client,rb,{keys:e},Jm,Xm)}}const sb=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:Js,Client:sl,KV:lr,ONTOLOGY_TYPE:Ks,Range:nl,Writer:il,aliasOntologyID:Gm,analyzeParams:sc,keyZ:ae,nameZ:Hs,newZ:nc,ontologyID:je,payloadZ:mr,sort:Fm},Symbol.toStringTag,{value:"Module"})),ib="/api/v1/";class ab{constructor(e,t={},n=!1){l(this,"url");l(this,"unary");l(this,"stream");l(this,"secure");this.secure=n,this.url=e.child(ib);const s=new Qe.JSONCodec;this.unary=rd(new td(this.url,s,this.secure),t),this.stream=new cd(this.url,s,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const ob="/workspace/lineplot/retrieve",cb="/workspace/lineplot/create",lb="/workspace/lineplot/rename",hb="/workspace/lineplot/set-data",ub="/workspace/lineplot/delete",db=i.z.object({keys:Nt.array()}),fb=i.z.object({workspace:Ee,linePlots:ac.array()}),yb=i.z.object({key:Nt,name:i.z.string()}),gb=i.z.object({key:Nt,data:i.z.string()}),pb=i.z.object({keys:Nt.array()}),wb=i.z.object({linePlots:X(on)}),mb=i.z.object({linePlots:on.array()}),Ln=i.z.object({});let al=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,cb,{workspace:e,linePlots:b(t)},fb,mb);return n?s.linePlots:s.linePlots[0]}async rename(e,t){await m(this.client,lb,{key:e,name:t},yb,Ln)}async setData(e,t){await m(this.client,hb,{key:e,data:JSON.stringify(t)},gb,Ln)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,ob,{keys:b(e)},db,wb);return t?n.linePlots:n.linePlots[0]}async delete(e){await m(this.client,ub,{keys:b(e)},pb,Ln)}};const bb=r=>new E({type:Qs,key:r}),vb=Object.freeze(Object.defineProperty({__proto__:null,Client:al,ONTOLOGY_TYPE:Qs,keyZ:Nt,linePlotZ:on,newZ:ac,ontologyID:bb},Symbol.toStringTag,{value:"Module"})),Tb="/workspace/log/retrieve",Ob="/workspace/log/create",Sb="/workspace/log/rename",Eb="/workspace/log/set-data",zb="/workspace/log/delete",Nb=i.z.object({keys:It.array()}),Ib=i.z.object({workspace:Ee,logs:oc.array()}),$b=i.z.object({key:It,name:i.z.string()}),xb=i.z.object({key:It,data:i.z.string()}),kb=i.z.object({keys:It.array()}),Ab=i.z.object({logs:cn.array()}),Ub=i.z.object({logs:cn.array()}),_n=i.z.object({});let ol=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,Ob,{workspace:e,logs:b(t)},Ib,Ub);return n?s.logs:s.logs[0]}async rename(e,t){await m(this.client,Sb,{key:e,name:t},$b,_n)}async setData(e,t){await m(this.client,Eb,{key:e,data:JSON.stringify(t)},xb,_n)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Tb,{keys:b(e)},Nb,Ab);return t?n.logs:n.logs[0]}async delete(e){await m(this.client,zb,{keys:b(e)},kb,_n)}};const Cb=r=>new E({type:ei,key:r}),Rb=Object.freeze(Object.defineProperty({__proto__:null,Client:ol,ONTOLOGY_TYPE:ei,keyZ:It,logZ:cn,newZ:oc,ontologyID:Cb},Symbol.toStringTag,{value:"Module"})),Bb="/workspace/schematic/retrieve",Pb="/workspace/schematic/create",Db="/workspace/schematic/rename",Mb="/workspace/schematic/set-data",jb="/workspace/schematic/delete",Lb="/workspace/schematic/copy",_b=i.z.object({keys:rt.array()}),Zb=i.z.object({workspace:Ee,schematics:hc.array()}),qb=i.z.object({key:rt,name:i.z.string()}),Fb=i.z.object({key:rt,data:i.z.string()}),Yb=i.z.object({keys:rt.array()}),Wb=i.z.object({key:rt,name:i.z.string(),snapshot:i.z.boolean()}),Vb=i.z.object({schematics:X(ti)}),Gb=i.z.object({schematics:ti.array()}),Hb=i.z.object({schematic:un}),Zn=i.z.object({});let cl=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,Pb,{workspace:e,schematics:b(t)},Zb,Gb);return n?s.schematics:s.schematics[0]}async rename(e,t){await m(this.client,Db,{key:e,name:t},qb,Zn)}async setData(e,t){await m(this.client,Mb,{key:e,data:JSON.stringify(t)},Fb,Zn)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Bb,{keys:b(e)},_b,Vb);return t?n.schematics:n.schematics[0]}async delete(e){await m(this.client,jb,{keys:b(e)},Yb,Zn)}async copy(e,t,n){return(await m(this.client,Lb,{key:e,name:t,snapshot:n},Wb,Hb)).schematic}};const Kb=r=>new E({type:ri,key:r}),Jb=Object.freeze(Object.defineProperty({__proto__:null,Client:cl,ONTOLOGY_TYPE:ri,keyZ:rt,newZ:hc,ontologyID:Kb,remoteZ:ti,schematicZ:un},Symbol.toStringTag,{value:"Module"})),Xb="/workspace/table/retrieve",Qb="/workspace/table/create",ev="/workspace/table/rename",tv="/workspace/table/set-data",rv="/workspace/table/delete",nv=i.z.object({keys:$t.array()}),sv=i.z.object({workspace:Ee,tables:uc.array()}),iv=i.z.object({key:$t,name:i.z.string()}),av=i.z.object({key:$t,data:i.z.string()}),ov=i.z.object({keys:$t.array()}),cv=i.z.object({tables:si.array()}),lv=i.z.object({tables:si.array()}),qn=i.z.object({});let ll=class{constructor(e){l(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),s=await m(this.client,Qb,{workspace:e,tables:b(t)},sv,lv);return n?s.tables:s.tables[0]}async rename(e,t){await m(this.client,ev,{key:e,name:t},iv,qn)}async setData(e,t){await m(this.client,tv,{key:e,data:JSON.stringify(t)},av,qn)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Xb,{keys:b(e)},nv,cv);return t?n.tables:n.tables[0]}async delete(e){await m(this.client,rv,{keys:b(e)},ov,qn)}};const hv=r=>new E({type:ii,key:r}),uv=Object.freeze(Object.defineProperty({__proto__:null,Client:ll,ONTOLOGY_TYPE:ii,keyZ:$t,newZ:uc,ontologyID:hv,remoteZ:si,tableZ:ni},Symbol.toStringTag,{value:"Module"})),Ar="/workspace/retrieve",dv="/workspace/create",fv="/workspace/rename",yv="/workspace/set-layout",gv="/workspace/delete",Ur=i.z.object({keys:Ee.array().optional(),search:i.z.string().optional(),author:tt.optional(),offset:i.z.number().optional(),limit:i.z.number().optional()}),pv=i.z.object({workspaces:cc.array()}),wv=i.z.object({key:Ee,name:i.z.string()}),mv=i.z.object({key:Ee,layout:i.z.string()}),bv=i.z.object({keys:Ee.array()}),Cr=i.z.object({workspaces:X(ln)}),vv=i.z.object({workspaces:lc.array()}),Fn=i.z.object({});class hl{constructor(e){l(this,"type",hn);l(this,"schematic");l(this,"linePlot");l(this,"log");l(this,"table");l(this,"client");this.client=e,this.schematic=new cl(e),this.linePlot=new al(e),this.log=new ol(e),this.table=new ll(e)}async create(e){const t=Array.isArray(e),n=await m(this.client,dv,{workspaces:b(e)},pv,vv);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await m(this.client,fv,{key:e,name:t},wv,Fn)}async setLayout(e,t){await m(this.client,yv,{key:e,layout:JSON.stringify(t)},mv,Fn)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Ar,{keys:b(e)},Ur,Cr);return t?n.workspaces:n.workspaces[0]}async retrieveByAuthor(e){return(await m(this.client,Ar,{author:e},Ur,Cr)).workspaces}async search(e){return(await m(this.client,Ar,{search:e},Ur,Cr)).workspaces}async page(e,t){return(await m(this.client,Ar,{offset:e,limit:t},Ur,Cr)).workspaces}async delete(e){await m(this.client,gv,{keys:b(e)},bv,Fn)}}const Tv=r=>new E({type:hn,key:r}),Ov=Object.freeze(Object.defineProperty({__proto__:null,Client:hl,ONTOLOGY_TYPE:hn,keyZ:Ee,newZ:cc,ontologyID:Tv,remoteZ:lc,workspaceZ:ln},Symbol.toStringTag,{value:"Module"})),ul=i.z.object({host:i.z.string({error:"Host is required"}).min(1,"Host is required"),port:i.z.number({error:"Port is required"}).or(i.z.string({error:"Port is required"})),username:i.z.string().min(1,"Username is required"),password:i.z.string().min(1,"Password is required"),connectivityPollFrequency:O.z.default(O.seconds(30)),secure:i.z.boolean().optional().default(!1),name:i.z.string().optional(),retry:jo.breakerConfig.optional()});class dl extends _c{constructor(t){const n=ul.parse(t),{host:s,port:a,username:o,password:c,connectivityPollFrequency:h,secure:d,retry:f}=n,u=new ab(new py({host:s,port:Number(a)}),f,d);u.use(Tg);let N;o!=null&&c!=null&&(N=new Jp(u.unary,{username:o,password:c}),u.use(N.middleware()));const S=new li(new ar(u.unary)),j=new kc(u.unary,S);super(u.stream,u.unary,S);l(this,"createdAt");l(this,"props");l(this,"ranges");l(this,"channels");l(this,"auth");l(this,"user");l(this,"access");l(this,"connectivity");l(this,"ontology");l(this,"workspaces");l(this,"labels");l(this,"hardware");l(this,"control");l(this,"transport");l(this,"clientVersion","0.42.3");this.createdAt=z.now(),this.props=n,this.auth=N,this.transport=u,this.channels=new Ic(this,S,u.unary,j),this.connectivity=new cr(u.unary,h,this.clientVersion,n.name),this.control=new qc(this),this.ontology=new vc(u.unary,this);const U=new il(this.transport.unary);this.labels=new tl(this.transport.unary,this,this.ontology),this.ranges=new sl(this,U,this.transport.unary,S,this.labels,this.ontology),this.access=new Sc(this.transport.unary),this.user=new Ac(this.transport.unary),this.workspaces=new hl(this.transport.unary);const ee=new Yc(this.transport.unary,this),A=new Kc(this.transport.unary,this,this.ontology,this.ranges),st=new Wc(this.transport.unary,A,this);this.hardware=new Fc(A,st,ee)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}l(dl,"connectivity",cr);exports.AuthError=sr;exports.Channel=hi;exports.ContiguityError=mg;exports.DataType=x;exports.Density=ne;exports.Frame=V;exports.MultiSeries=Po;exports.MultipleFoundError=Xe;exports.NotFoundError=Je;exports.QueryError=ke;exports.Rate=cs;exports.RouteError=ms;exports.Series=_e;exports.Synnax=dl;exports.TimeRange=q;exports.TimeSpan=O;exports.TimeStamp=z;exports.UnexpectedError=mt;exports.ValidationError=F;exports.access=np;exports.channel=Ep;exports.connection=Qp;exports.control=kw;exports.device=qw;exports.framer=Ew;exports.group=Cg;exports.hardware=Aw;exports.isCalculated=or;exports.label=Nm;exports.linePlot=vb;exports.log=Rb;exports.ontology=Zg;exports.policy=rp;exports.rack=Jw;exports.ranger=sb;exports.schematic=Jb;exports.signals=Uw;exports.synnaxPropsZ=ul;exports.table=uv;exports.task=dm;exports.user=qp;exports.workspace=Ov;