@synnaxlabs/client 0.44.3 → 0.44.4
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/.turbo/turbo-build.log +6 -6
- package/dist/channel/client.d.ts +1 -0
- package/dist/channel/client.d.ts.map +1 -1
- package/dist/channel/payload.d.ts +15 -15
- package/dist/channel/payload.d.ts.map +1 -1
- package/dist/channel/retriever.d.ts +1 -1
- package/dist/channel/writer.d.ts +2 -2
- package/dist/channel/writer.d.ts.map +1 -1
- package/dist/client.cjs +22 -22
- package/dist/client.js +2051 -2008
- package/dist/control/state.d.ts +4 -4
- package/dist/framer/deleter.d.ts +1 -1
- package/dist/framer/streamer.d.ts +14 -14
- package/dist/framer/writer.d.ts +17 -17
- package/dist/ontology/group/client.d.ts +2 -0
- package/dist/ontology/group/client.d.ts.map +1 -1
- package/dist/ranger/alias.d.ts +1 -1
- package/dist/ranger/alias.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/channel/client.ts +5 -3
- package/src/channel/payload.ts +10 -2
- package/src/channel/writer.ts +2 -1
- package/src/ontology/group/client.ts +3 -0
- package/src/ranger/alias.ts +1 -4
package/dist/client.cjs
CHANGED
|
@@ -1,44 +1,44 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),mo=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)},Es=r=>{const e=(t,n=jr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!wr(t))return t;n=vo(n);const i={},a=t;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),n):(Object.keys(a).forEach(o=>{let c=a[o];const u=r(o);n.recursive&&(wr(c)?jn(c)||(c=e(c,n)):n.recursiveInArray&&Mn(c)&&(c=[...c].map(l=>{let h=l;return wr(l)?jn(h)||(h=e(l,n)):Mn(l)&&(h=e({key:l},n).key),h}))),i[u]=c}),i)};return e},Os=Es(mo),wo=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),bo=Es(wo),To=[Number,String,Uint8Array],jr={recursive:!0,recursiveInArray:!0},vo=(r=jr)=>(r.recursive==null?r=jr:r.recursiveInArray??=!1,r),Mn=r=>r!=null&&Array.isArray(r),wr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),jn=r=>To.some(e=>r instanceof e);let Eo=class{contentType="application/json";decoder;encoder;constructor(){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),i=Os(n);return t!=null?t.parse(i):i}encodeString(e){const t=bo(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):typeof i=="bigint"?i.toString():i)}};const Ur=new Eo;let Ge=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const Oo=r=>r!=null&&typeof r=="object"&&"toString"in r,No=(r,e=!1)=>{const t=Oo(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?zo(n):n},zo=r=>(e,t)=>r(t,e),Xt=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ns=s.z.object({width:s.z.number(),height:s.z.number()}),So=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Ao=["width","height"];s.z.enum(Ao);const Io=["start","center","end"],$o=["signedWidth","signedHeight"];s.z.enum($o);const Ht=s.z.object({x:s.z.number(),y:s.z.number()}),ko=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Co=["x","y"],zs=s.z.enum(Co),Ss=["top","right","bottom","left"];s.z.enum(Ss);const xo=["left","right"],As=s.z.enum(xo),Ro=["top","bottom"],Is=s.z.enum(Ro),$s=["center"],Un=s.z.enum($s),Mo=[...Ss,...$s],ks=s.z.enum(Mo);s.z.enum(Io);const jo=["first","last"];s.z.enum(jo);const Uo=s.z.object({lower:s.z.number(),upper:s.z.number()}),Do=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Uo,Xt]);s.z.union([Do,Xt]);s.z.enum([...zs.options,...ks.options]);s.z.union([zs,ks,s.z.instanceof(String)]);const Qt=r=>(e,t)=>{if(typeof e=="bigint"){if(Po(t))return r(e,BigInt(t));const n=r(Number(e),Number(t));return typeof n=="number"?BigInt(Math.round(n)):n}return r(Number(e),Number(t))},er=Qt((r,e)=>r-e),tr=Qt((r,e)=>r+e),Po=r=>typeof r=="bigint"?!0:Number.isInteger(r),oe=Qt((r,e)=>r*e),rr=Qt((r,e)=>r/e),xe=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?Zo(n):n},Zo=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Dn=(r,e)=>{const t=xe(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:As.or(Un),y:Is.or(Un)});const Lo=s.z.object({x:As,y:Is}),Bo=Object.freeze({x:"left",y:"top"}),qo=(r,e)=>r.x===e.x&&r.y===e.y,Pn=s.z.union([s.z.number(),Ht,Xt,Ns,So,ko]),Fo=(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}},Zn=Object.freeze({x:0,y:0}),Ut=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Ut,left:Ut,width:Ut,height:Ut});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Ht,two:Ht,root:Lo});const an=(r,e,t=0,n=0,i)=>{const a={one:{...Zn},two:{...Zn},root:i??Bo};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:i??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))},br=r=>{const e=an(r);return{lower:e.one.x,upper:e.two.x}},Tr=r=>{const e=an(r);return{lower:e.one.y,upper:e.two.y}},Yo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Vo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ns,Vo,Ht,Xt]);const Wo=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Pn,scale:Pn});s.z.object({offset:s.z.number(),scale:s.z.number()});const Ho=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],_o=r=>(e,t,n,i)=>[e,i?n/r:n*r],Go=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:c}=r,u=a-i,l=c-o;if(t==="dimension")return[r,n*(l/u)];const h=(n-i)*(l/u)+o;return[r,h]},Ko=r=>(e,t,n)=>[r,n],Jo=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},Xo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Wo(n,i,a),[e,n]};let Ln=class Pe{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Pe().translate(e)}static magnify(e){return new Pe().magnify(e)}static scale(e,t){return new Pe().scale(e,t)}translate(e){const t=this.new(),n=Ho(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=_o(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=xe(e,t),i=this.new(),a=Go(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=xe(e,t),i=this.new(),a=Xo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=xe(e,t),i=this.new(),a=Ko(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Jo();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 Pe;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,c])=>i>=o&&i<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Pe};(class ne{x;y;currRoot;constructor(e=new Ln,t=new Ln,n=null){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=Fo(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}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(Yo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!qo(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(br(e)),t.y=t.y.scale(Tr(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(br(e)),t.y=this.y.reBound(Tr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(br(e)),t.y=this.y.clamp(Tr(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 an(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})}}static IDENTITY=new ne});let Cs=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const xs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Qo=`0123456789${xs}`,ec=11,tc=Cs(xs,1),rc=Cs(Qo,ec-1),nc=()=>`${tc()}${rc()}`,sc=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,ic=s.z.enum(["static","dynamic"]),ac=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),Rs=(r,e)=>{const t=new C(e);if(![A.DAY,A.HOUR,A.MINUTE,A.SECOND,A.MILLISECOND,A.MICROSECOND,A.NANOSECOND].some(i=>i.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 C?new C(n):new A(n)};let C=class m extends Ge{constructor(e,t="UTC"){if(e==null)super(m.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*m.MILLISECOND.valueOf());else if(typeof e=="string")super(m.parseDateTimeString(e,t).valueOf());else if(Array.isArray(e))super(m.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=m.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=m.MAX:e=m.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new m(BigInt(i.getTime())*m.MILLISECOND.valueOf()).truncate(m.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let u=m.hours(parseInt(n??"00")).add(m.minutes(parseInt(i??"00"))).add(m.seconds(parseInt(o??"00"))).add(m.milliseconds(parseInt(c??"00")));return t==="local"&&(u=u.add(m.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return m.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new m(BigInt(n.getTime())*m.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(m.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 A(BigInt(new Date().getTimezoneOffset())*m.MINUTE.valueOf())}static since(e){return new m().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new m(e).valueOf()}span(e){return this.range(e).span}range(e){return new at(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new m(e).valueOf()}afterEq(e){return this.valueOf()>=new m(e).valueOf()}before(e){return this.valueOf()<new m(e).valueOf()}beforeEq(e){return this.valueOf()<=new m(e).valueOf()}add(e){return new m(tr(this.valueOf(),new A(e).valueOf()))}sub(e){return new m(er(this.valueOf(),new A(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(A.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(A.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(A.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(A.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const t=this.date();return t.setUTCFullYear(e),new m(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new m(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new m(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new m(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new m(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new m(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new m(t)}toString(){return this.date().toISOString()}remainder(e){return Rs(this,e)}get isToday(){return this.truncate(A.DAY).equals(m.now().truncate(A.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new m(new Date)}static max(...e){let t=m.MIN;for(const n of e){const i=new m(n);i.after(t)&&(t=i)}return t}static min(...e){let t=m.MAX;for(const n of e){const i=new m(n);i.before(t)&&(t=i)}return t}static nanoseconds(e,t="UTC"){return new m(e,t)}static NANOSECOND=m.nanoseconds(1);static microseconds(e,t="UTC"){return m.nanoseconds(e*1e3,t)}static MICROSECOND=m.microseconds(1);static milliseconds(e,t="UTC"){return m.microseconds(e*1e3,t)}static MILLISECOND=m.milliseconds(1);static seconds(e,t="UTC"){return m.milliseconds(e*1e3,t)}static SECOND=m.seconds(1);static minutes(e,t="UTC"){return m.seconds(e*60,t)}static MINUTE=m.minutes(1);static hours(e,t="UTC"){return m.minutes(e*60,t)}static HOUR=m.hours(1);static days(e,t="UTC"){return m.hours(e*24,t)}static DAY=m.days(1);static MAX=new m((1n<<63n)-1n);static MIN=new m(0);static ZERO=new m(0);static z=s.z.union([s.z.instanceof(m),s.z.object({value:s.z.bigint()}).transform(e=>new m(e.value)),s.z.string().transform(e=>new m(BigInt(e))),s.z.number().transform(e=>new m(e)),s.z.bigint().transform(e=>new m(e)),s.z.date().transform(e=>new m(e)),s.z.custom(e=>e instanceof A).transform(e=>new m(e)),ac.transform(e=>new m(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},A=class b extends Ge{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof b?e:e instanceof vr?e.period:e instanceof C?new b(e):["number","bigint"].includes(typeof e)?b.seconds(e):new b(e)}static fromMilliseconds(e){return e instanceof b?e:e instanceof vr?e.period:e instanceof C?new b(e):["number","bigint"].includes(typeof e)?b.milliseconds(e):new b(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new b(e).valueOf()}greaterThan(e){return this.valueOf()>new b(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new b(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new b(e).valueOf()}remainder(e){return Rs(this,e)}truncate(e){return new b(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(b.DAY),t=this.truncate(b.HOUR),n=this.truncate(b.MINUTE),i=this.truncate(b.SECOND),a=this.truncate(b.MILLISECOND),o=this.truncate(b.MICROSECOND),c=this.truncate(b.NANOSECOND),u=e,l=t.sub(e),h=n.sub(t),g=i.sub(n),d=a.sub(i),O=o.sub(a),S=c.sub(o);let x="";return u.isZero||(x+=`${u.days}d `),l.isZero||(x+=`${l.hours}h `),h.isZero||(x+=`${h.minutes}m `),g.isZero||(x+=`${g.seconds}s `),d.isZero||(x+=`${d.milliseconds}ms `),O.isZero||(x+=`${O.microseconds}µs `),S.isZero||(x+=`${S.nanoseconds}ns`),x.trim()}mult(e){return new b(oe(this.valueOf(),e))}div(e){return new b(rr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(b.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(b.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(b.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(b.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(b.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new b(e).valueOf()}add(e){return new b(this.valueOf()+new b(e).valueOf())}sub(e){return new b(this.valueOf()-new b(e).valueOf())}static nanoseconds(e=1){return new b(e)}static NANOSECOND=b.nanoseconds(1);static microseconds(e=1){return b.nanoseconds(oe(e,1e3))}static MICROSECOND=b.microseconds(1);static milliseconds(e=1){return b.microseconds(oe(e,1e3))}static MILLISECOND=b.milliseconds(1);static seconds(e=1){return b.milliseconds(oe(e,1e3))}static SECOND=b.seconds(1);static minutes(e=1){return b.seconds(oe(e,60))}static MINUTE=b.minutes(1);static hours(e){return b.minutes(oe(e,60))}static HOUR=b.hours(1);static days(e){return b.hours(oe(e,24))}static DAY=b.days(1);static MAX=new b((1n<<63n)-1n);static MIN=new b(0);static ZERO=new b(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new b(e.value)),s.z.string().transform(e=>new b(BigInt(e))),s.z.number().transform(e=>new b(e)),s.z.bigint().transform(e=>new b(e)),s.z.instanceof(b),s.z.instanceof(C).transform(e=>new b(e)),s.z.custom(e=>e instanceof vr).transform(e=>new b(e))])},vr=class se extends Ge{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new se(e).valueOf()}get period(){return A.seconds(1/this.valueOf())}sampleCount(e){return new A(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new _(t).valueOf()}span(e){return A.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}add(e){return new se(tr(this.valueOf(),e.valueOf()))}sub(e){return new se(er(this.valueOf(),e.valueOf()))}mult(e){return new se(oe(this.valueOf(),e))}div(e){return new se(rr(this.valueOf(),e))}static hz(e){return new se(e)}static khz(e){return se.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new se(e)),s.z.instanceof(se)])},_=class K extends Ge{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Dr(e*this.valueOf())}add(e){return new K(tr(this.valueOf(),e.valueOf()))}sub(e){return new K(er(this.valueOf(),e.valueOf()))}mult(e){return new K(oe(this.valueOf(),e))}div(e){return new K(rr(this.valueOf(),e))}static UNKNOWN=new K(0);static BIT128=new K(16);static BIT64=new K(8);static BIT32=new K(4);static BIT16=new K(2);static BIT8=new K(1);static z=s.z.union([s.z.number().transform(e=>new K(e)),s.z.instanceof(K)])},at=class ie{start;end;constructor(e,t){typeof e=="object"&&"start"in e?(this.start=new C(e.start),this.end=new C(e.end)):(this.start=new C(e),this.end=new C(t))}get span(){return new A(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 ie(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=A.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=A.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 i=C.max(n.start,e.start),a=C.min(n.end,e.end);return a.before(i)?!1:new A(a.sub(i)).greaterThanOrEqual(t)}contains(e){return e instanceof ie?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new ie(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 ie(C.min(...e.map(t=>t.start)),C.max(...e.map(t=>t.end)))}static MAX=new ie(C.MIN,C.MAX);static MIN=new ie(C.MAX,C.MIN);static ZERO=new ie(C.ZERO,C.ZERO);static z=s.z.union([s.z.object({start:C.z,end:C.z}).transform(e=>new ie(e.start,e.end)),s.z.instanceof(ie)]);static sort(e,t){return C.sort(e.start,t.start)||C.sort(e.end,t.end)}},j=class f extends Ge{constructor(e){if(e instanceof f||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=f.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.valueOf())}}get Array(){const e=f.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(f.JSON)||this.equals(f.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(f.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=f.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(f.UINT8)||this.equals(f.UINT16)||this.equals(f.UINT32)||this.equals(f.UINT64)}get isSignedInteger(){return this.equals(f.INT8)||this.equals(f.INT16)||this.equals(f.INT32)||this.equals(f.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(f.INT32)&&e.equals(f.FLOAT64)||this.equals(f.INT8)&&e.equals(f.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return f.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new f("unknown");static FLOAT64=new f("float64");static FLOAT32=new f("float32");static INT64=new f("int64");static INT32=new f("int32");static INT16=new f("int16");static INT8=new f("int8");static UINT64=new f("uint64");static UINT32=new f("uint32");static UINT16=new f("uint16");static UINT8=new f("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new f("timestamp");static UUID=new f("uuid");static STRING=new f("string");static JSON=new f("json");static ARRAY_CONSTRUCTORS=new Map([[f.UINT8.toString(),Uint8Array],[f.UINT16.toString(),Uint16Array],[f.UINT32.toString(),Uint32Array],[f.UINT64.toString(),BigUint64Array],[f.FLOAT32.toString(),Float32Array],[f.FLOAT64.toString(),Float64Array],[f.INT8.toString(),Int8Array],[f.INT16.toString(),Int16Array],[f.INT32.toString(),Int32Array],[f.INT64.toString(),BigInt64Array],[f.TIMESTAMP.toString(),BigInt64Array],[f.STRING.toString(),Uint8Array],[f.JSON.toString(),Uint8Array],[f.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,f.UINT8],[Uint16Array.name,f.UINT16],[Uint32Array.name,f.UINT32],[BigUint64Array.name,f.UINT64],[Float32Array.name,f.FLOAT32],[Float64Array.name,f.FLOAT64],[Int8Array.name,f.INT8],[Int16Array.name,f.INT16],[Int32Array.name,f.INT32],[BigInt64Array.name,f.INT64]]);static DENSITIES=new Map([[f.UINT8.toString(),_.BIT8],[f.UINT16.toString(),_.BIT16],[f.UINT32.toString(),_.BIT32],[f.UINT64.toString(),_.BIT64],[f.FLOAT32.toString(),_.BIT32],[f.FLOAT64.toString(),_.BIT64],[f.INT8.toString(),_.BIT8],[f.INT16.toString(),_.BIT16],[f.INT32.toString(),_.BIT32],[f.INT64.toString(),_.BIT64],[f.TIMESTAMP.toString(),_.BIT64],[f.STRING.toString(),_.UNKNOWN],[f.JSON.toString(),_.UNKNOWN],[f.UUID.toString(),_.BIT128]]);static ALL=[f.UNKNOWN,f.FLOAT64,f.FLOAT32,f.INT64,f.INT32,f.INT16,f.INT8,f.UINT64,f.UINT32,f.UINT16,f.UINT8,f.TIMESTAMP,f.UUID,f.STRING,f.JSON];static BIG_INT_TYPES=[f.INT64,f.UINT64,f.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new f(e)),s.z.instanceof(f)])},Dr=class $ extends Ge{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new $(tr(this.valueOf(),e.valueOf()))}sub(e){return new $(er(this.valueOf(),e.valueOf()))}mult(e){return new $(oe(this.valueOf(),e))}div(e){return new $(rr(this.valueOf(),e))}truncate(e){return new $(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return $.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/$.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/$.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/$.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/$.TERABYTE.valueOf()}toString(){const e=this.truncate($.TERABYTE),t=this.truncate($.GIGABYTE),n=this.truncate($.MEGABYTE),i=this.truncate($.KILOBYTE),a=this.truncate($.BYTE),o=e,c=t.sub(e),u=n.sub(t),l=i.sub(n),h=a.sub(i);let g="";return o.isZero||(g+=`${o.terabytes}TB `),c.isZero||(g+=`${c.gigabytes}GB `),u.isZero||(g+=`${u.megabytes}MB `),l.isZero||(g+=`${l.kilobytes}KB `),(!h.isZero||g==="")&&(g+=`${h.valueOf()}B`),g.trim()}static bytes(e=1){return new $(e)}static BYTE=new $(1);static kilobytes(e=1){return $.bytes(e.valueOf()*1e3)}static KILOBYTE=$.kilobytes(1);static megabytes(e=1){return $.kilobytes(e.valueOf()*1e3)}static MEGABYTE=$.megabytes(1);static gigabytes(e=1){return $.megabytes(e.valueOf()*1e3)}static GIGABYTE=$.gigabytes(1);static terabytes(e){return $.gigabytes(e.valueOf()*1e3)}static TERABYTE=$.terabytes(1);static ZERO=new $(0);static z=s.z.union([s.z.number().transform(e=>new $(e)),s.z.instanceof($)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Ms=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof C||r instanceof A||r instanceof Date},oc=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):Bt(t,-n),Bt=(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),cc=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function lc(r){return typeof r=="string"&&cc.test(r)}const B=[];for(let r=0;r<256;++r)B.push((r+256).toString(16).slice(1));function uc(r,e=0){return(B[r[e+0]]+B[r[e+1]]+B[r[e+2]]+B[r[e+3]]+"-"+B[r[e+4]]+B[r[e+5]]+"-"+B[r[e+6]]+B[r[e+7]]+"-"+B[r[e+8]]+B[r[e+9]]+"-"+B[r[e+10]]+B[r[e+11]]+B[r[e+12]]+B[r[e+13]]+B[r[e+14]]+B[r[e+15]]).toLowerCase()}function hc(r,e=0){const t=uc(r,e);if(!lc(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const js=(r,e)=>hc(r,e),be=-1,dc=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),fc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Pr=10,yc=(r,e)=>{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`)},Us="sy_x_telem_series";let Ds=class Oe{key;discriminator=Us;dataType;sampleOffset;gl;_data;timeRange=at.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=be;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:at.z.optional(),dataType:j.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([dc,fc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:ic.optional().default("static").optional()});static z=Oe.crudeZ.transform(e=>new Oe(e));constructor(e){gc(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:u=nc(),data:l}=e;if(pc(l)){const d=l;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this.timeRange=d.timeRange,this.alignment=d.alignment,this.alignmentMultiple=d.alignmentMultiple,this.cachedMin=d.cachedMin,this.cachedMax=d.cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this.cachedLength=d.cachedLength;return}const h=Ms(l),g=Array.isArray(l);if(t!=null)this.dataType=new j(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(g||h){let d=l;if(!h){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=l[0]}if(typeof d=="string")this.dataType=j.STRING;else if(typeof d=="number")this.dataType=j.FLOAT64;else if(typeof d=="bigint")this.dataType=j.INT64;else if(typeof d=="boolean")this.dataType=j.BOOLEAN;else if(d instanceof C||d instanceof Date||d instanceof C)this.dataType=j.TIMESTAMP;else if(typeof d=="object")this.dataType=j.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new j(l)}if(!g&&!h)this._data=l;else if(g&&l.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[l]:l;const O=d[0];(O instanceof C||O instanceof Date||O instanceof A)&&(d=d.map(S=>new C(S).valueOf())),this.dataType.equals(j.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),wo=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)},Os=r=>{const e=(t,n=jr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!wr(t))return t;n=Eo(n);const i={},a=t;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),n):(Object.keys(a).forEach(o=>{let c=a[o];const u=r(o);n.recursive&&(wr(c)?jn(c)||(c=e(c,n)):n.recursiveInArray&&Mn(c)&&(c=[...c].map(l=>{let h=l;return wr(l)?jn(h)||(h=e(l,n)):Mn(l)&&(h=e({key:l},n).key),h}))),i[u]=c}),i)};return e},Ns=Os(wo),bo=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),To=Os(bo),vo=[Number,String,Uint8Array],jr={recursive:!0,recursiveInArray:!0},Eo=(r=jr)=>(r.recursive==null?r=jr:r.recursiveInArray??=!1,r),Mn=r=>r!=null&&Array.isArray(r),wr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),jn=r=>vo.some(e=>r instanceof e);let Oo=class{contentType="application/json";decoder;encoder;constructor(){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),i=Ns(n);return t!=null?t.parse(i):i}encodeString(e){const t=To(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):typeof i=="bigint"?i.toString():i)}};const Ur=new Oo;let Ge=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const No=r=>r!=null&&typeof r=="object"&&"toString"in r,zo=(r,e=!1)=>{const t=No(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?So(n):n},So=r=>(e,t)=>r(t,e),Xt=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const zs=s.z.object({width:s.z.number(),height:s.z.number()}),Ao=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Io=["width","height"];s.z.enum(Io);const $o=["start","center","end"],ko=["signedWidth","signedHeight"];s.z.enum(ko);const Ht=s.z.object({x:s.z.number(),y:s.z.number()}),Co=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),xo=["x","y"],Ss=s.z.enum(xo),As=["top","right","bottom","left"];s.z.enum(As);const Ro=["left","right"],Is=s.z.enum(Ro),Mo=["top","bottom"],$s=s.z.enum(Mo),ks=["center"],Un=s.z.enum(ks),jo=[...As,...ks],Cs=s.z.enum(jo);s.z.enum($o);const Uo=["first","last"];s.z.enum(Uo);const Do=s.z.object({lower:s.z.number(),upper:s.z.number()}),Po=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Do,Xt]);s.z.union([Po,Xt]);s.z.enum([...Ss.options,...Cs.options]);s.z.enum(["x","left","right"]);s.z.enum(["y","top","bottom"]);s.z.union([Ss,Cs,s.z.instanceof(String)]);const Qt=r=>(e,t)=>{if(typeof e=="bigint"){if(Zo(t))return r(e,BigInt(t));const n=r(Number(e),Number(t));return typeof n=="number"?BigInt(Math.round(n)):n}return r(Number(e),Number(t))},er=Qt((r,e)=>r-e),tr=Qt((r,e)=>r+e),Zo=r=>typeof r=="bigint"?!0:Number.isInteger(r),oe=Qt((r,e)=>r*e),rr=Qt((r,e)=>r/e),xe=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?Lo(n):n},Lo=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Dn=(r,e)=>{const t=xe(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:Is.or(Un),y:$s.or(Un)});const Bo=s.z.object({x:Is,y:$s}),qo=Object.freeze({x:"left",y:"top"}),Fo=(r,e)=>r.x===e.x&&r.y===e.y,Pn=s.z.union([s.z.number(),Ht,Xt,zs,Ao,Co]),Yo=(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}},Zn=Object.freeze({x:0,y:0}),Ut=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Ut,left:Ut,width:Ut,height:Ut});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Ht,two:Ht,root:Bo});const an=(r,e,t=0,n=0,i)=>{const a={one:{...Zn},two:{...Zn},root:i??qo};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:i??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))},br=r=>{const e=an(r);return{lower:e.one.x,upper:e.two.x}},Tr=r=>{const e=an(r);return{lower:e.one.y,upper:e.two.y}},Vo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Wo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([zs,Wo,Ht,Xt]);const Ho=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Pn,scale:Pn});s.z.object({offset:s.z.number(),scale:s.z.number()});const _o=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Go=r=>(e,t,n,i)=>[e,i?n/r:n*r],Ko=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:c}=r,u=a-i,l=c-o;if(t==="dimension")return[r,n*(l/u)];const h=(n-i)*(l/u)+o;return[r,h]},Jo=r=>(e,t,n)=>[r,n],Xo=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},Qo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Ho(n,i,a),[e,n]};let Ln=class Pe{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Pe().translate(e)}static magnify(e){return new Pe().magnify(e)}static scale(e,t){return new Pe().scale(e,t)}translate(e){const t=this.new(),n=_o(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Go(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=xe(e,t),i=this.new(),a=Ko(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=xe(e,t),i=this.new(),a=Qo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=xe(e,t),i=this.new(),a=Jo(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Xo();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 Pe;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,c])=>i>=o&&i<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Pe};(class se{x;y;currRoot;constructor(e=new Ln,t=new Ln,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new se().translate(e,t)}static translateX(e){return new se().translateX(e)}static translateY(e){return new se().translateY(e)}static clamp(e){return new se().clamp(e)}static magnify(e){return new se().magnify(e)}static scale(e){return new se().scale(e)}static reBound(e){return new se().reBound(e)}translate(e,t){const n=Yo(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}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(Vo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Fo(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(br(e)),t.y=t.y.scale(Tr(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(br(e)),t.y=this.y.reBound(Tr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(br(e)),t.y=this.y.clamp(Tr(e)),t}copy(){const e=new se;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 an(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})}}static IDENTITY=new se});let xs=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Rs="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ec=`0123456789${Rs}`,tc=11,rc=xs(Rs,1),nc=xs(ec,tc-1),sc=()=>`${rc()}${nc()}`,ic=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,ac=s.z.enum(["static","dynamic"]),oc=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),Ms=(r,e)=>{const t=new A(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(i=>i.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 A?new A(n):new z(n)};let A=class w extends Ge{constructor(e,t="UTC"){if(e==null)super(w.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*w.MILLISECOND.valueOf());else if(typeof e=="string")super(w.parseDateTimeString(e,t).valueOf());else if(Array.isArray(e))super(w.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=w.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=w.MAX:e=w.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new w(BigInt(i.getTime())*w.MILLISECOND.valueOf()).truncate(w.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let u=w.hours(parseInt(n??"00")).add(w.minutes(parseInt(i??"00"))).add(w.seconds(parseInt(o??"00"))).add(w.milliseconds(parseInt(c??"00")));return t==="local"&&(u=u.add(w.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return w.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new w(BigInt(n.getTime())*w.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(w.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 z(BigInt(new Date().getTimezoneOffset())*w.MINUTE.valueOf())}static since(e){return new w().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new w(e).valueOf()}span(e){return this.range(e).span}range(e){return new at(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new w(e).valueOf()}afterEq(e){return this.valueOf()>=new w(e).valueOf()}before(e){return this.valueOf()<new w(e).valueOf()}beforeEq(e){return this.valueOf()<=new w(e).valueOf()}add(e){return new w(tr(this.valueOf(),new z(e).valueOf()))}sub(e){return new w(er(this.valueOf(),new z(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(w.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(w.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const t=this.date();return t.setUTCFullYear(e),new w(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new w(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new w(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new w(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new w(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new w(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new w(t)}toString(){return this.date().toISOString()}remainder(e){return Ms(this,e)}get isToday(){return this.truncate(z.DAY).equals(w.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new w(new Date)}static max(...e){let t=w.MIN;for(const n of e){const i=new w(n);i.after(t)&&(t=i)}return t}static min(...e){let t=w.MAX;for(const n of e){const i=new w(n);i.before(t)&&(t=i)}return t}static nanoseconds(e,t="UTC"){return new w(e,t)}static NANOSECOND=w.nanoseconds(1);static microseconds(e,t="UTC"){return w.nanoseconds(e*1e3,t)}static MICROSECOND=w.microseconds(1);static milliseconds(e,t="UTC"){return w.microseconds(e*1e3,t)}static MILLISECOND=w.milliseconds(1);static seconds(e,t="UTC"){return w.milliseconds(e*1e3,t)}static SECOND=w.seconds(1);static minutes(e,t="UTC"){return w.seconds(e*60,t)}static MINUTE=w.minutes(1);static hours(e,t="UTC"){return w.minutes(e*60,t)}static HOUR=w.hours(1);static days(e,t="UTC"){return w.hours(e*24,t)}static DAY=w.days(1);static MAX=new w((1n<<63n)-1n);static MIN=new w(0);static ZERO=new w(0);static z=s.z.union([s.z.instanceof(w),s.z.object({value:s.z.bigint()}).transform(e=>new w(e.value)),s.z.string().transform(e=>new w(BigInt(e))),s.z.number().transform(e=>new w(e)),s.z.bigint().transform(e=>new w(e)),s.z.date().transform(e=>new w(e)),s.z.custom(e=>e instanceof z).transform(e=>new w(e)),oc.transform(e=>new w(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},z=class b extends Ge{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof b?e:e instanceof vr?e.period:e instanceof A?new b(e):["number","bigint"].includes(typeof e)?b.seconds(e):new b(e)}static fromMilliseconds(e){return e instanceof b?e:e instanceof vr?e.period:e instanceof A?new b(e):["number","bigint"].includes(typeof e)?b.milliseconds(e):new b(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new b(e).valueOf()}greaterThan(e){return this.valueOf()>new b(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new b(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new b(e).valueOf()}remainder(e){return Ms(this,e)}truncate(e){return new b(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(b.DAY),t=this.truncate(b.HOUR),n=this.truncate(b.MINUTE),i=this.truncate(b.SECOND),a=this.truncate(b.MILLISECOND),o=this.truncate(b.MICROSECOND),c=this.truncate(b.NANOSECOND),u=e,l=t.sub(e),h=n.sub(t),p=i.sub(n),f=a.sub(i),O=o.sub(a),N=c.sub(o);let k="";return u.isZero||(k+=`${u.days}d `),l.isZero||(k+=`${l.hours}h `),h.isZero||(k+=`${h.minutes}m `),p.isZero||(k+=`${p.seconds}s `),f.isZero||(k+=`${f.milliseconds}ms `),O.isZero||(k+=`${O.microseconds}µs `),N.isZero||(k+=`${N.nanoseconds}ns`),k.trim()}mult(e){return new b(oe(this.valueOf(),e))}div(e){return new b(rr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(b.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(b.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(b.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(b.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(b.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new b(e).valueOf()}add(e){return new b(this.valueOf()+new b(e).valueOf())}sub(e){return new b(this.valueOf()-new b(e).valueOf())}static nanoseconds(e=1){return new b(e)}static NANOSECOND=b.nanoseconds(1);static microseconds(e=1){return b.nanoseconds(oe(e,1e3))}static MICROSECOND=b.microseconds(1);static milliseconds(e=1){return b.microseconds(oe(e,1e3))}static MILLISECOND=b.milliseconds(1);static seconds(e=1){return b.milliseconds(oe(e,1e3))}static SECOND=b.seconds(1);static minutes(e=1){return b.seconds(oe(e,60))}static MINUTE=b.minutes(1);static hours(e){return b.minutes(oe(e,60))}static HOUR=b.hours(1);static days(e){return b.hours(oe(e,24))}static DAY=b.days(1);static MAX=new b((1n<<63n)-1n);static MIN=new b(0);static ZERO=new b(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new b(e.value)),s.z.string().transform(e=>new b(BigInt(e))),s.z.number().transform(e=>new b(e)),s.z.bigint().transform(e=>new b(e)),s.z.instanceof(b),s.z.instanceof(A).transform(e=>new b(e)),s.z.custom(e=>e instanceof vr).transform(e=>new b(e))])},vr=class ie extends Ge{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ie(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new H(t).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}add(e){return new ie(tr(this.valueOf(),e.valueOf()))}sub(e){return new ie(er(this.valueOf(),e.valueOf()))}mult(e){return new ie(oe(this.valueOf(),e))}div(e){return new ie(rr(this.valueOf(),e))}static hz(e){return new ie(e)}static khz(e){return ie.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new ie(e)),s.z.instanceof(ie)])},H=class G extends Ge{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Dr(e*this.valueOf())}add(e){return new G(tr(this.valueOf(),e.valueOf()))}sub(e){return new G(er(this.valueOf(),e.valueOf()))}mult(e){return new G(oe(this.valueOf(),e))}div(e){return new G(rr(this.valueOf(),e))}static UNKNOWN=new G(0);static BIT128=new G(16);static BIT64=new G(8);static BIT32=new G(4);static BIT16=new G(2);static BIT8=new G(1);static z=s.z.union([s.z.number().transform(e=>new G(e)),s.z.instanceof(G)])},at=class Q{start;end;constructor(e,t){typeof e=="object"&&"start"in e?(this.start=new A(e.start),this.end=new A(e.end)):(this.start=new A(e),this.end=new A(t))}get span(){return new z(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 Q(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=z.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=z.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 i=A.max(n.start,e.start),a=A.min(n.end,e.end);return a.before(i)?!1:new z(a.sub(i)).greaterThanOrEqual(t)}contains(e){return e instanceof Q?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Q(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 Q(A.min(...e.map(t=>t.start)),A.max(...e.map(t=>t.end)))}static MAX=new Q(A.MIN,A.MAX);static MIN=new Q(A.MAX,A.MIN);static ZERO=new Q(A.ZERO,A.ZERO);static z=s.z.union([s.z.object({start:A.z,end:A.z}).transform(e=>new Q(e.start,e.end)),s.z.instanceof(Q)]);static sort(e,t){return A.sort(e.start,t.start)||A.sort(e.end,t.end)}static simplify(e){return e.map(t=>t.makeValid()).sort((t,n)=>Q.sort(t,n)).reduce((t,n)=>{if(n.isZero)return t;if(t.length===0)return t.push(n),t;const i=t[t.length-1];return i.overlapsWith(n)||i.end.equals(n.start)?i.end=A.max(i.end,n.end):t.push(n),t},[])}},j=class y extends Ge{constructor(e){if(e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.valueOf())}}get Array(){const e=y.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(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.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=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),H.BIT8],[y.UINT16.toString(),H.BIT16],[y.UINT32.toString(),H.BIT32],[y.UINT64.toString(),H.BIT64],[y.FLOAT32.toString(),H.BIT32],[y.FLOAT64.toString(),H.BIT64],[y.INT8.toString(),H.BIT8],[y.INT16.toString(),H.BIT16],[y.INT32.toString(),H.BIT32],[y.INT64.toString(),H.BIT64],[y.TIMESTAMP.toString(),H.BIT64],[y.STRING.toString(),H.UNKNOWN],[y.JSON.toString(),H.UNKNOWN],[y.UUID.toString(),H.BIT128]]);static ALL=[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON];static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new y(e)),s.z.instanceof(y)])},Dr=class I extends Ge{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new I(tr(this.valueOf(),e.valueOf()))}sub(e){return new I(er(this.valueOf(),e.valueOf()))}mult(e){return new I(oe(this.valueOf(),e))}div(e){return new I(rr(this.valueOf(),e))}truncate(e){return new I(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return I.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),t=this.truncate(I.GIGABYTE),n=this.truncate(I.MEGABYTE),i=this.truncate(I.KILOBYTE),a=this.truncate(I.BYTE),o=e,c=t.sub(e),u=n.sub(t),l=i.sub(n),h=a.sub(i);let p="";return o.isZero||(p+=`${o.terabytes}TB `),c.isZero||(p+=`${c.gigabytes}GB `),u.isZero||(p+=`${u.megabytes}MB `),l.isZero||(p+=`${l.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new I(e)}static BYTE=new I(1);static kilobytes(e=1){return I.bytes(e.valueOf()*1e3)}static KILOBYTE=I.kilobytes(1);static megabytes(e=1){return I.kilobytes(e.valueOf()*1e3)}static MEGABYTE=I.megabytes(1);static gigabytes(e=1){return I.megabytes(e.valueOf()*1e3)}static GIGABYTE=I.gigabytes(1);static terabytes(e){return I.gigabytes(e.valueOf()*1e3)}static TERABYTE=I.terabytes(1);static ZERO=new I(0);static z=s.z.union([s.z.number().transform(e=>new I(e)),s.z.instanceof(I)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const js=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof A||r instanceof z||r instanceof Date},cc=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):Bt(t,-n),Bt=(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),lc=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function uc(r){return typeof r=="string"&&lc.test(r)}const L=[];for(let r=0;r<256;++r)L.push((r+256).toString(16).slice(1));function hc(r,e=0){return(L[r[e+0]]+L[r[e+1]]+L[r[e+2]]+L[r[e+3]]+"-"+L[r[e+4]]+L[r[e+5]]+"-"+L[r[e+6]]+L[r[e+7]]+"-"+L[r[e+8]]+L[r[e+9]]+"-"+L[r[e+10]]+L[r[e+11]]+L[r[e+12]]+L[r[e+13]]+L[r[e+14]]+L[r[e+15]]).toLowerCase()}function dc(r,e=0){const t=hc(r,e);if(!uc(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Us=(r,e)=>dc(r,e),be=-1,fc=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),yc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Pr=10,gc=(r,e)=>{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`)},Ds="sy_x_telem_series";let Ps=class Oe{key;discriminator=Ds;dataType;sampleOffset;gl;_data;timeRange=at.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=be;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:at.z.optional(),dataType:j.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([fc,yc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:ac.optional().default("static").optional()});static z=Oe.crudeZ.transform(e=>new Oe(e));constructor(e){pc(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:u=sc(),data:l}=e;if(mc(l)){const f=l;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=js(l),p=Array.isArray(l);if(t!=null)this.dataType=new j(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(p||h){let f=l;if(!h){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=l[0]}if(typeof f=="string")this.dataType=j.STRING;else if(typeof f=="number")this.dataType=j.FLOAT64;else if(typeof f=="bigint")this.dataType=j.INT64;else if(typeof f=="boolean")this.dataType=j.BOOLEAN;else if(f instanceof A||f instanceof Date||f instanceof A)this.dataType=j.TIMESTAMP;else if(typeof f=="object")this.dataType=j.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new j(l)}if(!p&&!h)this._data=l;else if(p&&l.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[l]:l;const O=f[0];(O instanceof A||O instanceof Date||O instanceof z)&&(f=f.map(N=>new A(N).valueOf())),this.dataType.equals(j.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`).buffer):this.dataType.equals(j.JSON)?(this.cachedLength=
|
|
3
|
+
`).buffer):this.dataType.equals(j.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(N=>Ur.encodeString(N)).join(`
|
|
4
4
|
`)}
|
|
5
|
-
`).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(
|
|
6
|
-
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(j.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(Ur.decodeString(t)))}get byteCapacity(){return new Dr(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===be?this.byteCapacity:this.dataType.isVariable?new Dr(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===be?this.byteCapacity.valueOf()/this.dataType.density.valueOf():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,i)=>{n===Pr&&(e++,t.push(i+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 i=0;i<this.length;i++)n[i]=oc(this.dataType,e,this.data[i],t);return new Oe({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(j.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(){return this.calcMax()}calcMax(){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.calcRawMax(),Bt(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(j.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(){return this.calcMin()}calcMin(){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.calcRawMin(),Bt(this.cachedMin,this.sampleOffset))}get bounds(){return xe(Number(this.min),Number(this.max),{makeValid:!1})}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)}}atAlignment(e,t){const n=Number((e-this.alignment)/this.alignmentMultiple);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=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(j.UUID))return this.atUUID(e,t);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 Bt(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=js(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=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]===Pr){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(j.STRING)?new TextDecoder().decode(a):Os(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=No(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(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(j.FLOAT32)&&!this.dataType.equals(j.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==be){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).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=be}as(e){return yc(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:qn(this.alignmentBounds.lower),upper:qn(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return xe(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 mc(this);return this.dataType.equals(j.JSON)?new wc(e):e}return this.dataType.equals(j.UUID)?new bc(this):new Tc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Bn(this,e,t??this.length)}subAlignmentIterator(e,t){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),i=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new Bn(this,n,i)}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new Oe({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 i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new Oe({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new Oe({data:this.buffer,dataType:this.dataType,timeRange:at.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}};const gc=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Ds?!0:Ms(r),pc=sc(Us,Ds);class Bn{series;end;index;constructor(e,t,n){this.series=e;const i=xe(0,e.length+1);this.end=Dn(i,n),this.index=Dn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class mc{series;index;decoder;constructor(e){if(!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]!==Pr;)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))})}}let wc=class Ps{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Ur.decodeString(e.value,Ps.schema)}}};class bc{series;index;data;density;constructor(e){if(!e.dataType.equals(j.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=j.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=js(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Tc=class{series;index;constructor(r){this.series=r,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};const qn=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const vc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";vc();const Ec=["macOS","Windows","Linux"],Oc=["macos","windows","linux"],Nc={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(Ec).or(s.z.enum(Oc).transform(r=>Nc[r]));const zc=(...r)=>r.map(Zs).join(""),Zs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Sc=r=>r.endsWith("/")?r.slice(0,-1):r,Ac=(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("&")}`;let Ic=class qt{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){this.protocol=n,this.host=e,this.port=t,this.path=Zs(i)}replace(e){return new qt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new qt({...this,pathPrefix:zc(this.path,e)})}toString(){return Sc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new qt({host:"unknown",port:0})};const $c=async r=>await new Promise(e=>setTimeout(e,A.fromMilliseconds(r).milliseconds));class kc{config;retries;interval;constructor(e){this.config={baseInterval:new A(e?.baseInterval??A.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??$c},this.retries=0,this.interval=new A(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)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Cc=s.z.object({baseInterval:A.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),xc=Object.freeze(Object.defineProperty({__proto__:null,Breaker:kc,breakerConfigZ:Cc},Symbol.toStringTag,{value:"Module"})),Rc=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Ls=s.z.string().regex(Rc),Fe=s.z.number().min(0).max(255),Bs=s.z.number().min(0).max(1),qs=s.z.tuple([Fe,Fe,Fe,Bs]),Mc=s.z.tuple([Fe,Fe,Fe]),jc=s.z.object({rgba255:qs}),Uc=s.z.number().min(0).max(360),Dc=s.z.number().min(0).max(100),Pc=s.z.number().min(0).max(100),Zc=s.z.tuple([Uc,Dc,Pc,Bs]),on=s.z.union([Ls,Mc,qs,Zc,jc]),Lc=on.transform(r=>cn(r)),cn=(r,e=1)=>{if(r=on.parse(r),typeof r=="string")return Bc(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}return r.rgba255},Bc=(r,e=1)=>(r=Ls.parse(r),r=qc(r),[Dt(r,0),Dt(r,2),Dt(r,4),r.length===8?Dt(r,6)/255:e]),Dt=(r,e)=>parseInt(r.slice(e,e+2),16),qc=r=>r.startsWith("#")?r.slice(1):r;cn("#000000");cn("#ffffff");const Fc=s.z.object({key:s.z.string(),color:on,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(Fc);const Yc=s.z.object({key:s.z.string(),name:s.z.string(),color:Lc});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(Yc)});s.z.int().min(0).max(255);s.z.object({name:s.z.string(),key:s.z.string()});const Vc=r=>Object.getOwnPropertySymbols(globalThis).includes(r),Wc=(r,e)=>{const t=Symbol.for(r);if(!Vc(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},Fs="sy_x_error",Hc=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),Et=r=>class ot extends Error{static discriminator=Fs;discriminator=ot.discriminator;static TYPE=r;type=ot.TYPE;static matches=Hc(r);matches=ot.matches;constructor(t,n){super(t,n),this.name=ot.TYPE}static sub(t){return Et(`${r}.${t}`)}},Ys=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==Fs)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Ze="unknown",Zr="nil";class _c{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Zr,data:""};if(Ys(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Ze,data:e.message};if(typeof e=="string")return{type:Ze,data:e};try{return{type:Ze,data:JSON.stringify(e)}}catch{return{type:Ze,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Zr)return null;if(e.type===Ze)return new Lr(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Lr(e.data)}}const ln=Wc("synnax-error-registry",()=>new _c),Gc=({encode:r,decode:e})=>ln().register({encode:r,decode:e}),Kc=r=>ln().encode(r),Jc=r=>r==null?null:ln().decode(r);class Lr extends Et("unknown"){}const Xc=s.z.object({type:s.z.string(),data:s.z.string()});class Qc extends Et("canceled"){}class el extends Et("not_implemented"){}const Ne=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Qc,NONE:Zr,NotImplemented:el,UNKNOWN:Ze,Unknown:Lr,createTyped:Et,decode:Jc,encode:Kc,isTyped:Ys,payloadZ:Xc,register:Gc},Symbol.toStringTag,{value:"Module"})),tl=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Vs=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),rl=Vs.extend({result:s.json()}),nl=Vs.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),sl=s.union([rl,nl]);s.union([tl,sl]);s.z.string().regex(/^\d+\.\d+\.\d+$/);const il=["standard","scientific","engineering"];s.z.enum(il);s.z.enum(["success","info","warning","error","loading","disabled"]);let Ot=class extends Ne.createTyped("freighter"){},te=class extends Ot.sub("eof"){constructor(){super("EOF")}},We=class extends Ot.sub("stream_closed"){constructor(){super("StreamClosed")}},ze=class extends Ot.sub("unreachable"){url;constructor(e={}){const{message:t="Unreachable",url:n=Ic.UNKNOWN}=e;super(t),this.url=n}};const al=r=>{if(!r.type.startsWith(Ot.TYPE))return null;if(te.matches(r))return{type:te.TYPE,data:"EOF"};if(We.matches(r))return{type:We.TYPE,data:"StreamClosed"};if(ze.matches(r))return{type:ze.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},ol=r=>{if(!r.type.startsWith(Ot.TYPE))return null;switch(r.type){case te.TYPE:return new te;case We.TYPE:return new We;case ze.TYPE:return new ze;default:throw new Ne.Unknown(`Unknown error type: ${r.data}`)}};Ne.register({encode:al,decode:ol});class Ws{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const i=async a=>{if(n===this.middleware.length)return await t(a);const o=this.middleware[n];return n++,await o(a,i)};return await i(e)}}const Hs="Content-Type",cl=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),ll=r=>{const e=r?.cause?.code??r?.code??r?.errno;if(typeof e=="string"&&cl.has(e))return!0;if(r.name==="TypeError"){const t=String(r.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(t))return!0}return r?.name==="AbortError"||r?.code,!1},ul=400;class hl extends Ws{endpoint;encoder;constructor(e,t,n=!1){return super(),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[Hs]:this.encoder.contentType}}async send(e,t,n,i){t=n?.parse(t);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async l=>{const h={...l,params:{}};c.headers={...this.headers,...l.params};let g;try{g=await fetch(l.target,c)}catch(O){if(!(O instanceof Error))throw O;return[h,ll(O)?new ze({url:o}):O]}const d=await g.arrayBuffer();if(g?.ok)return i!=null&&(a=this.encoder.decode(d,i)),[h,null];try{if(g.status!==ul)return[h,new Error(g.statusText)];const O=this.encoder.decode(d,Ne.payloadZ),S=Ne.decode(O);return[h,S]}catch(O){return[h,new Error(`[freighter] - failed to decode error: ${g.statusText}: ${O.message}`)]}});if(u!=null)return[null,u];if(a==null)throw new Error("Response must be defined");return[a,null]}}const dl=(r,e)=>{class t{wrapped;constructor(i){this.wrapped=i}use(...i){this.wrapped.use(...i)}async send(i,a,o,c){const u=new xc.Breaker(e);do{const[l,h]=await this.wrapped.send(i,a,o,c);if(h==null)return[l,null];if(!ze.matches(h))return[null,h];if(console.warn(`[freighter] ${u.retryMessage}`,h),!await u.wait())return[l,h]}while(!0)}}return new t(r)},p=async(r,e,t,n,i)=>{const[a,o]=await r.send(e,t,n,i);if(o!=null)throw o;return a},fl=s.z.object({type:s.z.enum(["data","close","open"]),payload:s.z.unknown(),error:s.z.optional(Ne.payloadZ)});class yl{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,t,n,i){this.codec=t,this.reqSchema=n,this.resSchema=i,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 Ne.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new te;if(this.sendClosed)throw new We;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");if(this.serverClosed=Ne.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[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,fl))}onClose(e){this.addMessage({type:"close",error:{type:e.code===pl?te.TYPE:We.TYPE,data:""}})}}const gl="freighterctx",pl=1e3;let ml=class Br extends Ws{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,t,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}withCodec(e){const t=new Br(this.baseUrl,e,this.secure);return t.use(...this.middleware),t}async stream(e,t,n){let i;const[,a]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),u={...o,params:{}};c.binaryType=Br.MESSAGE_TYPE;const l=await this.wrapSocket(c,t,n);return l instanceof Error?[u,l]:(i=l,[u,null])});if(a!=null)throw a;return i}buildURL(e,t){const n=Ac({[Hs]:this.encoder.contentType,...t.params},gl);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{const a=new yl(e,this.encoder,t,n);a.receiveOpenAck().then(o=>{o!=null?i(o):i(a)}).catch(o=>i(o))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};const wl=r=>Array.isArray(r)?r:r==null?[]:[r],v=Object.freeze(Object.defineProperty({__proto__:null,toArray:wl},Symbol.toStringTag,{value:"Module"})),bl=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)},un=r=>{const e=(t,n=qr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Er(t))return t;n=Ol(n);const i={},a=t;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),n):(Object.keys(a).forEach(o=>{let c=a[o];const u=r(o);n.recursive&&(Er(c)?Yn(c)||(c=e(c,n)):n.recursiveInArray&&Fn(c)&&(c=[...c].map(l=>{let h=l;return Er(l)?Yn(h)||(h=e(l,n)):Fn(l)&&(h=e({key:l},n).key),h}))),i[u]=c}),i)};return e},hn=un(bl),Tl=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),_s=un(Tl),vl=r=>r.length===0?r:r[0].toUpperCase()+r.slice(1),El=[Number,String,Uint8Array],qr={recursive:!0,recursiveInArray:!0},Ol=(r=qr)=>(r.recursive==null?r=qr:r.recursiveInArray??=!1,r),Fn=r=>r!=null&&Array.isArray(r),Er=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Yn=r=>El.some(e=>r instanceof e),Nl=r=>r.replace(/\s+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}-${n.toLowerCase()}`).toLowerCase(),zl=un(Nl),Sl=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:_s,capitalize:vl,snakeToCamel:hn,toKebab:zl},Symbol.toStringTag,{value:"Module"})),Gs=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);let Ks=class{contentType="application/json";decoder;encoder;constructor(){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),i=hn(n);return t!=null?t.parse(i):i}encodeString(e){const t=_s(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):typeof i=="bigint"?i.toString():i)}},Js=class{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||!Gs(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(o=>JSON.stringify(i[o]??""));n.push(a.join(","))}),n.join(`
|
|
5
|
+
`).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=u,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=i??0,this.timeRange=n??at.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new j(t).Array(e),a=new Oe({data:i.buffer,dataType:t,...n});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}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===be)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===be)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===be?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
|
|
6
|
+
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(j.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(Ur.decodeString(t)))}get byteCapacity(){return new Dr(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===be?this.byteCapacity:this.dataType.isVariable?new Dr(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===be?this.byteCapacity.valueOf()/this.dataType.density.valueOf():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,i)=>{n===Pr&&(e++,t.push(i+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 i=0;i<this.length;i++)n[i]=cc(this.dataType,e,this.data[i],t);return new Oe({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(j.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(){return this.calcMax()}calcMax(){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.calcRawMax(),Bt(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(j.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(){return this.calcMin()}calcMin(){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.calcRawMin(),Bt(this.cachedMin,this.sampleOffset))}get bounds(){return xe(Number(this.min),Number(this.max),{makeValid:!1})}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)}}atAlignment(e,t){const n=Number((e-this.alignment)/this.alignmentMultiple);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=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(j.UUID))return this.atUUID(e,t);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 Bt(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=Us(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=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]===Pr){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(j.STRING)?new TextDecoder().decode(a):Ns(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=zo(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(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(j.FLOAT32)&&!this.dataType.equals(j.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==be){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).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=be}as(e){return gc(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:qn(this.alignmentBounds.lower),upper:qn(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return xe(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 wc(this);return this.dataType.equals(j.JSON)?new bc(e):e}return this.dataType.equals(j.UUID)?new Tc(this):new vc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Bn(this,e,t??this.length)}subAlignmentIterator(e,t){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),i=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new Bn(this,n,i)}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new Oe({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 i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new Oe({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new Oe({data:this.buffer,dataType:this.dataType,timeRange:at.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}};const pc=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Ps?!0:js(r),mc=ic(Ds,Ps);class Bn{series;end;index;constructor(e,t,n){this.series=e;const i=xe(0,e.length+1);this.end=Dn(i,n),this.index=Dn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class wc{series;index;decoder;constructor(e){if(!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]!==Pr;)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))})}}let bc=class Zs{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Ur.decodeString(e.value,Zs.schema)}}};class Tc{series;index;data;density;constructor(e){if(!e.dataType.equals(j.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=j.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Us(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let vc=class{series;index;constructor(e){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)}}};const qn=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const Ec=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Ec();const Oc=["macOS","Windows","Linux"],Nc=["macos","windows","linux"],zc={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(Oc).or(s.z.enum(Nc).transform(r=>zc[r]));const Sc=(...r)=>r.map(Ls).join(""),Ls=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Ac=r=>r.endsWith("/")?r.slice(0,-1):r,Ic=(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("&")}`;let $c=class qt{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){this.protocol=n,this.host=e,this.port=t,this.path=Ls(i)}replace(e){return new qt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new qt({...this,pathPrefix:Sc(this.path,e)})}toString(){return Ac(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new qt({host:"unknown",port:0})};const kc=async r=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(r).milliseconds));let Cc=class{config;retries;interval;constructor(e){this.config={baseInterval:new z(e?.baseInterval??z.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??kc},this.retries=0,this.interval=new z(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)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}};const xc=s.z.object({baseInterval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Rc=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Cc,breakerConfigZ:xc},Symbol.toStringTag,{value:"Module"})),Mc=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Bs=s.z.string().regex(Mc),Fe=s.z.number().min(0).max(255),qs=s.z.number().min(0).max(1),Fs=s.z.tuple([Fe,Fe,Fe,qs]),jc=s.z.tuple([Fe,Fe,Fe]),Uc=s.z.object({rgba255:Fs}),Dc=s.z.number().min(0).max(360),Pc=s.z.number().min(0).max(100),Zc=s.z.number().min(0).max(100),Lc=s.z.tuple([Dc,Pc,Zc,qs]),on=s.z.union([Bs,jc,Fs,Lc,Uc]),Bc=on.transform(r=>cn(r)),cn=(r,e=1)=>{if(r=on.parse(r),typeof r=="string")return qc(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}return r.rgba255},qc=(r,e=1)=>(r=Bs.parse(r),r=Fc(r),[Dt(r,0),Dt(r,2),Dt(r,4),r.length===8?Dt(r,6)/255:e]),Dt=(r,e)=>parseInt(r.slice(e,e+2),16),Fc=r=>r.startsWith("#")?r.slice(1):r;cn("#000000");cn("#ffffff");const Yc=s.z.object({key:s.z.string(),color:on,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(Yc);const Vc=s.z.object({key:s.z.string(),name:s.z.string(),color:Bc});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(Vc)});s.z.int().min(0).max(255);s.z.object({name:s.z.string(),key:s.z.string()});const Wc=r=>Object.getOwnPropertySymbols(globalThis).includes(r),Hc=(r,e)=>{const t=Symbol.for(r);if(!Wc(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},Ys="sy_x_error",_c=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),Et=r=>class ot extends Error{static discriminator=Ys;discriminator=ot.discriminator;static TYPE=r;type=ot.TYPE;static matches=_c(r);matches=ot.matches;constructor(t,n){super(t,n),this.name=ot.TYPE}static sub(t){return Et(`${r}.${t}`)}},Vs=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==Ys)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Ze="unknown",Zr="nil";class Gc{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Zr,data:""};if(Vs(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Ze,data:e.message};if(typeof e=="string")return{type:Ze,data:e};try{return{type:Ze,data:JSON.stringify(e)}}catch{return{type:Ze,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Zr)return null;if(e.type===Ze)return new Lr(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Lr(e.data)}}const ln=Hc("synnax-error-registry",()=>new Gc),Kc=({encode:r,decode:e})=>ln().register({encode:r,decode:e}),Jc=r=>ln().encode(r),Xc=r=>r==null?null:ln().decode(r);let Lr=class extends Et("unknown"){};const Qc=s.z.object({type:s.z.string(),data:s.z.string()});class el extends Et("canceled"){}class tl extends Et("not_implemented"){}const Ne=Object.freeze(Object.defineProperty({__proto__:null,Canceled:el,NONE:Zr,NotImplemented:tl,UNKNOWN:Ze,Unknown:Lr,createTyped:Et,decode:Xc,encode:Jc,isTyped:Vs,payloadZ:Qc,register:Kc},Symbol.toStringTag,{value:"Module"})),rl=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Ws=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),nl=Ws.extend({result:s.json()}),sl=Ws.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),il=s.union([nl,sl]);s.union([rl,il]);s.z.string().regex(/^\d+\.\d+\.\d+$/);const al=["standard","scientific","engineering"];s.z.enum(al);s.z.enum(["success","info","warning","error","loading","disabled"]);let Ot=class extends Ne.createTyped("freighter"){},re=class extends Ot.sub("eof"){constructor(){super("EOF")}},We=class extends Ot.sub("stream_closed"){constructor(){super("StreamClosed")}},ze=class extends Ot.sub("unreachable"){url;constructor(e={}){const{message:t="Unreachable",url:n=$c.UNKNOWN}=e;super(t),this.url=n}};const ol=r=>{if(!r.type.startsWith(Ot.TYPE))return null;if(re.matches(r))return{type:re.TYPE,data:"EOF"};if(We.matches(r))return{type:We.TYPE,data:"StreamClosed"};if(ze.matches(r))return{type:ze.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},cl=r=>{if(!r.type.startsWith(Ot.TYPE))return null;switch(r.type){case re.TYPE:return new re;case We.TYPE:return new We;case ze.TYPE:return new ze;default:throw new Ne.Unknown(`Unknown error type: ${r.data}`)}};Ne.register({encode:ol,decode:cl});class Hs{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const i=async a=>{if(n===this.middleware.length)return await t(a);const o=this.middleware[n];return n++,await o(a,i)};return await i(e)}}const _s="Content-Type",ll=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),ul=r=>{const e=r?.cause?.code??r?.code??r?.errno;if(typeof e=="string"&&ll.has(e))return!0;if(r.name==="TypeError"){const t=String(r.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(t))return!0}return r?.name==="AbortError"||r?.code,!1},hl=400;class dl extends Hs{endpoint;encoder;constructor(e,t,n=!1){return super(),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[_s]:this.encoder.contentType}}async send(e,t,n,i){t=n?.parse(t);let a=null;const o=this.endpoint.child(e),c={};c.method="POST",c.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async l=>{const h={...l,params:{}};c.headers={...this.headers,...l.params};let p;try{p=await fetch(l.target,c)}catch(O){if(!(O instanceof Error))throw O;return[h,ul(O)?new ze({url:o}):O]}const f=await p.arrayBuffer();if(p?.ok)return i!=null&&(a=this.encoder.decode(f,i)),[h,null];try{if(p.status!==hl)return[h,new Error(p.statusText)];const O=this.encoder.decode(f,Ne.payloadZ),N=Ne.decode(O);return[h,N]}catch(O){return[h,new Error(`[freighter] - failed to decode error: ${p.statusText}: ${O.message}`)]}});if(u!=null)return[null,u];if(a==null)throw new Error("Response must be defined");return[a,null]}}const fl=(r,e)=>{class t{wrapped;constructor(i){this.wrapped=i}use(...i){this.wrapped.use(...i)}async send(i,a,o,c){const u=new Rc.Breaker(e);do{const[l,h]=await this.wrapped.send(i,a,o,c);if(h==null)return[l,null];if(!ze.matches(h))return[null,h];if(console.warn(`[freighter] ${u.retryMessage}`,h),!await u.wait())return[l,h]}while(!0)}}return new t(r)},m=async(r,e,t,n,i)=>{const[a,o]=await r.send(e,t,n,i);if(o!=null)throw o;return a},yl=s.z.object({type:s.z.enum(["data","close","open"]),payload:s.z.unknown(),error:s.z.optional(Ne.payloadZ)});class gl{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,t,n,i){this.codec=t,this.reqSchema=n,this.resSchema=i,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 Ne.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new re;if(this.sendClosed)throw new We;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");if(this.serverClosed=Ne.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[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,yl))}onClose(e){this.addMessage({type:"close",error:{type:e.code===ml?re.TYPE:We.TYPE,data:""}})}}const pl="freighterctx",ml=1e3;let wl=class Br extends Hs{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,t,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}withCodec(e){const t=new Br(this.baseUrl,e,this.secure);return t.use(...this.middleware),t}async stream(e,t,n){let i;const[,a]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const c=new WebSocket(this.buildURL(e,o)),u={...o,params:{}};c.binaryType=Br.MESSAGE_TYPE;const l=await this.wrapSocket(c,t,n);return l instanceof Error?[u,l]:(i=l,[u,null])});if(a!=null)throw a;return i}buildURL(e,t){const n=Ic({[_s]:this.encoder.contentType,...t.params},pl);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{const a=new gl(e,this.encoder,t,n);a.receiveOpenAck().then(o=>{o!=null?i(o):i(a)}).catch(o=>i(o))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};const bl=r=>Array.isArray(r)?r:r==null?[]:[r],v=Object.freeze(Object.defineProperty({__proto__:null,toArray:bl},Symbol.toStringTag,{value:"Module"})),Tl=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)},un=r=>{const e=(t,n=qr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Er(t))return t;n=Nl(n);const i={},a=t;return"toJSON"in a&&typeof a.toJSON=="function"?e(a.toJSON(),n):(Object.keys(a).forEach(o=>{let c=a[o];const u=r(o);n.recursive&&(Er(c)?Yn(c)||(c=e(c,n)):n.recursiveInArray&&Fn(c)&&(c=[...c].map(l=>{let h=l;return Er(l)?Yn(h)||(h=e(l,n)):Fn(l)&&(h=e({key:l},n).key),h}))),i[u]=c}),i)};return e},hn=un(Tl),vl=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Gs=un(vl),El=r=>r.length===0?r:r[0].toUpperCase()+r.slice(1),Ol=[Number,String,Uint8Array],qr={recursive:!0,recursiveInArray:!0},Nl=(r=qr)=>(r.recursive==null?r=qr:r.recursiveInArray??=!1,r),Fn=r=>r!=null&&Array.isArray(r),Er=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Yn=r=>Ol.some(e=>r instanceof e),zl=r=>r.replace(/\s+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}-${n.toLowerCase()}`).toLowerCase(),Sl=un(zl),Al=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Gs,capitalize:El,snakeToCamel:hn,toKebab:Sl},Symbol.toStringTag,{value:"Module"})),Ks=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);let Js=class{contentType="application/json";decoder;encoder;constructor(){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),i=hn(n);return t!=null?t.parse(i):i}encodeString(e){const t=Gs(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):typeof i=="bigint"?i.toString():i)}},Xs=class{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||!Ks(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(o=>JSON.stringify(i[o]??""));n.push(a.join(","))}),n.join(`
|
|
7
7
|
`)}decodeString(e,t){const[n,...i]=e.trim().split(`
|
|
8
|
-
`).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]=[]}),i.forEach(c=>{const u=c.split(",").map(l=>l.trim());a.forEach((l,h)=>{const g=this.parseValue(u[h]);g!=null&&o[l].push(g)})}),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}},Xs=class{contentType="text/plain";encode(e){if(typeof e!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(e)}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const ht=new Ks,Al=new Js,Il=new Xs,$l=[ht],je=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Js,CSV_CODEC:Al,ENCODERS:$l,JSONCodec:Ks,JSON_CODEC:ht,TEXT_CODEC:Il,TextCodec:Xs},Symbol.toStringTag,{value:"Module"})),Fr=r=>[...new Set(r)],kl=(r,e,t=!0)=>{const n=new Map;return r.forEach(i=>{const a=e(i);if(n.has(a)){if(t)return;n.delete(a)}n.set(a,i)}),Array.from(n.values())},Vn=Object.freeze(Object.defineProperty({__proto__:null,by:kl,unique:Fr},Symbol.toStringTag,{value:"Module"}));class Ke{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const Cl=r=>r!=null&&typeof r=="object"&&"toString"in r,nr=(r,e=!1)=>{const t=Cl(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?ei(n):n},xl=(r,e,t)=>{const n=nr(e[r],t);return(i,a)=>n(i[r],a[r])},Rl=(r,e)=>r.length!==e.length?r.length-e.length:r.every((t,n)=>t===e[n])?0:-1,Qs=(r,e)=>{if(r.length!==e.length)return r.length-e.length;if(r.length===0)return 0;const t=nr(r[0]),n=[...r].sort(t),i=[...e].sort(t);return n.every((a,o)=>a===i[o])?0:-1},Ml=(r,e)=>{const t=Fr(r),n=Fr(e);return Qs(t,n)},jl=(r,e)=>r===e?0:r==="first"&&e==="last"?1:-1,ei=r=>(e,t)=>r(t,e),Je=0,Ft=-1,Yt=1,ti=r=>r<Je,ri=r=>r>Je,Ul=r=>r>=Je,ni=r=>r===Je,Dl=(r,e)=>{const t=/([a-zA-Z]+)|(\d+)/g,n=r.replace(/[\s_.-]+/g,"").match(t),i=e.replace(/[\s_.-]+/g,"").match(t);if(!n||!i)return 0;for(let a=0;a<Math.min(n.length,i.length);a++){const o=n[a],c=i[a];if(isNaN(Number(o))&&isNaN(Number(c))){const u=o.localeCompare(c);if(u!==0)return u}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const u=Number(o)-Number(c);if(u!==0)return u}else return isNaN(Number(o))?-1:1}return n.length-i.length},Wn=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:Je,GREATER_THAN:Yt,LESS_THAN:Ft,isEqualTo:ni,isGreaterThan:ri,isGreaterThanEqual:Ul,isLessThan:ti,newF:nr,newFieldF:xl,order:jl,primitiveArrays:Rl,reverseF:ei,stringsWithNumbers:Dl,uniqueUnorderedPrimitiveArrays:Ml,unorderedPrimitiveArrays:Qs},Symbol.toStringTag,{value:"Module"})),sr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const si=s.z.object({width:s.z.number(),height:s.z.number()}),Pl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Zl=["width","height"];s.z.enum(Zl);const Ll=["start","center","end"],Bl=["signedWidth","signedHeight"];s.z.enum(Bl);const _t=s.z.object({x:s.z.number(),y:s.z.number()}),ql=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Fl=["x","y"],ii=s.z.enum(Fl),ai=["top","right","bottom","left"];s.z.enum(ai);const Yl=["left","right"],oi=s.z.enum(Yl),Vl=["top","bottom"],ci=s.z.enum(Vl),li=["center"],Hn=s.z.enum(li),Wl=[...ai,...li],ui=s.z.enum(Wl);s.z.enum(Ll);const Hl=["first","last"];s.z.enum(Hl);const _l=s.z.object({lower:s.z.number(),upper:s.z.number()}),Gl=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([_l,sr]);s.z.union([Gl,sr]);s.z.enum([...ii.options,...ui.options]);s.z.union([ii,ui,s.z.instanceof(String)]);const Nt=r=>(e,t)=>{if(typeof e=="bigint"){if(Yr(t))return r(e,BigInt(t));const n=r(Number(e),Number(t));return typeof n=="number"?BigInt(Math.round(n)):n}return r(Number(e),Number(t))},Re=Nt((r,e)=>r-e),zt=Nt((r,e)=>r+e),_n=(r,e)=>{const t=typeof r=="bigint",n=typeof e=="bigint";return t&&n?r===e:t&&Yr(e)?r===BigInt(e):n&&Yr(r)?e===BigInt(r):r===e},Kl=Nt((r,e)=>r<=e?r:e),Yr=r=>typeof r=="bigint"?!0:Number.isInteger(r),Jl=r=>typeof r=="bigint"?r<0n?-r:r:r<0?-r:r,ce=Nt((r,e)=>r*e),ir=Nt((r,e)=>r/e),Y=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?Xl(n):n},Xl=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Gn=(r,e)=>{const t=Y(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},Pt=(r,e)=>{const t=Y(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=Y(e);return n.lower>=t.lower&&n.upper<=t.upper},Ql=r=>({lower:Math.min(...r.map(e=>Y(e).lower)),upper:Math.max(...r.map(e=>Y(e).upper))}),eu=(r,e,t)=>{const n=r.map(c=>Y(c)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;_n(a,0)===!1;){const c=n.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(c!==-1){const u=n[c];let l;if(i>0?l=Re(u.upper,o):l=Re(o,u.lower),l>0){const h=Kl(Jl(a),l);if(o=zt(o,i>0?h:-h),a=Re(a,i>0?h:-h),_n(a,0))return o;continue}}if(i>0){const u=n.filter(l=>l.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=n.filter(l=>l.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},tu=(r,e,t)=>{const n=r.map(o=>Y(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?Y([e,t]):Y([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const c=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(c<u){const l=u-c;a=a+l}}return a};s.z.object({x:oi.or(Hn),y:ci.or(Hn)});const ru=s.z.object({x:oi,y:ci}),nu=Object.freeze({x:"left",y:"top"}),su=(r,e)=>r.x===e.x&&r.y===e.y,Kn=s.z.union([s.z.number(),_t,sr,si,Pl,ql]),iu=(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}},Jn=Object.freeze({x:0,y:0}),Zt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Zt,left:Zt,width:Zt,height:Zt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:_t,two:_t,root:ru});const dn=(r,e,t=0,n=0,i)=>{const a={one:{...Jn},two:{...Jn},root:i??nu};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:i??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))},Or=r=>{const e=dn(r);return{lower:e.one.x,upper:e.two.x}},Nr=r=>{const e=dn(r);return{lower:e.one.y,upper:e.two.y}},au=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,ou=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([si,ou,_t,sr]);const cu=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Kn,scale:Kn});s.z.object({offset:s.z.number(),scale:s.z.number()});const lu=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],uu=r=>(e,t,n,i)=>[e,i?n/r:n*r],hu=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:c}=r,u=a-i,l=c-o;if(t==="dimension")return[r,n*(l/u)];const h=(n-i)*(l/u)+o;return[r,h]},du=r=>(e,t,n)=>[r,n],fu=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},yu=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=cu(n,i,a),[e,n]};let Xn=class Le{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Le().translate(e)}static magnify(e){return new Le().magnify(e)}static scale(e,t){return new Le().scale(e,t)}translate(e){const t=this.new(),n=lu(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=uu(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Y(e,t),i=this.new(),a=hu(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=Y(e,t),i=this.new(),a=yu(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=Y(e,t),i=this.new(),a=du(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=fu();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 Le;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,c])=>i>=o&&i<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Le},ew=class ae{x;y;currRoot;constructor(e=new Xn,t=new Xn,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ae().translate(e,t)}static translateX(e){return new ae().translateX(e)}static translateY(e){return new ae().translateY(e)}static clamp(e){return new ae().clamp(e)}static magnify(e){return new ae().magnify(e)}static scale(e){return new ae().scale(e)}static reBound(e){return new ae().reBound(e)}translate(e,t){const n=iu(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}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(au(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!su(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(Or(e)),t.y=t.y.scale(Nr(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(Or(e)),t.y=this.y.reBound(Nr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Or(e)),t.y=this.y.clamp(Nr(e)),t}copy(){const e=new ae;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 dn(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})}}static IDENTITY=new ae},hi=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const di="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",gu=`0123456789${di}`,fi=11,pu=hi(di,1),mu=hi(gu,fi-1),fn=()=>`${pu()}${mu()}`,wu=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:fi,create:fn},Symbol.toStringTag,{value:"Module"})),bu=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,Tu=s.z.enum(["static","dynamic"]),vu=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),yi=(r,e)=>{const t=new N(e);if(![E.DAY,E.HOUR,E.MINUTE,E.SECOND,E.MILLISECOND,E.MICROSECOND,E.NANOSECOND].some(i=>i.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 N?new N(n):new E(n)};let N=class w extends Ke{constructor(e,t="UTC"){if(e==null)super(w.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*w.MILLISECOND.valueOf());else if(typeof e=="string")super(w.parseDateTimeString(e,t).valueOf());else if(Array.isArray(e))super(w.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=w.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=w.MAX:e=w.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new w(BigInt(i.getTime())*w.MILLISECOND.valueOf()).truncate(w.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let u=w.hours(parseInt(n??"00")).add(w.minutes(parseInt(i??"00"))).add(w.seconds(parseInt(o??"00"))).add(w.milliseconds(parseInt(c??"00")));return t==="local"&&(u=u.add(w.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return w.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new w(BigInt(n.getTime())*w.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(w.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 E(BigInt(new Date().getTimezoneOffset())*w.MINUTE.valueOf())}static since(e){return new w().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new w(e).valueOf()}span(e){return this.range(e).span}range(e){return new z(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new w(e).valueOf()}afterEq(e){return this.valueOf()>=new w(e).valueOf()}before(e){return this.valueOf()<new w(e).valueOf()}beforeEq(e){return this.valueOf()<=new w(e).valueOf()}add(e){return new w(zt(this.valueOf(),new E(e).valueOf()))}sub(e){return new w(Re(this.valueOf(),new E(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(w.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(w.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const t=this.date();return t.setUTCFullYear(e),new w(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new w(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new w(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new w(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new w(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new w(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new w(t)}toString(){return this.date().toISOString()}remainder(e){return yi(this,e)}get isToday(){return this.truncate(E.DAY).equals(w.now().truncate(E.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new w(new Date)}static max(...e){let t=w.MIN;for(const n of e){const i=new w(n);i.after(t)&&(t=i)}return t}static min(...e){let t=w.MAX;for(const n of e){const i=new w(n);i.before(t)&&(t=i)}return t}static nanoseconds(e,t="UTC"){return new w(e,t)}static NANOSECOND=w.nanoseconds(1);static microseconds(e,t="UTC"){return w.nanoseconds(e*1e3,t)}static MICROSECOND=w.microseconds(1);static milliseconds(e,t="UTC"){return w.microseconds(e*1e3,t)}static MILLISECOND=w.milliseconds(1);static seconds(e,t="UTC"){return w.milliseconds(e*1e3,t)}static SECOND=w.seconds(1);static minutes(e,t="UTC"){return w.seconds(e*60,t)}static MINUTE=w.minutes(1);static hours(e,t="UTC"){return w.minutes(e*60,t)}static HOUR=w.hours(1);static days(e,t="UTC"){return w.hours(e*24,t)}static DAY=w.days(1);static MAX=new w((1n<<63n)-1n);static MIN=new w(0);static ZERO=new w(0);static z=s.z.union([s.z.instanceof(w),s.z.object({value:s.z.bigint()}).transform(e=>new w(e.value)),s.z.string().transform(e=>new w(BigInt(e))),s.z.number().transform(e=>new w(e)),s.z.bigint().transform(e=>new w(e)),s.z.date().transform(e=>new w(e)),s.z.custom(e=>e instanceof E).transform(e=>new w(e)),vu.transform(e=>new w(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},E=class T extends Ke{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof T?e:e instanceof G?e.period:e instanceof N?new T(e):["number","bigint"].includes(typeof e)?T.seconds(e):new T(e)}static fromMilliseconds(e){return e instanceof T?e:e instanceof G?e.period:e instanceof N?new T(e):["number","bigint"].includes(typeof e)?T.milliseconds(e):new T(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new T(e).valueOf()}greaterThan(e){return this.valueOf()>new T(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new T(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new T(e).valueOf()}remainder(e){return yi(this,e)}truncate(e){return new T(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(T.DAY),t=this.truncate(T.HOUR),n=this.truncate(T.MINUTE),i=this.truncate(T.SECOND),a=this.truncate(T.MILLISECOND),o=this.truncate(T.MICROSECOND),c=this.truncate(T.NANOSECOND),u=e,l=t.sub(e),h=n.sub(t),g=i.sub(n),d=a.sub(i),O=o.sub(a),S=c.sub(o);let x="";return u.isZero||(x+=`${u.days}d `),l.isZero||(x+=`${l.hours}h `),h.isZero||(x+=`${h.minutes}m `),g.isZero||(x+=`${g.seconds}s `),d.isZero||(x+=`${d.milliseconds}ms `),O.isZero||(x+=`${O.microseconds}µs `),S.isZero||(x+=`${S.nanoseconds}ns`),x.trim()}mult(e){return new T(ce(this.valueOf(),e))}div(e){return new T(ir(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(T.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(T.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(T.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(T.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 isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new T(e).valueOf()}add(e){return new T(this.valueOf()+new T(e).valueOf())}sub(e){return new T(this.valueOf()-new T(e).valueOf())}static nanoseconds(e=1){return new T(e)}static NANOSECOND=T.nanoseconds(1);static microseconds(e=1){return T.nanoseconds(ce(e,1e3))}static MICROSECOND=T.microseconds(1);static milliseconds(e=1){return T.microseconds(ce(e,1e3))}static MILLISECOND=T.milliseconds(1);static seconds(e=1){return T.milliseconds(ce(e,1e3))}static SECOND=T.seconds(1);static minutes(e=1){return T.seconds(ce(e,60))}static MINUTE=T.minutes(1);static hours(e){return T.minutes(ce(e,60))}static HOUR=T.hours(1);static days(e){return T.hours(ce(e,24))}static DAY=T.days(1);static MAX=new T((1n<<63n)-1n);static MIN=new T(0);static ZERO=new T(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new T(e.value)),s.z.string().transform(e=>new T(BigInt(e))),s.z.number().transform(e=>new T(e)),s.z.bigint().transform(e=>new T(e)),s.z.instanceof(T),s.z.instanceof(N).transform(e=>new T(e)),s.z.custom(e=>e instanceof G).transform(e=>new T(e))])};class G extends Ke{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new G(e).valueOf()}get period(){return E.seconds(1/this.valueOf())}sampleCount(e){return new E(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new H(t).valueOf()}span(e){return E.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}add(e){return new G(zt(this.valueOf(),e.valueOf()))}sub(e){return new G(Re(this.valueOf(),e.valueOf()))}mult(e){return new G(ce(this.valueOf(),e))}div(e){return new G(ir(this.valueOf(),e))}static hz(e){return new G(e)}static khz(e){return G.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new G(e)),s.z.instanceof(G)])}let H=class J extends Ke{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new He(e*this.valueOf())}add(e){return new J(zt(this.valueOf(),e.valueOf()))}sub(e){return new J(Re(this.valueOf(),e.valueOf()))}mult(e){return new J(ce(this.valueOf(),e))}div(e){return new J(ir(this.valueOf(),e))}static UNKNOWN=new J(0);static BIT128=new J(16);static BIT64=new J(8);static BIT32=new J(4);static BIT16=new J(2);static BIT8=new J(1);static z=s.z.union([s.z.number().transform(e=>new J(e)),s.z.instanceof(J)])};class z{start;end;constructor(e,t){typeof e=="object"&&"start"in e?(this.start=new N(e.start),this.end=new N(e.end)):(this.start=new N(e),this.end=new N(t))}get span(){return new E(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 z(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=E.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=E.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 i=N.max(n.start,e.start),a=N.min(n.end,e.end);return a.before(i)?!1:new E(a.sub(i)).greaterThanOrEqual(t)}contains(e){return e instanceof z?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new z(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 z(N.min(...e.map(t=>t.start)),N.max(...e.map(t=>t.end)))}static MAX=new z(N.MIN,N.MAX);static MIN=new z(N.MAX,N.MIN);static ZERO=new z(N.ZERO,N.ZERO);static z=s.z.union([s.z.object({start:N.z,end:N.z}).transform(e=>new z(e.start,e.end)),s.z.instanceof(z)]);static sort(e,t){return N.sort(e.start,t.start)||N.sort(e.end,t.end)}}let I=class y extends Ke{constructor(e){if(e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.valueOf())}}get Array(){const e=y.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(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.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=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),H.BIT8],[y.UINT16.toString(),H.BIT16],[y.UINT32.toString(),H.BIT32],[y.UINT64.toString(),H.BIT64],[y.FLOAT32.toString(),H.BIT32],[y.FLOAT64.toString(),H.BIT64],[y.INT8.toString(),H.BIT8],[y.INT16.toString(),H.BIT16],[y.INT32.toString(),H.BIT32],[y.INT64.toString(),H.BIT64],[y.TIMESTAMP.toString(),H.BIT64],[y.STRING.toString(),H.UNKNOWN],[y.JSON.toString(),H.UNKNOWN],[y.UUID.toString(),H.BIT128]]);static ALL=[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON];static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new y(e)),s.z.instanceof(y)])},He=class k extends Ke{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new k(zt(this.valueOf(),e.valueOf()))}sub(e){return new k(Re(this.valueOf(),e.valueOf()))}mult(e){return new k(ce(this.valueOf(),e))}div(e){return new k(ir(this.valueOf(),e))}truncate(e){return new k(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return k.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/k.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/k.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/k.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/k.TERABYTE.valueOf()}toString(){const e=this.truncate(k.TERABYTE),t=this.truncate(k.GIGABYTE),n=this.truncate(k.MEGABYTE),i=this.truncate(k.KILOBYTE),a=this.truncate(k.BYTE),o=e,c=t.sub(e),u=n.sub(t),l=i.sub(n),h=a.sub(i);let g="";return o.isZero||(g+=`${o.terabytes}TB `),c.isZero||(g+=`${c.gigabytes}GB `),u.isZero||(g+=`${u.megabytes}MB `),l.isZero||(g+=`${l.kilobytes}KB `),(!h.isZero||g==="")&&(g+=`${h.valueOf()}B`),g.trim()}static bytes(e=1){return new k(e)}static BYTE=new k(1);static kilobytes(e=1){return k.bytes(e.valueOf()*1e3)}static KILOBYTE=k.kilobytes(1);static megabytes(e=1){return k.kilobytes(e.valueOf()*1e3)}static MEGABYTE=k.megabytes(1);static gigabytes(e=1){return k.megabytes(e.valueOf()*1e3)}static GIGABYTE=k.gigabytes(1);static terabytes(e){return k.gigabytes(e.valueOf()*1e3)}static TERABYTE=k.terabytes(1);static ZERO=new k(0);static z=s.z.union([s.z.number().transform(e=>new k(e)),s.z.instanceof(k)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const gi=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof N||r instanceof E||r instanceof Date},Eu=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):Vt(t,-n),Vt=(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),Ou=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Nu(r){return typeof r=="string"&&Ou.test(r)}const q=[];for(let r=0;r<256;++r)q.push((r+256).toString(16).slice(1));function zu(r,e=0){return(q[r[e+0]]+q[r[e+1]]+q[r[e+2]]+q[r[e+3]]+"-"+q[r[e+4]]+q[r[e+5]]+"-"+q[r[e+6]]+q[r[e+7]]+"-"+q[r[e+8]]+q[r[e+9]]+"-"+q[r[e+10]]+q[r[e+11]]+q[r[e+12]]+q[r[e+13]]+q[r[e+14]]+q[r[e+15]]).toLowerCase()}function Su(r,e=0){const t=zu(r,e);if(!Nu(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const pi=(r,e)=>Su(r,e),Te=-1,Vr={[Symbol.iterator]:()=>Vr,next:()=>({done:!0,value:void 0})},Au=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Iu=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Wr=10,mi=(r,e)=>{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`)},wi="sy_x_telem_series";class F{key;discriminator=wi;dataType;sampleOffset;gl;_data;timeRange=z.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Te;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:z.z.optional(),dataType:I.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Au,Iu,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Tu.optional().default("static").optional()});static z=F.crudeZ.transform(e=>new F(e));constructor(e){$u(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:u=fn(),data:l}=e;if(bi(l)){const d=l;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this.timeRange=d.timeRange,this.alignment=d.alignment,this.alignmentMultiple=d.alignmentMultiple,this.cachedMin=d.cachedMin,this.cachedMax=d.cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this.cachedLength=d.cachedLength;return}const h=gi(l),g=Array.isArray(l);if(t!=null)this.dataType=new I(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(g||h){let d=l;if(!h){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=l[0]}if(typeof d=="string")this.dataType=I.STRING;else if(typeof d=="number")this.dataType=I.FLOAT64;else if(typeof d=="bigint")this.dataType=I.INT64;else if(typeof d=="boolean")this.dataType=I.BOOLEAN;else if(d instanceof N||d instanceof Date||d instanceof N)this.dataType=I.TIMESTAMP;else if(typeof d=="object")this.dataType=I.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new I(l)}if(!g&&!h)this._data=l;else if(g&&l.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[l]:l;const O=d[0];(O instanceof N||O instanceof Date||O instanceof E)&&(d=d.map(S=>new N(S).valueOf())),this.dataType.equals(I.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
8
|
+
`).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]=[]}),i.forEach(c=>{const u=c.split(",").map(l=>l.trim());a.forEach((l,h)=>{const p=this.parseValue(u[h]);p!=null&&o[l].push(p)})}),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}},Qs=class{contentType="text/plain";encode(e){if(typeof e!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(e)}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const ht=new Js,Il=new Xs,$l=new Qs,kl=[ht],je=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Xs,CSV_CODEC:Il,ENCODERS:kl,JSONCodec:Js,JSON_CODEC:ht,TEXT_CODEC:$l,TextCodec:Qs},Symbol.toStringTag,{value:"Module"})),Fr=r=>[...new Set(r)],Cl=(r,e,t=!0)=>{const n=new Map;return r.forEach(i=>{const a=e(i);if(n.has(a)){if(t)return;n.delete(a)}n.set(a,i)}),Array.from(n.values())},Vn=Object.freeze(Object.defineProperty({__proto__:null,by:Cl,unique:Fr},Symbol.toStringTag,{value:"Module"}));let Ke=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const xl=r=>r!=null&&typeof r=="object"&&"toString"in r,nr=(r,e=!1)=>{const t=xl(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?ti(n):n},Rl=(r,e,t)=>{const n=nr(e[r],t);return(i,a)=>n(i[r],a[r])},Ml=(r,e)=>r.length!==e.length?r.length-e.length:r.every((t,n)=>t===e[n])?0:-1,ei=(r,e)=>{if(r.length!==e.length)return r.length-e.length;if(r.length===0)return 0;const t=nr(r[0]),n=[...r].sort(t),i=[...e].sort(t);return n.every((a,o)=>a===i[o])?0:-1},jl=(r,e)=>{const t=Fr(r),n=Fr(e);return ei(t,n)},Ul=(r,e)=>r===e?0:r==="first"&&e==="last"?1:-1,ti=r=>(e,t)=>r(t,e),Je=0,Ft=-1,Yt=1,ri=r=>r<Je,ni=r=>r>Je,Dl=r=>r>=Je,si=r=>r===Je,Pl=(r,e)=>{const t=/([a-zA-Z]+)|(\d+)/g,n=r.replace(/[\s_.-]+/g,"").match(t),i=e.replace(/[\s_.-]+/g,"").match(t);if(!n||!i)return 0;for(let a=0;a<Math.min(n.length,i.length);a++){const o=n[a],c=i[a];if(isNaN(Number(o))&&isNaN(Number(c))){const u=o.localeCompare(c);if(u!==0)return u}else if(!isNaN(Number(o))&&!isNaN(Number(c))){const u=Number(o)-Number(c);if(u!==0)return u}else return isNaN(Number(o))?-1:1}return n.length-i.length},Wn=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:Je,GREATER_THAN:Yt,LESS_THAN:Ft,isEqualTo:si,isGreaterThan:ni,isGreaterThanEqual:Dl,isLessThan:ri,newF:nr,newFieldF:Rl,order:Ul,primitiveArrays:Ml,reverseF:ti,stringsWithNumbers:Pl,uniqueUnorderedPrimitiveArrays:jl,unorderedPrimitiveArrays:ei},Symbol.toStringTag,{value:"Module"})),sr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ii=s.z.object({width:s.z.number(),height:s.z.number()}),Zl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Ll=["width","height"];s.z.enum(Ll);const Bl=["start","center","end"],ql=["signedWidth","signedHeight"];s.z.enum(ql);const _t=s.z.object({x:s.z.number(),y:s.z.number()}),Fl=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Yl=["x","y"],ai=s.z.enum(Yl),oi=["top","right","bottom","left"];s.z.enum(oi);const Vl=["left","right"],ci=s.z.enum(Vl),Wl=["top","bottom"],li=s.z.enum(Wl),ui=["center"],Hn=s.z.enum(ui),Hl=[...oi,...ui],hi=s.z.enum(Hl);s.z.enum(Bl);const _l=["first","last"];s.z.enum(_l);const Gl=s.z.object({lower:s.z.number(),upper:s.z.number()}),Kl=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Gl,sr]);s.z.union([Kl,sr]);s.z.enum([...ai.options,...hi.options]);s.z.enum(["x","left","right"]);s.z.enum(["y","top","bottom"]);s.z.union([ai,hi,s.z.instanceof(String)]);const Nt=r=>(e,t)=>{if(typeof e=="bigint"){if(Yr(t))return r(e,BigInt(t));const n=r(Number(e),Number(t));return typeof n=="number"?BigInt(Math.round(n)):n}return r(Number(e),Number(t))},Re=Nt((r,e)=>r-e),zt=Nt((r,e)=>r+e),_n=(r,e)=>{const t=typeof r=="bigint",n=typeof e=="bigint";return t&&n?r===e:t&&Yr(e)?r===BigInt(e):n&&Yr(r)?e===BigInt(r):r===e},Jl=Nt((r,e)=>r<=e?r:e),Yr=r=>typeof r=="bigint"?!0:Number.isInteger(r),Xl=r=>typeof r=="bigint"?r<0n?-r:r:r<0?-r:r,ce=Nt((r,e)=>r*e),ir=Nt((r,e)=>r/e),F=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?Ql(n):n},Ql=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Gn=(r,e)=>{const t=F(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},Pt=(r,e)=>{const t=F(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=F(e);return n.lower>=t.lower&&n.upper<=t.upper},eu=r=>({lower:Math.min(...r.map(e=>F(e).lower)),upper:Math.max(...r.map(e=>F(e).upper))}),tu=(r,e,t)=>{const n=r.map(c=>F(c)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;_n(a,0)===!1;){const c=n.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(c!==-1){const u=n[c];let l;if(i>0?l=Re(u.upper,o):l=Re(o,u.lower),l>0){const h=Jl(Xl(a),l);if(o=zt(o,i>0?h:-h),a=Re(a,i>0?h:-h),_n(a,0))return o;continue}}if(i>0){const u=n.filter(l=>l.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=n.filter(l=>l.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},ru=(r,e,t)=>{const n=r.map(o=>F(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?F([e,t]):F([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const c=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(c<u){const l=u-c;a=a+l}}return a};s.z.object({x:ci.or(Hn),y:li.or(Hn)});const nu=s.z.object({x:ci,y:li}),su=Object.freeze({x:"left",y:"top"}),iu=(r,e)=>r.x===e.x&&r.y===e.y,Kn=s.z.union([s.z.number(),_t,sr,ii,Zl,Fl]),au=(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}},Jn=Object.freeze({x:0,y:0}),Zt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Zt,left:Zt,width:Zt,height:Zt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:_t,two:_t,root:nu});const dn=(r,e,t=0,n=0,i)=>{const a={one:{...Jn},two:{...Jn},root:i??su};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:i??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))},Or=r=>{const e=dn(r);return{lower:e.one.x,upper:e.two.x}},Nr=r=>{const e=dn(r);return{lower:e.one.y,upper:e.two.y}},ou=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,cu=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ii,cu,_t,sr]);const lu=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Kn,scale:Kn});s.z.object({offset:s.z.number(),scale:s.z.number()});const uu=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],hu=r=>(e,t,n,i)=>[e,i?n/r:n*r],du=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:c}=r,u=a-i,l=c-o;if(t==="dimension")return[r,n*(l/u)];const h=(n-i)*(l/u)+o;return[r,h]},fu=r=>(e,t,n)=>[r,n],yu=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:i}=r;return[r,i-(t-n)]},gu=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=lu(n,i,a),[e,n]};let Xn=class Le{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Le().translate(e)}static magnify(e){return new Le().magnify(e)}static scale(e,t){return new Le().scale(e,t)}translate(e){const t=this.new(),n=uu(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=hu(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=F(e,t),i=this.new(),a=du(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=F(e,t),i=this.new(),a=gu(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=F(e,t),i=this.new(),a=fu(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=yu();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 Le;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,c])=>i>=o&&i<=c))return;const a=e.ops.findIndex((o,c)=>o.type==="scale"&&c>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Le},cw=class ae{x;y;currRoot;constructor(e=new Xn,t=new Xn,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ae().translate(e,t)}static translateX(e){return new ae().translateX(e)}static translateY(e){return new ae().translateY(e)}static clamp(e){return new ae().clamp(e)}static magnify(e){return new ae().magnify(e)}static scale(e){return new ae().scale(e)}static reBound(e){return new ae().reBound(e)}translate(e,t){const n=au(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}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(ou(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!iu(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(Or(e)),t.y=t.y.scale(Nr(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(Or(e)),t.y=this.y.reBound(Nr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Or(e)),t.y=this.y.clamp(Nr(e)),t}copy(){const e=new ae;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 dn(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})}}static IDENTITY=new ae},di=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const fi="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pu=`0123456789${fi}`,yi=11,mu=di(fi,1),wu=di(pu,yi-1),fn=()=>`${mu()}${wu()}`,bu=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:yi,create:fn},Symbol.toStringTag,{value:"Module"})),Tu=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,vu=s.z.enum(["static","dynamic"]),Eu=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),gi=(r,e)=>{const t=new d(e);if(![E.DAY,E.HOUR,E.MINUTE,E.SECOND,E.MILLISECOND,E.MICROSECOND,E.NANOSECOND].some(i=>i.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 d?new d(n):new E(n)};class d extends Ke{constructor(e,t="UTC"){if(e==null)super(d.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*d.MILLISECOND.valueOf());else if(typeof e=="string")super(d.parseDateTimeString(e,t).valueOf());else if(Array.isArray(e))super(d.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=d.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=d.MAX:e=d.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new d(BigInt(i.getTime())*d.MILLISECOND.valueOf()).truncate(d.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",c="00";a!=null&&([o,c]=a.split("."));let u=d.hours(parseInt(n??"00")).add(d.minutes(parseInt(i??"00"))).add(d.seconds(parseInt(o??"00"))).add(d.milliseconds(parseInt(c??"00")));return t==="local"&&(u=u.add(d.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return d.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new d(BigInt(n.getTime())*d.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(d.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 E(BigInt(new Date().getTimezoneOffset())*d.MINUTE.valueOf())}static since(e){return new d().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new d(e).valueOf()}span(e){return this.range(e).span}range(e){return new M(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new d(e).valueOf()}afterEq(e){return this.valueOf()>=new d(e).valueOf()}before(e){return this.valueOf()<new d(e).valueOf()}beforeEq(e){return this.valueOf()<=new d(e).valueOf()}add(e){return new d(zt(this.valueOf(),new E(e).valueOf()))}sub(e){return new d(Re(this.valueOf(),new E(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(d.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(d.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const t=this.date();return t.setUTCFullYear(e),new d(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new d(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new d(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new d(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new d(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new d(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new d(t)}toString(){return this.date().toISOString()}remainder(e){return gi(this,e)}get isToday(){return this.truncate(E.DAY).equals(d.now().truncate(E.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new d(new Date)}static max(...e){let t=d.MIN;for(const n of e){const i=new d(n);i.after(t)&&(t=i)}return t}static min(...e){let t=d.MAX;for(const n of e){const i=new d(n);i.before(t)&&(t=i)}return t}static nanoseconds(e,t="UTC"){return new d(e,t)}static NANOSECOND=d.nanoseconds(1);static microseconds(e,t="UTC"){return d.nanoseconds(e*1e3,t)}static MICROSECOND=d.microseconds(1);static milliseconds(e,t="UTC"){return d.microseconds(e*1e3,t)}static MILLISECOND=d.milliseconds(1);static seconds(e,t="UTC"){return d.milliseconds(e*1e3,t)}static SECOND=d.seconds(1);static minutes(e,t="UTC"){return d.seconds(e*60,t)}static MINUTE=d.minutes(1);static hours(e,t="UTC"){return d.minutes(e*60,t)}static HOUR=d.hours(1);static days(e,t="UTC"){return d.hours(e*24,t)}static DAY=d.days(1);static MAX=new d((1n<<63n)-1n);static MIN=new d(0);static ZERO=new d(0);static z=s.z.union([s.z.instanceof(d),s.z.object({value:s.z.bigint()}).transform(e=>new d(e.value)),s.z.string().transform(e=>new d(BigInt(e))),s.z.number().transform(e=>new d(e)),s.z.bigint().transform(e=>new d(e)),s.z.date().transform(e=>new d(e)),s.z.custom(e=>e instanceof E).transform(e=>new d(e)),Eu.transform(e=>new d(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}}let E=class T extends Ke{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof T?e:e instanceof _?e.period:e instanceof d?new T(e):["number","bigint"].includes(typeof e)?T.seconds(e):new T(e)}static fromMilliseconds(e){return e instanceof T?e:e instanceof _?e.period:e instanceof d?new T(e):["number","bigint"].includes(typeof e)?T.milliseconds(e):new T(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new T(e).valueOf()}greaterThan(e){return this.valueOf()>new T(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new T(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new T(e).valueOf()}remainder(e){return gi(this,e)}truncate(e){return new T(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(T.DAY),t=this.truncate(T.HOUR),n=this.truncate(T.MINUTE),i=this.truncate(T.SECOND),a=this.truncate(T.MILLISECOND),o=this.truncate(T.MICROSECOND),c=this.truncate(T.NANOSECOND),u=e,l=t.sub(e),h=n.sub(t),p=i.sub(n),f=a.sub(i),O=o.sub(a),N=c.sub(o);let k="";return u.isZero||(k+=`${u.days}d `),l.isZero||(k+=`${l.hours}h `),h.isZero||(k+=`${h.minutes}m `),p.isZero||(k+=`${p.seconds}s `),f.isZero||(k+=`${f.milliseconds}ms `),O.isZero||(k+=`${O.microseconds}µs `),N.isZero||(k+=`${N.nanoseconds}ns`),k.trim()}mult(e){return new T(ce(this.valueOf(),e))}div(e){return new T(ir(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(T.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(T.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(T.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(T.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 isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new T(e).valueOf()}add(e){return new T(this.valueOf()+new T(e).valueOf())}sub(e){return new T(this.valueOf()-new T(e).valueOf())}static nanoseconds(e=1){return new T(e)}static NANOSECOND=T.nanoseconds(1);static microseconds(e=1){return T.nanoseconds(ce(e,1e3))}static MICROSECOND=T.microseconds(1);static milliseconds(e=1){return T.microseconds(ce(e,1e3))}static MILLISECOND=T.milliseconds(1);static seconds(e=1){return T.milliseconds(ce(e,1e3))}static SECOND=T.seconds(1);static minutes(e=1){return T.seconds(ce(e,60))}static MINUTE=T.minutes(1);static hours(e){return T.minutes(ce(e,60))}static HOUR=T.hours(1);static days(e){return T.hours(ce(e,24))}static DAY=T.days(1);static MAX=new T((1n<<63n)-1n);static MIN=new T(0);static ZERO=new T(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new T(e.value)),s.z.string().transform(e=>new T(BigInt(e))),s.z.number().transform(e=>new T(e)),s.z.bigint().transform(e=>new T(e)),s.z.instanceof(T),s.z.instanceof(d).transform(e=>new T(e)),s.z.custom(e=>e instanceof _).transform(e=>new T(e))])};class _ extends Ke{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new _(e).valueOf()}get period(){return E.seconds(1/this.valueOf())}sampleCount(e){return new E(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new W(t).valueOf()}span(e){return E.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}add(e){return new _(zt(this.valueOf(),e.valueOf()))}sub(e){return new _(Re(this.valueOf(),e.valueOf()))}mult(e){return new _(ce(this.valueOf(),e))}div(e){return new _(ir(this.valueOf(),e))}static hz(e){return new _(e)}static khz(e){return _.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new _(e)),s.z.instanceof(_)])}let W=class K extends Ke{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new He(e*this.valueOf())}add(e){return new K(zt(this.valueOf(),e.valueOf()))}sub(e){return new K(Re(this.valueOf(),e.valueOf()))}mult(e){return new K(ce(this.valueOf(),e))}div(e){return new K(ir(this.valueOf(),e))}static UNKNOWN=new K(0);static BIT128=new K(16);static BIT64=new K(8);static BIT32=new K(4);static BIT16=new K(2);static BIT8=new K(1);static z=s.z.union([s.z.number().transform(e=>new K(e)),s.z.instanceof(K)])},M=class ee{start;end;constructor(e,t){typeof e=="object"&&"start"in e?(this.start=new d(e.start),this.end=new d(e.end)):(this.start=new d(e),this.end=new d(t))}get span(){return new E(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 ee(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=E.ZERO){if(t.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return n<0&&(n=-n),i<0&&(i=-i),n<=t.valueOf()&&i<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=E.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 i=d.max(n.start,e.start),a=d.min(n.end,e.end);return a.before(i)?!1:new E(a.sub(i)).greaterThanOrEqual(t)}contains(e){return e instanceof ee?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new ee(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 ee(d.min(...e.map(t=>t.start)),d.max(...e.map(t=>t.end)))}static MAX=new ee(d.MIN,d.MAX);static MIN=new ee(d.MAX,d.MIN);static ZERO=new ee(d.ZERO,d.ZERO);static z=s.z.union([s.z.object({start:d.z,end:d.z}).transform(e=>new ee(e.start,e.end)),s.z.instanceof(ee)]);static sort(e,t){return d.sort(e.start,t.start)||d.sort(e.end,t.end)}static simplify(e){return e.map(t=>t.makeValid()).sort((t,n)=>ee.sort(t,n)).reduce((t,n)=>{if(n.isZero)return t;if(t.length===0)return t.push(n),t;const i=t[t.length-1];return i.overlapsWith(n)||i.end.equals(n.start)?i.end=d.max(i.end,n.end):t.push(n),t},[])}},S=class g extends Ke{constructor(e){if(e instanceof g||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=g.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.valueOf())}}get Array(){const e=g.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(g.JSON)||this.equals(g.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(g.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=g.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(g.UINT8)||this.equals(g.UINT16)||this.equals(g.UINT32)||this.equals(g.UINT64)}get isSignedInteger(){return this.equals(g.INT8)||this.equals(g.INT16)||this.equals(g.INT32)||this.equals(g.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(g.INT32)&&e.equals(g.FLOAT64)||this.equals(g.INT8)&&e.equals(g.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return g.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new g("unknown");static FLOAT64=new g("float64");static FLOAT32=new g("float32");static INT64=new g("int64");static INT32=new g("int32");static INT16=new g("int16");static INT8=new g("int8");static UINT64=new g("uint64");static UINT32=new g("uint32");static UINT16=new g("uint16");static UINT8=new g("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new g("timestamp");static UUID=new g("uuid");static STRING=new g("string");static JSON=new g("json");static ARRAY_CONSTRUCTORS=new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]]);static DENSITIES=new Map([[g.UINT8.toString(),W.BIT8],[g.UINT16.toString(),W.BIT16],[g.UINT32.toString(),W.BIT32],[g.UINT64.toString(),W.BIT64],[g.FLOAT32.toString(),W.BIT32],[g.FLOAT64.toString(),W.BIT64],[g.INT8.toString(),W.BIT8],[g.INT16.toString(),W.BIT16],[g.INT32.toString(),W.BIT32],[g.INT64.toString(),W.BIT64],[g.TIMESTAMP.toString(),W.BIT64],[g.STRING.toString(),W.UNKNOWN],[g.JSON.toString(),W.UNKNOWN],[g.UUID.toString(),W.BIT128]]);static ALL=[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON];static BIG_INT_TYPES=[g.INT64,g.UINT64,g.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new g(e)),s.z.instanceof(g)])},He=class $ extends Ke{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new $(zt(this.valueOf(),e.valueOf()))}sub(e){return new $(Re(this.valueOf(),e.valueOf()))}mult(e){return new $(ce(this.valueOf(),e))}div(e){return new $(ir(this.valueOf(),e))}truncate(e){return new $(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return $.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/$.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/$.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/$.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/$.TERABYTE.valueOf()}toString(){const e=this.truncate($.TERABYTE),t=this.truncate($.GIGABYTE),n=this.truncate($.MEGABYTE),i=this.truncate($.KILOBYTE),a=this.truncate($.BYTE),o=e,c=t.sub(e),u=n.sub(t),l=i.sub(n),h=a.sub(i);let p="";return o.isZero||(p+=`${o.terabytes}TB `),c.isZero||(p+=`${c.gigabytes}GB `),u.isZero||(p+=`${u.megabytes}MB `),l.isZero||(p+=`${l.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new $(e)}static BYTE=new $(1);static kilobytes(e=1){return $.bytes(e.valueOf()*1e3)}static KILOBYTE=$.kilobytes(1);static megabytes(e=1){return $.kilobytes(e.valueOf()*1e3)}static MEGABYTE=$.megabytes(1);static gigabytes(e=1){return $.megabytes(e.valueOf()*1e3)}static GIGABYTE=$.gigabytes(1);static terabytes(e){return $.gigabytes(e.valueOf()*1e3)}static TERABYTE=$.terabytes(1);static ZERO=new $(0);static z=s.z.union([s.z.number().transform(e=>new $(e)),s.z.instanceof($)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const pi=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof d||r instanceof E||r instanceof Date},Ou=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):Vt(t,-n),Vt=(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),Nu=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function zu(r){return typeof r=="string"&&Nu.test(r)}const B=[];for(let r=0;r<256;++r)B.push((r+256).toString(16).slice(1));function Su(r,e=0){return(B[r[e+0]]+B[r[e+1]]+B[r[e+2]]+B[r[e+3]]+"-"+B[r[e+4]]+B[r[e+5]]+"-"+B[r[e+6]]+B[r[e+7]]+"-"+B[r[e+8]]+B[r[e+9]]+"-"+B[r[e+10]]+B[r[e+11]]+B[r[e+12]]+B[r[e+13]]+B[r[e+14]]+B[r[e+15]]).toLowerCase()}function Au(r,e=0){const t=Su(r,e);if(!zu(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const mi=(r,e)=>Au(r,e),Te=-1,Vr={[Symbol.iterator]:()=>Vr,next:()=>({done:!0,value:void 0})},Iu=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),$u=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Wr=10,wi=(r,e)=>{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`)},bi="sy_x_telem_series";class q{key;discriminator=bi;dataType;sampleOffset;gl;_data;timeRange=M.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Te;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:M.z.optional(),dataType:S.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Iu,$u,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:vu.optional().default("static").optional()});static z=q.crudeZ.transform(e=>new q(e));constructor(e){ku(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,alignmentMultiple:c=1n,key:u=fn(),data:l}=e;if(Ti(l)){const f=l;this.key=f.key,this.dataType=f.dataType,this.sampleOffset=f.sampleOffset,this.gl=f.gl,this._data=f._data,this.timeRange=f.timeRange,this.alignment=f.alignment,this.alignmentMultiple=f.alignmentMultiple,this.cachedMin=f.cachedMin,this.cachedMax=f.cachedMax,this.writePos=f.writePos,this._refCount=f._refCount,this.cachedLength=f.cachedLength;return}const h=pi(l),p=Array.isArray(l);if(t!=null)this.dataType=new S(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(p||h){let f=l;if(!h){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");f=l[0]}if(typeof f=="string")this.dataType=S.STRING;else if(typeof f=="number")this.dataType=S.FLOAT64;else if(typeof f=="bigint")this.dataType=S.INT64;else if(typeof f=="boolean")this.dataType=S.BOOLEAN;else if(f instanceof d||f instanceof Date||f instanceof d)this.dataType=S.TIMESTAMP;else if(typeof f=="object")this.dataType=S.JSON;else throw new Error(`cannot infer data type of ${typeof f} when constructing a Series from a JS array`)}else this.dataType=new S(l)}if(!p&&!h)this._data=l;else if(p&&l.length===0)this._data=new this.dataType.Array([]).buffer;else{let f=h?[l]:l;const O=f[0];(O instanceof d||O instanceof Date||O instanceof E)&&(f=f.map(N=>new d(N).valueOf())),this.dataType.equals(S.STRING)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.join(`
|
|
9
9
|
`)}
|
|
10
|
-
`).buffer):this.dataType.equals(
|
|
10
|
+
`).buffer):this.dataType.equals(S.JSON)?(this.cachedLength=f.length,this._data=new TextEncoder().encode(`${f.map(N=>ht.encodeString(N)).join(`
|
|
11
11
|
`)}
|
|
12
|
-
`).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(
|
|
13
|
-
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(I.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(ht.decodeString(t)))}get byteCapacity(){return new He(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Te?this.byteCapacity:this.dataType.isVariable?new He(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Te?this.byteCapacity.valueOf()/this.dataType.density.valueOf():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,i)=>{n===Wr&&(e++,t.push(i+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 i=0;i<this.length;i++)n[i]=Eu(this.dataType,e,this.data[i],t);return new F({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(I.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(){return this.calcMax()}calcMax(){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.calcRawMax(),Vt(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(I.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(){return this.calcMin()}calcMin(){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.calcRawMin(),Vt(this.cachedMin,this.sampleOffset))}get bounds(){return Y(Number(this.min),Number(this.max),{makeValid:!1})}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)}}atAlignment(e,t){const n=Number((e-this.alignment)/this.alignmentMultiple);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=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(I.UUID))return this.atUUID(e,t);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 Vt(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=pi(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=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]===Wr){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(I.STRING)?new TextDecoder().decode(a):hn(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=nr(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(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(I.FLOAT32)&&!this.dataType.equals(I.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Te){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).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=Te}as(e){return mi(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:es(this.alignmentBounds.lower),upper:es(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return Y(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 ku(this);return this.dataType.equals(I.JSON)?new Cu(e):e}return this.dataType.equals(I.UUID)?new xu(this):new Ru(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Qn(this,e,t??this.length)}subAlignmentIterator(e,t){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),i=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new Qn(this,n,i)}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new F({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 i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new F({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new F({data:this.buffer,dataType:this.dataType,timeRange:z.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}}const $u=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof F?!0:gi(r),bi=bu(wi,F);class Qn{series;end;index;constructor(e,t,n){this.series=e;const i=Y(0,e.length+1);this.end=Gn(i,n),this.index=Gn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let ku=class{series;index;decoder;constructor(e){if(!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]!==Wr;)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))})}},Cu=class Ti{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:ht.decodeString(e.value,Ti.schema)}}};class xu{series;index;data;density;constructor(e){if(!e.dataType.equals(I.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=I.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=pi(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Ru=class{series;index;constructor(e){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)}}},vi=class{series;constructor(e=[]){if(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 mi(e,this.dataType),this}get dataType(){return this.series.length===0?I.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?z.ZERO:new z(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?Y(0n,0n):Y(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const t=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),n=e.dataType.equals(this.dataType);if(bi(e)){if(this.series.length!==0&&!n)throw t();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!n)throw t();this.series.push(...e.series)}}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){for(const n of this.series)if(Pt(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 zr(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return Vr;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(Pt(o.alignmentBounds,e)){n+=Math.ceil(Number(e-o.alignment)/Number(o.alignmentMultiple));break}}let i=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)i+=o.length;else if(Pt(o.alignmentBounds,t)){i+=Math.ceil(Number(t-o.alignment)/Number(o.alignmentMultiple));break}}return new zr(this,n,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return Vr;t=Math.min(t,Number(this.distance(e,this.alignmentBounds.upper)));let n=0;for(let i=0;i<this.series.length;i++){const a=this.series[i];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)n+=a.length;else if(Pt(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new zr(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return Ql(this.series.map(e=>e.bounds))}get byteLength(){return new He(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(i=>i.alignmentBounds);return eu(n,e,t)}acquire(e){this.series.forEach(t=>t.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,t){const n=this.series.map(i=>i.alignmentBounds);return tu(n,e,t)}parseJSON(e){if(!this.dataType.equals(I.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 Mu(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}},Mu=class{series;seriesIndex;internal;constructor(e){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())}[Symbol.iterator](){return this}};class zr{series;index;end;constructor(e,t,n){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 es=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},ju=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Uu=(r,e,t=".")=>{const n=r.split(t);return n.map((i,a)=>{const o=e(i,a,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(i=>i!=null).join(t)},Du=(r,e)=>{if(!Array.isArray(r))return r[e];const t=r[e];if(t!=null||r.length==0)return t;const n=r[0];if(typeof n=="object"&&"key"in n)return r.find(i=>i.key===e)},Pu=(r,e,t={optional:!1,separator:"."})=>{t.separator??=".";const{optional:n,getter:i=Du}=t,a=e.split(t.separator);if(a.length===1&&a[0]==="")return r;let o=r;for(const c of a){const u=i(o,c);if(u==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${c} is null`)}o=u}return o};s.z.object({key:s.z.string(),value:s.z.string()});class Zu{handlers;transform;closer;constructor(e,t){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,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}let Lu=class{handlers;constructor(e){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 Bu=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Lu,Observer:Zu},Symbol.toStringTag,{value:"Module"})),qu=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),yn=r=>Object.entries(r),Fu=(r,e)=>Object.fromEntries(yn(r).map(([t,n])=>[t,e(n,t)])),Yu=r=>Object.fromEntries(yn(r).filter(([e,t])=>t!==void 0)),ge=Object.freeze(Object.defineProperty({__proto__:null,entries:yn,map:Fu,purgeUndefined:Yu,unknownZ:qu},Symbol.toStringTag,{value:"Module"})),Vu=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Vu();const Wu=["macOS","Windows","Linux"],Hu=["macos","windows","linux"],_u={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(Wu).or(s.z.enum(Hu).transform(r=>_u[r]));const Gu=(...r)=>r.map(Ei).join(""),Ei=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Ku=r=>r.endsWith("/")?r.slice(0,-1):r;class lt{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){this.protocol=n,this.host=e,this.port=t,this.path=Ei(i)}replace(e){return new lt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new lt({...this,pathPrefix:Gu(this.path,e)})}toString(){return Ku(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new lt({host:"unknown",port:0})}const Ju=r=>r.nullable().transform(e=>e===null?void 0:e).optional(),Xu=r=>s.array(r).or(r.transform(e=>[e])),Oi=r=>Uu(r,(e,t,n)=>{const i=t===n.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[t+1]));return a&&(e="element"),i||o?e:[e,"shape"]}),ts=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},Qu=(r,e,t)=>e===""?r:Pu(ts(r,"shape"),Oi(e),{...t,getter:ts}),ut=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:Qu,getFieldSchemaPath:Oi,nullToUndefined:Ju,toArray:Xu},Symbol.toStringTag,{value:"Module"})),eh=async r=>await new Promise(e=>setTimeout(e,E.fromMilliseconds(r).milliseconds));class th{config;retries;interval;constructor(e){this.config={baseInterval:new E(e?.baseInterval??E.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??eh},this.retries=0,this.interval=new E(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)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const rh=s.z.object({baseInterval:E.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Ni=Object.freeze(Object.defineProperty({__proto__:null,Breaker:th,breakerConfigZ:rh},Symbol.toStringTag,{value:"Module"})),nh=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,zi=s.z.string().regex(nh),Ye=s.z.number().min(0).max(255),Si=s.z.number().min(0).max(1),Ai=s.z.tuple([Ye,Ye,Ye,Si]),sh=s.z.tuple([Ye,Ye,Ye]),ih=s.z.object({rgba255:Ai}),ah=s.z.number().min(0).max(360),oh=s.z.number().min(0).max(100),ch=s.z.number().min(0).max(100),lh=s.z.tuple([ah,oh,ch,Si]),gn=s.z.union([zi,sh,Ai,lh,ih]),uh=gn.transform(r=>pn(r)),pn=(r,e=1)=>{if(r=gn.parse(r),typeof r=="string")return hh(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}return r.rgba255},hh=(r,e=1)=>(r=zi.parse(r),r=dh(r),[Lt(r,0),Lt(r,2),Lt(r,4),r.length===8?Lt(r,6)/255:e]),Lt=(r,e)=>parseInt(r.slice(e,e+2),16),dh=r=>r.startsWith("#")?r.slice(1):r;pn("#000000");pn("#ffffff");const fh=s.z.object({key:s.z.string(),color:gn,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(fh);const yh=s.z.object({key:s.z.string(),name:s.z.string(),color:uh});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(yh)});const Ii=s.z.int().min(0).max(255),$i=255,ki=0,gh={lower:ki,upper:$i+1},Ci=s.z.object({name:s.z.string(),key:s.z.string()}),dt=r=>s.z.object({subject:Ci,resource:r,authority:Ii}),ph=(...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}),xi=r=>s.z.object({from:dt(r),to:s.z.null()}),Ri=r=>s.z.object({from:s.z.null(),to:dt(r)}),mh=r=>s.z.union([xi(r),Ri(r),s.z.object({from:dt(r),to:dt(r)})]),Q=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:$i,AUTHORITY_BOUNDS:gh,ZERO_AUTHORITY:ki,acquireZ:Ri,authorityZ:Ii,filterTransfersByChannelKey:ph,releaseZ:xi,stateZ:dt,subjectZ:Ci,transferZ:mh},Symbol.toStringTag,{value:"Module"})),wh=r=>Object.getOwnPropertySymbols(globalThis).includes(r),bh=(r,e)=>{const t=Symbol.for(r);if(!wh(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},Mi="sy_x_error",Th=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),St=r=>class ct extends Error{static discriminator=Mi;discriminator=ct.discriminator;static TYPE=r;type=ct.TYPE;static matches=Th(r);matches=ct.matches;constructor(t,n){super(t,n),this.name=ct.TYPE}static sub(t){return St(`${r}.${t}`)}},ji=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==Mi)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Be="unknown",Hr="nil";class vh{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Hr,data:""};if(ji(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Be,data:e.message};if(typeof e=="string")return{type:Be,data:e};try{return{type:Be,data:JSON.stringify(e)}}catch{return{type:Be,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Hr)return null;if(e.type===Be)return new _r(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new _r(e.data)}}const mn=bh("synnax-error-registry",()=>new vh),Eh=({encode:r,decode:e})=>mn().register({encode:r,decode:e}),Oh=r=>mn().encode(r),Nh=r=>r==null?null:mn().decode(r);class _r extends St("unknown"){}const zh=s.z.object({type:s.z.string(),data:s.z.string()});class Sh extends St("canceled"){}class Ah extends St("not_implemented"){}const ye=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Sh,NONE:Hr,NotImplemented:Ah,UNKNOWN:Be,Unknown:_r,createTyped:St,decode:Nh,encode:Oh,isTyped:ji,payloadZ:zh,register:Eh},Symbol.toStringTag,{value:"Module"})),Ih=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Ui=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),$h=Ui.extend({result:s.json()}),kh=Ui.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),Ch=s.union([$h,kh]);s.union([Ih,Ch]);const Gr=s.z.string().regex(/^\d+\.\d+\.\d+$/),At=(r,e,t={})=>{t.checkMajor??=!0,t.checkMinor??=!0,t.checkPatch??=!0;const n=Gr.parse(r),i=Gr.parse(e),[a,o,c]=n.split(".").map(Number),[u,l,h]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return Ft;if(a>u)return Yt}if(t.checkMinor){if(o<l)return Ft;if(o>l)return Yt}if(t.checkPatch){if(c<h)return Ft;if(c>h)return Yt}return Je},xh=(r,e,t={})=>ni(At(r,e,t)),Di=(r,e,t={})=>ri(At(r,e,t)),Rh=(r,e,t={})=>ti(At(r,e,t)),Mh=({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}},jh=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(At).pop();if(a==null)return l=>{if(l.version??=n,l.version!==i.version)return console.log(`${r} version ${l.version} is newer than latest version of ${i.version}.
|
|
12
|
+
`).buffer):this.dataType.usesBigInt&&typeof O=="number"?this._data=new this.dataType.Array(f.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof O=="bigint"?this._data=new this.dataType.Array(f.map(Number)).buffer:this._data=new this.dataType.Array(f).buffer}this.key=u,this.alignment=o,this.alignmentMultiple=c,this.sampleOffset=i??0,this.timeRange=n??M.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new S(t).Array(e),a=new q({data:i.buffer,dataType:t,...n});return a.writePos=0,a}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}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===Te)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===Te)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===Te?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
|
|
13
|
+
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(S.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(ht.decodeString(t)))}get byteCapacity(){return new He(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Te?this.byteCapacity:this.dataType.isVariable?new He(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Te?this.byteCapacity.valueOf()/this.dataType.density.valueOf():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,i)=>{n===Wr&&(e++,t.push(i+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 i=0;i<this.length;i++)n[i]=Ou(this.dataType,e,this.data[i],t);return new q({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(S.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(){return this.calcMax()}calcMax(){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.calcRawMax(),Vt(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(S.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(){return this.calcMin()}calcMin(){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.calcRawMin(),Vt(this.cachedMin,this.sampleOffset))}get bounds(){return F(Number(this.min),Number(this.max),{makeValid:!1})}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)}}atAlignment(e,t){const n=Number((e-this.alignment)/this.alignmentMultiple);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=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(S.UUID))return this.atUUID(e,t);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 Vt(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=mi(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=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]===Wr){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(S.STRING)?new TextDecoder().decode(a):hn(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=nr(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(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(S.FLOAT32)&&!this.dataType.equals(S.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Te){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).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=Te}as(e){return wi(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:es(this.alignmentBounds.lower),upper:es(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return F(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}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 Cu(this);return this.dataType.equals(S.JSON)?new xu(e):e}return this.dataType.equals(S.UUID)?new Ru(this):new Mu(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Qn(this,e,t??this.length)}subAlignmentIterator(e,t){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),i=Math.ceil(Number(t-this.alignment)/Number(this.alignmentMultiple));return new Qn(this,n,i)}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new q({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 i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new q({data:i,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new q({data:this.buffer,dataType:this.dataType,timeRange:M.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}}const ku=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof q?!0:pi(r),Ti=Tu(bi,q);class Qn{series;end;index;constructor(e,t,n){this.series=e;const i=F(0,e.length+1);this.end=Gn(i,n),this.index=Gn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let Cu=class{series;index;decoder;constructor(e){if(!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]!==Wr;)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))})}},xu=class vi{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:ht.decodeString(e.value,vi.schema)}}};class Ru{series;index;data;density;constructor(e){if(!e.dataType.equals(S.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=S.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=mi(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Mu=class{series;index;constructor(e){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)}}},Ei=class{series;constructor(e=[]){if(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 wi(e,this.dataType),this}get dataType(){return this.series.length===0?S.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?M.ZERO:new M(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?F(0n,0n):F(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const t=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),n=e.dataType.equals(this.dataType);if(Ti(e)){if(this.series.length!==0&&!n)throw t();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!n)throw t();this.series.push(...e.series)}}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){for(const n of this.series)if(Pt(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 zr(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return Vr;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(Pt(o.alignmentBounds,e)){n+=Math.ceil(Number(e-o.alignment)/Number(o.alignmentMultiple));break}}let i=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)i+=o.length;else if(Pt(o.alignmentBounds,t)){i+=Math.ceil(Number(t-o.alignment)/Number(o.alignmentMultiple));break}}return new zr(this,n,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return Vr;t=Math.min(t,Number(this.distance(e,this.alignmentBounds.upper)));let n=0;for(let i=0;i<this.series.length;i++){const a=this.series[i];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)n+=a.length;else if(Pt(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new zr(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return eu(this.series.map(e=>e.bounds))}get byteLength(){return new He(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(i=>i.alignmentBounds);return tu(n,e,t)}acquire(e){this.series.forEach(t=>t.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,t){const n=this.series.map(i=>i.alignmentBounds);return ru(n,e,t)}parseJSON(e){if(!this.dataType.equals(S.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 ju(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}},ju=class{series;seriesIndex;internal;constructor(e){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())}[Symbol.iterator](){return this}};class zr{series;index;end;constructor(e,t,n){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 es=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},Uu=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Du=(r,e,t=".")=>{const n=r.split(t);return n.map((i,a)=>{const o=e(i,a,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(i=>i!=null).join(t)},Pu=(r,e)=>{if(!Array.isArray(r))return r[e];const t=r[e];if(t!=null||r.length==0)return t;const n=r[0];if(typeof n=="object"&&"key"in n)return r.find(i=>i.key===e)},Zu=(r,e,t={optional:!1,separator:"."})=>{t.separator??=".";const{optional:n,getter:i=Pu}=t,a=e.split(t.separator);if(a.length===1&&a[0]==="")return r;let o=r;for(const c of a){const u=i(o,c);if(u==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${c} is null`)}o=u}return o};s.z.object({key:s.z.string(),value:s.z.string()});let Lu=class{handlers;transform;closer;constructor(e,t){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,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}},Bu=class{handlers;constructor(e){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 qu=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Bu,Observer:Lu},Symbol.toStringTag,{value:"Module"})),Fu=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),yn=r=>Object.entries(r),Yu=(r,e)=>Object.fromEntries(yn(r).map(([t,n])=>[t,e(n,t)])),Vu=r=>Object.fromEntries(yn(r).filter(([e,t])=>t!==void 0)),Wu=(r,...e)=>{const t={...r};for(const n of e)delete t[n];return t},ge=Object.freeze(Object.defineProperty({__proto__:null,entries:yn,map:Yu,omit:Wu,purgeUndefined:Vu,unknownZ:Fu},Symbol.toStringTag,{value:"Module"})),Hu=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Hu();const _u=["macOS","Windows","Linux"],Gu=["macos","windows","linux"],Ku={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(_u).or(s.z.enum(Gu).transform(r=>Ku[r]));const Ju=(...r)=>r.map(Oi).join(""),Oi=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Xu=r=>r.endsWith("/")?r.slice(0,-1):r;class lt{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){this.protocol=n,this.host=e,this.port=t,this.path=Oi(i)}replace(e){return new lt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new lt({...this,pathPrefix:Ju(this.path,e)})}toString(){return Xu(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new lt({host:"unknown",port:0})}const Qu=r=>r.nullable().transform(e=>e===null?void 0:e).optional(),eh=r=>s.array(r).or(r.transform(e=>[e])),Ni=r=>Du(r,(e,t,n)=>{const i=t===n.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[t+1]));return a&&(e="element"),i||o?e:[e,"shape"]}),ts=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},th=(r,e,t)=>e===""?r:Zu(ts(r,"shape"),Ni(e),{...t,getter:ts}),ut=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:th,getFieldSchemaPath:Ni,nullToUndefined:Qu,toArray:eh},Symbol.toStringTag,{value:"Module"})),rh=async r=>await new Promise(e=>setTimeout(e,E.fromMilliseconds(r).milliseconds));class nh{config;retries;interval;constructor(e){this.config={baseInterval:new E(e?.baseInterval??E.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??rh},this.retries=0,this.interval=new E(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)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const sh=s.z.object({baseInterval:E.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),zi=Object.freeze(Object.defineProperty({__proto__:null,Breaker:nh,breakerConfigZ:sh},Symbol.toStringTag,{value:"Module"})),ih=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Si=s.z.string().regex(ih),Ye=s.z.number().min(0).max(255),Ai=s.z.number().min(0).max(1),Ii=s.z.tuple([Ye,Ye,Ye,Ai]),ah=s.z.tuple([Ye,Ye,Ye]),oh=s.z.object({rgba255:Ii}),ch=s.z.number().min(0).max(360),lh=s.z.number().min(0).max(100),uh=s.z.number().min(0).max(100),hh=s.z.tuple([ch,lh,uh,Ai]),gn=s.z.union([Si,ah,Ii,hh,oh]),dh=gn.transform(r=>pn(r)),pn=(r,e=1)=>{if(r=gn.parse(r),typeof r=="string")return fh(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}return r.rgba255},fh=(r,e=1)=>(r=Si.parse(r),r=yh(r),[Lt(r,0),Lt(r,2),Lt(r,4),r.length===8?Lt(r,6)/255:e]),Lt=(r,e)=>parseInt(r.slice(e,e+2),16),yh=r=>r.startsWith("#")?r.slice(1):r;pn("#000000");pn("#ffffff");const gh=s.z.object({key:s.z.string(),color:gn,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(gh);const ph=s.z.object({key:s.z.string(),name:s.z.string(),color:dh});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(ph)});const $i=s.z.int().min(0).max(255),ki=255,Ci=0,mh={lower:Ci,upper:ki+1},xi=s.z.object({name:s.z.string(),key:s.z.string()}),dt=r=>s.z.object({subject:xi,resource:r,authority:$i}),wh=(...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}),Ri=r=>s.z.object({from:dt(r),to:s.z.null()}),Mi=r=>s.z.object({from:s.z.null(),to:dt(r)}),bh=r=>s.z.union([Ri(r),Mi(r),s.z.object({from:dt(r),to:dt(r)})]),X=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:ki,AUTHORITY_BOUNDS:mh,ZERO_AUTHORITY:Ci,acquireZ:Mi,authorityZ:$i,filterTransfersByChannelKey:wh,releaseZ:Ri,stateZ:dt,subjectZ:xi,transferZ:bh},Symbol.toStringTag,{value:"Module"})),Th=r=>Object.getOwnPropertySymbols(globalThis).includes(r),vh=(r,e)=>{const t=Symbol.for(r);if(!Th(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},ji="sy_x_error",Eh=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),St=r=>class ct extends Error{static discriminator=ji;discriminator=ct.discriminator;static TYPE=r;type=ct.TYPE;static matches=Eh(r);matches=ct.matches;constructor(t,n){super(t,n),this.name=ct.TYPE}static sub(t){return St(`${r}.${t}`)}},Ui=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==ji)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Be="unknown",Hr="nil";class Oh{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Hr,data:""};if(Ui(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Be,data:e.message};if(typeof e=="string")return{type:Be,data:e};try{return{type:Be,data:JSON.stringify(e)}}catch{return{type:Be,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Hr)return null;if(e.type===Be)return new _r(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new _r(e.data)}}const mn=vh("synnax-error-registry",()=>new Oh),Nh=({encode:r,decode:e})=>mn().register({encode:r,decode:e}),zh=r=>mn().encode(r),Sh=r=>r==null?null:mn().decode(r);class _r extends St("unknown"){}const Ah=s.z.object({type:s.z.string(),data:s.z.string()});class Ih extends St("canceled"){}class $h extends St("not_implemented"){}const ye=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Ih,NONE:Hr,NotImplemented:$h,UNKNOWN:Be,Unknown:_r,createTyped:St,decode:Sh,encode:zh,isTyped:Ui,payloadZ:Ah,register:Nh},Symbol.toStringTag,{value:"Module"})),kh=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Di=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),Ch=Di.extend({result:s.json()}),xh=Di.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),Rh=s.union([Ch,xh]);s.union([kh,Rh]);const Gr=s.z.string().regex(/^\d+\.\d+\.\d+$/),At=(r,e,t={})=>{t.checkMajor??=!0,t.checkMinor??=!0,t.checkPatch??=!0;const n=Gr.parse(r),i=Gr.parse(e),[a,o,c]=n.split(".").map(Number),[u,l,h]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return Ft;if(a>u)return Yt}if(t.checkMinor){if(o<l)return Ft;if(o>l)return Yt}if(t.checkPatch){if(c<h)return Ft;if(c>h)return Yt}return Je},Mh=(r,e,t={})=>si(At(r,e,t)),Pi=(r,e,t={})=>ni(At(r,e,t)),jh=(r,e,t={})=>ri(At(r,e,t)),Uh=({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}},Dh=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(At).pop();if(a==null)return l=>{if(l.version??=n,l.version!==i.version)return console.log(`${r} version ${l.version} is newer than latest version of ${i.version}.
|
|
14
14
|
Returning default instead.
|
|
15
|
-
`),i;try{return t!=null?t.parse(l):l}catch(h){return console.log(`${r} failed to parse default. Exiting with default`),console.error(h),i}};const o=Object.keys(e).length;let c=!1;const u=l=>{try{if(o===0||
|
|
15
|
+
`),i;try{return t!=null?t.parse(l):l}catch(h){return console.log(`${r} failed to parse default. Exiting with default`),console.error(h),i}};const o=Object.keys(e).length;let c=!1;const u=l=>{try{if(o===0||Pi(l.version,a))return console.log(c?`${r} ${l.version} now up to date`:`${r} version ${l.version} is up to date with target version ${i.version}`),l;const h=l.version,p=e[h],f=p(l);return c=!0,u(f)}catch(h){return console.log(`${r} failed to migrate from ${l.version} to ${a}`),console.error(h),i}};return l=>{try{if(l.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),l.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),i;return u(l)}catch(h){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(h),i}}},rs=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:At,createMigration:Uh,migrator:Dh,semVerNewer:Pi,semVerOlder:jh,semVerZ:Gr,versionsEqual:Mh},Symbol.toStringTag,{value:"Module"})),Ph=["standard","scientific","engineering"];s.z.enum(Ph);const Zi=s.z.enum(["success","info","warning","error","loading","disabled"]),Zh=r=>s.z.object({key:s.z.string(),variant:Zi,message:s.z.string(),description:s.z.string().optional(),time:d.z,details:r??s.z.unknown().optional()}),Lh=(r,e)=>{if(!(r instanceof Error))throw r;return Li({variant:"error",message:e??r.message,description:e!=null?r.message:void 0,details:{stack:r.stack??""}})},Li=r=>({key:fn(),time:d.now(),...r}),Bh=(r,e=[])=>Array.isArray(e)?e.includes(r)?r:void 0:e===r?r:void 0,It=Object.freeze(Object.defineProperty({__proto__:null,create:Li,filterVariant:Bh,fromException:Lh,statusZ:Zh,variantZ:Zi},Symbol.toStringTag,{value:"Module"})),qh=(r,e="")=>{if(typeof r=="string")return r;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]}`},Fh=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 i=/\d+/g;r.match(i)&&e.forEach((o,c)=>{if(i.test(o)){const u=e.map((l,h)=>h!==c?l.charAt(0).toLowerCase():l).join("");t.add(u.replace(/-/g,"_")),t.add(u.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))},Yh=(r,e)=>r.startsWith(e)?r.slice(e.length):r,Kr=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:Fh,naturalLanguageJoin:qh,trimPrefix:Yh},Symbol.toStringTag,{value:"Module"})),Bi="all",qi="create",Fi="delete",Yi="retrieve",Vi="update",Gt=s.z.enum([Bi,qi,Fi,Yi,Vi]);class le extends ye.createTyped("sy"){}class D extends le.sub("validation"){}class ft extends D.sub("path"){path;error;static encodedSchema=s.z.object({path:s.z.string().array(),error:ye.payloadZ});constructor(e,t){const n=v.toArray(e);super(`${n.join(".")}: ${t.message}`),this.path=n.flatMap(i=>i.split(".")),this.error=t}static decode(e){const t=ft.encodedSchema.parse(JSON.parse(e.data));return new ft(t.path,ye.decode(t.error))}}class yt extends le.sub("auth"){}class Jr extends yt.sub("invalid_token"){}class Xr extends yt.sub("expired_token"){}class Ve extends le.sub("unexpected"){constructor(e){super(`
|
|
16
16
|
Unexpected error encountered:
|
|
17
17
|
|
|
18
18
|
${e}
|
|
19
19
|
|
|
20
20
|
Please report this to the Synnax team.
|
|
21
|
-
`)}}class Se extends le.sub("query"){}class gt extends Se.sub("not_found"){}class pt extends Se.sub("multiple_results"){}class Qr extends le.sub("route"){path;constructor(e,t){super(e),this.path=t}}class en extends le.sub("control"){}class ns extends en.sub("unauthorized"){}class Fh extends le.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class Yh extends le.sub("contiguity"){}const Vh=r=>r.type.startsWith(le.TYPE)?r.type.startsWith(P.TYPE)?r.type===ft.TYPE?ft.decode(r):new P(r.data):r.type.startsWith(yt.TYPE)?r.type.startsWith(Jr.TYPE)?new Jr(r.data):r.type.startsWith(Xr.TYPE)?new Xr(r.data):new yt(r.data):r.type.startsWith(Ve.TYPE)?new Ve(r.data):r.type.startsWith(Se.TYPE)?r.type.startsWith(gt.TYPE)?new gt(r.data):r.type.startsWith(pt.TYPE)?new pt(r.data):new Se(r.data):r.type.startsWith(en.TYPE)?r.type.startsWith(ns.TYPE)?new ns(r.data):new en(r.data):r.type.startsWith(Qr.TYPE)?new Qr(r.data,r.data):new Ve(r.data):null,Wh=()=>{throw new ye.NotImplemented};ye.register({encode:Wh,decode:Vh});const Hh=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof ze?[t,new ze({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class wn{key;name;constructor(e,t){this.key=t,this.name=e}get ontologyID(){return Vi(this.key)}}const Vi=r=>({type:"group",key:r}),$t=s.z.uuid(),ar=s.z.string(),bn=s.z.object({key:$t,name:ar}),Wi="builtin",_h="cluster",Gh="node",or=s.z.enum(["label","log","allow_all","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","table"]),Kh=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:or.parse(e),key:t??""}}),M=s.z.object({type:or,key:s.z.string()}).or(Kh),Jh={type:Wi,key:"root"},mt=r=>`${r.type}:${r.key}`,Xh=(r,e)=>r.type===e.type&&r.key===e.key,Hi=r=>{const e=v.toArray(r);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:t})=>t):e.map(t=>M.parse(t))},_i=s.z.object({id:M,name:s.z.string(),data:ge.unknownZ.optional().nullable()}).transform(r=>({key:mt(r.id),...r})),Qh=r=>r==="to"?"from":"to",ed=s.z.object({from:M,type:s.z.string(),to:M}).or(s.z.string().transform(r=>{const[e,t,n]=r.split("->");return{from:M.parse(e),type:t,to:M.parse(n)}})),td=r=>`${mt(r.from)}->${r.type}->${mt(r.to)}`,rd="parent",nd=(r,e)=>!(e.type!=null&&e.type!==r.type||e.from?.type!=null&&e.from.type!==r.from.type||e.to?.type!=null&&e.to.type!==r.to.type||e.from?.key!=null&&e.from.key!==r.from.key||e.to?.key!=null&&e.to.key!==r.to.key),sd=s.z.object({group:bn}),id=s.z.object({parent:M,key:$t.optional(),name:ar}),ad=s.z.object({key:$t,name:ar}),od=s.z.object({keys:s.z.array($t)});let cd=class Wt{static CREATE_ENDPOINT="/ontology/create-group";static RENAME_ENDPOINT="/ontology/rename-group";static DELETE_ENDPOINT="/ontology/delete-group";client;constructor(e){this.client=e}async create(e,t,n){return(await p(this.client,Wt.CREATE_ENDPOINT,{parent:e,name:t,key:n},id,sd)).group}async rename(e,t){await p(this.client,Wt.RENAME_ENDPOINT,{key:e,name:t},ad,s.z.object({}))}async delete(e){await p(this.client,Wt.DELETE_ENDPOINT,{keys:e},od,s.z.object({}))}},Gi=class{creator;constructor(e){this.creator=new cd(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 wn(e.name,e.key)}};const ld=Object.freeze(Object.defineProperty({__proto__:null,Client:Gi,Group:wn,groupZ:bn,keyZ:$t,nameZ:ar,ontologyID:Vi},Symbol.toStringTag,{value:"Module"})),ud="/ontology/add-children",hd="/ontology/remove-children",dd="/ontology/move-children",ss=s.z.object({id:M,children:M.array()}),fd=s.z.object({from:M,to:M,children:M.array()}),Sr=s.z.object({});let yd=class{client;constructor(e){this.client=e}async addChildren(e,...t){await p(this.client,ud,{id:e,children:t},ss,Sr)}async removeChildren(e,...t){await p(this.client,hd,{id:e,children:t},ss,Sr)}async moveChildren(e,t,...n){await p(this.client,dd,{from:e,to:t,children:n},fd,Sr)}};const gd="/ontology/retrieve",pd=s.z.object({ids:M.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:or.array().optional()}),md=s.z.object({resources:_i.array()});let Ki=class{type="ontology";groups;client;writer;framer;constructor(e,t){this.client=e,this.writer=new yd(e),this.groups=new Gi(e),this.framer=t}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const n=Hi(e),i=await this.execRetrieve({ids:n,...t});if(Array.isArray(e))return i;if(i.length===0)throw new Se(`No resource found with ID ${Kr.naturalLanguageJoin(n.map(a=>mt(a)))}`);return i[0]}async retrieveChildren(e,t){return await this.execRetrieve({ids:v.toArray(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:v.toArray(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 execRetrieve(e){const{resources:t}=await p(this.client,gd,e,pd,md);return t}};const wd="sy_ontology_resource_set",bd="sy_ontology_resource_delete",Td="sy_ontology_relationship_set",vd="sy_ontology_relationship_delete",Ed=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Wi,CLUSTER_TYPE:_h,Client:Ki,NODE_TYPE:Gh,PARENT_OF_RELATIONSHIP_TYPE:rd,RELATIONSHIP_DELETE_CHANNEL_NAME:vd,RELATIONSHIP_SET_CHANNEL_NAME:Td,RESOURCE_DELETE_CHANNEL_NAME:bd,RESOURCE_SET_CHANNEL_NAME:wd,ROOT_ID:Jh,idToString:mt,idZ:M,idsEqual:Xh,matchRelationship:nd,oppositeRelationshipDirection:Qh,parseIDs:Hi,relationshipToString:td,relationshipZ:ed,resourceTypeZ:or,resourceZ:_i},Symbol.toStringTag,{value:"Module"})),V=r=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),r.array()]),Xe=s.z.uuid(),cr=s.z.object({key:Xe,subjects:V(M),objects:V(M),actions:V(Gt)}),Ji=s.z.object({key:Xe.optional(),subjects:M.array().or(M),objects:M.array().or(M),actions:Gt.array().or(Gt)}),Od=s.z.object({keys:Xe.array().optional(),subjects:M.array().optional()}),Nd=s.z.object({key:Xe}).transform(({key:r})=>({keys:[r]})),zd=s.z.union([s.z.object({for:M}).transform(({for:r})=>({subjects:[r]})),s.z.object({for:M.array()}).transform(({for:r})=>({subjects:r})),Od]),Sd=s.z.union([Nd,zd]),Ad=s.z.object({policies:V(cr)}),Id=s.z.object({policies:cr.partial({key:!0}).array()}),$d=s.z.object({policies:cr.array()}),kd=s.z.object({keys:Xe.array()}),Cd=s.z.object({}),xd="/access/policy/retrieve",Rd="/access/policy/create",Md="/access/policy/delete";let Xi=class{client;constructor(e){this.client=e}async create(e){const t=Array.isArray(e),i=Ji.array().parse(v.toArray(e)).map(o=>({objects:v.toArray(o.objects),actions:v.toArray(o.actions),subjects:v.toArray(o.subjects)})),a=await p(this.client,Rd,{policies:i},Id,$d);return t?a.policies:a.policies[0]}async retrieve(e){const t="key"in e,n=await p(this.client,xd,e,Sd,Ad);return t?n.policies[0]:n.policies}async delete(e){await p(this.client,Md,{keys:v.toArray(e)},kd,Cd)}};const jd=r=>({type:"policy",key:r}),Ud={type:"allow_all",key:""},Dd=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Ud,Client:Xi,keyZ:Xe,newZ:Ji,ontologyID:jd,policyZ:cr},Symbol.toStringTag,{value:"Module"}));let Qi=class{policy;constructor(e){this.policy=new Xi(e)}};const Pd=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:Li,CREATE_ACTION:Bi,Client:Qi,DELETE_ACTION:qi,RETRIEVE_ACTION:Fi,UPDATE_ACTION:Yi,actionZ:Gt},Symbol.toStringTag,{value:"Module"})),U=s.z.number(),fe=s.z.string(),ea=It.statusZ(),Qe=s.z.object({name:fe,key:U,dataType:I.z,leaseholder:s.z.number(),index:U,isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:V(U),status:ea.optional()}),ta=Qe.extend({key:U.optional(),leaseholder:s.z.number().optional(),index:U.optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1),expression:s.z.string().optional().default(""),requires:V(U).optional().default([])}),Ue=s.z.union([ut.toArray(U),ut.toArray(fe),ut.toArray(Qe).transform(r=>r.map(e=>e.key))]),Zd=new Error("request for lock canceled");var Ld=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(h){try{l(n.next(h))}catch(g){o(g)}}function u(h){try{l(n.throw(h))}catch(g){o(g)}}function l(h){h.done?a(h.value):i(h.value).then(c,u)}l((n=n.apply(r,e||[])).next())})};class Bd{constructor(e,t=Zd){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,i)=>{const a={resolve:n,reject:i,weight:e,priority:t},o=ra(this._queue,c=>t<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return Ld(this,arguments,void 0,function*(t,n=1,i=0){const[a,o]=yield this.acquire(n,i);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]=[]),qd(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 i=n.findIndex(a=>a.priority<=e);(i===-1?n:n.splice(0,i)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function qd(r,e){const t=ra(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function ra(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Fd=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(h){try{l(n.next(h))}catch(g){o(g)}}function u(h){try{l(n.throw(h))}catch(g){o(g)}}function l(h){h.done?a(h.value):i(h.value).then(c,u)}l((n=n.apply(r,e||[])).next())})};class Yd{constructor(e){this._semaphore=new Bd(1,e)}acquire(){return Fd(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 Vd=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=v.toArray(r);const a=i[0],o=typeof a;let c;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,i=i.map(u=>parseInt(u))):c=e[o],{single:n,variant:c,normalized:i,actual:r}},et=(r,e,t,n)=>{if(n){if(t.length===0)throw new gt(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new pt(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Wd=s.z.object({leaseholder:s.z.number().optional(),keys:U.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:I.z.array().optional(),notDataTypes:I.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional(),calculated:s.z.boolean().optional()}),Hd=s.z.object({channels:V(Qe)}),ee=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]),Vd(r,{number:"keys",string:"names"}));class kt{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const n=ee(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async execute(e){const[t,n]=await this.client.send(kt.ENDPOINT,e,Wd,Hd);if(n!=null)throw n;return t.channels}}class Tn{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n}=ee(e),i=[],a=[];if(n.forEach(c=>{const u=this.get(c);u!=null?i.push(...u):a.push(c)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,t);return this.set(o),i.concat(o)}delete(e){const{variant:t,normalized:n}=ee(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,i)=>{const a=t[i],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 u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.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 i=this.cache.get(e);return i==null?void 0:[i]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class na{mu=new Yd;requests=new Map;wrapped;debouncedRun;constructor(e,t){this.wrapped=e,this.debouncedRun=ju(()=>{this.run()},t)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:t,variant:n}=ee(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(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const sa=async(r,e)=>{const{normalized:t}=ee(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new Se(`Could not find channels: ${JSON.stringify(i)}`);return n},_d="sy_channel_set",Gd="sy_channel_delete";class Kt{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;requires;status;constructor({dataType:e,name:t,leaseholder:n=0,key:i=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:u=!1,frameClient:l,alias:h,status:g,expression:d="",requires:O=[]}){this.key=i,this.name=t,this.dataType=new I(e),this.leaseholder=n,this.index=o,this.isIndex=a,this.internal=c,this.alias=h,this.virtual=u,this.expression=d,this.requires=O??[],g!=null&&(this.status=It.create(g)),this._frameClient=l??null}get framer(){if(this._frameClient==null)throw new P("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Qe.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,status:this.status})}get isCalculated(){return wt(this.payload)}get ontologyID(){return oa(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 Kd="sy_calculation_status",Jd="/channel/retrieve-group",Xd=s.z.object({}),Qd=s.z.object({group:bn});let ia=class{type="channel";frameClient;client;retriever;writer;constructor(e,t,n,i){this.frameClient=e,this.retriever=t,this.client=n,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,i=!Array.isArray(e);let a=v.toArray(e),o=[];if(n){const c=await this.retriever.retrieve(a.map(l=>l.name)),u=new Set(c.map(l=>l.name));a=a.filter(l=>!u.has(l.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){if(typeof e=="object"&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return et("channel",e,i,n),n?i[0]:i}async delete(e){const{normalized:t,variant:n}=ee(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(v.toArray(e),v.toArray(t))}createDebouncedBatchRetriever(e=10){return new Tn(new na(new kt(this.client),e))}sugar(e){const{frameClient:t}=this;return Array.isArray(e)?e.map(n=>new Kt({...n,frameClient:t})):new Kt({...e,frameClient:t})}async retrieveGroup(){const e=await p(this.client,Jd,{},Xd,Qd);return new wn(e.group.name,e.group.key)}};const wt=({virtual:r,expression:e})=>r&&e!=="",aa=async(r,e)=>{if(!wt(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(wt(n)){const i=await aa(r,n);if(i!=null)return i}}return null},oa=r=>({type:"channel",key:r.toString()}),ef=s.z.object({channels:ta.array()}),tf=s.z.object({channels:Qe.array()}),rf=s.z.object({keys:U.array().optional(),names:fe.array().optional()}),nf=s.z.object({}),sf=s.z.object({keys:U.array(),names:fe.array()}),af=s.z.object({}),of="/channel/create",cf="/channel/delete",lf="/channel/rename";let ca=class{client;cache;constructor(e,t){this.client=e,this.cache=t}async create(e){const{channels:t}=await p(this.client,of,{channels:e.map(n=>({...n,dataType:n.dataType}))},ef,tf);return this.cache.set(t),t}async delete(e){await p(this.client,cf,e,rf,nf),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await p(this.client,lf,{keys:e,names:t},sf,af),this.cache.rename(e,t)}};const uf=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:Kd,CacheRetriever:Tn,Channel:Kt,Client:ia,ClusterRetriever:kt,DELETE_CHANNEL_NAME:Gd,DebouncedBatchRetriever:na,SET_CHANNEL_NAME:_d,Writer:ca,analyzeParams:ee,isCalculated:wt,keyZ:U,nameZ:fe,newZ:ta,ontologyID:oa,paramsZ:Ue,payloadZ:Qe,resolveCalculatedIndex:aa,retrieveRequired:sa,statusZ:ea},Symbol.toStringTag,{value:"Module"})),Ae=s.z.uuid(),Ct=s.z.object({key:Ae,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),la=Ct.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),hf=s.z.object({keys:Ae.array().optional(),usernames:s.z.string().array().optional()}),df=s.z.object({key:Ae}).transform(({key:r})=>({keys:[r]})),ff=s.z.object({username:s.z.string()}).transform(({username:r})=>({usernames:[r]})),yf=s.z.object({usernames:s.z.string().array()}).transform(({usernames:r})=>({usernames:r})),gf=s.z.union([df,ff,yf,hf]),pf=s.z.object({users:V(Ct)}),mf=s.z.object({users:la.array()}),wf=s.z.object({users:Ct.array()}),bf=s.z.object({key:Ae,username:s.z.string().min(1)}),Tf=s.z.object({}),vf=s.z.object({key:Ae,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Ef=s.z.object({}),Of=s.z.object({keys:Ae.array()}),Nf=s.z.object({}),zf="/user/retrieve",Sf="/user/create",Af="/user/change-username",If="/user/rename",$f="/user/delete";let ua=class{client;constructor(e){this.client=e}async create(e){const t=Array.isArray(e),n=await p(this.client,Sf,{users:v.toArray(e)},mf,wf);return t?n.users:n.users[0]}async changeUsername(e,t){await p(this.client,Af,{key:e,username:t},bf,Tf)}async retrieve(e){const t="key"in e||"username"in e,n=await p(this.client,zf,e,gf,pf);if(!t)return n.users;if(n.users.length===0){const i="key"in e?`key ${e.key}`:`username ${e.username}`;throw new gt(`No user with ${i} found`)}if(n.users.length>1){const i="key"in e?`key ${e.key}`:`username ${e.username}`;throw new pt(`Multiple users found with ${i}`)}return n.users[0]}async rename(e,t,n){await p(this.client,If,{key:e,firstName:t,lastName:n},vf,Ef)}async delete(e){await p(this.client,$f,{keys:v.toArray(e)},Of,Nf)}};const kf=r=>({type:"user",key:r}),Cf=Object.freeze(Object.defineProperty({__proto__:null,Client:ua,keyZ:Ae,newZ:la,ontologyID:kf,userZ:Ct},Symbol.toStringTag,{value:"Module"})),xf=s.z.object({username:s.z.string(),password:s.z.string()}),Rf=s.z.object({token:s.z.string(),user:Ct}),is="/auth/login",Mf=3,jf="/auth/change-password",Uf=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),Df=s.z.object({}),Pf=[Jr,Xr];let Zf=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(e,t){this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await p(this.client,jf,{username:this.credentials.username,password:this.credentials.password,newPassword:e},Uf,Df),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(is)){this.authenticating??=new Promise((c,u)=>{this.client.send(is,this.credentials,xf,Rf).then(([l,h])=>{if(h!=null)return c(h);this.token=l?.token,this.user=l?.user,this.authenticated=!0,c(null)}).catch(u)});const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return Pf.some(o=>o.matches(a))&&this.retryCount<Mf?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const ha=s.z.enum(["disconnected","connecting","connected","failed"]),da=s.z.object({status:ha,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),Lf=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),as={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.44.3"},os=(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}.
|
|
21
|
+
`)}}class Se extends le.sub("query"){}class gt extends Se.sub("not_found"){}class pt extends Se.sub("multiple_results"){}class Qr extends le.sub("route"){path;constructor(e,t){super(e),this.path=t}}class en extends le.sub("control"){}class ns extends en.sub("unauthorized"){}class Vh extends le.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class Wh extends le.sub("contiguity"){}const Hh=r=>r.type.startsWith(le.TYPE)?r.type.startsWith(D.TYPE)?r.type===ft.TYPE?ft.decode(r):new D(r.data):r.type.startsWith(yt.TYPE)?r.type.startsWith(Jr.TYPE)?new Jr(r.data):r.type.startsWith(Xr.TYPE)?new Xr(r.data):new yt(r.data):r.type.startsWith(Ve.TYPE)?new Ve(r.data):r.type.startsWith(Se.TYPE)?r.type.startsWith(gt.TYPE)?new gt(r.data):r.type.startsWith(pt.TYPE)?new pt(r.data):new Se(r.data):r.type.startsWith(en.TYPE)?r.type.startsWith(ns.TYPE)?new ns(r.data):new en(r.data):r.type.startsWith(Qr.TYPE)?new Qr(r.data,r.data):new Ve(r.data):null,_h=()=>{throw new ye.NotImplemented};ye.register({encode:_h,decode:Hh});const Gh=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof ze?[t,new ze({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class wn{key;name;constructor(e,t){this.key=t,this.name=e}get ontologyID(){return Wi(this.key)}}const Wi=r=>({type:"group",key:r}),$t=s.z.uuid(),ar=s.z.string(),bn=s.z.object({key:$t,name:ar}),Hi="builtin",Kh="cluster",Jh="node",or=s.z.enum(["label","log","allow_all","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","table"]),Xh=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:or.parse(e),key:t??""}}),R=s.z.object({type:or,key:s.z.string()}).or(Xh),Qh={type:Hi,key:"root"},mt=r=>`${r.type}:${r.key}`,ed=(r,e)=>r.type===e.type&&r.key===e.key,_i=r=>{const e=v.toArray(r);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:t})=>t):e.map(t=>R.parse(t))},Gi=s.z.object({id:R,name:s.z.string(),data:ge.unknownZ.optional().nullable()}).transform(r=>({key:mt(r.id),...r})),td=r=>r==="to"?"from":"to",rd=s.z.object({from:R,type:s.z.string(),to:R}).or(s.z.string().transform(r=>{const[e,t,n]=r.split("->");return{from:R.parse(e),type:t,to:R.parse(n)}})),nd=r=>`${mt(r.from)}->${r.type}->${mt(r.to)}`,sd="parent",id=(r,e)=>!(e.type!=null&&e.type!==r.type||e.from?.type!=null&&e.from.type!==r.from.type||e.to?.type!=null&&e.to.type!==r.to.type||e.from?.key!=null&&e.from.key!==r.from.key||e.to?.key!=null&&e.to.key!==r.to.key),ad=s.z.object({group:bn}),od=s.z.object({parent:R,key:$t.optional(),name:ar}),cd=s.z.object({key:$t,name:ar}),ld=s.z.object({keys:s.z.array($t)});let ud=class Wt{static CREATE_ENDPOINT="/ontology/create-group";static RENAME_ENDPOINT="/ontology/rename-group";static DELETE_ENDPOINT="/ontology/delete-group";client;constructor(e){this.client=e}async create(e,t,n){return(await m(this.client,Wt.CREATE_ENDPOINT,{parent:e,name:t,key:n},od,ad)).group}async rename(e,t){await m(this.client,Wt.RENAME_ENDPOINT,{key:e,name:t},cd,s.z.object({}))}async delete(e){await m(this.client,Wt.DELETE_ENDPOINT,{keys:e},ld,s.z.object({}))}};const hd="sy_group_set",dd="sy_group_delete";let Ki=class{creator;constructor(e){this.creator=new ud(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 wn(e.name,e.key)}};const fd=Object.freeze(Object.defineProperty({__proto__:null,Client:Ki,DELETE_CHANNEL_NAME:dd,Group:wn,SET_CHANNEL_NAME:hd,groupZ:bn,keyZ:$t,nameZ:ar,ontologyID:Wi},Symbol.toStringTag,{value:"Module"})),yd="/ontology/add-children",gd="/ontology/remove-children",pd="/ontology/move-children",ss=s.z.object({id:R,children:R.array()}),md=s.z.object({from:R,to:R,children:R.array()}),Sr=s.z.object({});let wd=class{client;constructor(e){this.client=e}async addChildren(e,...t){await m(this.client,yd,{id:e,children:t},ss,Sr)}async removeChildren(e,...t){await m(this.client,gd,{id:e,children:t},ss,Sr)}async moveChildren(e,t,...n){await m(this.client,pd,{from:e,to:t,children:n},md,Sr)}};const bd="/ontology/retrieve",Td=s.z.object({ids:R.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:or.array().optional()}),vd=s.z.object({resources:Gi.array()});let Ji=class{type="ontology";groups;client;writer;framer;constructor(e,t){this.client=e,this.writer=new wd(e),this.groups=new Ki(e),this.framer=t}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object"&&!("key"in e))return this.execRetrieve(e);const n=_i(e),i=await this.execRetrieve({ids:n,...t});if(Array.isArray(e))return i;if(i.length===0)throw new Se(`No resource found with ID ${Kr.naturalLanguageJoin(n.map(a=>mt(a)))}`);return i[0]}async retrieveChildren(e,t){return await this.execRetrieve({ids:v.toArray(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:v.toArray(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 execRetrieve(e){const{resources:t}=await m(this.client,bd,e,Td,vd);return t}};const Ed="sy_ontology_resource_set",Od="sy_ontology_resource_delete",Nd="sy_ontology_relationship_set",zd="sy_ontology_relationship_delete",Sd=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Hi,CLUSTER_TYPE:Kh,Client:Ji,NODE_TYPE:Jh,PARENT_OF_RELATIONSHIP_TYPE:sd,RELATIONSHIP_DELETE_CHANNEL_NAME:zd,RELATIONSHIP_SET_CHANNEL_NAME:Nd,RESOURCE_DELETE_CHANNEL_NAME:Od,RESOURCE_SET_CHANNEL_NAME:Ed,ROOT_ID:Qh,idToString:mt,idZ:R,idsEqual:ed,matchRelationship:id,oppositeRelationshipDirection:td,parseIDs:_i,relationshipToString:nd,relationshipZ:rd,resourceTypeZ:or,resourceZ:Gi},Symbol.toStringTag,{value:"Module"})),Y=r=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),r.array()]),Xe=s.z.uuid(),cr=s.z.object({key:Xe,subjects:Y(R),objects:Y(R),actions:Y(Gt)}),Xi=s.z.object({key:Xe.optional(),subjects:R.array().or(R),objects:R.array().or(R),actions:Gt.array().or(Gt)}),Ad=s.z.object({keys:Xe.array().optional(),subjects:R.array().optional()}),Id=s.z.object({key:Xe}).transform(({key:r})=>({keys:[r]})),$d=s.z.union([s.z.object({for:R}).transform(({for:r})=>({subjects:[r]})),s.z.object({for:R.array()}).transform(({for:r})=>({subjects:r})),Ad]),kd=s.z.union([Id,$d]),Cd=s.z.object({policies:Y(cr)}),xd=s.z.object({policies:cr.partial({key:!0}).array()}),Rd=s.z.object({policies:cr.array()}),Md=s.z.object({keys:Xe.array()}),jd=s.z.object({}),Ud="/access/policy/retrieve",Dd="/access/policy/create",Pd="/access/policy/delete";let Qi=class{client;constructor(e){this.client=e}async create(e){const t=Array.isArray(e),i=Xi.array().parse(v.toArray(e)).map(o=>({objects:v.toArray(o.objects),actions:v.toArray(o.actions),subjects:v.toArray(o.subjects)})),a=await m(this.client,Dd,{policies:i},xd,Rd);return t?a.policies:a.policies[0]}async retrieve(e){const t="key"in e,n=await m(this.client,Ud,e,kd,Cd);return t?n.policies[0]:n.policies}async delete(e){await m(this.client,Pd,{keys:v.toArray(e)},Md,jd)}};const Zd=r=>({type:"policy",key:r}),Ld={type:"allow_all",key:""},Bd=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Ld,Client:Qi,keyZ:Xe,newZ:Xi,ontologyID:Zd,policyZ:cr},Symbol.toStringTag,{value:"Module"}));let ea=class{policy;constructor(e){this.policy=new Qi(e)}};const qd=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:Bi,CREATE_ACTION:qi,Client:ea,DELETE_ACTION:Fi,RETRIEVE_ACTION:Yi,UPDATE_ACTION:Vi,actionZ:Gt},Symbol.toStringTag,{value:"Module"})),is="Channel key must be a valid uint32.",x=s.z.uint32().or(s.z.string().refine(r=>!isNaN(Number(r)),{message:is}).transform(Number).refine(r=>r<2**32-1,{message:is})),fe=s.z.string(),ta=It.statusZ(),Qe=s.z.object({name:fe,key:x,dataType:S.z,leaseholder:s.z.number(),index:x,isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:Y(x),status:ta.optional()}),ra=Qe.extend({key:x.optional(),leaseholder:s.z.number().optional(),index:x.optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1),expression:s.z.string().optional().default(""),requires:Y(x).optional().default([])}),Ue=s.z.union([ut.toArray(x),ut.toArray(fe),ut.toArray(Qe).transform(r=>r.map(e=>e.key))]),Fd=new Error("request for lock canceled");var Yd=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(h){try{l(n.next(h))}catch(p){o(p)}}function u(h){try{l(n.throw(h))}catch(p){o(p)}}function l(h){h.done?a(h.value):i(h.value).then(c,u)}l((n=n.apply(r,e||[])).next())})};class Vd{constructor(e,t=Fd){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,i)=>{const a={resolve:n,reject:i,weight:e,priority:t},o=na(this._queue,c=>t<=c.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return Yd(this,arguments,void 0,function*(t,n=1,i=0){const[a,o]=yield this.acquire(n,i);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]=[]),Wd(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 i=n.findIndex(a=>a.priority<=e);(i===-1?n:n.splice(0,i)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Wd(r,e){const t=na(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function na(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Hd=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function c(h){try{l(n.next(h))}catch(p){o(p)}}function u(h){try{l(n.throw(h))}catch(p){o(p)}}function l(h){h.done?a(h.value):i(h.value).then(c,u)}l((n=n.apply(r,e||[])).next())})};class _d{constructor(e){this._semaphore=new Vd(1,e)}acquire(){return Hd(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 Gd=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=v.toArray(r);const a=i[0],o=typeof a;let c;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(c=e.number,i=i.map(u=>parseInt(u))):c=e[o],{single:n,variant:c,normalized:i,actual:r}},et=(r,e,t,n)=>{if(n){if(t.length===0)throw new gt(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new pt(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Kd=s.z.object({leaseholder:s.z.number().optional(),keys:x.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:S.z.array().optional(),notDataTypes:S.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional(),calculated:s.z.boolean().optional()}),Jd=s.z.object({channels:Y(Qe)}),te=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]),Gd(r,{number:"keys",string:"names"}));class kt{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const n=te(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async execute(e){const[t,n]=await this.client.send(kt.ENDPOINT,e,Kd,Jd);if(n!=null)throw n;return t.channels}}class Tn{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n}=te(e),i=[],a=[];if(n.forEach(c=>{const u=this.get(c);u!=null?i.push(...u):a.push(c)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,t);return this.set(o),i.concat(o)}delete(e){const{variant:t,normalized:n}=te(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,i)=>{const a=t[i],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 u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.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 i=this.cache.get(e);return i==null?void 0:[i]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class sa{mu=new _d;requests=new Map;wrapped;debouncedRun;constructor(e,t){this.wrapped=e,this.debouncedRun=Uu(()=>{this.run()},t)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:t,variant:n}=te(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(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const ia=async(r,e)=>{const{normalized:t}=te(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new Se(`Could not find channels: ${JSON.stringify(i)}`);return n},Xd="sy_channel_set",Qd="sy_channel_delete";class Kt{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;requires;status;constructor({dataType:e,name:t,leaseholder:n=0,key:i=0,isIndex:a=!1,index:o=0,internal:c=!1,virtual:u=!1,frameClient:l,alias:h,status:p,expression:f="",requires:O=[]}){this.key=x.parse(i),this.name=t,this.dataType=new S(e),this.leaseholder=n,this.index=x.parse(o),this.isIndex=a,this.internal=c,this.alias=h,this.virtual=u,this.expression=f,this.requires=x.array().parse(O??[]),p!=null&&(this.status=It.create(p)),this._frameClient=l??null}get framer(){if(this._frameClient==null)throw new D("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Qe.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,status:this.status})}get isCalculated(){return wt(this.payload)}get ontologyID(){return ca(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 ef="sy_calculation_status",tf="/channel/retrieve-group",rf=s.z.object({}),nf=s.z.object({group:bn});let aa=class{type="channel";frameClient;client;retriever;writer;constructor(e,t,n,i){this.frameClient=e,this.retriever=t,this.client=n,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,i=!Array.isArray(e);let a=v.toArray(e),o=[];if(n){const c=await this.retriever.retrieve(a.map(l=>l.name)),u=new Set(c.map(l=>l.name));a=a.filter(l=>!u.has(l.name)),o=this.sugar(c)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){if(typeof e=="object"&&!Array.isArray(e))return this.sugar(await this.retriever.retrieve(e));const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return et("channel",e,i,n),n?i[0]:i}async delete(e){const{normalized:t,variant:n}=te(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(v.toArray(e),v.toArray(t))}createDebouncedBatchRetriever(e=10){return new Tn(new sa(new kt(this.client),e))}sugar(e){const{frameClient:t}=this;return Array.isArray(e)?e.map(n=>new Kt({...n,frameClient:t})):new Kt({...e,frameClient:t})}async retrieveGroup(){const e=await m(this.client,tf,{},rf,nf);return new wn(e.group.name,e.group.key)}};const wt=({virtual:r,expression:e})=>r&&e!=="",oa=async(r,e)=>{if(!wt(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(wt(n)){const i=await oa(r,n);if(i!=null)return i}}return null},ca=r=>({type:"channel",key:r.toString()}),sf=s.z.object({channels:ra.array()}),af=s.z.object({channels:Qe.array()}),of=s.z.object({keys:x.array().optional(),names:fe.array().optional()}),cf=s.z.object({}),lf=s.z.object({keys:x.array(),names:fe.array()}),uf=s.z.object({}),hf="/channel/create",df="/channel/delete",ff="/channel/rename";let la=class{client;cache;constructor(e,t){this.client=e,this.cache=t}async create(e){const{channels:t}=await m(this.client,hf,{channels:e.map(n=>({...n,dataType:n.dataType}))},sf,af);return this.cache.set(t),t}async delete(e){const t=x.array().parse(e.keys??[]);await m(this.client,df,e,of,cf),t.length>0&&this.cache.delete(t),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await m(this.client,ff,{keys:e,names:t},lf,uf),this.cache.rename(e,t)}};const yf=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:ef,CacheRetriever:Tn,Channel:Kt,Client:aa,ClusterRetriever:kt,DELETE_CHANNEL_NAME:Qd,DebouncedBatchRetriever:sa,SET_CHANNEL_NAME:Xd,Writer:la,analyzeParams:te,isCalculated:wt,keyZ:x,nameZ:fe,newZ:ra,ontologyID:ca,paramsZ:Ue,payloadZ:Qe,resolveCalculatedIndex:oa,retrieveRequired:ia,statusZ:ta},Symbol.toStringTag,{value:"Module"})),Ae=s.z.uuid(),Ct=s.z.object({key:Ae,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),ua=Ct.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),gf=s.z.object({keys:Ae.array().optional(),usernames:s.z.string().array().optional()}),pf=s.z.object({key:Ae}).transform(({key:r})=>({keys:[r]})),mf=s.z.object({username:s.z.string()}).transform(({username:r})=>({usernames:[r]})),wf=s.z.object({usernames:s.z.string().array()}).transform(({usernames:r})=>({usernames:r})),bf=s.z.union([pf,mf,wf,gf]),Tf=s.z.object({users:Y(Ct)}),vf=s.z.object({users:ua.array()}),Ef=s.z.object({users:Ct.array()}),Of=s.z.object({key:Ae,username:s.z.string().min(1)}),Nf=s.z.object({}),zf=s.z.object({key:Ae,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Sf=s.z.object({}),Af=s.z.object({keys:Ae.array()}),If=s.z.object({}),$f="/user/retrieve",kf="/user/create",Cf="/user/change-username",xf="/user/rename",Rf="/user/delete";let ha=class{client;constructor(e){this.client=e}async create(e){const t=Array.isArray(e),n=await m(this.client,kf,{users:v.toArray(e)},vf,Ef);return t?n.users:n.users[0]}async changeUsername(e,t){await m(this.client,Cf,{key:e,username:t},Of,Nf)}async retrieve(e){const t="key"in e||"username"in e,n=await m(this.client,$f,e,bf,Tf);if(!t)return n.users;if(n.users.length===0){const i="key"in e?`key ${e.key}`:`username ${e.username}`;throw new gt(`No user with ${i} found`)}if(n.users.length>1){const i="key"in e?`key ${e.key}`:`username ${e.username}`;throw new pt(`Multiple users found with ${i}`)}return n.users[0]}async rename(e,t,n){await m(this.client,xf,{key:e,firstName:t,lastName:n},zf,Sf)}async delete(e){await m(this.client,Rf,{keys:v.toArray(e)},Af,If)}};const Mf=r=>({type:"user",key:r}),jf=Object.freeze(Object.defineProperty({__proto__:null,Client:ha,keyZ:Ae,newZ:ua,ontologyID:Mf,userZ:Ct},Symbol.toStringTag,{value:"Module"})),Uf=s.z.object({username:s.z.string(),password:s.z.string()}),Df=s.z.object({token:s.z.string(),user:Ct}),as="/auth/login",Pf=3,Zf="/auth/change-password",Lf=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),Bf=s.z.object({}),qf=[Jr,Xr];let Ff=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(e,t){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,Zf,{username:this.credentials.username,password:this.credentials.password,newPassword:e},Lf,Bf),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(as)){this.authenticating??=new Promise((c,u)=>{this.client.send(as,this.credentials,Uf,Df).then(([l,h])=>{if(h!=null)return c(h);this.token=l?.token,this.user=l?.user,this.authenticated=!0,c(null)}).catch(u)});const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return qf.some(o=>o.matches(a))&&this.retryCount<Pf?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const da=s.z.enum(["disconnected","connecting","connected","failed"]),fa=s.z.object({status:da,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),Yf=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),os={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.44.4"},cs=(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}.
|
|
22
22
|
This may cause compatibility issues. We recommend updating the ${n}. For more information, see
|
|
23
|
-
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`};class bt{static ENDPOINT="/connectivity/check";static DEFAULT=
|
|
24
|
-
Got ${t.length} ${n}s and ${e.length} series.`)};class
|
|
23
|
+
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`};class bt{static ENDPOINT="/connectivity/check";static DEFAULT=os;_state;pollFrequency=E.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=fa;versionWarned=!1;constructor(e,t=E.seconds(30),n,i){this._state={...os},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=i,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const[t,n]=await this.client.send(bt.ENDPOINT,{},s.z.object({}),Yf);if(n!=null)throw n;const i=t.nodeVersion,a=this.clientVersion,o=this.versionWarned;i==null?(this._state.clientServerCompatible=!1,o||(console.warn(cs(null,a,!0)),this.versionWarned=!0)):rs.versionsEqual(a,i,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,o||(console.warn(cs(i,a,rs.semVerNewer(a,i))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=t.clusterKey,this._state.nodeVersion=t.nodeVersion,this._state.clientVersion=this.clientVersion}catch(t){this._state.status="failed",this._state.error=t,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(t=>t(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}}const Vf=Object.freeze(Object.defineProperty({__proto__:null,Checker:bt,stateZ:fa,statusZ:da},Symbol.toStringTag,{value:"Module"})),Wf=s.z.object({keys:x.array().optional(),bounds:M.z,names:fe.array().optional()}),Hf=s.z.object({}),_f="/frame/delete";class Gf{client;constructor(e){this.client=e}async delete(e){await m(this.client,_f,e,Wf,Hf)}}const ls=r=>{const e=v.toArray(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},us=(r,e)=>{const t=v.toArray(r);if(t.length===e.length)return;const n=ls(r);throw ls===null?new D("[Frame] - channel keys or names must be provided when constructing a frame."):new D(`[Frame] - ${n}s and series must be the same length.
|
|
24
|
+
Got ${t.length} ${n}s and ${e.length} series.`)};class P{columns=[];series=[];constructor(e=[],t=[]){if(e instanceof P){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...v.toArray(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e;i.series??=[],i.keys??=[];const a=i.series.map(o=>ya(o));us(i.keys,a),i.keys.forEach((o,c)=>this.push(o,a[c]))}else Object.entries(e).forEach(([i,a])=>{const o=parseInt(i);if(!isNaN(o))return this.push(o,...v.toArray(a));this.push(i,...v.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=v.toArray(t),a=v.toArray(e);us(a,i),i.forEach((o,c)=>this.push(a[c],o));return}throw new D(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
25
25
|
payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
|
|
26
|
-
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 Ve("colType is not key");return this.columns??[]}get uniqueKeys(){return Vn.unique(this.keys)}get names(){if(this.colType==="key")throw new Ve("colType is not name");return this.columns??[]}get uniqueNames(){return Vn.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>
|
|
26
|
+
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 Ve("colType is not key");return this.columns??[]}get uniqueKeys(){return Vn.unique(this.keys)}get names(){if(this.colType==="key")throw new Ve("colType is not name");return this.columns??[]}get uniqueNames(){return Vn.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>ga(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 M.ZERO;const n=d.min(...this.series.map(a=>a.timeRange.start)),i=d.max(...this.series.map(a=>a.timeRange.end));return new M(n,i)}const t=this.get(e);return t==null?M.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 Ei(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof P){if(this.colType!==null&&e.colType!==this.colType)throw new D("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 D("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new D("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new P([...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 P;return this.forEach((n,i,a)=>t.push(...e(n,i,a))),t}forEach(e){this.columns.forEach((t,n)=>{const i=this.series[n];e(t,i,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(i=>{n[i]=this.get(i).at(e,t)}),n}filter(e){const t=new P;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new He(this.series.reduce((e,t)=>e.add(t.byteLength),He.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const i=this.series[n].digest;t in e?e[t].push(i):e[t]=[i]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}toString(){let e=`Frame{
|
|
27
27
|
`;return this.uniqueColumns.forEach(t=>{e+=` ${t}: ${this.get(t).series.map(n=>n.toString()).join(",")}
|
|
28
|
-
`}),e+="}",e}}const lr=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),
|
|
28
|
+
`}),e+="}",e}}const lr=s.z.object({keys:s.z.union([s.z.null().transform(()=>[]),s.z.number().array().optional().default([])]),series:s.z.union([s.z.null().transform(()=>[]),q.crudeZ.array().optional().default([])])}),ya=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new q({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},ga=r=>({timeRange:r.timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});var _e=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.SetAuthority=3]="SetAuthority",r))(_e||{}),Tt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(Tt||{});const Kf=new E(-1);class tn extends le.sub("writer_closed"){constructor(){super("WriterClosed")}}const Jf=s.z.enum(Tt).or(s.z.enum(["persist","stream","persistStream"]).transform(r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),pa=s.z.object({start:d.z.optional(),controlSubject:X.subjectZ.optional(),authorities:s.z.union([X.authorityZ.transform(r=>[r]),X.authorityZ.array()]).default([X.ABSOLUTE_AUTHORITY]),mode:Jf.default(1),errOnUnauthorized:s.z.boolean().default(!1),enableAutoCommit:s.z.boolean().default(!1),autoIndexPersistInterval:E.z.default(E.SECOND),useHighPerformanceCodec:s.z.boolean().default(!0)}),Xf=pa.extend({keys:x.array().optional()}),hs=pa.extend({channels:Ue}),ma=hs.or(Ue.transform(r=>hs.parse({channels:r,start:d.now()}))),Qf=s.z.object({command:s.z.enum(_e),config:Xf.optional(),frame:lr.optional(),buffer:s.z.instanceof(Uint8Array).optional()}),ey=s.z.object({command:s.z.enum(_e),end:d.z,err:ye.payloadZ.optional()}),ty=s.z.tuple([s.z.union([s.z.record(x.or(fe),X.authorityZ),x.or(fe),X.authorityZ]),X.authorityZ.optional()]).transform(([r,e])=>{if(X.authorityZ.safeParse(r).success)return{keys:[],authorities:[r]};if(x.or(fe).safeParse(r).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[r],authorities:[e]}}const t=r;return{keys:Object.keys(t),authorities:Object.values(t)}});let wa=class rn{static ENDPOINT="/frame/write";stream;adapter;closeErr=null;constructor(e,t){this.stream=e,this.adapter=t}static async _open(e,t,n){const i=ma.parse(n),a=await En.open(e,i.channels);i.useHighPerformanceCodec&&(t=t.withCodec(new oy(a.codec)));const o=await t.stream(rn.ENDPOINT,Qf,ey),c=new rn(o,a);return await c.execute({command:0,config:{...i,keys:a.keys}}),c}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;const n=ty.parse([e,t]),i={keys:await this.adapter.adaptParams(n.keys),authorities:n.authorities};await this.execute({command:3,config:i})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),d.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(tn.matches(this.closeErr))return null;throw this.closeErr}const[t,n]=await this.stream.receive();n!=null?this.closeErr=re.matches(n)?new tn:n:this.closeErr=ye.decode(t?.err)}}async execute(e){const t=this.stream.send(e);for(t!=null&&await this.closeInternal(t);;){const[n,i]=await this.stream.receive();i!=null&&await this.closeInternal(i);const a=ye.decode(n?.err);if(a!=null&&await this.closeInternal(a),n?.command==e.command)return n}}};const ds=r=>r.data.byteLength/r.dataType.density.valueOf(),ry=r=>{const{keys:e,series:t}=r;e.forEach((n,i)=>{t[i].key=n}),t.sort((n,i)=>n.key-i.key),e.sort((n,i)=>n-i),t.forEach(n=>delete n.key)},fs=5,ys=4,gs=3,ps=2,ms=1,ws=0,ne=S.TIMESTAMP.density.valueOf(),ve=8,Ee=4,Ar=4,Ir=4,ny=1;class ba{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],t=[]){(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((i,a)=>{const o=t[a];n.keyDataTypes.set(i,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 D(`
|
|
29
29
|
The codec has not been updated with a list of channels and data types.
|
|
30
30
|
Please call the update method before calling ${e}.
|
|
31
|
-
`)}encode(e,t=0){this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),
|
|
31
|
+
`)}encode(e,t=0){this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),ry(n);let i=-1,a,o,c,u=t+ny+Ir,l=!this.currState?.hasVariableDataTypes,h=!0,p=!0,f=!0,O=!0,N=!0;n.keys.length!==this.currState?.keys.length&&(f=!1,u+=n.keys.length*Ar),n.series.forEach((U,we)=>{const de=ds(U),it=n.keys[we],$e=this.currState?.keyDataTypes.get(it);if($e==null)throw new D(`Channel ${it} was not provided in the list of channels when opening the writer`);if(!$e.equals(U.dataType))throw new D(`Series data type of ${U.dataType.toString()} does not match the data type of ${$e.toString()} for channel ${it}`);if(u+=U.data.byteLength,i===-1){i=de,a=U.timeRange?.start,o=U.timeRange?.end,c=BigInt(U.alignment??0n);return}i!==de&&(l=!1),(a?.valueOf()!==U.timeRange?.start.valueOf()||o?.valueOf()!==U.timeRange?.end.valueOf())&&(h=!1),c!==BigInt(U.alignment??0)&&(O=!1)}),p=h&&a==null&&o==null,N=O&&(c===void 0||c===0n),l?u+=Ee:u+=n.keys.length*Ee,p||(h?u+=ne*2:u+=n.keys.length*ne*2),N||(O?u+=ve:u+=n.keys.length*ve);const k=new Uint8Array(u),Z=new DataView(k.buffer);let C=t;return k[C]=Number(N)<<fs|Number(O)<<ys|Number(l)<<gs|Number(h)<<ps|Number(p)<<ms|Number(f)<<ws,C++,Z.setUint32(C,this.seqNum,!0),C+=Ir,l&&(Z.setUint32(C,i,!0),C+=Ee),h&&!p&&(Z.setBigUint64(C,a?.valueOf()??0n,!0),Z.setBigUint64(C,o?.valueOf()??0n,!0),C+=ne*2),O&&!N&&(Z.setBigUint64(C,c??0n,!0),C+=ve),n.series.forEach((U,we)=>{if(f||(Z.setUint32(C,n.keys[we],!0),C+=Ar),!l){let de=U.data.byteLength;U.dataType.isVariable||(de=ds(U)),Z.setUint32(C,de,!0),C+=Ee}k.set(new Uint8Array(U.data),C),C+=U.data.byteLength,!h&&!p&&(Z.setBigUint64(C,U.timeRange?.start.valueOf()??0n,!0),Z.setBigUint64(C,U.timeRange?.end.valueOf()??0n,!0),C+=ne*2),!O&&!N&&(Z.setBigUint64(C,U.alignment??0n,!0),C+=ve)}),k}decode(e,t=0){this.throwIfNotUpdated("decode");const n=e instanceof Uint8Array?e:new Uint8Array(e),i={keys:[],series:[]};let a=t,o=0,c=0,u,l,h;const p=new DataView(n.buffer,n.byteOffset,n.byteLength),f=!!(n[a]>>fs&1),O=!!(n[a]>>ys&1),N=!!(n[a]>>gs&1),k=!!(n[a]>>ps&1),Z=!!(n[a]>>ms&1),C=!!(n[a]>>ws&1);a++;const U=p.getUint32(a,!0);a+=Ir;const we=this.states.get(U);if(we==null)return i;if(N){if(a+Ee>p.byteLength)return i;o=p.getUint32(a,!0),a+=Ee}if(k&&!Z){if(a+ne>p.byteLength)return i;u=new d(p.getBigUint64(a,!0)),a+=ne,l=new d(p.getBigUint64(a,!0)),a+=ne}if(O&&!f){if(a+ve>p.byteLength)return i;h=p.getBigUint64(a,!0),a+=ve}return C&&(i.keys=[...we.keys]),we.keys.forEach((de,it)=>{if(!C){if(a>=p.byteLength||p.getUint32(a,!0)!==de)return;a+=Ar,i.keys.push(de)}const $e=we.keyDataTypes.get(de);if(c=0,N)c=o;else{if(a+Ee>p.byteLength)return;c=p.getUint32(a,!0),a+=Ee}let jt=c;if($e.isVariable||(jt*=$e.density.valueOf()),a+jt>p.byteLength){i.keys.splice(it,1);return}const ke={dataType:$e,data:n.slice(a,a+jt).buffer};if(a+=jt,!k&&!Z){if(a+ne*2>p.byteLength)return;const Rn=p.getBigUint64(a,!0);a+=ne;const mo=p.getBigUint64(a,!0);a+=ne,ke.timeRange=new M({start:Rn,end:mo})}else Z?ke.timeRange=new M({start:0n,end:0n}):ke.timeRange=new M({start:u?.valueOf()??0n,end:l?.valueOf()??0n});if(!O&&!f){if(a+ve>p.byteLength)return;h=p.getBigUint64(a,!0),a+=ve,ke.alignment=h}else f?ke.alignment=0n:ke.alignment=h;i.series.push(ke)}),i}}const vn=254,sy=new Uint8Array([vn]),iy=255,ay=new Uint8Array([iy]),Ta="application/sy-framer";class oy{contentType=Ta;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=je.JSON_CODEC}encode(e){const t=e;if(t.type=="close"||t.payload?.command!=_e.Write){const i=this.lowPerfCodec.encode(t),a=new Uint8Array({length:i.byteLength+1});return a.set(sy,0),a.set(new Uint8Array(i),1),a}const n=this.base.encode(t.payload?.frame,1);return n.set(ay,0),n}decode(e,t){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===vn)return this.lowPerfCodec.decode(e.slice(1),t);const a={type:"data"},o=this.base.decode(e,1);return a.payload={command:_e.Write,frame:o},a}}class cy{contentType=Ta;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=je.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,t){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===vn?this.lowPerfCodec.decode(e.slice(1),t):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class ur{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new ba}static async open(e,t){const n=new ur(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=te(e),i=await this.retriever.retrieve(n),a=i.map(c=>c.key);if(Wn.uniqueUnorderedPrimitiveArrays(this.keys,a)===Wn.EQUAL)return!1;if(this.codec.update(a,i.map(c=>c.dataType)),t==="keys")return this.adapter=null,this.keys=n,!0;const o=new Map;return this.adapter=o,n.forEach(c=>{const u=i.find(l=>l.name===c);if(u==null)throw new Error(`Channel ${c} not found`);o.set(u.key,u.name)}),this.keys=Array.from(this.adapter.keys()),!0}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,i)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,i]}return[n,i]})}}class En{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new ba}static async open(e,t){const n=new En(e);return await n.update(t),n}async adaptParams(e){const t=Ue.parse(e);return await Promise.all(t.map(async i=>await this.adaptToKey(i)))}async update(e){const t=await ia(this.retriever,e),n=t.map(l=>l.key),i=new Set(this.keys),a=new Set(n),o=!a.isSubsetOf(i),c=!i.isSubsetOf(a);return o||c?(this.adapter=new Map(t.map(l=>[l.name,l.key])),this.keys=n,this.codec.update(this.keys,t.map(l=>l.dataType)),!0):!1}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 D(`
|
|
32
32
|
Received a single channel name or key but no series.
|
|
33
|
-
`);if(Array.isArray(t)){if(t.some(u=>u instanceof
|
|
33
|
+
`);if(Array.isArray(t)){if(t.some(u=>u instanceof q||Array.isArray(u)))throw new D(`
|
|
34
34
|
Received a single channel name or key but multiple series.
|
|
35
|
-
`);t=t}const o=await this.fetchChannel(e),c=new
|
|
35
|
+
`);t=t}const o=await this.fetchChannel(e),c=new q({data:t,dataType:o.dataType});return new P(o.key,c)}if(Array.isArray(e)){if(t==null)throw new D(`
|
|
36
36
|
Received an array of channel names or keys but no series.
|
|
37
|
-
`);if(!Array.isArray(t))throw new
|
|
37
|
+
`);if(!Array.isArray(t))throw new D(`
|
|
38
38
|
Received an array of channel names or keys but no array of series.
|
|
39
|
-
`);const o=[],c=[];for(let u=0;u<e.length;u++){const l=await this.fetchChannel(e[u]);if(u>=t.length)throw new
|
|
39
|
+
`);const o=[],c=[];for(let u=0;u<e.length;u++){const l=await this.fetchChannel(e[u]);if(u>=t.length)throw new D(`
|
|
40
40
|
Received an array of channel names or keys but not enough series.
|
|
41
|
-
`);const h=new
|
|
41
|
+
`);const h=new q({data:t[u],dataType:l.dataType});o.push(l.key),c.push(h)}return new P(o,c)}if(e instanceof P||e instanceof Map){const o=new P(e);if(this.adapter==null)return o;const c=o.columns.map(u=>{const l=typeof u=="string"?this.adapter?.get(u):u;if(l==null)throw new D(`
|
|
42
42
|
Channel ${u} was not provided in the list of channels when opening the writer
|
|
43
|
-
`);return l});return new
|
|
44
|
-
Please report this error to the Synnax team.`),t!=null){if(te.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Jt=new E(-1);var On=(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))(On||{}),va=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(va||{});const iy=s.z.object({command:s.z.enum(On),span:E.z.optional(),bounds:z.z.optional(),stamp:N.z.optional(),keys:U.array().optional(),chunkSize:s.z.number().optional()}),ay=s.z.object({variant:s.z.enum(va),ack:s.z.boolean(),command:s.z.enum(On),error:ye.payloadZ.optional().nullable(),frame:lr.optional()});class vt{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,t){this.stream=new Ta("Iterator",e),this.value=new Z,this.adapter=t}static async _open(e,t,n,i,a={}){const o=await ur.open(n,t),c=await i.stream(vt.ENDPOINT,iy,ay),u=new vt(c,o);return await u.execute({command:0,keys:o.keys,bounds:new z(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Jt){return await this.execute({command:1,span:new E(e)})}async prev(e=Jt){return await this.execute({command:2,span:new E(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 N(e)})}async seekGE(e){return await this.execute({command:6,stamp:new N(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new oy(this)}async execute(e){for(this.stream.send(e),this.value=new Z;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new Z(t.frame)))}}}class oy{iter;open=!1;constructor(e){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 cy=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),ly=s.z.object({frame:lr}),uy="/frame/stream",ws=s.z.object({channels:Ue,downsampleFactor:s.z.number().optional().default(1),useHighPerformanceCodec:s.z.boolean().optional().default(!0)}),Nn=ws.or(Ue.transform(r=>ws.parse({channels:r}))),Ea=(r,e)=>async t=>{const n=Nn.parse(t),i=await ur.open(r,n.channels);n.useHighPerformanceCodec&&(e=e.withCodec(new sy(i.codec)));const a=await e.stream(uy,cy,ly),o=new hy(a,i);a.send({keys:i.keys,downsampleFactor:n.downsampleFactor??1});const[,c]=await a.receive();if(c!=null)throw c;return o},Oa=async(r,e,t)=>await Ea(r,e)(t);class hy{stream;adapter;downsampleFactor;constructor(e,t){this.stream=new Ta("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(te.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new Z((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 hr{wrapped_=null;breaker;opener;config;constructor(e,t,n={}){this.opener=e,this.config=Nn.parse(t);const{maxRetries:i=5e3,baseInterval:a=E.seconds(1),scale:o=1}=n??{};this.breaker=new Ni.Breaker({maxRetries:i,baseInterval:a,scale:o})}static async open(e,t,n){const i=new hr(e,t,n);return await i.runStreamer(),i}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;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=Ue.parse(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(te.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(te.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 Na extends Bu.Observer{streamer;closePromise;constructor(e,t){super(t),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}const dy=r=>({type:"framer",key:r.toString()});let za=class{streamClient;retriever;deleter;constructor(e,t,n){this.streamClient=e,this.retriever=n,this.deleter=new Vf(t)}async openIterator(e,t,n){return await vt._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return await ma._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await Oa(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:Tt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});return await o.write(a),await o.close()}const i=await this.openWriter({start:e,channels:t,mode:Tt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});await i.write(t,n),await i.close()}async read(e,t){const{single:n}=ee(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new Z;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async readLatest(e,t=1){const{single:n}=ee(e),i=await this.readLatestNFrame(e,t);return n?i.get(e):i}async readLatestNFrame(e,t){const n=await this.openIterator(z.MAX,e,{chunkSize:t}),i=new Z;if(t>0)try{await n.seekLast(),await n.prev(Jt),i.push(n.value)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=ee(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const fy=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Wf,AUTO_SPAN:Jt,Client:za,Frame:Z,HardenedStreamer:hr,Iterator:vt,ObservableStreamer:Na,Writer:ma,WriterClosedError:tn,WriterCommand:_e,WriterMode:Tt,createStreamOpener:Ea,frameZ:lr,ontologyID:dy,openStreamer:Oa,seriesFromPayload:fa,seriesToPayload:ya,streamerConfigZ:Nn,writerConfigZ:pa},Symbol.toStringTag,{value:"Module"})),yy=Q.ABSOLUTE_AUTHORITY,gy=Q.ZERO_AUTHORITY,py=Q.stateZ(s.z.number()),my=r=>r.to==null?`${r.from?.resource} - ${r.from?.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()})`,wy=s.z.object({transfers:s.z.array(Q.transferZ(U))});class Sa extends Na{states;codec;constructor(e){super(e,t=>{const n=this.codec.decode(t.series[0].buffer,wy);return this.merge(n),[n.transfers,!0]}),this.states=new Map,this.codec=new je.JSONCodec}subjects(){const e=new Map;return this.states.forEach(t=>e.set(t.subject.key,t.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(t=>{t.from==null&&t.to==null&&console.warn("Invalid transfer: ",t),t.to==null?this.states.delete(t.from.resource):this.states.set(t.to.resource,t.to)})}}const Aa="sy_node_1_control";let Ia=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await hr.open(async t=>await this.framer.openStreamer(t),Aa);return new Sa(e)}};const by=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:yy,CONTROL_STATE_CHANNEL_NAME:Aa,Client:Ia,StateTracker:Sa,ZERO_AUTHORITY:gy,stateZ:py,transferString:my},Symbol.toStringTag,{value:"Module"}));let $a=class{tasks;racks;devices;constructor(e,t,n){this.tasks=e,this.racks=t,this.devices=n}};const Ty=Object.freeze(Object.defineProperty({__proto__:null,Client:$a},Symbol.toStringTag,{value:"Module"})),ue=s.z.uint32(),ka=It.statusZ(s.z.object({rack:ue})),dr=s.z.object({key:ue,name:s.z.string(),status:ut.nullToUndefined(ka)}),Ca=dr.partial({key:!0}),xa=r=>r?je.JSON_CODEC.decodeString(r,ge.unknownZ):{},tt=s.z.string(),Ra=It.statusZ(s.z.object({rack:ue,device:tt})),fr=s.z.object({key:tt,rack:ue,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:ge.unknownZ.or(s.z.string().transform(xa)),status:ut.nullToUndefined(Ra)}),Ma=fr.extend({properties:s.z.unknown().transform(r=>je.JSON_CODEC.encodeString(r))}),vy="sy_device_set",Ey="sy_device_delete",Oy="sy_device_status",Ny="/hardware/device/retrieve",zy="/hardware/device/create",Sy="/hardware/device/delete",Ay=s.z.object({devices:Ma.array()}),Iy=s.z.object({devices:fr.array()}),$y=s.z.object({keys:tt.array()}),ky=s.z.object({}),Cy=s.z.object({keys:tt.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional(),models:s.z.string().array().optional(),locations:s.z.string().array().optional(),racks:ue.array().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),xy=s.z.object({devices:V(fr)}),Ry=s.z.object({key:tt,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),My=s.z.union([Ry,Cy]);let ja=class{type="device";client;constructor(e){this.client=e}async retrieve(e){const t=typeof e=="object"&&"key"in e,n=await p(this.client,Ny,e,My,xy);et("Device",e,n.devices,t);const i=n.devices;return t?i[0]:i}async create(e){const t=!Array.isArray(e),i=(await p(this.client,zy,{devices:v.toArray(e)},Ay,Iy)).devices;return t?i[0]:i}async delete(e){await p(this.client,Sy,{keys:v.toArray(e)},$y,ky)}};const jy=r=>({type:"device",key:r}),Uy=Object.freeze(Object.defineProperty({__proto__:null,Client:ja,DELETE_CHANNEL_NAME:Ey,SET_CHANNEL_NAME:vy,STATUS_CHANNEL_NAME:Oy,deviceZ:fr,keyZ:tt,newZ:Ma,ontologyID:jy,statusZ:Ra},Symbol.toStringTag,{value:"Module"})),Dy="/hardware/rack/retrieve",Py="/hardware/rack/create",Zy="/hardware/rack/delete",Ly="sy_rack_status",By="sy_rack_set",qy="sy_rack_delete",Fy=s.z.object({keys:ue.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),embedded:s.z.boolean().optional(),hostIsNode:s.z.boolean().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),Yy=s.z.object({racks:V(dr)}),Vy=s.z.union([s.z.object({key:ue,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),Wy=Fy,Hy=s.z.union([Vy,Wy]),_y=s.z.object({racks:Ca.array()}),Gy=s.z.object({racks:dr.array()}),Ky=s.z.object({keys:ue.array()}),Jy=s.z.object({});let Ua=class{type="rack";client;tasks;constructor(e,t){this.client=e,this.tasks=t}async delete(e){await p(this.client,Zy,{keys:v.toArray(e)},Ky,Jy)}async create(e){const t=!Array.isArray(e),n=await p(this.client,Py,{racks:v.toArray(e)},_y,Gy),i=this.sugar(n.racks);return t?i[0]:i}async retrieve(e){const t="key"in e||"name"in e,n=await p(this.client,Dy,e,Hy,Yy),i=this.sugar(n.racks);return et("Rack",e,i,t),t?i[0]:i}sugar(e){const t=!Array.isArray(e),n=v.toArray(e).map(({key:i,name:a,status:o})=>new Da(i,a,this.tasks,o));return t?n[0]:n}};class Da{key;name;status;tasks;constructor(e,t,n,i){this.key=e,this.name=t,this.tasks=n,this.status=i}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,t){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,t)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const Xy=r=>({type:"rack",key:r.toString()}),Qy=Object.freeze(Object.defineProperty({__proto__:null,Client:Ua,DELETE_CHANNEL_NAME:qy,Rack:Da,SET_CHANNEL_NAME:By,STATUS_CHANNEL_NAME:Ly,keyZ:ue,newZ:Ca,ontologyID:Xy,rackZ:dr,statusZ:ka},Symbol.toStringTag,{value:"Module"})),pe=r=>r?JSON.parse(r):{},me=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),Pa=r=>s.z.object({task:me,running:s.z.boolean(),data:r}),zn=r=>It.statusZ(Pa(r)),xt=(r={typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()})=>s.z.object({key:me,name:s.z.string(),type:r.typeSchema,internal:s.z.boolean().optional(),config:s.z.string().transform(xa).or(r.configSchema),status:zn(r.statusDataSchema).optional().nullable(),snapshot:s.z.boolean().optional()}),Za=r=>xt(r).omit({key:!0}).extend({key:me.transform(e=>e.toString()).optional(),config:s.z.unknown().transform(e=>je.JSON_CODEC.encodeString(e))}),eg=s.z.object({task:me,type:s.z.string(),key:s.z.string(),args:ge.unknownZ.or(s.z.string().transform(pe)).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),tg=r=>Number(BigInt(r)>>32n),nn="sy_task_status",sn="sy_task_cmd",rg="sy_task_set",ng="sy_task_delete",Ce=new Error("Task not created"),La=async(r,e)=>{const t=await e.retrieveParents(Sn(r));return t.length===0?null:t[0]};class Ba{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Ce;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Ce;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Ce;return this.rangeClient_}constructor({key:e,type:t,name:n,config:i,internal:a=!1,snapshot:o=!1,status:c},u,l,h,g){this.key=e,this.name=n,this.type=t,this.config=i,this.schemas=u??{typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()},this.internal=a,this.snapshot=o,this.status=c,this.frameClient_=l,this.ontologyClient_=h,this.rangeClient_=g}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return Sn(this.key)}async executeCommand(e,t){return await Fa(this.frameClient,this.key,e,t)}async executeCommandSync(e,t,n){return await Ya(this.frameClient,this.key,e,t,this.name,this.schemas?.statusDataSchema,n)}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Ce;return this.snapshot?await La(this.key,this.ontologyClient):null}}const sg=s.z.object({rack:ue.optional(),keys:me.array().optional(),names:s.z.string().array().optional(),types:s.z.string().array().optional(),includeStatus:s.z.boolean().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),ig=s.z.union([s.z.object({key:me,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),ag=sg,og=s.z.union([ig,ag]),cg=r=>s.z.object({tasks:V(xt(r))}),lg="/hardware/task/retrieve",ug="/hardware/task/create",hg="/hardware/task/delete",dg="/hardware/task/copy",fg=r=>s.z.object({tasks:Za(r).array()}),yg=r=>s.z.object({tasks:xt(r).array()}),gg=s.z.object({keys:me.array()}),pg=s.z.object({}),mg=s.z.object({key:me,name:s.z.string(),snapshot:s.z.boolean()}),wg=r=>s.z.object({task:xt(r)});let qa=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(e,t,n,i){this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e,t){const n=!Array.isArray(e),i=fg(t),a=yg(t),o=await p(this.client,ug,{tasks:v.toArray(e)},i,a),c=this.sugar(o.tasks,t);return n?c[0]:c}async delete(e){await p(this.client,hg,{keys:v.toArray(e)},gg,pg)}async retrieve({schemas:e,...t}){const n="key"in t||"name"in t,a=(await p(this.client,lg,t,og,cg(e))).tasks,o=this.sugar(a,e);return et("Task",t,o,n),n?o[0]:o}async copy(e,t,n){const i=wg(),a=await p(this.client,dg,{key:e,name:t,snapshot:n},mg,i);return this.sugar(a.task)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw Ce;return await La(e,this.ontologyClient)}sugar(e,t){const n=!Array.isArray(e),i=v.toArray(e).map(({key:a,name:o,type:c,config:u,status:l,internal:h,snapshot:g})=>new Ba({key:a,name:o,type:c,config:u,internal:h,snapshot:g,status:l},t,this.frameClient,this.ontologyClient,this.rangeClient));return n?i[0]:i}async executeCommand(e,t,n){if(Array.isArray(e))return await An(this.frameClient,e);if(t==null)throw new Error("Type is required");return await Fa(this.frameClient,e,t,n)}async executeCommandSync(e,t,n,i,a,o=s.z.unknown()){if(Array.isArray(e)){const u=async()=>(await this.retrieve({keys:e.map(h=>h.task)})).map(h=>h.name);return await Va(this.frameClient,e,t,o,u)}const c=async()=>(await this.retrieve({key:e})).name;return await Ya(this.frameClient,e,t,n,a??c,o,i)}};const Sn=r=>({type:"task",key:r}),Fa=async(r,e,t,n)=>(await An(r,[{args:n,task:e,type:t}]))[0],An=async(r,e)=>{if(r==null)throw Ce;const t=await r.openWriter(sn),n=e.map(i=>({...i,key:wu.create()}));return await t.write(sn,n),await t.close(),n.map(i=>i.key)},Ya=async(r,e,t,n,i,a,o)=>(await Va(r,[{args:o,task:e,type:t}],n,a,i))[0],Va=async(r,e,t,n,i)=>{if(r==null)throw Ce;const a=await r.openStreamer(nn),o=await An(r,e),c=new E(t);let u=[],l;const h=new Promise((g,d)=>{l=setTimeout(()=>{(async()=>{const O=e.map(S=>S.task);d(await bg("command",i,c,O))})()},c.milliseconds)});try{for(;;){const g=await Promise.race([a.read(),h]),d=zn(n).parse(g.at(-1)[nn]);if(o.includes(d.key)&&(u=[...u.filter(O=>O.key!==d.key),d],u.length===o.length))return u}}finally{clearTimeout(l),a.close()}},bg=async(r,e,t,n)=>{const i=Sl.capitalize(r),a=t.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=v.toArray(await e());const c=Kr.naturalLanguageJoin(o);return new Error(`${i} command to ${c} timed out after ${a}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${i} command to task with key ${Kr.naturalLanguageJoin(n)} timed out after ${a}`)}},Tg=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:sn,Client:qa,DELETE_CHANNEL_NAME:ng,SET_CHANNEL_NAME:rg,STATUS_CHANNEL_NAME:nn,Task:Ba,commandZ:eg,keyZ:me,newZ:Za,ontologyID:Sn,rackKey:tg,statusDetailsZ:Pa,statusZ:zn,taskZ:xt},Symbol.toStringTag,{value:"Module"})),Ie=s.z.uuid(),Rt=s.z.object({key:Ie,name:s.z.string().min(1),color:s.z.string()}),vg="labeled_by",Eg="sy_label_set",Og="sy_label_delete",Wa=Rt.extend({key:Ie.optional()}),Ng=s.object({labels:Wa.array()}),zg=s.object({labels:Rt.array()}),Sg=s.object({keys:Ie.array()}),Ha=s.object({id:M,labels:Ie.array(),replace:s.boolean().optional()}),Ag=Ha.omit({replace:!0}),$r=s.object({}),Ig="/label/create",$g="/label/delete",kg="/label/set",Cg="/label/remove",xg="/label/retrieve",Rg=s.object({keys:Ie.array().optional(),for:M.optional(),searchTerm:s.string().optional(),offset:s.number().optional(),limit:s.number().optional()}),Mg=s.object({key:Ie}).transform(({key:r})=>({keys:[r]})),jg=s.union([Mg,Rg]),Ug=s.object({labels:V(Rt)});let _a=class{type="label";client;constructor(e){this.client=e}async retrieve(e){const t="key"in e,n=await p(this.client,xg,e,jg,Ug);return et("Label",e,n.labels,t),t?n.labels[0]:n.labels}async label(e,t,n={}){await p(this.client,kg,{id:e,labels:t,replace:n.replace},Ha,$r)}async remove(e,t){await p(this.client,Cg,{id:e,labels:t},Ag,$r)}async create(e){const t=Array.isArray(e),n=await p(this.client,Ig,{labels:v.toArray(e)},Ng,zg);return t?n.labels:n.labels[0]}async delete(e){await p(this.client,$g,{keys:v.toArray(e)},Sg,$r)}};const Dg=r=>({type:"label",key:r}),Pg=Object.freeze(Object.defineProperty({__proto__:null,Client:_a,DELETE_CHANNEL_NAME:Og,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:vg,SET_CHANNEL_NAME:Eg,keyZ:Ie,labelZ:Rt,newZ:Wa,ontologyID:Dg},Symbol.toStringTag,{value:"Module"})),W=s.z.uuid(),In=s.z.string().min(1),Mt=s.z.object({key:W,name:In,timeRange:z.z,color:s.z.string().optional(),labels:Rt.array().or(s.z.null().transform(()=>{})).optional(),get parent(){return Mt.optional().nullable().transform(r=>r===void 0?null:r)}}),Ga=Mt.omit({parent:!0,labels:!0}).partial({key:!0}),Zg="sy_range_alias_set",Lg="sy_range_alias_delete",Bg=s.z.object({range:W,aliases:s.z.string().array()}),qg=s.z.object({aliases:s.z.record(s.z.string(),U)}),Fg=s.z.object({range:W,aliases:s.z.record(U.or(s.z.string()),s.z.string())}),Yg=s.z.unknown(),Vg=s.z.object({range:W,channels:U.array()}),Wg=s.z.unknown(),Hg=s.z.object({range:W}),_g=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),Gg=s.z.object({range:W,channels:U.array()}),Kg=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())});class X{static SET_ENDPOINT="/range/alias/set";static RESOLVE_ENDPOINT="/range/alias/resolve";static LIST_ENDPOINT="/range/alias/list";static RETRIEVE_ENDPOINT="/range/alias/retrieve";static DELETE_ENDPOINT="/range/alias/delete";frameClient;cache=new Map;client;rangeKey;constructor(e,t,n){this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",i={};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?i[o]=c:t.push(o)});if(t.length===0)return i;const a=await p(this.client,X.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Bg,qg);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await p(this.client,X.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Fg,Yg)}async list(){return(await p(this.client,X.LIST_ENDPOINT,{range:this.rangeKey},Hg,_g)).aliases}async retrieve(e){const t=typeof e=="number",n=await p(this.client,X.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:v.toArray(e)},Gg,Kg);return t?n.aliases[e]:n.aliases}async delete(e){await p(this.client,X.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Vg,Wg)}}const Jg=s.z.object({alias:s.z.string().optional(),channel:U,range:W}),Ka="---",Xg=r=>`${r.range}${Ka}${r.channel}`,Qg=r=>{const[e,t]=r.split(Ka);return{range:e,channel:Number(t)}},ep="sy_range_kv_set",tp="sy_range_kv_delete",$n=s.z.object({range:W,key:s.z.string(),value:s.z.string()}),rp=({range:r,key:e})=>`${r}<--->${e}`,np=s.z.object({range:W,keys:s.z.string().array()}),sp=s.z.object({pairs:V($n)}),ip=s.z.object({range:W,pairs:$n.array()}),ap=s.z.object({range:W,keys:s.z.string().array()});class Me{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,t){this.rangeKey=e,this.client=t}async get(e){const t=await p(this.client,Me.GET_ENDPOINT,{range:this.rangeKey,keys:v.toArray(e)},np,sp);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;Gs(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await p(this.client,Me.SET_ENDPOINT,{range:this.rangeKey,pairs:n},ip,s.z.unknown())}async delete(e){await p(this.client,Me.DELETE_ENDPOINT,{range:this.rangeKey,keys:v.toArray(e)},ap,s.z.unknown())}}const op="sy_range_set",cp="sy_range_delete";class Ja{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:t=z.ZERO,key:n,color:i,parent:a,labels:o},{frameClient:c,kv:u,aliaser:l,channels:h,labelClient:g,ontologyClient:d,rangeClient:O}){this.key=n,this.name=e,this.timeRange=t,this.parent=a,this.labels=o,this.frameClient=c,this.color=i,this.kv=u,this.aliaser=l,this.channels=h,this.labelClient=g,this.ontologyClient=d,this.rangeClient=O}get ontologyID(){return qe(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new Se(`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 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 retrieveLabels(){return await this.labelClient.retrieve({for:qe(this.key)})}async addLabel(...e){await this.labelClient.label(qe(this.key),e)}async removeLabel(...e){await this.labelClient.remove(qe(this.key),e)}static sort(e,t){return z.sort(e.timeRange,t.timeRange)}}const lp=s.z.object({keys:W.array().optional(),names:s.z.array(s.z.string()).optional(),searchTerm:s.z.string().optional(),overlapsWith:z.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional(),hasLabels:Ie.array().optional(),includeLabels:s.z.boolean().optional(),includeParent:s.z.boolean().optional()}),up=lp.or(W.array().transform(r=>({keys:r}))).or(W.transform(r=>({keys:[r]}))).or(s.z.string().transform(r=>({names:[r]}))).or(s.z.string().array().transform(r=>({names:r}))).or(z.z.transform(r=>({overlapsWith:r}))),hp="/range/retrieve",dp=s.z.object({ranges:V(Mt)});let Xa=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(e,t,n,i,a,o){this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=o}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(v.toArray(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(v.toArray(e))}async retrieve(e){const t=typeof e=="string",{ranges:n}=await p(this.unaryClient,hp,e,up,dp);return et("Range",e,n,t),t?this.sugarMany(n)[0]:this.sugarMany(n)}getKV(e){return new Me(e,this.unaryClient)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents(qe(e));if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOntologyResource(e){return this.sugarOne(Qa(e))}async retrieveAlias(e,t){return await new X(e,this.frameClient,this.unaryClient).retrieve(t)}async retrieveAliases(e,t){return await new X(e,this.frameClient,this.unaryClient).retrieve(t)}async listAliases(e){return await new X(e,this.frameClient,this.unaryClient).list()}async setAlias(e,t,n){await new X(e,this.frameClient,this.unaryClient).set({[t]:n})}sugarOne(e){return new Ja(e,{frameClient:this.frameClient,kv:new Me(e.key,this.unaryClient),aliaser:new X(e.key,this.frameClient,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(t=>this.sugarOne(t))}resourceToRange(e){return this.sugarOne({key:e.id.key,name:e.data?.name,timeRange:new z(e.data?.timeRange),color:e.data?.color,labels:[],parent:null})}};const qe=r=>({type:"range",key:r}),fp=r=>({type:"range-alias",key:r}),Qa=({data:r,id:{key:e},name:t})=>{const n=z.z.parse(r?.timeRange);return{key:e,name:t,timeRange:n,color:typeof r?.color=="string"?r.color:void 0,labels:[],parent:null}},yp=s.z.object({ranges:Mt.array()}),gp=s.z.object({parent:M.optional(),ranges:Ga.array()}),pp=s.z.object({keys:W.array()}),mp=s.z.object({}),wp=s.z.object({key:W,name:In}),bp=s.z.object({}),Tp="/range/create",vp="/range/delete",Ep="/range/rename";class eo{client;constructor(e){this.client=e}async rename(e,t){await p(this.client,Ep,{key:e,name:t},wp,bp)}async create(e,t){return(await p(this.client,Tp,{ranges:e,...t},gp,yp)).ranges}async delete(e){await p(this.client,vp,{keys:e},pp,mp)}}const Op=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:X,Client:Xa,DELETE_ALIAS_CHANNEL_NAME:Lg,DELETE_CHANNEL_NAME:cp,KV:Me,KV_DELETE_CHANNEL:tp,KV_SET_CHANNEL:ep,Range:Ja,SET_ALIAS_CHANNEL_NAME:Zg,SET_CHANNEL_NAME:op,Writer:eo,aliasKey:Xg,aliasOntologyID:fp,aliasZ:Jg,convertOntologyResourceToPayload:Qa,decodeDeleteAliasChange:Qg,keyZ:W,kvPairKey:rp,kvPairZ:$n,nameZ:In,newZ:Ga,ontologyID:qe,payloadZ:Mt},Symbol.toStringTag,{value:"Module"})),Np="/api/v1/";class zp{url;unary;stream;secure;constructor(e,t={},n=!1){this.secure=n,this.url=e.child(Np);const i=new je.JSONCodec;this.unary=dl(new hl(this.url,i,this.secure),t),this.stream=new ml(this.url,i,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const rt=s.z.uuid(),yr=s.z.object({key:rt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe))}),to=yr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),he=s.z.uuid(),gr=s.z.object({key:he,name:s.z.string(),layout:ge.unknownZ.or(s.z.string().transform(pe))}),ro=gr.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),no=gr.omit({layout:!0}).extend({layout:s.z.string().transform(pe)}),Sp="/workspace/lineplot/retrieve",Ap="/workspace/lineplot/create",Ip="/workspace/lineplot/rename",$p="/workspace/lineplot/set-data",kp="/workspace/lineplot/delete",Cp=s.z.object({keys:rt.array()}),xp=s.z.object({workspace:he,linePlots:to.array()}),Rp=s.z.object({key:rt,name:s.z.string()}),Mp=s.z.object({key:rt,data:s.z.string()}),jp=s.z.object({keys:rt.array()}),Up=s.z.object({linePlots:V(yr)}),Dp=s.z.object({linePlots:yr.array()}),kr=s.z.object({});let so=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await p(this.client,Ap,{workspace:e,linePlots:v.toArray(t)},xp,Dp);return n?i.linePlots:i.linePlots[0]}async rename(e,t){await p(this.client,Ip,{key:e,name:t},Rp,kr)}async setData(e,t){await p(this.client,$p,{key:e,data:JSON.stringify(t)},Mp,kr)}async retrieve(e){const t=Array.isArray(e),n=await p(this.client,Sp,{keys:v.toArray(e)},Cp,Up);return t?n.linePlots:n.linePlots[0]}async delete(e){await p(this.client,kp,{keys:v.toArray(e)},jp,kr)}};const Pp=r=>({type:"lineplot",key:r}),Zp=Object.freeze(Object.defineProperty({__proto__:null,Client:so,keyZ:rt,linePlotZ:yr,newZ:to,ontologyID:Pp},Symbol.toStringTag,{value:"Module"})),nt=s.z.uuid(),pr=s.z.object({key:nt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe))}),io=pr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Lp="/workspace/log/retrieve",Bp="/workspace/log/create",qp="/workspace/log/rename",Fp="/workspace/log/set-data",Yp="/workspace/log/delete",Vp=s.z.object({keys:nt.array()}),Wp=s.z.object({workspace:he,logs:io.array()}),Hp=s.z.object({key:nt,name:s.z.string()}),_p=s.z.object({key:nt,data:s.z.string()}),Gp=s.z.object({keys:nt.array()}),Kp=s.z.object({logs:pr.array()}),Jp=s.z.object({logs:pr.array()}),Cr=s.z.object({});let ao=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await p(this.client,Bp,{workspace:e,logs:v.toArray(t)},Wp,Jp);return n?i.logs:i.logs[0]}async rename(e,t){await p(this.client,qp,{key:e,name:t},Hp,Cr)}async setData(e,t){await p(this.client,Fp,{key:e,data:JSON.stringify(t)},_p,Cr)}async retrieve(e){const t=Array.isArray(e),n=await p(this.client,Lp,{keys:v.toArray(e)},Vp,Kp);return t?n.logs:n.logs[0]}async delete(e){await p(this.client,Yp,{keys:v.toArray(e)},Gp,Cr)}};const Xp=r=>({type:"log",key:r}),Qp=Object.freeze(Object.defineProperty({__proto__:null,Client:ao,keyZ:nt,logZ:pr,newZ:io,ontologyID:Xp},Symbol.toStringTag,{value:"Module"})),De=s.z.uuid(),mr=s.z.object({key:De,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe)),snapshot:s.z.boolean()}),oo=mr.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),kn=mr.extend({data:s.z.string().transform(pe)}),em="/workspace/schematic/retrieve",tm="/workspace/schematic/create",rm="/workspace/schematic/rename",nm="/workspace/schematic/set-data",sm="/workspace/schematic/delete",im="/workspace/schematic/copy",am=s.z.object({keys:De.array()}),om=s.z.object({workspace:he,schematics:oo.array()}),cm=s.z.object({key:De,name:s.z.string()}),lm=s.z.object({key:De,data:s.z.string()}),um=s.z.object({keys:De.array()}),hm=s.z.object({key:De,name:s.z.string(),snapshot:s.z.boolean()}),dm=s.z.object({schematics:V(kn)}),fm=s.z.object({schematics:kn.array()}),ym=s.z.object({schematic:mr}),xr=s.z.object({});let co=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await p(this.client,tm,{workspace:e,schematics:v.toArray(t)},om,fm);return n?i.schematics:i.schematics[0]}async rename(e,t){await p(this.client,rm,{key:e,name:t},cm,xr)}async setData(e,t){await p(this.client,nm,{key:e,data:JSON.stringify(t)},lm,xr)}async retrieve(e){const t=Array.isArray(e),n=await p(this.client,em,{keys:v.toArray(e)},am,dm);return t?n.schematics:n.schematics[0]}async delete(e){await p(this.client,sm,{keys:v.toArray(e)},um,xr)}async copy(e,t,n){return(await p(this.client,im,{key:e,name:t,snapshot:n},hm,ym)).schematic}};const gm=r=>({type:"schematic",key:r}),pm=Object.freeze(Object.defineProperty({__proto__:null,Client:co,keyZ:De,newZ:oo,ontologyID:gm,remoteZ:kn,schematicZ:mr},Symbol.toStringTag,{value:"Module"})),st=s.z.uuid(),Cn=s.z.object({key:st,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe))}),lo=Cn.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),xn=Cn.extend({data:s.z.string().transform(pe)}),mm="/workspace/table/retrieve",wm="/workspace/table/create",bm="/workspace/table/rename",Tm="/workspace/table/set-data",vm="/workspace/table/delete",Em=s.z.object({keys:st.array()}),Om=s.z.object({workspace:he,tables:lo.array()}),Nm=s.z.object({key:st,name:s.z.string()}),zm=s.z.object({key:st,data:s.z.string()}),Sm=s.z.object({keys:st.array()}),Am=s.z.object({tables:xn.array()}),Im=s.z.object({tables:xn.array()}),Rr=s.z.object({});let uo=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await p(this.client,wm,{workspace:e,tables:v.toArray(t)},Om,Im);return n?i.tables:i.tables[0]}async rename(e,t){await p(this.client,bm,{key:e,name:t},Nm,Rr)}async setData(e,t){await p(this.client,Tm,{key:e,data:JSON.stringify(t)},zm,Rr)}async retrieve(e){const t=Array.isArray(e),n=await p(this.client,mm,{keys:v.toArray(e)},Em,Am);return t?n.tables:n.tables[0]}async delete(e){await p(this.client,vm,{keys:v.toArray(e)},Sm,Rr)}};const $m=r=>({type:"table",key:r}),km=Object.freeze(Object.defineProperty({__proto__:null,Client:uo,keyZ:st,newZ:lo,ontologyID:$m,remoteZ:xn,tableZ:Cn},Symbol.toStringTag,{value:"Module"})),bs="/workspace/retrieve",Cm="/workspace/create",xm="/workspace/rename",Rm="/workspace/set-layout",Mm="/workspace/delete",Ts=s.z.object({keys:he.array().optional(),searchTerm:s.z.string().optional(),author:Ae.optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),jm=s.z.object({workspaces:ro.array()}),Um=s.z.object({key:he,name:s.z.string()}),Dm=s.z.object({key:he,layout:s.z.string()}),Pm=s.z.object({keys:he.array()}),vs=s.z.object({workspaces:V(gr)}),Zm=s.z.object({workspaces:no.array()}),Mr=s.z.object({}),Lm="sy_workspace_set",Bm="sy_workspace_delete";class ho{type="workspace";schematic;linePlot;log;table;client;constructor(e){this.client=e,this.schematic=new co(e),this.linePlot=new so(e),this.log=new ao(e),this.table=new uo(e)}async create(e){const t=Array.isArray(e),n=await p(this.client,Cm,{workspaces:v.toArray(e)},jm,Zm);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await p(this.client,xm,{key:e,name:t},Um,Mr)}async setLayout(e,t){await p(this.client,Rm,{key:e,layout:JSON.stringify(t)},Dm,Mr)}async retrieve(e){let t;const n=typeof e!="string";typeof e=="string"||Array.isArray(e)?t={keys:v.toArray(e)}:t=e;const i=await p(this.client,bs,t,Ts,vs);return n?i.workspaces:i.workspaces[0]}async retrieveByAuthor(e){return(await p(this.client,bs,{author:e},Ts,vs)).workspaces}async delete(e){await p(this.client,Mm,{keys:v.toArray(e)},Pm,Mr)}}const qm=r=>({type:"workspace",key:r}),Fm=Object.freeze(Object.defineProperty({__proto__:null,Client:ho,DELETE_CHANNEL_NAME:Bm,SET_CHANNEL_NAME:Lm,keyZ:he,newZ:ro,ontologyID:qm,remoteZ:no,workspaceZ:gr},Symbol.toStringTag,{value:"Module"})),fo=s.z.object({host:s.z.string({error:"Host is required"}).min(1,"Host is required"),port:s.z.number({error:"Port is required"}).or(s.z.string({error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:E.z.default(E.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:Ni.breakerConfigZ.optional()});class yo extends za{createdAt;props;ranges;channels;auth;user;access;connectivity;ontology;workspaces;labels;hardware;control;static connectivity=bt;transport;clientVersion="0.44.3";constructor(e){const t=fo.parse(e),{host:n,port:i,username:a,password:o,connectivityPollFrequency:c,secure:u,retry:l}=t,h=new zp(new lt({host:n,port:Number(i)}),l,u);h.use(Hh);let g;a!=null&&o!=null&&(g=new Zf(h.unary,{username:a,password:o}),h.use(g.middleware()));const d=new Tn(new kt(h.unary)),O=new ca(h.unary,d);super(h.stream,h.unary,d),this.createdAt=N.now(),this.props=t,this.auth=g,this.transport=h,this.channels=new ia(this,d,h.unary,O),this.connectivity=new bt(h.unary,c,this.clientVersion,t.name),this.control=new Ia(this),this.ontology=new Ki(h.unary,this);const S=new eo(this.transport.unary);this.labels=new _a(this.transport.unary),this.ranges=new Xa(this,S,this.transport.unary,d,this.labels,this.ontology),this.access=new Qi(this.transport.unary),this.user=new ua(this.transport.unary),this.workspaces=new ho(this.transport.unary);const x=new ja(this.transport.unary),L=new qa(this.transport.unary,this,this.ontology,this.ranges),R=new Ua(this.transport.unary,L);this.hardware=new $a(L,R,x)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}const go={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:E.seconds(1),scale:1.5}},Ym=r=>new yo({...go,...r});exports.AuthError=yt;exports.Channel=Kt;exports.ContiguityError=Yh;exports.DataType=I;exports.Density=H;exports.DisconnectedError=Fh;exports.Frame=Z;exports.MultiSeries=vi;exports.MultipleFoundError=pt;exports.NotFoundError=gt;exports.QueryError=Se;exports.Rate=G;exports.RouteError=Qr;exports.Series=F;exports.Synnax=yo;exports.TEST_CLIENT_PROPS=go;exports.TimeRange=z;exports.TimeSpan=E;exports.TimeStamp=N;exports.UnexpectedError=Ve;exports.ValidationError=P;exports.access=Pd;exports.channel=uf;exports.connection=Bf;exports.control=by;exports.createTestClient=Ym;exports.device=Uy;exports.framer=fy;exports.group=ld;exports.hardware=Ty;exports.isCalculated=wt;exports.label=Pg;exports.linePlot=Zp;exports.log=Qp;exports.ontology=Ed;exports.policy=Dd;exports.rack=Qy;exports.ranger=Op;exports.schematic=pm;exports.synnaxPropsZ=fo;exports.table=km;exports.task=Tg;exports.user=Cf;exports.workspace=Fm;
|
|
43
|
+
`);return l});return new P(c,o.series)}const n=[],i=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[c,u]=a[o],l=await this.fetchChannel(c),h=new q({data:u,dataType:l.dataType});n.push(l.key),i.push(h)}return new P(n,i)}}class va{name;stream;constructor(e,t){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 ${JSON.stringify(e)} closure.
|
|
44
|
+
Please report this error to the Synnax team.`),t!=null){if(re.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Jt=new E(-1);var On=(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))(On||{}),Ea=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Ea||{});const ly=s.z.object({command:s.z.enum(On),span:E.z.optional(),bounds:M.z.optional(),stamp:d.z.optional(),keys:x.array().optional(),chunkSize:s.z.number().optional()}),uy=s.z.object({variant:s.z.enum(Ea),ack:s.z.boolean(),command:s.z.enum(On),error:ye.payloadZ.optional().nullable(),frame:lr.optional()});class vt{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,t){this.stream=new va("Iterator",e),this.value=new P,this.adapter=t}static async _open(e,t,n,i,a={}){const o=await ur.open(n,t),c=await i.stream(vt.ENDPOINT,ly,uy),u=new vt(c,o);return await u.execute({command:0,keys:o.keys,bounds:new M(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Jt){return await this.execute({command:1,span:new E(e)})}async prev(e=Jt){return await this.execute({command:2,span:new E(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 d(e)})}async seekGE(e){return await this.execute({command:6,stamp:new d(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new hy(this)}async execute(e){for(this.stream.send(e),this.value=new P;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new P(t.frame)))}}}class hy{iter;open=!1;constructor(e){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 dy=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),fy=s.z.object({frame:lr}),yy="/frame/stream",bs=s.z.object({channels:Ue,downsampleFactor:s.z.number().optional().default(1),useHighPerformanceCodec:s.z.boolean().optional().default(!0)}),Nn=bs.or(Ue.transform(r=>bs.parse({channels:r}))),Oa=(r,e)=>async t=>{const n=Nn.parse(t),i=await ur.open(r,n.channels);n.useHighPerformanceCodec&&(e=e.withCodec(new cy(i.codec)));const a=await e.stream(yy,dy,fy),o=new gy(a,i);a.send({keys:i.keys,downsampleFactor:n.downsampleFactor??1});const[,c]=await a.receive();if(c!=null)throw c;return o},Na=async(r,e,t)=>await Oa(r,e)(t);class gy{stream;adapter;downsampleFactor;constructor(e,t){this.stream=new va("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(re.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new P((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 hr{wrapped_=null;breaker;opener;config;constructor(e,t,n={}){this.opener=e,this.config=Nn.parse(t);const{maxRetries:i=5e3,baseInterval:a=E.seconds(1),scale:o=1}=n??{};this.breaker=new zi.Breaker({maxRetries:i,baseInterval:a,scale:o})}static async open(e,t,n){const i=new hr(e,t,n);return await i.runStreamer(),i}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;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=Ue.parse(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(re.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(re.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 za extends qu.Observer{streamer;closePromise;constructor(e,t){super(t),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}const py=r=>({type:"framer",key:r.toString()});let Sa=class{streamClient;retriever;deleter;constructor(e,t,n){this.streamClient=e,this.retriever=n,this.deleter=new Gf(t)}async openIterator(e,t,n){return await vt._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return await wa._open(this.retriever,this.streamClient,e)}async openStreamer(e){return await Na(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:Tt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});return await o.write(a),await o.close()}const i=await this.openWriter({start:e,channels:t,mode:Tt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});await i.write(t,n),await i.close()}async read(e,t){const{single:n}=te(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new P;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async readLatest(e,t=1){const{single:n}=te(e),i=await this.readLatestNFrame(e,t);return n?i.get(e):i}async readLatestNFrame(e,t){const n=await this.openIterator(M.MAX,e,{chunkSize:t}),i=new P;if(t>0)try{await n.seekLast(),await n.prev(Jt),i.push(n.value)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=te(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const my=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Kf,AUTO_SPAN:Jt,Client:Sa,Frame:P,HardenedStreamer:hr,Iterator:vt,ObservableStreamer:za,Writer:wa,WriterClosedError:tn,WriterCommand:_e,WriterMode:Tt,createStreamOpener:Oa,frameZ:lr,ontologyID:py,openStreamer:Na,seriesFromPayload:ya,seriesToPayload:ga,streamerConfigZ:Nn,writerConfigZ:ma},Symbol.toStringTag,{value:"Module"})),wy=X.ABSOLUTE_AUTHORITY,by=X.ZERO_AUTHORITY,Ty=X.stateZ(s.z.number()),vy=r=>r.to==null?`${r.from?.resource} - ${r.from?.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()})`,Ey=s.z.object({transfers:s.z.array(X.transferZ(x))});class Aa extends za{states;codec;constructor(e){super(e,t=>{const n=this.codec.decode(t.series[0].buffer,Ey);return this.merge(n),[n.transfers,!0]}),this.states=new Map,this.codec=new je.JSONCodec}subjects(){const e=new Map;return this.states.forEach(t=>e.set(t.subject.key,t.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(t=>{t.from==null&&t.to==null&&console.warn("Invalid transfer: ",t),t.to==null?this.states.delete(t.from.resource):this.states.set(t.to.resource,t.to)})}}const Ia="sy_node_1_control";let $a=class{framer;constructor(e){this.framer=e}async openStateTracker(){const e=await hr.open(async t=>await this.framer.openStreamer(t),Ia);return new Aa(e)}};const Oy=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:wy,CONTROL_STATE_CHANNEL_NAME:Ia,Client:$a,StateTracker:Aa,ZERO_AUTHORITY:by,stateZ:Ty,transferString:vy},Symbol.toStringTag,{value:"Module"}));let ka=class{tasks;racks;devices;constructor(e,t,n){this.tasks=e,this.racks=t,this.devices=n}};const Ny=Object.freeze(Object.defineProperty({__proto__:null,Client:ka},Symbol.toStringTag,{value:"Module"})),ue=s.z.uint32(),Ca=It.statusZ(s.z.object({rack:ue})),dr=s.z.object({key:ue,name:s.z.string(),status:ut.nullToUndefined(Ca)}),xa=dr.partial({key:!0}),Ra=r=>r?je.JSON_CODEC.decodeString(r,ge.unknownZ):{},tt=s.z.string(),Ma=It.statusZ(s.z.object({rack:ue,device:tt})),fr=s.z.object({key:tt,rack:ue,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:ge.unknownZ.or(s.z.string().transform(Ra)),status:ut.nullToUndefined(Ma)}),ja=fr.extend({properties:s.z.unknown().transform(r=>je.JSON_CODEC.encodeString(r))}),zy="sy_device_set",Sy="sy_device_delete",Ay="sy_device_status",Iy="/hardware/device/retrieve",$y="/hardware/device/create",ky="/hardware/device/delete",Cy=s.z.object({devices:ja.array()}),xy=s.z.object({devices:fr.array()}),Ry=s.z.object({keys:tt.array()}),My=s.z.object({}),jy=s.z.object({keys:tt.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional(),models:s.z.string().array().optional(),locations:s.z.string().array().optional(),racks:ue.array().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),Uy=s.z.object({devices:Y(fr)}),Dy=s.z.object({key:tt,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),Py=s.z.union([Dy,jy]);let Ua=class{type="device";client;constructor(e){this.client=e}async retrieve(e){const t=typeof e=="object"&&"key"in e,n=await m(this.client,Iy,e,Py,Uy);et("Device",e,n.devices,t);const i=n.devices;return t?i[0]:i}async create(e){const t=!Array.isArray(e),i=(await m(this.client,$y,{devices:v.toArray(e)},Cy,xy)).devices;return t?i[0]:i}async delete(e){await m(this.client,ky,{keys:v.toArray(e)},Ry,My)}};const Zy=r=>({type:"device",key:r}),Ly=Object.freeze(Object.defineProperty({__proto__:null,Client:Ua,DELETE_CHANNEL_NAME:Sy,SET_CHANNEL_NAME:zy,STATUS_CHANNEL_NAME:Ay,deviceZ:fr,keyZ:tt,newZ:ja,ontologyID:Zy,statusZ:Ma},Symbol.toStringTag,{value:"Module"})),By="/hardware/rack/retrieve",qy="/hardware/rack/create",Fy="/hardware/rack/delete",Yy="sy_rack_status",Vy="sy_rack_set",Wy="sy_rack_delete",Hy=s.z.object({keys:ue.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),embedded:s.z.boolean().optional(),hostIsNode:s.z.boolean().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),_y=s.z.object({racks:Y(dr)}),Gy=s.z.union([s.z.object({key:ue,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),Ky=Hy,Jy=s.z.union([Gy,Ky]),Xy=s.z.object({racks:xa.array()}),Qy=s.z.object({racks:dr.array()}),eg=s.z.object({keys:ue.array()}),tg=s.z.object({});let Da=class{type="rack";client;tasks;constructor(e,t){this.client=e,this.tasks=t}async delete(e){await m(this.client,Fy,{keys:v.toArray(e)},eg,tg)}async create(e){const t=!Array.isArray(e),n=await m(this.client,qy,{racks:v.toArray(e)},Xy,Qy),i=this.sugar(n.racks);return t?i[0]:i}async retrieve(e){const t="key"in e||"name"in e,n=await m(this.client,By,e,Jy,_y),i=this.sugar(n.racks);return et("Rack",e,i,t),t?i[0]:i}sugar(e){const t=!Array.isArray(e),n=v.toArray(e).map(({key:i,name:a,status:o})=>new Pa(i,a,this.tasks,o));return t?n[0]:n}};class Pa{key;name;status;tasks;constructor(e,t,n,i){this.key=e,this.name=t,this.tasks=n,this.status=i}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,t){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,t)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const rg=r=>({type:"rack",key:r.toString()}),ng=Object.freeze(Object.defineProperty({__proto__:null,Client:Da,DELETE_CHANNEL_NAME:Wy,Rack:Pa,SET_CHANNEL_NAME:Vy,STATUS_CHANNEL_NAME:Yy,keyZ:ue,newZ:xa,ontologyID:rg,rackZ:dr,statusZ:Ca},Symbol.toStringTag,{value:"Module"})),pe=r=>r?JSON.parse(r):{},me=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),Za=r=>s.z.object({task:me,running:s.z.boolean(),data:r}),zn=r=>It.statusZ(Za(r)),xt=(r={typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()})=>s.z.object({key:me,name:s.z.string(),type:r.typeSchema,internal:s.z.boolean().optional(),config:s.z.string().transform(Ra).or(r.configSchema),status:zn(r.statusDataSchema).optional().nullable(),snapshot:s.z.boolean().optional()}),La=r=>xt(r).omit({key:!0}).extend({key:me.transform(e=>e.toString()).optional(),config:s.z.unknown().transform(e=>je.JSON_CODEC.encodeString(e))}),sg=s.z.object({task:me,type:s.z.string(),key:s.z.string(),args:ge.unknownZ.or(s.z.string().transform(pe)).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),ig=r=>Number(BigInt(r)>>32n),nn="sy_task_status",sn="sy_task_cmd",ag="sy_task_set",og="sy_task_delete",Ce=new Error("Task not created"),Ba=async(r,e)=>{const t=await e.retrieveParents(Sn(r));return t.length===0?null:t[0]};class qa{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Ce;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Ce;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Ce;return this.rangeClient_}constructor({key:e,type:t,name:n,config:i,internal:a=!1,snapshot:o=!1,status:c},u,l,h,p){this.key=e,this.name=n,this.type=t,this.config=i,this.schemas=u??{typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()},this.internal=a,this.snapshot=o,this.status=c,this.frameClient_=l,this.ontologyClient_=h,this.rangeClient_=p}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return Sn(this.key)}async executeCommand(e,t){return await Ya(this.frameClient,this.key,e,t)}async executeCommandSync(e,t,n){return await Va(this.frameClient,this.key,e,t,this.name,this.schemas?.statusDataSchema,n)}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Ce;return this.snapshot?await Ba(this.key,this.ontologyClient):null}}const cg=s.z.object({rack:ue.optional(),keys:me.array().optional(),names:s.z.string().array().optional(),types:s.z.string().array().optional(),includeStatus:s.z.boolean().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),lg=s.z.union([s.z.object({key:me,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),ug=cg,hg=s.z.union([lg,ug]),dg=r=>s.z.object({tasks:Y(xt(r))}),fg="/hardware/task/retrieve",yg="/hardware/task/create",gg="/hardware/task/delete",pg="/hardware/task/copy",mg=r=>s.z.object({tasks:La(r).array()}),wg=r=>s.z.object({tasks:xt(r).array()}),bg=s.z.object({keys:me.array()}),Tg=s.z.object({}),vg=s.z.object({key:me,name:s.z.string(),snapshot:s.z.boolean()}),Eg=r=>s.z.object({task:xt(r)});let Fa=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(e,t,n,i){this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e,t){const n=!Array.isArray(e),i=mg(t),a=wg(t),o=await m(this.client,yg,{tasks:v.toArray(e)},i,a),c=this.sugar(o.tasks,t);return n?c[0]:c}async delete(e){await m(this.client,gg,{keys:v.toArray(e)},bg,Tg)}async retrieve({schemas:e,...t}){const n="key"in t||"name"in t,a=(await m(this.client,fg,t,hg,dg(e))).tasks,o=this.sugar(a,e);return et("Task",t,o,n),n?o[0]:o}async copy(e,t,n){const i=Eg(),a=await m(this.client,pg,{key:e,name:t,snapshot:n},vg,i);return this.sugar(a.task)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw Ce;return await Ba(e,this.ontologyClient)}sugar(e,t){const n=!Array.isArray(e),i=v.toArray(e).map(({key:a,name:o,type:c,config:u,status:l,internal:h,snapshot:p})=>new qa({key:a,name:o,type:c,config:u,internal:h,snapshot:p,status:l},t,this.frameClient,this.ontologyClient,this.rangeClient));return n?i[0]:i}async executeCommand(e,t,n){if(Array.isArray(e))return await An(this.frameClient,e);if(t==null)throw new Error("Type is required");return await Ya(this.frameClient,e,t,n)}async executeCommandSync(e,t,n,i,a,o=s.z.unknown()){if(Array.isArray(e)){const u=async()=>(await this.retrieve({keys:e.map(h=>h.task)})).map(h=>h.name);return await Wa(this.frameClient,e,t,o,u)}const c=async()=>(await this.retrieve({key:e})).name;return await Va(this.frameClient,e,t,n,a??c,o,i)}};const Sn=r=>({type:"task",key:r}),Ya=async(r,e,t,n)=>(await An(r,[{args:n,task:e,type:t}]))[0],An=async(r,e)=>{if(r==null)throw Ce;const t=await r.openWriter(sn),n=e.map(i=>({...i,key:bu.create()}));return await t.write(sn,n),await t.close(),n.map(i=>i.key)},Va=async(r,e,t,n,i,a,o)=>(await Wa(r,[{args:o,task:e,type:t}],n,a,i))[0],Wa=async(r,e,t,n,i)=>{if(r==null)throw Ce;const a=await r.openStreamer(nn),o=await An(r,e),c=new E(t);let u=[],l;const h=new Promise((p,f)=>{l=setTimeout(()=>{(async()=>{const O=e.map(N=>N.task);f(await Og("command",i,c,O))})()},c.milliseconds)});try{for(;;){const p=await Promise.race([a.read(),h]),f=zn(n).parse(p.at(-1)[nn]);if(o.includes(f.key)&&(u=[...u.filter(O=>O.key!==f.key),f],u.length===o.length))return u}}finally{clearTimeout(l),a.close()}},Og=async(r,e,t,n)=>{const i=Al.capitalize(r),a=t.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=v.toArray(await e());const c=Kr.naturalLanguageJoin(o);return new Error(`${i} command to ${c} timed out after ${a}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${i} command to task with key ${Kr.naturalLanguageJoin(n)} timed out after ${a}`)}},Ng=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:sn,Client:Fa,DELETE_CHANNEL_NAME:og,SET_CHANNEL_NAME:ag,STATUS_CHANNEL_NAME:nn,Task:qa,commandZ:sg,keyZ:me,newZ:La,ontologyID:Sn,rackKey:ig,statusDetailsZ:Za,statusZ:zn,taskZ:xt},Symbol.toStringTag,{value:"Module"})),Ie=s.z.uuid(),Rt=s.z.object({key:Ie,name:s.z.string().min(1),color:s.z.string()}),zg="labeled_by",Sg="sy_label_set",Ag="sy_label_delete",Ha=Rt.extend({key:Ie.optional()}),Ig=s.object({labels:Ha.array()}),$g=s.object({labels:Rt.array()}),kg=s.object({keys:Ie.array()}),_a=s.object({id:R,labels:Ie.array(),replace:s.boolean().optional()}),Cg=_a.omit({replace:!0}),$r=s.object({}),xg="/label/create",Rg="/label/delete",Mg="/label/set",jg="/label/remove",Ug="/label/retrieve",Dg=s.object({keys:Ie.array().optional(),for:R.optional(),searchTerm:s.string().optional(),offset:s.number().optional(),limit:s.number().optional()}),Pg=s.object({key:Ie}).transform(({key:r})=>({keys:[r]})),Zg=s.union([Pg,Dg]),Lg=s.object({labels:Y(Rt)});let Ga=class{type="label";client;constructor(e){this.client=e}async retrieve(e){const t="key"in e,n=await m(this.client,Ug,e,Zg,Lg);return et("Label",e,n.labels,t),t?n.labels[0]:n.labels}async label(e,t,n={}){await m(this.client,Mg,{id:e,labels:t,replace:n.replace},_a,$r)}async remove(e,t){await m(this.client,jg,{id:e,labels:t},Cg,$r)}async create(e){const t=Array.isArray(e),n=await m(this.client,xg,{labels:v.toArray(e)},Ig,$g);return t?n.labels:n.labels[0]}async delete(e){await m(this.client,Rg,{keys:v.toArray(e)},kg,$r)}};const Bg=r=>({type:"label",key:r}),qg=Object.freeze(Object.defineProperty({__proto__:null,Client:Ga,DELETE_CHANNEL_NAME:Ag,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:zg,SET_CHANNEL_NAME:Sg,keyZ:Ie,labelZ:Rt,newZ:Ha,ontologyID:Bg},Symbol.toStringTag,{value:"Module"})),V=s.z.uuid(),In=s.z.string().min(1),Mt=s.z.object({key:V,name:In,timeRange:M.z,color:s.z.string().optional(),labels:Rt.array().or(s.z.null().transform(()=>{})).optional(),get parent(){return Mt.optional().nullable().transform(r=>r===void 0?null:r)}}),Ka=Mt.omit({parent:!0,labels:!0}).partial({key:!0}),Fg="sy_range_alias_set",Yg="sy_range_alias_delete",Vg=s.z.object({range:V,aliases:s.z.string().array()}),Wg=s.z.object({aliases:s.z.record(s.z.string(),x)}),Hg=s.z.object({range:V,aliases:s.z.record(x,s.z.string())}),_g=s.z.unknown(),Gg=s.z.object({range:V,channels:x.array()}),Kg=s.z.unknown(),Jg=s.z.object({range:V}),Xg=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),Qg=s.z.object({range:V,channels:x.array()}),ep=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())});class J{static SET_ENDPOINT="/range/alias/set";static RESOLVE_ENDPOINT="/range/alias/resolve";static LIST_ENDPOINT="/range/alias/list";static RETRIEVE_ENDPOINT="/range/alias/retrieve";static DELETE_ENDPOINT="/range/alias/delete";frameClient;cache=new Map;client;rangeKey;constructor(e,t,n){this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",i={};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?i[o]=c:t.push(o)});if(t.length===0)return i;const a=await m(this.client,J.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Vg,Wg);return Object.entries(a.aliases).forEach(([o,c])=>this.cache.set(o,c)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await m(this.client,J.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Hg,_g)}async list(){return(await m(this.client,J.LIST_ENDPOINT,{range:this.rangeKey},Jg,Xg)).aliases}async retrieve(e){const t=typeof e=="number",n=await m(this.client,J.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:v.toArray(e)},Qg,ep);return t?n.aliases[e]:n.aliases}async delete(e){await m(this.client,J.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Gg,Kg)}}const tp=s.z.object({alias:s.z.string().optional(),channel:x,range:V}),Ja="---",rp=r=>`${r.range}${Ja}${r.channel}`,np=r=>{const[e,t]=r.split(Ja);return{range:e,channel:Number(t)}},sp="sy_range_kv_set",ip="sy_range_kv_delete",$n=s.z.object({range:V,key:s.z.string(),value:s.z.string()}),ap=({range:r,key:e})=>`${r}<--->${e}`,op=s.z.object({range:V,keys:s.z.string().array()}),cp=s.z.object({pairs:Y($n)}),lp=s.z.object({range:V,pairs:$n.array()}),up=s.z.object({range:V,keys:s.z.string().array()});class Me{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,t){this.rangeKey=e,this.client=t}async get(e){const t=await m(this.client,Me.GET_ENDPOINT,{range:this.rangeKey,keys:v.toArray(e)},op,cp);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;Ks(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await m(this.client,Me.SET_ENDPOINT,{range:this.rangeKey,pairs:n},lp,s.z.unknown())}async delete(e){await m(this.client,Me.DELETE_ENDPOINT,{range:this.rangeKey,keys:v.toArray(e)},up,s.z.unknown())}}const hp="sy_range_set",dp="sy_range_delete";class Xa{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:t=M.ZERO,key:n,color:i,parent:a,labels:o},{frameClient:c,kv:u,aliaser:l,channels:h,labelClient:p,ontologyClient:f,rangeClient:O}){this.key=n,this.name=e,this.timeRange=t,this.parent=a,this.labels=o,this.frameClient=c,this.color=i,this.kv=u,this.aliaser=l,this.channels=h,this.labelClient=p,this.ontologyClient=f,this.rangeClient=O}get ontologyID(){return qe(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new Se(`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 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 retrieveLabels(){return await this.labelClient.retrieve({for:qe(this.key)})}async addLabel(...e){await this.labelClient.label(qe(this.key),e)}async removeLabel(...e){await this.labelClient.remove(qe(this.key),e)}static sort(e,t){return M.sort(e.timeRange,t.timeRange)}}const fp=s.z.object({keys:V.array().optional(),names:s.z.array(s.z.string()).optional(),searchTerm:s.z.string().optional(),overlapsWith:M.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional(),hasLabels:Ie.array().optional(),includeLabels:s.z.boolean().optional(),includeParent:s.z.boolean().optional()}),yp=fp.or(V.array().transform(r=>({keys:r}))).or(V.transform(r=>({keys:[r]}))).or(s.z.string().transform(r=>({names:[r]}))).or(s.z.string().array().transform(r=>({names:r}))).or(M.z.transform(r=>({overlapsWith:r}))),gp="/range/retrieve",pp=s.z.object({ranges:Y(Mt)});let Qa=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(e,t,n,i,a,o){this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=o}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(v.toArray(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(v.toArray(e))}async retrieve(e){const t=typeof e=="string",{ranges:n}=await m(this.unaryClient,gp,e,yp,pp);return et("Range",e,n,t),t?this.sugarMany(n)[0]:this.sugarMany(n)}getKV(e){return new Me(e,this.unaryClient)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents(qe(e));if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOntologyResource(e){return this.sugarOne(eo(e))}async retrieveAlias(e,t){return await new J(e,this.frameClient,this.unaryClient).retrieve(t)}async retrieveAliases(e,t){return await new J(e,this.frameClient,this.unaryClient).retrieve(t)}async listAliases(e){return await new J(e,this.frameClient,this.unaryClient).list()}async setAlias(e,t,n){await new J(e,this.frameClient,this.unaryClient).set({[t]:n})}sugarOne(e){return new Xa(e,{frameClient:this.frameClient,kv:new Me(e.key,this.unaryClient),aliaser:new J(e.key,this.frameClient,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(e){return e.map(t=>this.sugarOne(t))}resourceToRange(e){return this.sugarOne({key:e.id.key,name:e.data?.name,timeRange:new M(e.data?.timeRange),color:e.data?.color,labels:[],parent:null})}};const qe=r=>({type:"range",key:r}),mp=r=>({type:"range-alias",key:r}),eo=({data:r,id:{key:e},name:t})=>{const n=M.z.parse(r?.timeRange);return{key:e,name:t,timeRange:n,color:typeof r?.color=="string"?r.color:void 0,labels:[],parent:null}},wp=s.z.object({ranges:Mt.array()}),bp=s.z.object({parent:R.optional(),ranges:Ka.array()}),Tp=s.z.object({keys:V.array()}),vp=s.z.object({}),Ep=s.z.object({key:V,name:In}),Op=s.z.object({}),Np="/range/create",zp="/range/delete",Sp="/range/rename";class to{client;constructor(e){this.client=e}async rename(e,t){await m(this.client,Sp,{key:e,name:t},Ep,Op)}async create(e,t){return(await m(this.client,Np,{ranges:e,...t},bp,wp)).ranges}async delete(e){await m(this.client,zp,{keys:e},Tp,vp)}}const Ap=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:J,Client:Qa,DELETE_ALIAS_CHANNEL_NAME:Yg,DELETE_CHANNEL_NAME:dp,KV:Me,KV_DELETE_CHANNEL:ip,KV_SET_CHANNEL:sp,Range:Xa,SET_ALIAS_CHANNEL_NAME:Fg,SET_CHANNEL_NAME:hp,Writer:to,aliasKey:rp,aliasOntologyID:mp,aliasZ:tp,convertOntologyResourceToPayload:eo,decodeDeleteAliasChange:np,keyZ:V,kvPairKey:ap,kvPairZ:$n,nameZ:In,newZ:Ka,ontologyID:qe,payloadZ:Mt},Symbol.toStringTag,{value:"Module"})),Ip="/api/v1/";class $p{url;unary;stream;secure;constructor(e,t={},n=!1){this.secure=n,this.url=e.child(Ip);const i=new je.JSONCodec;this.unary=fl(new dl(this.url,i,this.secure),t),this.stream=new wl(this.url,i,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const rt=s.z.uuid(),yr=s.z.object({key:rt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe))}),ro=yr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),he=s.z.uuid(),gr=s.z.object({key:he,name:s.z.string(),layout:ge.unknownZ.or(s.z.string().transform(pe))}),no=gr.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),so=gr.omit({layout:!0}).extend({layout:s.z.string().transform(pe)}),kp="/workspace/lineplot/retrieve",Cp="/workspace/lineplot/create",xp="/workspace/lineplot/rename",Rp="/workspace/lineplot/set-data",Mp="/workspace/lineplot/delete",jp=s.z.object({keys:rt.array()}),Up=s.z.object({workspace:he,linePlots:ro.array()}),Dp=s.z.object({key:rt,name:s.z.string()}),Pp=s.z.object({key:rt,data:s.z.string()}),Zp=s.z.object({keys:rt.array()}),Lp=s.z.object({linePlots:Y(yr)}),Bp=s.z.object({linePlots:yr.array()}),kr=s.z.object({});let io=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await m(this.client,Cp,{workspace:e,linePlots:v.toArray(t)},Up,Bp);return n?i.linePlots:i.linePlots[0]}async rename(e,t){await m(this.client,xp,{key:e,name:t},Dp,kr)}async setData(e,t){await m(this.client,Rp,{key:e,data:JSON.stringify(t)},Pp,kr)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,kp,{keys:v.toArray(e)},jp,Lp);return t?n.linePlots:n.linePlots[0]}async delete(e){await m(this.client,Mp,{keys:v.toArray(e)},Zp,kr)}};const qp=r=>({type:"lineplot",key:r}),Fp=Object.freeze(Object.defineProperty({__proto__:null,Client:io,keyZ:rt,linePlotZ:yr,newZ:ro,ontologyID:qp},Symbol.toStringTag,{value:"Module"})),nt=s.z.uuid(),pr=s.z.object({key:nt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe))}),ao=pr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Yp="/workspace/log/retrieve",Vp="/workspace/log/create",Wp="/workspace/log/rename",Hp="/workspace/log/set-data",_p="/workspace/log/delete",Gp=s.z.object({keys:nt.array()}),Kp=s.z.object({workspace:he,logs:ao.array()}),Jp=s.z.object({key:nt,name:s.z.string()}),Xp=s.z.object({key:nt,data:s.z.string()}),Qp=s.z.object({keys:nt.array()}),em=s.z.object({logs:pr.array()}),tm=s.z.object({logs:pr.array()}),Cr=s.z.object({});let oo=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await m(this.client,Vp,{workspace:e,logs:v.toArray(t)},Kp,tm);return n?i.logs:i.logs[0]}async rename(e,t){await m(this.client,Wp,{key:e,name:t},Jp,Cr)}async setData(e,t){await m(this.client,Hp,{key:e,data:JSON.stringify(t)},Xp,Cr)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,Yp,{keys:v.toArray(e)},Gp,em);return t?n.logs:n.logs[0]}async delete(e){await m(this.client,_p,{keys:v.toArray(e)},Qp,Cr)}};const rm=r=>({type:"log",key:r}),nm=Object.freeze(Object.defineProperty({__proto__:null,Client:oo,keyZ:nt,logZ:pr,newZ:ao,ontologyID:rm},Symbol.toStringTag,{value:"Module"})),De=s.z.uuid(),mr=s.z.object({key:De,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe)),snapshot:s.z.boolean()}),co=mr.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),kn=mr.extend({data:s.z.string().transform(pe)}),sm="/workspace/schematic/retrieve",im="/workspace/schematic/create",am="/workspace/schematic/rename",om="/workspace/schematic/set-data",cm="/workspace/schematic/delete",lm="/workspace/schematic/copy",um=s.z.object({keys:De.array()}),hm=s.z.object({workspace:he,schematics:co.array()}),dm=s.z.object({key:De,name:s.z.string()}),fm=s.z.object({key:De,data:s.z.string()}),ym=s.z.object({keys:De.array()}),gm=s.z.object({key:De,name:s.z.string(),snapshot:s.z.boolean()}),pm=s.z.object({schematics:Y(kn)}),mm=s.z.object({schematics:kn.array()}),wm=s.z.object({schematic:mr}),xr=s.z.object({});let lo=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await m(this.client,im,{workspace:e,schematics:v.toArray(t)},hm,mm);return n?i.schematics:i.schematics[0]}async rename(e,t){await m(this.client,am,{key:e,name:t},dm,xr)}async setData(e,t){await m(this.client,om,{key:e,data:JSON.stringify(t)},fm,xr)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,sm,{keys:v.toArray(e)},um,pm);return t?n.schematics:n.schematics[0]}async delete(e){await m(this.client,cm,{keys:v.toArray(e)},ym,xr)}async copy(e,t,n){return(await m(this.client,lm,{key:e,name:t,snapshot:n},gm,wm)).schematic}};const bm=r=>({type:"schematic",key:r}),Tm=Object.freeze(Object.defineProperty({__proto__:null,Client:lo,keyZ:De,newZ:co,ontologyID:bm,remoteZ:kn,schematicZ:mr},Symbol.toStringTag,{value:"Module"})),st=s.z.uuid(),Cn=s.z.object({key:st,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(pe))}),uo=Cn.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),xn=Cn.extend({data:s.z.string().transform(pe)}),vm="/workspace/table/retrieve",Em="/workspace/table/create",Om="/workspace/table/rename",Nm="/workspace/table/set-data",zm="/workspace/table/delete",Sm=s.z.object({keys:st.array()}),Am=s.z.object({workspace:he,tables:uo.array()}),Im=s.z.object({key:st,name:s.z.string()}),$m=s.z.object({key:st,data:s.z.string()}),km=s.z.object({keys:st.array()}),Cm=s.z.object({tables:xn.array()}),xm=s.z.object({tables:xn.array()}),Rr=s.z.object({});let ho=class{client;constructor(e){this.client=e}async create(e,t){const n=Array.isArray(t),i=await m(this.client,Em,{workspace:e,tables:v.toArray(t)},Am,xm);return n?i.tables:i.tables[0]}async rename(e,t){await m(this.client,Om,{key:e,name:t},Im,Rr)}async setData(e,t){await m(this.client,Nm,{key:e,data:JSON.stringify(t)},$m,Rr)}async retrieve(e){const t=Array.isArray(e),n=await m(this.client,vm,{keys:v.toArray(e)},Sm,Cm);return t?n.tables:n.tables[0]}async delete(e){await m(this.client,zm,{keys:v.toArray(e)},km,Rr)}};const Rm=r=>({type:"table",key:r}),Mm=Object.freeze(Object.defineProperty({__proto__:null,Client:ho,keyZ:st,newZ:uo,ontologyID:Rm,remoteZ:xn,tableZ:Cn},Symbol.toStringTag,{value:"Module"})),Ts="/workspace/retrieve",jm="/workspace/create",Um="/workspace/rename",Dm="/workspace/set-layout",Pm="/workspace/delete",vs=s.z.object({keys:he.array().optional(),searchTerm:s.z.string().optional(),author:Ae.optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Zm=s.z.object({workspaces:no.array()}),Lm=s.z.object({key:he,name:s.z.string()}),Bm=s.z.object({key:he,layout:s.z.string()}),qm=s.z.object({keys:he.array()}),Es=s.z.object({workspaces:Y(gr)}),Fm=s.z.object({workspaces:so.array()}),Mr=s.z.object({}),Ym="sy_workspace_set",Vm="sy_workspace_delete";class fo{type="workspace";schematic;linePlot;log;table;client;constructor(e){this.client=e,this.schematic=new lo(e),this.linePlot=new io(e),this.log=new oo(e),this.table=new ho(e)}async create(e){const t=Array.isArray(e),n=await m(this.client,jm,{workspaces:v.toArray(e)},Zm,Fm);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await m(this.client,Um,{key:e,name:t},Lm,Mr)}async setLayout(e,t){await m(this.client,Dm,{key:e,layout:JSON.stringify(t)},Bm,Mr)}async retrieve(e){let t;const n=typeof e!="string";typeof e=="string"||Array.isArray(e)?t={keys:v.toArray(e)}:t=e;const i=await m(this.client,Ts,t,vs,Es);return n?i.workspaces:i.workspaces[0]}async retrieveByAuthor(e){return(await m(this.client,Ts,{author:e},vs,Es)).workspaces}async delete(e){await m(this.client,Pm,{keys:v.toArray(e)},qm,Mr)}}const Wm=r=>({type:"workspace",key:r}),Hm=Object.freeze(Object.defineProperty({__proto__:null,Client:fo,DELETE_CHANNEL_NAME:Vm,SET_CHANNEL_NAME:Ym,keyZ:he,newZ:no,ontologyID:Wm,remoteZ:so,workspaceZ:gr},Symbol.toStringTag,{value:"Module"})),yo=s.z.object({host:s.z.string({error:"Host is required"}).min(1,"Host is required"),port:s.z.number({error:"Port is required"}).or(s.z.string({error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:E.z.default(E.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:zi.breakerConfigZ.optional()});class go extends Sa{createdAt;props;ranges;channels;auth;user;access;connectivity;ontology;workspaces;labels;hardware;control;static connectivity=bt;transport;clientVersion="0.44.4";constructor(e){const t=yo.parse(e),{host:n,port:i,username:a,password:o,connectivityPollFrequency:c,secure:u,retry:l}=t,h=new $p(new lt({host:n,port:Number(i)}),l,u);h.use(Gh);let p;a!=null&&o!=null&&(p=new Ff(h.unary,{username:a,password:o}),h.use(p.middleware()));const f=new Tn(new kt(h.unary)),O=new la(h.unary,f);super(h.stream,h.unary,f),this.createdAt=d.now(),this.props=t,this.auth=p,this.transport=h,this.channels=new aa(this,f,h.unary,O),this.connectivity=new bt(h.unary,c,this.clientVersion,t.name),this.control=new $a(this),this.ontology=new Ji(h.unary,this);const N=new to(this.transport.unary);this.labels=new Ga(this.transport.unary),this.ranges=new Qa(this,N,this.transport.unary,f,this.labels,this.ontology),this.access=new ea(this.transport.unary),this.user=new ha(this.transport.unary),this.workspaces=new fo(this.transport.unary);const k=new Ua(this.transport.unary),Z=new Fa(this.transport.unary,this,this.ontology,this.ranges),C=new Da(this.transport.unary,Z);this.hardware=new ka(Z,C,k)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}const po={host:"localhost",port:9090,username:"synnax",password:"seldon",retry:{maxRetries:4,baseInterval:E.seconds(1),scale:1.5}},_m=r=>new go({...po,...r});exports.AuthError=yt;exports.Channel=Kt;exports.ContiguityError=Wh;exports.DataType=S;exports.Density=W;exports.DisconnectedError=Vh;exports.Frame=P;exports.MultiSeries=Ei;exports.MultipleFoundError=pt;exports.NotFoundError=gt;exports.QueryError=Se;exports.Rate=_;exports.RouteError=Qr;exports.Series=q;exports.Synnax=go;exports.TEST_CLIENT_PROPS=po;exports.TimeRange=M;exports.TimeSpan=E;exports.TimeStamp=d;exports.UnexpectedError=Ve;exports.ValidationError=D;exports.access=qd;exports.channel=yf;exports.connection=Vf;exports.control=Oy;exports.createTestClient=_m;exports.device=Ly;exports.framer=my;exports.group=fd;exports.hardware=Ny;exports.isCalculated=wt;exports.label=qg;exports.linePlot=Fp;exports.log=nm;exports.ontology=Sd;exports.policy=Bd;exports.rack=ng;exports.ranger=Ap;exports.schematic=Tm;exports.synnaxPropsZ=yo;exports.table=Mm;exports.task=Ng;exports.user=jf;exports.workspace=Hm;
|