@synnaxlabs/client 0.33.0 → 0.34.0
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/auth/auth.d.ts.map +1 -1
- package/dist/channel/writer.d.ts.map +1 -1
- package/dist/client.cjs +26 -26
- package/dist/client.js +235 -190
- package/dist/control/client.d.ts.map +1 -1
- package/dist/control/state.d.ts.map +1 -1
- package/dist/errors.d.ts +3 -3
- package/dist/errors.d.ts.map +1 -1
- package/dist/framer/adapter.d.ts.map +1 -1
- package/dist/framer/client.d.ts.map +1 -1
- package/dist/framer/deleter.d.ts.map +1 -1
- package/dist/framer/frame.d.ts.map +1 -1
- package/dist/framer/writer.d.ts.map +1 -1
- package/dist/hardware/device/client.d.ts.map +1 -1
- package/dist/hardware/device/payload.d.ts.map +1 -1
- package/dist/hardware/rack/client.d.ts.map +1 -1
- package/dist/hardware/task/client.d.ts +1 -1
- package/dist/hardware/task/client.d.ts.map +1 -1
- package/dist/hardware/task/ni/types.d.ts.map +1 -1
- package/dist/hardware/task/payload.d.ts.map +1 -1
- package/dist/label/client.d.ts.map +1 -1
- package/dist/ontology/client.d.ts.map +1 -1
- package/dist/ontology/payload.d.ts.map +1 -1
- package/dist/ranger/alias.d.ts.map +1 -1
- package/dist/ranger/client.d.ts.map +1 -1
- package/dist/ranger/kv.d.ts.map +1 -1
- package/dist/ranger/payload.d.ts.map +1 -1
- package/dist/util/telem.d.ts.map +1 -1
- package/dist/workspace/lineplot/payload.d.ts.map +1 -1
- package/dist/workspace/log/payload.d.ts.map +1 -1
- package/dist/workspace/payload.d.ts.map +1 -1
- package/dist/workspace/schematic/payload.d.ts.map +1 -1
- package/eslint.config.js +1 -1
- package/package.json +11 -11
- package/src/access/policy/policy.spec.ts +2 -4
- package/src/auth/auth.spec.ts +1 -1
- package/src/auth/auth.ts +17 -18
- package/src/channel/writer.ts +2 -2
- package/src/connection/checker.ts +1 -1
- package/src/control/client.ts +1 -1
- package/src/control/state.ts +1 -1
- package/src/errors.spec.ts +1 -1
- package/src/errors.ts +14 -15
- package/src/framer/adapter.ts +5 -6
- package/src/framer/client.ts +9 -4
- package/src/framer/deleter.ts +1 -1
- package/src/framer/frame.ts +9 -11
- package/src/framer/iterator.spec.ts +2 -3
- package/src/framer/writer.ts +1 -1
- package/src/hardware/device/client.ts +3 -3
- package/src/hardware/device/payload.ts +1 -1
- package/src/hardware/rack/client.ts +3 -3
- package/src/hardware/task/client.ts +13 -11
- package/src/hardware/task/ni/types.ts +1 -1
- package/src/hardware/task/payload.ts +1 -1
- package/src/hardware/task/task.spec.ts +1 -1
- package/src/label/client.ts +1 -1
- package/src/ontology/client.ts +1 -3
- package/src/ontology/group/payload.ts +2 -2
- package/src/ontology/payload.ts +1 -1
- package/src/ranger/alias.ts +2 -3
- package/src/ranger/client.ts +7 -9
- package/src/ranger/kv.ts +2 -2
- package/src/ranger/payload.ts +2 -2
- package/src/ranger/ranger.spec.ts +2 -2
- package/src/user/user.spec.ts +1 -2
- package/src/util/telem.ts +1 -3
- package/src/workspace/lineplot/payload.ts +1 -1
- package/src/workspace/log/payload.ts +1 -1
- package/src/workspace/payload.ts +1 -1
- package/src/workspace/schematic/payload.ts +1 -1
package/dist/client.cjs
CHANGED
|
@@ -1,39 +1,39 @@
|
|
|
1
|
-
"use strict";var _a=Object.defineProperty;var Ya=(r,e,t)=>e in r?_a(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>Ya(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),b=r=>Array.isArray(r)?r:[r];var qa=Object.defineProperty,Wa=(r,e,t)=>e in r?qa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>Wa(r,typeof e!="symbol"?e+"":e,t);const Ga=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)},xs=r=>{const e=(t,n=rn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!jr(t))return t;n=Ja(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(jr(l)?Mn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&jn(l)&&(l=[...l].map(h=>{let y=h;return jr(h)?Mn(y,n.keepTypesOnRecursion)||(y=e(h,n)):jn(h)&&(y=e({key:h},n).key),y}))),i[u]=l}),i};return e},Cs=xs(Ga),Va=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Fa=xs(Va),rn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Ja=(r=rn)=>(r.recursive==null?r=rn:r.recursiveInArray
|
|
1
|
+
"use strict";var _a=Object.defineProperty;var Ya=(r,e,t)=>e in r?_a(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>Ya(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),b=r=>Array.isArray(r)?r:[r];var qa=Object.defineProperty,Wa=(r,e,t)=>e in r?qa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>Wa(r,typeof e!="symbol"?e+"":e,t);const Ga=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)},xs=r=>{const e=(t,n=rn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!jr(t))return t;n=Ja(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(jr(l)?Mn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&jn(l)&&(l=[...l].map(h=>{let y=h;return jr(h)?Mn(y,n.keepTypesOnRecursion)||(y=e(h,n)):jn(h)&&(y=e({key:h},n).key),y}))),i[u]=l}),i};return e},Cs=xs(Ga),Va=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Fa=xs(Va),rn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Ja=(r=rn)=>(r.recursive==null?r=rn:r.recursiveInArray??(r.recursiveInArray=!1),r),jn=r=>r!=null&&Array.isArray(r),jr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Mn=(r,e)=>(e||[]).some(t=>r instanceof t),Ps=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Ka=Object.defineProperty,Ha=(r,e,t)=>e in r?Ka(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Nt=(r,e,t)=>Ha(r,typeof e!="symbol"?e+"":e,t);let Xa=class{constructor(){Nt(this,"contentType","application/json"),Nt(this,"decoder"),Nt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r)).buffer}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Cs(t);return e!=null?e.parse(n):n}encodeString(r){const e=Fa(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):Ps(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},Qa=class{constructor(){Nt(this,"contentType","text/csv")}encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e).buffer}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!Ps(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(n=>{const i=e.map(a=>JSON.stringify(n[a]??""));t.push(i.join(","))}),t.join(`
|
|
2
2
|
`)}decodeString(r,e){const[t,...n]=r.trim().split(`
|
|
3
|
-
`).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const i=t.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),n.forEach(o=>{const l=o.split(",").map(u=>u.trim());i.forEach((u,h)=>{const y=this.parseValue(l[h]);y!=null&&a[u].push(y)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},eo=class{constructor(){Nt(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r).buffer}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const Qt=new Xa;new Qa;new eo;const wr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ds=s.z.object({width:s.z.number(),height:s.z.number()}),to=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),ro=["width","height"];s.z.enum(ro);const no=["start","center","end"],so=["signedWidth","signedHeight"];s.z.enum(so);const hr=s.z.object({x:s.z.number(),y:s.z.number()}),io=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),ao=["x","y"],js=s.z.enum(ao),Ms=["top","right","bottom","left"];s.z.enum(Ms);const oo=["left","right"],Bs=s.z.enum(oo),co=["top","bottom"],Us=s.z.enum(co),Zs=["center"],Bn=s.z.enum(Zs),lo=[...Ms,...Zs],Ls=s.z.enum(lo);s.z.enum(no);const uo=["first","last"];s.z.enum(uo);const ho=s.z.object({lower:s.z.number(),upper:s.z.number()}),yo=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([ho,wr]);s.z.union([yo,wr]);s.z.union([js,Ls]);s.z.union([js,Ls,s.z.instanceof(String)]);const fo=r=>typeof r=="bigint"||r instanceof BigInt,Be=(r,e)=>fo(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),xe=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Un(r);return Un(t)},Un=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Zn=(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:Bs.or(Bn),y:Us.or(Bn)});const go=s.z.object({x:Bs,y:Us}),po=Object.freeze({x:"left",y:"top"}),mo=(r,e)=>r.x===e.x&&r.y===e.y,Ln=s.z.union([s.z.number(),hr,wr,Ds,to,io]),wo=(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}},_n=Object.freeze({x:0,y:0}),Jt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Jt,left:Jt,width:Jt,height:Jt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:hr,two:hr,root:go});const vn=(r,e,t=0,n=0,i)=>{const a={one:{..._n},two:{..._n},root:i??po};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))},Mr=r=>{const e=vn(r);return{lower:e.one.x,upper:e.two.x}},Br=r=>{const e=vn(r);return{lower:e.one.y,upper:e.two.y}},bo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var vo=Object.defineProperty,To=(r,e,t)=>e in r?vo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,fe=(r,e,t)=>To(r,typeof e!="symbol"?e+"":e,t);const Oo=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Ln,scale:Ln});const zo=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Eo=r=>(e,t,n,i)=>[e,i?n/r:n*r],So=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},No=r=>(e,t,n)=>[r,n],Io=()=>(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)]},ko=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Oo(n,i,a),[e,n]},nn=class ft{constructor(){fe(this,"ops",[]),fe(this,"currBounds",null),fe(this,"currType",null),fe(this,"reversed",!1),this.ops=[]}static translate(e){return new ft().translate(e)}static magnify(e){return new ft().magnify(e)}static scale(e,t){return new ft().scale(e,t)}translate(e){const t=this.new(),n=zo(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Eo(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=xe(e,t),i=this.new(),a=So(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=xe(e,t),i=this.new(),a=ko(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=xe(e,t),i=this.new(),a=No(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Io();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 ft;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,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>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}};fe(nn,"IDENTITY",new nn);let Yn=nn;const qn=class de{constructor(e=new Yn,t=new Yn,n=null){fe(this,"x"),fe(this,"y"),fe(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new de().translate(e,t)}static translateX(e){return new de().translateX(e)}static translateY(e){return new de().translateY(e)}static clamp(e){return new de().clamp(e)}static magnify(e){return new de().magnify(e)}static scale(e){return new de().scale(e)}static reBound(e){return new de().reBound(e)}translate(e,t){const n=wo(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(bo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!mo(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(Mr(e)),t.y=t.y.scale(Br(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(Mr(e)),t.y=this.y.reBound(Br(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Mr(e)),t.y=this.y.clamp(Br(e)),t}copy(){const e=new de;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)}}box(e){return vn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};fe(qn,"IDENTITY",new qn);const Ao=r=>r!=null&&typeof r=="object"&&"toString"in r,$o=(r,e=!1)=>{const t=Ao(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?Ro(n):n},Ro=r=>(e,t)=>r(t,e),xo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ds,xo,hr,wr]);const Co=s.z.bigint().or(s.z.string().transform(BigInt));var Po=Object.defineProperty,Do=(r,e,t)=>e in r?Po(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>Do(r,typeof e!="symbol"?e+"":e,t);let jo=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Mo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Bo=jo(Mo,11),Uo=s.z.enum(["static","dynamic"]),_s=(r,e)=>{const t=new j(e);if(![L.DAY,L.HOUR,L.MINUTE,L.SECOND,L.MILLISECOND,L.MICROSECOND,L.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 j?new j(n):new L(n)},A=class T{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new T(BigInt(i.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=T.hours(parseInt(n??"00",10)).add(T.minutes(parseInt(i??"00",10))).add(T.seconds(parseInt(o??"00",10))).add(T.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(T.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new T(BigInt(n.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new L(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new Tn(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return _s(this,e)}get isToday(){return this.truncate(L.DAY).equals(T.now().truncate(L.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const n of e){const i=new T(n);i.after(t)&&(t=i)}return t}static min(...e){let t=T.MAX;for(const n of e){const i=new T(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new T(e)}static microseconds(e){return T.nanoseconds(e*1e3)}static milliseconds(e){return T.microseconds(e*1e3)}static seconds(e){return T.milliseconds(e*1e3)}static minutes(e){return T.seconds(e*60)}static hours(e){return T.minutes(e*60)}static days(e){return T.hours(e*24)}};m(A,"NANOSECOND",A.nanoseconds(1)),m(A,"MICROSECOND",A.microseconds(1)),m(A,"MILLISECOND",A.milliseconds(1)),m(A,"SECOND",A.seconds(1)),m(A,"MINUTE",A.minutes(1)),m(A,"HOUR",A.hours(1)),m(A,"DAY",A.days(1)),m(A,"MAX",new A((1n<<63n)-1n)),m(A,"MIN",new A(0)),m(A,"ZERO",new A(0)),m(A,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new A(r.value)),s.z.string().transform(r=>new A(BigInt(r))),s.z.instanceof(Number).transform(r=>new A(r)),s.z.number().transform(r=>new A(r)),s.z.instanceof(A)]));let j=A;const $=class z{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof z?e:e instanceof Wn?e.period:e instanceof j?new z(e):["number","bigint"].includes(typeof e)?z.seconds(e):new z(e)}static fromMilliseconds(e){return e instanceof z?e:e instanceof Wn?e.period:e instanceof j?new z(e):["number","bigint"].includes(typeof e)?z.milliseconds(e):new z(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new z(e).valueOf()}greaterThan(e){return this.valueOf()>new z(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new z(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new z(e).valueOf()}remainder(e){return _s(this,e)}truncate(e){return new z(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(z.DAY),t=this.truncate(z.HOUR),n=this.truncate(z.MINUTE),i=this.truncate(z.SECOND),a=this.truncate(z.MILLISECOND),o=this.truncate(z.MICROSECOND),l=this.truncate(z.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),P=a.sub(i),D=o.sub(a),ee=l.sub(o);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),y.isZero||(B+=`${y.minutes}m `),d.isZero||(B+=`${d.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),ee.isZero||(B+=`${ee.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(z.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new z(e).valueOf()}add(e){return new z(this.valueOf()+new z(e).valueOf())}sub(e){return new z(this.valueOf()-new z(e).valueOf())}static nanoseconds(e=1){return new z(e)}static microseconds(e=1){return z.nanoseconds(Be(e,1e3))}static milliseconds(e=1){return z.microseconds(Be(e,1e3))}static seconds(e=1){return z.milliseconds(Be(e,1e3))}static minutes(e=1){return z.seconds(Be(e,60))}static hours(e){return z.minutes(Be(e,60))}static days(e){return z.hours(Be(e,24))}};m($,"NANOSECOND",$.nanoseconds(1)),m($,"MICROSECOND",$.microseconds(1)),m($,"MILLISECOND",$.milliseconds(1)),m($,"SECOND",$.seconds(1)),m($,"MINUTE",$.minutes(1)),m($,"HOUR",$.hours(1)),m($,"DAY",$.days(1)),m($,"MAX",new $((1n<<63n)-1n)),m($,"MIN",new $(0)),m($,"ZERO",new $(0)),m($,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new $(r.value)),s.z.string().transform(r=>new $(BigInt(r))),s.z.instanceof(Number).transform(r=>new $(r)),s.z.number().transform(r=>new $(r)),s.z.instanceof($)]));let L=$;const gt=class er extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new er(e).valueOf()}get period(){return L.seconds(1/this.valueOf())}sampleCount(e){return new L(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new J(t).valueOf()}span(e){return L.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new er(e)}static khz(e){return er.hz(e*1e3)}};m(gt,"z",s.z.union([s.z.number().transform(r=>new gt(r)),s.z.instanceof(Number).transform(r=>new gt(r)),s.z.instanceof(gt)]));let Wn=gt;const Y=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new sn(e*this.valueOf())}};m(Y,"UNKNOWN",new Y(0)),m(Y,"BIT128",new Y(16)),m(Y,"BIT64",new Y(8)),m(Y,"BIT32",new Y(4)),m(Y,"BIT16",new Y(2)),m(Y,"BIT8",new Y(1)),m(Y,"z",s.z.union([s.z.number().transform(r=>new Y(r)),s.z.instanceof(Number).transform(r=>new Y(r)),s.z.instanceof(Y)]));let J=Y;const ie=class tr{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new j(e.start),this.end=new j(e.end)):(this.start=new j(e),this.end=new j(t))}get span(){return new L(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 tr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=L.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=j.max(n.start,e.start),a=j.min(n.end,e.end);return a.before(i)?!1:new L(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){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()}contains(e){return e instanceof tr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new tr(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}};m(ie,"MAX",new ie(j.MIN,j.MAX)),m(ie,"MIN",new ie(j.MAX,j.MIN)),m(ie,"ZERO",new ie(j.ZERO,j.ZERO)),m(ie,"z",s.z.union([s.z.object({start:j.z,end:j.z}).transform(r=>new ie(r.start,r.end)),s.z.instanceof(ie)]));let Tn=ie;const g=class ae extends String{constructor(e){if(e instanceof ae||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ae.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ae.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ae.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(ae.JSON)||this.equals(ae.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ae.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ae.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ae.BIG_INT_TYPES.some(e=>e.equals(this))}};m(g,"UNKNOWN",new g("unknown")),m(g,"FLOAT64",new g("float64")),m(g,"FLOAT32",new g("float32")),m(g,"INT64",new g("int64")),m(g,"INT32",new g("int32")),m(g,"INT16",new g("int16")),m(g,"INT8",new g("int8")),m(g,"UINT64",new g("uint64")),m(g,"UINT32",new g("uint32")),m(g,"UINT16",new g("uint16")),m(g,"UINT8",new g("uint8")),m(g,"BOOLEAN",g.UINT8),m(g,"TIMESTAMP",new g("timestamp")),m(g,"UUID",new g("uuid")),m(g,"STRING",new g("string")),m(g,"JSON",new g("json")),m(g,"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]])),m(g,"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]])),m(g,"DENSITIES",new Map([[g.UINT8.toString(),J.BIT8],[g.UINT16.toString(),J.BIT16],[g.UINT32.toString(),J.BIT32],[g.UINT64.toString(),J.BIT64],[g.FLOAT32.toString(),J.BIT32],[g.FLOAT64.toString(),J.BIT64],[g.INT8.toString(),J.BIT8],[g.INT16.toString(),J.BIT16],[g.INT32.toString(),J.BIT32],[g.INT64.toString(),J.BIT64],[g.TIMESTAMP.toString(),J.BIT64],[g.STRING.toString(),J.UNKNOWN],[g.JSON.toString(),J.UNKNOWN],[g.UUID.toString(),J.BIT128]])),m(g,"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]),m(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),m(g,"z",s.z.union([s.z.string().transform(r=>new g(r)),s.z.instanceof(g)]));let R=g;const G=class U extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return U.bytes(this.valueOf()+e.valueOf())}sub(e){return U.bytes(this.valueOf()-e.valueOf())}truncate(e){return new U(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return U.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/U.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/U.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/U.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/U.TERABYTE.valueOf()}toString(){const e=this.truncate(U.TERABYTE),t=this.truncate(U.GIGABYTE),n=this.truncate(U.MEGABYTE),i=this.truncate(U.KILOBYTE),a=this.truncate(U.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new U(e)}static kilobytes(e=1){return U.bytes(e.valueOf()*1e3)}static megabytes(e=1){return U.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return U.megabytes(e.valueOf()*1e3)}static terabytes(e){return U.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(G,"BYTE",new G(1)),m(G,"KILOBYTE",G.kilobytes(1)),m(G,"MEGABYTE",G.megabytes(1)),m(G,"GIGABYTE",G.gigabytes(1)),m(G,"TERABYTE",G.terabytes(1)),m(G,"ZERO",new G(0)),m(G,"z",s.z.union([s.z.number().transform(r=>new G(r)),s.z.instanceof(G)]));let sn=G;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 Ys=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof j||r instanceof L||r instanceof Date},Zo=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):mt(t,-n).valueOf(),Lo=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof qo?!0:Ys(r),ve=-1,_o=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Yo=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),an=10,pt=class oe{constructor(e){m(this,"key",""),m(this,"isSynnaxSeries",!0),m(this,"dataType"),m(this,"sampleOffset"),m(this,"gl"),m(this,"_data"),m(this,"_timeRange"),m(this,"alignment",0n),m(this,"_cachedMin"),m(this,"_cachedMax"),m(this,"writePos",ve),m(this,"_refCount",0),m(this,"_cachedLength"),m(this,"_cachedIndexes"),Lo(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=Bo()}=e,u=e.data??[];if(u instanceof oe||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;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._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=Ys(u),y=Array.isArray(u);if(t!=null)this.dataType=new R(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.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=u[0]}if(typeof d=="string")this.dataType=R.STRING;else if(typeof d=="number")this.dataType=R.FLOAT64;else if(typeof d=="bigint")this.dataType=R.INT64;else if(typeof d=="boolean")this.dataType=R.BOOLEAN;else if(d instanceof j||d instanceof Date||d instanceof j)this.dataType=R.TIMESTAMP;else if(typeof d=="object")this.dataType=R.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new R(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const P=d[0];(P instanceof j||P instanceof Date||P instanceof L)&&(d=d.map(D=>new j(D).valueOf())),this.dataType.equals(R.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(d.join(`
|
|
4
|
-
`)
|
|
5
|
-
`)):this.dataType.equals(R.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(d.map(D=>Qt.encodeString(D)).join(`
|
|
6
|
-
`)
|
|
7
|
-
`)):this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,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 R(t).Array(e),a=new oe({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(t.span(o)).valueOf());return new oe({data:a,dataType:R.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
|
|
8
|
-
`)
|
|
9
|
-
`);return new oe({data:n,dataType:R.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>Qt.encodeString(i)).join(`
|
|
10
|
-
`)
|
|
3
|
+
`).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const i=t.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),n.forEach(o=>{const l=o.split(",").map(u=>u.trim());i.forEach((u,h)=>{const y=this.parseValue(l[h]);y!=null&&a[u].push(y)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},eo=class{constructor(){Nt(this,"contentType","text/plain")}encode(r){return new TextEncoder().encode(r).buffer}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const Qt=new Xa;new Qa;new eo;const wr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ds=s.z.object({width:s.z.number(),height:s.z.number()}),to=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),ro=["width","height"];s.z.enum(ro);const no=["start","center","end"],so=["signedWidth","signedHeight"];s.z.enum(so);const hr=s.z.object({x:s.z.number(),y:s.z.number()}),io=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),ao=["x","y"],js=s.z.enum(ao),Ms=["top","right","bottom","left"];s.z.enum(Ms);const oo=["left","right"],Bs=s.z.enum(oo),co=["top","bottom"],Us=s.z.enum(co),Zs=["center"],Bn=s.z.enum(Zs),lo=[...Ms,...Zs],Ls=s.z.enum(lo);s.z.enum(no);const uo=["first","last"];s.z.enum(uo);const ho=s.z.object({lower:s.z.number(),upper:s.z.number()}),yo=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([ho,wr]);s.z.union([yo,wr]);s.z.union([js,Ls]);s.z.union([js,Ls,s.z.instanceof(String)]);const fo=r=>typeof r=="bigint"||r instanceof BigInt,Be=(r,e)=>fo(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),xe=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return Un(r);return Un(t)},Un=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Zn=(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:Bs.or(Bn),y:Us.or(Bn)});const go=s.z.object({x:Bs,y:Us}),po=Object.freeze({x:"left",y:"top"}),mo=(r,e)=>r.x===e.x&&r.y===e.y,Ln=s.z.union([s.z.number(),hr,wr,Ds,to,io]),wo=(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}},_n=Object.freeze({x:0,y:0}),Jt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Jt,left:Jt,width:Jt,height:Jt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:hr,two:hr,root:go});const vn=(r,e,t=0,n=0,i)=>{const a={one:{..._n},two:{..._n},root:i??po};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))},Mr=r=>{const e=vn(r);return{lower:e.one.x,upper:e.two.x}},Br=r=>{const e=vn(r);return{lower:e.one.y,upper:e.two.y}},bo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var vo=Object.defineProperty,To=(r,e,t)=>e in r?vo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,fe=(r,e,t)=>To(r,typeof e!="symbol"?e+"":e,t);const Oo=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Ln,scale:Ln});const zo=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Eo=r=>(e,t,n,i)=>[e,i?n/r:n*r],So=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},No=r=>(e,t,n)=>[r,n],Io=()=>(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)]},ko=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Oo(n,i,a),[e,n]},nn=class ft{constructor(){fe(this,"ops",[]),fe(this,"currBounds",null),fe(this,"currType",null),fe(this,"reversed",!1),this.ops=[]}static translate(e){return new ft().translate(e)}static magnify(e){return new ft().magnify(e)}static scale(e,t){return new ft().scale(e,t)}translate(e){const t=this.new(),n=zo(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Eo(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=xe(e,t),i=this.new(),a=So(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=xe(e,t),i=this.new(),a=ko(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=xe(e,t),i=this.new(),a=No(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Io();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 ft;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,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>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}};fe(nn,"IDENTITY",new nn);let Yn=nn;const qn=class de{constructor(e=new Yn,t=new Yn,n=null){fe(this,"x"),fe(this,"y"),fe(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new de().translate(e,t)}static translateX(e){return new de().translateX(e)}static translateY(e){return new de().translateY(e)}static clamp(e){return new de().clamp(e)}static magnify(e){return new de().magnify(e)}static scale(e){return new de().scale(e)}static reBound(e){return new de().reBound(e)}translate(e,t){const n=wo(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(bo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!mo(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(Mr(e)),t.y=t.y.scale(Br(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(Mr(e)),t.y=this.y.reBound(Br(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Mr(e)),t.y=this.y.clamp(Br(e)),t}copy(){const e=new de;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)}}box(e){return vn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};fe(qn,"IDENTITY",new qn);const $o=r=>r!=null&&typeof r=="object"&&"toString"in r,Ao=(r,e=!1)=>{const t=$o(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?Ro(n):n},Ro=r=>(e,t)=>r(t,e),xo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ds,xo,hr,wr]);const Co=s.z.bigint().or(s.z.string().transform(BigInt));var Po=Object.defineProperty,Do=(r,e,t)=>e in r?Po(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>Do(r,typeof e!="symbol"?e+"":e,t);let jo=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Mo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Bo=jo(Mo,11),Uo=s.z.enum(["static","dynamic"]),_s=(r,e)=>{const t=new j(e);if(![L.DAY,L.HOUR,L.MINUTE,L.SECOND,L.MILLISECOND,L.MICROSECOND,L.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 j?new j(n):new L(n)},$=class T{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new T(BigInt(i.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=T.hours(parseInt(n??"00")).add(T.minutes(parseInt(i??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(T.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new T(BigInt(n.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new L(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new Tn(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return _s(this,e)}get isToday(){return this.truncate(L.DAY).equals(T.now().truncate(L.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const n of e){const i=new T(n);i.after(t)&&(t=i)}return t}static min(...e){let t=T.MAX;for(const n of e){const i=new T(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new T(e)}static microseconds(e){return T.nanoseconds(e*1e3)}static milliseconds(e){return T.microseconds(e*1e3)}static seconds(e){return T.milliseconds(e*1e3)}static minutes(e){return T.seconds(e*60)}static hours(e){return T.minutes(e*60)}static days(e){return T.hours(e*24)}};m($,"NANOSECOND",$.nanoseconds(1)),m($,"MICROSECOND",$.microseconds(1)),m($,"MILLISECOND",$.milliseconds(1)),m($,"SECOND",$.seconds(1)),m($,"MINUTE",$.minutes(1)),m($,"HOUR",$.hours(1)),m($,"DAY",$.days(1)),m($,"MAX",new $((1n<<63n)-1n)),m($,"MIN",new $(0)),m($,"ZERO",new $(0)),m($,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new $(r.value)),s.z.string().transform(r=>new $(BigInt(r))),s.z.instanceof(Number).transform(r=>new $(r)),s.z.number().transform(r=>new $(r)),s.z.instanceof($)]));let j=$;const A=class z{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof z?e:e instanceof Wn?e.period:e instanceof j?new z(e):["number","bigint"].includes(typeof e)?z.seconds(e):new z(e)}static fromMilliseconds(e){return e instanceof z?e:e instanceof Wn?e.period:e instanceof j?new z(e):["number","bigint"].includes(typeof e)?z.milliseconds(e):new z(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new z(e).valueOf()}greaterThan(e){return this.valueOf()>new z(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new z(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new z(e).valueOf()}remainder(e){return _s(this,e)}truncate(e){return new z(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(z.DAY),t=this.truncate(z.HOUR),n=this.truncate(z.MINUTE),i=this.truncate(z.SECOND),a=this.truncate(z.MILLISECOND),o=this.truncate(z.MICROSECOND),l=this.truncate(z.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),P=a.sub(i),D=o.sub(a),ee=l.sub(o);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),y.isZero||(B+=`${y.minutes}m `),d.isZero||(B+=`${d.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),ee.isZero||(B+=`${ee.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(z.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new z(e).valueOf()}add(e){return new z(this.valueOf()+new z(e).valueOf())}sub(e){return new z(this.valueOf()-new z(e).valueOf())}static nanoseconds(e=1){return new z(e)}static microseconds(e=1){return z.nanoseconds(Be(e,1e3))}static milliseconds(e=1){return z.microseconds(Be(e,1e3))}static seconds(e=1){return z.milliseconds(Be(e,1e3))}static minutes(e=1){return z.seconds(Be(e,60))}static hours(e){return z.minutes(Be(e,60))}static days(e){return z.hours(Be(e,24))}};m(A,"NANOSECOND",A.nanoseconds(1)),m(A,"MICROSECOND",A.microseconds(1)),m(A,"MILLISECOND",A.milliseconds(1)),m(A,"SECOND",A.seconds(1)),m(A,"MINUTE",A.minutes(1)),m(A,"HOUR",A.hours(1)),m(A,"DAY",A.days(1)),m(A,"MAX",new A((1n<<63n)-1n)),m(A,"MIN",new A(0)),m(A,"ZERO",new A(0)),m(A,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new A(r.value)),s.z.string().transform(r=>new A(BigInt(r))),s.z.instanceof(Number).transform(r=>new A(r)),s.z.number().transform(r=>new A(r)),s.z.instanceof(A)]));let L=A;const gt=class er extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new er(e).valueOf()}get period(){return L.seconds(1/this.valueOf())}sampleCount(e){return new L(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new J(t).valueOf()}span(e){return L.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new er(e)}static khz(e){return er.hz(e*1e3)}};m(gt,"z",s.z.union([s.z.number().transform(r=>new gt(r)),s.z.instanceof(Number).transform(r=>new gt(r)),s.z.instanceof(gt)]));let Wn=gt;const Y=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new sn(e*this.valueOf())}};m(Y,"UNKNOWN",new Y(0)),m(Y,"BIT128",new Y(16)),m(Y,"BIT64",new Y(8)),m(Y,"BIT32",new Y(4)),m(Y,"BIT16",new Y(2)),m(Y,"BIT8",new Y(1)),m(Y,"z",s.z.union([s.z.number().transform(r=>new Y(r)),s.z.instanceof(Number).transform(r=>new Y(r)),s.z.instanceof(Y)]));let J=Y;const ie=class tr{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new j(e.start),this.end=new j(e.end)):(this.start=new j(e),this.end=new j(t))}get span(){return new L(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 tr(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=L.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=j.max(n.start,e.start),a=j.min(n.end,e.end);return a.before(i)?!1:new L(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){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()}contains(e){return e instanceof tr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new tr(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}};m(ie,"MAX",new ie(j.MIN,j.MAX)),m(ie,"MIN",new ie(j.MAX,j.MIN)),m(ie,"ZERO",new ie(j.ZERO,j.ZERO)),m(ie,"z",s.z.union([s.z.object({start:j.z,end:j.z}).transform(r=>new ie(r.start,r.end)),s.z.instanceof(ie)]));let Tn=ie;const g=class ae extends String{constructor(e){if(e instanceof ae||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=ae.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(ae.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ae.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(ae.JSON)||this.equals(ae.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ae.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ae.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return ae.BIG_INT_TYPES.some(e=>e.equals(this))}};m(g,"UNKNOWN",new g("unknown")),m(g,"FLOAT64",new g("float64")),m(g,"FLOAT32",new g("float32")),m(g,"INT64",new g("int64")),m(g,"INT32",new g("int32")),m(g,"INT16",new g("int16")),m(g,"INT8",new g("int8")),m(g,"UINT64",new g("uint64")),m(g,"UINT32",new g("uint32")),m(g,"UINT16",new g("uint16")),m(g,"UINT8",new g("uint8")),m(g,"BOOLEAN",g.UINT8),m(g,"TIMESTAMP",new g("timestamp")),m(g,"UUID",new g("uuid")),m(g,"STRING",new g("string")),m(g,"JSON",new g("json")),m(g,"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]])),m(g,"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]])),m(g,"DENSITIES",new Map([[g.UINT8.toString(),J.BIT8],[g.UINT16.toString(),J.BIT16],[g.UINT32.toString(),J.BIT32],[g.UINT64.toString(),J.BIT64],[g.FLOAT32.toString(),J.BIT32],[g.FLOAT64.toString(),J.BIT64],[g.INT8.toString(),J.BIT8],[g.INT16.toString(),J.BIT16],[g.INT32.toString(),J.BIT32],[g.INT64.toString(),J.BIT64],[g.TIMESTAMP.toString(),J.BIT64],[g.STRING.toString(),J.UNKNOWN],[g.JSON.toString(),J.UNKNOWN],[g.UUID.toString(),J.BIT128]])),m(g,"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]),m(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),m(g,"z",s.z.union([s.z.string().transform(r=>new g(r)),s.z.instanceof(g)]));let R=g;const G=class U extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return U.bytes(this.valueOf()+e.valueOf())}sub(e){return U.bytes(this.valueOf()-e.valueOf())}truncate(e){return new U(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return U.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/U.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/U.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/U.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/U.TERABYTE.valueOf()}toString(){const e=this.truncate(U.TERABYTE),t=this.truncate(U.GIGABYTE),n=this.truncate(U.MEGABYTE),i=this.truncate(U.KILOBYTE),a=this.truncate(U.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new U(e)}static kilobytes(e=1){return U.bytes(e.valueOf()*1e3)}static megabytes(e=1){return U.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return U.megabytes(e.valueOf()*1e3)}static terabytes(e){return U.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(G,"BYTE",new G(1)),m(G,"KILOBYTE",G.kilobytes(1)),m(G,"MEGABYTE",G.megabytes(1)),m(G,"GIGABYTE",G.gigabytes(1)),m(G,"TERABYTE",G.terabytes(1)),m(G,"ZERO",new G(0)),m(G,"z",s.z.union([s.z.number().transform(r=>new G(r)),s.z.instanceof(G)]));let sn=G;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 Ys=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof j||r instanceof L||r instanceof Date},Zo=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):mt(t,-n).valueOf(),Lo=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof qo?!0:Ys(r),ve=-1,_o=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Yo=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),an=10,pt=class oe{constructor(e){m(this,"key",""),m(this,"isSynnaxSeries",!0),m(this,"dataType"),m(this,"sampleOffset"),m(this,"gl"),m(this,"_data"),m(this,"_timeRange"),m(this,"alignment",0n),m(this,"_cachedMin"),m(this,"_cachedMax"),m(this,"writePos",ve),m(this,"_refCount",0),m(this,"_cachedLength"),m(this,"_cachedIndexes"),Lo(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=Bo()}=e,u=e.data??[];if(u instanceof oe||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;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._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=Ys(u),y=Array.isArray(u);if(t!=null)this.dataType=new R(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.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=u[0]}if(typeof d=="string")this.dataType=R.STRING;else if(typeof d=="number")this.dataType=R.FLOAT64;else if(typeof d=="bigint")this.dataType=R.INT64;else if(typeof d=="boolean")this.dataType=R.BOOLEAN;else if(d instanceof j||d instanceof Date||d instanceof j)this.dataType=R.TIMESTAMP;else if(typeof d=="object")this.dataType=R.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new R(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const P=d[0];(P instanceof j||P instanceof Date||P instanceof L)&&(d=d.map(D=>new j(D).valueOf())),this.dataType.equals(R.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
4
|
+
`)}
|
|
5
|
+
`)):this.dataType.equals(R.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(D=>Qt.encodeString(D)).join(`
|
|
6
|
+
`)}
|
|
7
|
+
`)):this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,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 R(t).Array(e),a=new oe({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(t.span(o)).valueOf());return new oe({data:a,dataType:R.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(`${e.join(`
|
|
8
|
+
`)}
|
|
9
|
+
`);return new oe({data:n,dataType:R.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(`${e.map(i=>Qt.encodeString(i)).join(`
|
|
10
|
+
`)}
|
|
11
11
|
`);return new oe({data:n,dataType:R.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array 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===ve)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===ve)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 this._data instanceof ArrayBuffer||this._data instanceof SharedArrayBuffer?this._data:this._data.buffer}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===ve?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(R.STRING,R.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
|
|
12
12
|
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(R.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=R.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(R.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
|
|
13
|
-
`).slice(0,-1).map(t=>e.parse(Qt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new sn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity:this.dataType.isVariable?new sn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ve?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===an&&(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]=Zo(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(R.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax==null&&(this._cachedMax=this.calcRawMax()),mt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(R.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin==null&&(this._cachedMin=this.calcRawMin()),mt(this._cachedMin,this.sampleOffset))}get bounds(){return xe(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return mt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return mt(n,this.sampleOffset)}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]===an){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(R.STRING)?new TextDecoder().decode(a):Cs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=$o(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(R.FLOAT32))throw new Error("Only FLOAT32 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!==ve){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.underlyingData,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ve}as(e){if(e==="string"){if(!this.dataType.equals(R.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(R.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:this.alignmentBounds,timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return xe(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Wo(this);return this.dataType.equals(R.JSON)?new Go(e):e}return new Vo(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Gn(this,e,t??this.length)}subAlignmentIterator(e,t){return new Gn(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new 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:Tn.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(pt,"crudeZ",s.z.object({timeRange:Tn.z.optional(),dataType:R.z,alignment:Co.optional(),data:s.z.union([_o,Yo,s.z.instanceof(ArrayBuffer)]),glBufferUsage:Uo.optional().default("static").optional()})),m(pt,"z",pt.crudeZ.transform(r=>new pt(r)));let qo=pt;class Gn{constructor(e,t,n){m(this,"series"),m(this,"end"),m(this,"index"),this.series=e;const i=xe(0,e.length);this.end=Zn(i,n),this.index=Zn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}class Wo{constructor(e){if(m(this,"series"),m(this,"index"),m(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==an;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Vn,Fn;class Go{constructor(e){m(this,"wrapped"),m(this,Vn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Qt.decodeString(e.value)}}[(Fn=Symbol.iterator,Vn=Symbol.toStringTag,Fn)](){return this}}var Jn,Kn;class Vo{constructor(e){m(this,"series"),m(this,"index"),m(this,Jn,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Kn=Symbol.iterator,Jn=Symbol.toStringTag,Kn)](){return this}}const mt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);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 qs=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Fo=qs(),Ws=["MacOS","Windows","Linux","Docker"],Jo=s.z.enum(Ws);let Ur;const Ko=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},Ho=(r={})=>{const{force:e,default:t}=r;return e??Ur??(Ur=Ko(),Ur??t)},Gs=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Ws,RUNTIME:Fo,detect:qs,getOS:Ho,osZ:Jo},Symbol.toStringTag,{value:"Module"}));var Xo=Object.defineProperty,Qo=(r,e,t)=>e in r?Xo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wt=(r,e,t)=>Qo(r,typeof e!="symbol"?e+"":e,t);const ec=(...r)=>r.map(Vs).join(""),Vs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),tc=r=>r.endsWith("/")?r.slice(0,-1):r,rc=(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("&"),on=class cn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){wt(this,"protocol"),wt(this,"host"),wt(this,"port"),wt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Vs(i)}replace(e){return new cn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new cn({...this,pathPrefix:ec(this.path,e)})}toString(){return tc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};wt(on,"UNKNOWN",new on({host:"unknown",port:0}));let nc=on;var sc=Object.defineProperty,ic=(r,e,t)=>e in r?sc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,rr=(r,e,t)=>ic(r,typeof e!="symbol"?e+"":e,t);const Ue=class extends Number{};rr(Ue,"Absolute",255),rr(Ue,"Default",1),rr(Ue,"z",s.z.union([s.z.instanceof(Ue),s.z.number().int().min(0).max(255).transform(r=>new Ue(r)),s.z.instanceof(Number).transform(r=>new Ue(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const Fs=class bt extends Error{constructor(){super(bt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(bt.MESSAGE):e instanceof bt||e.message.includes(bt.MESSAGE)}};rr(Fs,"MESSAGE","canceled");let ac=Fs;new ac;s.z.string().regex(/^\d+\.\d+\.\d+$/);const X=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);class se extends Error{constructor(e){super(e),k(this,"discriminator","FreighterError"),k(this,"type","")}}const oc=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},Hn="unknown",Xn="nil",cc="freighter",jt=s.z.object({type:s.z.string(),data:s.z.string()});class lc{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Xn,data:""};if(oc(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:Hn,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Xn)return null;if(e.type===Hn)return new Qn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Qn(e.data)}}const Js=new lc,Ks=({encode:r,decode:e})=>Js.register({encode:r,decode:e}),On=r=>Js.decode(r);class Qn extends se{constructor(e){super(e),k(this,"type","unknown")}}const br="freighter.",nr=class Hs extends se{constructor(){super("EOF"),k(this,"type",Hs.TYPE)}};k(nr,"TYPE",br+"eof"),k(nr,"matches",X(nr.TYPE));let Ne=nr;const sr=class Xs extends se{constructor(){super("StreamClosed"),k(this,"type",Xs.TYPE)}};k(sr,"TYPE",br+"stream_closed"),k(sr,"matches",X(sr.TYPE));let nt=sr;const ir=class Qs extends se{constructor(e={}){const{message:t="Unreachable",url:n=nc.UNKNOWN}=e;super(t),k(this,"type",Qs.TYPE),k(this,"url"),this.url=n}};k(ir,"TYPE",br+"unreachable"),k(ir,"matches",X(ir.TYPE));let Ce=ir;const uc=r=>{if(!r.type.startsWith(cc))return null;if(Ne.matches(r))return{type:Ne.TYPE,data:"EOF"};if(nt.matches(r))return{type:nt.TYPE,data:"StreamClosed"};if(Ce.matches(r))return{type:Ce.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},hc=r=>{if(!r.type.startsWith(br))return null;switch(r.type){case Ne.TYPE:return new Ne;case nt.TYPE:return new nt;case Ce.TYPE:return new Ce;default:throw new Error(`Unknown error type: ${r.data}`)}};Ks({encode:uc,decode:hc});let ei=class{constructor(){k(this,"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 ti="Content-Type",es=r=>{if(Gs.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class dc extends ei{constructor(e,t,n=!1){return super(),k(this,"endpoint"),k(this,"encoder"),k(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=es(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[ti]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const y={...h,params:{}};l.headers={...this.headers,...h.params};let d;try{d=await es(h.protocol)(h.target,l)}catch(D){let ee=D;return ee.message==="Load failed"&&(ee=new Ce({url:o})),[y,ee]}const P=await d.arrayBuffer();if(d!=null&&d.ok)return i!=null&&(a=this.encoder.decode(P,i)),[y,null];try{if(d.status!==400)return[y,new Error(d.statusText)];const D=this.encoder.decode(P,jt),ee=On(D);return[y,ee]}catch(D){return[y,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${D.message}`)]}});return[a,u]}}const w=async(r,e,t,n,i)=>{const[a,o]=await r.send(e,t,n,i);if(o!=null)throw o;return a},yc=()=>Gs.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),fc=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(jt)});class gc{constructor(e,t,n,i){k(this,"encoder"),k(this,"reqSchema"),k(this,"resSchema"),k(this,"ws"),k(this,"serverClosed"),k(this,"sendClosed"),k(this,"receiveDataQueue",[]),k(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=n,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}send(e){if(this.serverClosed!=null)return new Ne;if(this.sendClosed)throw new nt;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=On(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.encoder.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=e=>this.addMessage(this.encoder.decode(e.data,fc)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:vc(e)?Ne.TYPE:nt.TYPE,data:""}})}}const pc="freighterctx",mc=1e3,wc=1001,bc=[mc,wc],vc=r=>bc.includes(r.code),ri=class ni extends ei{constructor(e,t,n=!1){super(),k(this,"baseUrl"),k(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=yc();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=ni.MESSAGE_TYPE;const y=await this.wrapSocket(u,t,n);return y instanceof Error?[h,y]:(a=y,[h,null])});if(o!=null)throw o;return a}buildURL(e,t){const n=rc({[ti]:this.encoder.contentType,...t.params},pc);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new gc(e,this.encoder,t,n))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};k(ri,"MESSAGE_TYPE","arraybuffer");let Tc=ri;const dr=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),Oc="all",zc="create",Ec="delete",Sc="retrieve",Nc="update",Ic=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)},si=r=>{const e=(t,n=ln)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Zr(t))return t;n=$c(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(Zr(l)?rs(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&ts(l)&&(l=[...l].map(h=>{let y=h;return Zr(h)?rs(y,n.keepTypesOnRecursion)||(y=e(h,n)):ts(h)&&(y=e({key:h},n).key),y}))),i[u]=l}),i};return e},ii=si(Ic),kc=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Ac=si(kc),ln={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},$c=(r=ln)=>(r.recursive==null?r=ln:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),ts=r=>r!=null&&Array.isArray(r),Zr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),rs=(r,e)=>(e||[]).some(t=>r instanceof t),zn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Rc=Object.defineProperty,xc=(r,e,t)=>e in r?Rc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,It=(r,e,t)=>xc(r,typeof e!="symbol"?e+"":e,t);let ai=class{constructor(){It(this,"contentType","application/json"),It(this,"decoder"),It(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=ii(n);return t!=null?t.parse(i):i}encodeString(e){const t=Ac(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):zn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},oi=class{constructor(){It(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!zn(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(`
|
|
13
|
+
`).slice(0,-1).map(t=>e.parse(Qt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new sn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity:this.dataType.isVariable?new sn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ve?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===an&&(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]=Zo(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(R.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),mt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(R.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),mt(this._cachedMin,this.sampleOffset))}get bounds(){return xe(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return mt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return mt(n,this.sampleOffset)}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]===an){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(R.STRING)?new TextDecoder().decode(a):Cs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Ao(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(R.FLOAT32))throw new Error("Only FLOAT32 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!==ve){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.underlyingData,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ve}as(e){if(e==="string"){if(!this.dataType.equals(R.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(R.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:this.alignmentBounds,timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return xe(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Wo(this);return this.dataType.equals(R.JSON)?new Go(e):e}return new Vo(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Gn(this,e,t??this.length)}subAlignmentIterator(e,t){return new Gn(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new 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:Tn.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(pt,"crudeZ",s.z.object({timeRange:Tn.z.optional(),dataType:R.z,alignment:Co.optional(),data:s.z.union([_o,Yo,s.z.instanceof(ArrayBuffer)]),glBufferUsage:Uo.optional().default("static").optional()})),m(pt,"z",pt.crudeZ.transform(r=>new pt(r)));let qo=pt;class Gn{constructor(e,t,n){m(this,"series"),m(this,"end"),m(this,"index"),this.series=e;const i=xe(0,e.length);this.end=Zn(i,n),this.index=Zn(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}class Wo{constructor(e){if(m(this,"series"),m(this,"index"),m(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==an;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var Vn,Fn;class Go{constructor(e){m(this,"wrapped"),m(this,Vn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Qt.decodeString(e.value)}}[(Fn=Symbol.iterator,Vn=Symbol.toStringTag,Fn)](){return this}}var Jn,Kn;class Vo{constructor(e){m(this,"series"),m(this,"index"),m(this,Jn,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(Kn=Symbol.iterator,Jn=Symbol.toStringTag,Kn)](){return this}}const mt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);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 qs=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Fo=qs(),Ws=["MacOS","Windows","Linux","Docker"],Jo=s.z.enum(Ws);let Ur;const Ko=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"MacOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"},Ho=(r={})=>{const{force:e,default:t}=r;return e??Ur??(Ur=Ko(),Ur??t)},Gs=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Ws,RUNTIME:Fo,detect:qs,getOS:Ho,osZ:Jo},Symbol.toStringTag,{value:"Module"}));var Xo=Object.defineProperty,Qo=(r,e,t)=>e in r?Xo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wt=(r,e,t)=>Qo(r,typeof e!="symbol"?e+"":e,t);const ec=(...r)=>r.map(Vs).join(""),Vs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),tc=r=>r.endsWith("/")?r.slice(0,-1):r,rc=(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("&")}`,on=class cn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){wt(this,"protocol"),wt(this,"host"),wt(this,"port"),wt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Vs(i)}replace(e){return new cn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new cn({...this,pathPrefix:ec(this.path,e)})}toString(){return tc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};wt(on,"UNKNOWN",new on({host:"unknown",port:0}));let nc=on;var sc=Object.defineProperty,ic=(r,e,t)=>e in r?sc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,rr=(r,e,t)=>ic(r,typeof e!="symbol"?e+"":e,t);const Ue=class extends Number{};rr(Ue,"Absolute",255),rr(Ue,"Default",1),rr(Ue,"z",s.z.union([s.z.instanceof(Ue),s.z.number().int().min(0).max(255).transform(r=>new Ue(r)),s.z.instanceof(Number).transform(r=>new Ue(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const Fs=class bt extends Error{constructor(){super(bt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(bt.MESSAGE):e instanceof bt||e.message.includes(bt.MESSAGE)}};rr(Fs,"MESSAGE","canceled");let ac=Fs;new ac;s.z.string().regex(/^\d+\.\d+\.\d+$/);const X=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(r):e instanceof Error?e.message.includes(r):typeof e!="string"?!1:e.includes(r);class se extends Error{constructor(){super(...arguments),k(this,"discriminator","FreighterError"),k(this,"type","")}}const oc=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!=="FreighterError")return!1;if(!("type"in e))throw new Error(`Freighter error is missing its type property: ${JSON.stringify(e)}`);return!0},Hn="unknown",Xn="nil",cc="freighter",jt=s.z.object({type:s.z.string(),data:s.z.string()});class lc{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Xn,data:""};if(oc(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:Hn,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Xn)return null;if(e.type===Hn)return new Qn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Qn(e.data)}}const Js=new lc,Ks=({encode:r,decode:e})=>Js.register({encode:r,decode:e}),On=r=>Js.decode(r);class Qn extends se{constructor(){super(...arguments),k(this,"type","unknown")}}const br="freighter.",nr=class Hs extends se{constructor(){super("EOF"),k(this,"type",Hs.TYPE)}};k(nr,"TYPE",`${br}eof`),k(nr,"matches",X(nr.TYPE));let Ne=nr;const sr=class Xs extends se{constructor(){super("StreamClosed"),k(this,"type",Xs.TYPE)}};k(sr,"TYPE",`${br}stream_closed`),k(sr,"matches",X(sr.TYPE));let nt=sr;const ir=class Qs extends se{constructor(e={}){const{message:t="Unreachable",url:n=nc.UNKNOWN}=e;super(t),k(this,"type",Qs.TYPE),k(this,"url"),this.url=n}};k(ir,"TYPE",`${br}unreachable`),k(ir,"matches",X(ir.TYPE));let Ce=ir;const uc=r=>{if(!r.type.startsWith(cc))return null;if(Ne.matches(r))return{type:Ne.TYPE,data:"EOF"};if(nt.matches(r))return{type:nt.TYPE,data:"StreamClosed"};if(Ce.matches(r))return{type:Ce.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},hc=r=>{if(!r.type.startsWith(br))return null;switch(r.type){case Ne.TYPE:return new Ne;case nt.TYPE:return new nt;case Ce.TYPE:return new Ce;default:throw new Error(`Unknown error type: ${r.data}`)}};Ks({encode:uc,decode:hc});let ei=class{constructor(){k(this,"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 ti="Content-Type",es=r=>{if(Gs.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(r==="http")return e;const t=require("https"),n=new t.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:n})};class dc extends ei{constructor(e,t,n=!1){return super(),k(this,"endpoint"),k(this,"encoder"),k(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=es(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[ti]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const y={...h,params:{}};l.headers={...this.headers,...h.params};let d;try{d=await es(h.protocol)(h.target,l)}catch(D){let ee=D;return ee.message==="Load failed"&&(ee=new Ce({url:o})),[y,ee]}const P=await d.arrayBuffer();if(d!=null&&d.ok)return i!=null&&(a=this.encoder.decode(P,i)),[y,null];try{if(d.status!==400)return[y,new Error(d.statusText)];const D=this.encoder.decode(P,jt),ee=On(D);return[y,ee]}catch(D){return[y,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${D.message}`)]}});return[a,u]}}const w=async(r,e,t,n,i)=>{const[a,o]=await r.send(e,t,n,i);if(o!=null)throw o;return a},yc=()=>Gs.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),fc=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(jt)});class gc{constructor(e,t,n,i){k(this,"encoder"),k(this,"reqSchema"),k(this,"resSchema"),k(this,"ws"),k(this,"serverClosed"),k(this,"sendClosed"),k(this,"receiveDataQueue",[]),k(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=n,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}send(e){if(this.serverClosed!=null)return new Ne;if(this.sendClosed)throw new nt;return this.ws.send(this.encoder.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");return this.serverClosed=On(e.error),[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.encoder.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=e=>this.addMessage(this.encoder.decode(e.data,fc)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:vc(e)?Ne.TYPE:nt.TYPE,data:""}})}}const pc="freighterctx",mc=1e3,wc=1001,bc=[mc,wc],vc=r=>bc.includes(r.code),ri=class ni extends ei{constructor(e,t,n=!1){super(),k(this,"baseUrl"),k(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=yc();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=ni.MESSAGE_TYPE;const y=await this.wrapSocket(u,t,n);return y instanceof Error?[h,y]:(a=y,[h,null])});if(o!=null)throw o;return a}buildURL(e,t){const n=rc({[ti]:this.encoder.contentType,...t.params},pc);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new gc(e,this.encoder,t,n))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};k(ri,"MESSAGE_TYPE","arraybuffer");let Tc=ri;const dr=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),Oc="all",zc="create",Ec="delete",Sc="retrieve",Nc="update",Ic=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)},si=r=>{const e=(t,n=ln)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Zr(t))return t;n=Ac(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(Zr(l)?rs(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&ts(l)&&(l=[...l].map(h=>{let y=h;return Zr(h)?rs(y,n.keepTypesOnRecursion)||(y=e(h,n)):ts(h)&&(y=e({key:h},n).key),y}))),i[u]=l}),i};return e},ii=si(Ic),kc=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),$c=si(kc),ln={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Ac=(r=ln)=>(r.recursive==null?r=ln:r.recursiveInArray??(r.recursiveInArray=!1),r),ts=r=>r!=null&&Array.isArray(r),Zr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),rs=(r,e)=>(e||[]).some(t=>r instanceof t),zn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Rc=Object.defineProperty,xc=(r,e,t)=>e in r?Rc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,It=(r,e,t)=>xc(r,typeof e!="symbol"?e+"":e,t);let ai=class{constructor(){It(this,"contentType","application/json"),It(this,"decoder"),It(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(e){return this.encoder.encode(this.encodeString(e)).buffer}decode(e,t){return this.decodeString(this.decoder.decode(e),t)}decodeString(e,t){const n=JSON.parse(e),i=ii(n);return t!=null?t.parse(i):i}encodeString(e){const t=$c(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):zn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},oi=class{constructor(){It(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const n=new TextDecoder().decode(e);return this.decodeString(n,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!zn(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(`
|
|
14
14
|
`)}decodeString(e,t){const[n,...i]=e.trim().split(`
|
|
15
|
-
`).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,y)=>{const d=this.parseValue(u[y]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},ci=class{constructor(){It(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const rt=new ai,Cc=new oi,Pc=new ci,Dc=[rt],lt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:oi,CSV_CODEC:Cc,ENCODERS:Dc,JSONCodec:ai,JSON_CODEC:rt,TEXT_CODEC:Pc,TextCodec:ci},Symbol.toStringTag,{value:"Module"})),vr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const li=s.z.object({width:s.z.number(),height:s.z.number()}),jc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Mc=["width","height"];s.z.enum(Mc);const Bc=["start","center","end"],Uc=["signedWidth","signedHeight"];s.z.enum(Uc);const yr=s.z.object({x:s.z.number(),y:s.z.number()}),Zc=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Lc=["x","y"],ui=s.z.enum(Lc),hi=["top","right","bottom","left"];s.z.enum(hi);const _c=["left","right"],di=s.z.enum(_c),Yc=["top","bottom"],yi=s.z.enum(Yc),fi=["center"],ns=s.z.enum(fi),qc=[...hi,...fi],gi=s.z.enum(qc);s.z.enum(Bc);const Wc=["first","last"];s.z.enum(Wc);const Gc=s.z.object({lower:s.z.number(),upper:s.z.number()}),Vc=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Gc,vr]);s.z.union([Vc,vr]);s.z.union([ui,gi]);s.z.union([ui,gi,s.z.instanceof(String)]);const ut=r=>typeof r=="bigint"||r instanceof BigInt,Lr=(r,e)=>ut(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),Fc=(r,e)=>ut(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),ss=(r,e)=>ut(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),Jc=(r,e)=>ut(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),Kc=r=>ut(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,Ze=(r,e)=>ut(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),K=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return is(r);return is(t)},is=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,as=(r,e)=>{const t=K(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},Kt=(r,e)=>{const t=K(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=K(e);return n.lower>=t.lower&&n.upper<=t.upper},Hc=(r,e,t)=>{const n=r.map(l=>K(l)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;ss(a,0)===!1;){const l=n.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(l!==-1){const u=n[l];let h;if(i>0?h=Lr(u.upper,o):h=Lr(o,u.lower),h>0){const y=Jc(Kc(a),h);if(o=Fc(o,i>0?y:-y),a=Lr(a,i>0?y:-y),ss(a,0))return o;continue}}if(i>0){const u=n.filter(h=>h.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=n.filter(h=>h.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},Xc=(r,e,t)=>{const n=r.map(o=>K(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?K([e,t]):K([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(l<u){const h=u-l;a=a+h}}return a};s.z.object({x:di.or(ns),y:yi.or(ns)});const Qc=s.z.object({x:di,y:yi}),el=Object.freeze({x:"left",y:"top"}),tl=(r,e)=>r.x===e.x&&r.y===e.y,os=s.z.union([s.z.number(),yr,vr,li,jc,Zc]),rl=(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}},cs=Object.freeze({x:0,y:0}),Ht=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Ht,left:Ht,width:Ht,height:Ht});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:yr,two:yr,root:Qc});const En=(r,e,t=0,n=0,i)=>{const a={one:{...cs},two:{...cs},root:i??el};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))},_r=r=>{const e=En(r);return{lower:e.one.x,upper:e.two.x}},Yr=r=>{const e=En(r);return{lower:e.one.y,upper:e.two.y}},nl=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var sl=Object.defineProperty,il=(r,e,t)=>e in r?sl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ge=(r,e,t)=>il(r,typeof e!="symbol"?e+"":e,t);const al=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:os,scale:os});const ol=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],cl=r=>(e,t,n,i)=>[e,i?n/r:n*r],ll=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},ul=r=>(e,t,n)=>[r,n],hl=()=>(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)]},dl=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=al(n,i,a),[e,n]},un=class vt{constructor(){ge(this,"ops",[]),ge(this,"currBounds",null),ge(this,"currType",null),ge(this,"reversed",!1),this.ops=[]}static translate(e){return new vt().translate(e)}static magnify(e){return new vt().magnify(e)}static scale(e,t){return new vt().scale(e,t)}translate(e){const t=this.new(),n=ol(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=cl(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=K(e,t),i=this.new(),a=ll(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=K(e,t),i=this.new(),a=dl(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=K(e,t),i=this.new(),a=ul(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=hl();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 vt;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,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>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}};ge(un,"IDENTITY",new un);let ls=un;const us=class ye{constructor(e=new ls,t=new ls,n=null){ge(this,"x"),ge(this,"y"),ge(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ye().translate(e,t)}static translateX(e){return new ye().translateX(e)}static translateY(e){return new ye().translateY(e)}static clamp(e){return new ye().clamp(e)}static magnify(e){return new ye().magnify(e)}static scale(e){return new ye().scale(e)}static reBound(e){return new ye().reBound(e)}translate(e,t){const n=rl(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(nl(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!tl(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(_r(e)),t.y=t.y.scale(Yr(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(_r(e)),t.y=this.y.reBound(Yr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(_r(e)),t.y=this.y.clamp(Yr(e)),t}copy(){const e=new ye;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)}}box(e){return En(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};ge(us,"IDENTITY",new us);const hs=r=>[...new Set(r)],yl=r=>r!=null&&typeof r=="object"&&"toString"in r,fl=(r,e=!1)=>{const t=yl(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?gl(n):n},gl=r=>(e,t)=>r(t,e),Tr=0,qr=-1,Wr=1,pl=r=>r<Tr,ml=r=>r>Tr,wl=r=>r===Tr,bl=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},vl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([li,vl,yr,vr]);const Tl=s.z.bigint().or(s.z.string().transform(BigInt));var Ol=Object.defineProperty,zl=(r,e,t)=>e in r?Ol(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e,t)=>zl(r,typeof e!="symbol"?e+"":e,t);let El=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Sl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pi=El(Sl,11),Nl=Object.freeze(Object.defineProperty({__proto__:null,id:pi},Symbol.toStringTag,{value:"Module"})),Il=s.z.enum(["static","dynamic"]),mi=(r,e)=>{const t=new N(e);if(![I.DAY,I.HOUR,I.MINUTE,I.SECOND,I.MILLISECOND,I.MICROSECOND,I.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 I(n)},x=class O{constructor(e,t="UTC"){if(f(this,"value"),f(this,"encodeValue",!0),e==null)this.value=O.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*O.MILLISECOND.valueOf();else if(typeof e=="string")this.value=O.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=O.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=O.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=O.MAX:e=O.MIN)),this.value=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 O(BigInt(i.getTime())*O.MILLISECOND.valueOf()).truncate(O.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=O.hours(parseInt(n??"00",10)).add(O.minutes(parseInt(i??"00",10))).add(O.seconds(parseInt(o??"00",10))).add(O.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(O.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return O.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new O(BigInt(n.getTime())*O.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(O.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 I(BigInt(new Date().getTimezoneOffset())*O.MINUTE.valueOf())}static since(e){return new O().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new O(e).valueOf()}span(e){return this.range(e).span}range(e){return new W(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new O(e).valueOf()}afterEq(e){return this.valueOf()>=new O(e).valueOf()}before(e){return this.valueOf()<new O(e).valueOf()}beforeEq(e){return this.valueOf()<=new O(e).valueOf()}add(e){return new O(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new O(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(O.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return mi(this,e)}get isToday(){return this.truncate(I.DAY).equals(O.now().truncate(I.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new O(new Date)}static max(...e){let t=O.MIN;for(const n of e){const i=new O(n);i.after(t)&&(t=i)}return t}static min(...e){let t=O.MAX;for(const n of e){const i=new O(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new O(e)}static microseconds(e){return O.nanoseconds(e*1e3)}static milliseconds(e){return O.microseconds(e*1e3)}static seconds(e){return O.milliseconds(e*1e3)}static minutes(e){return O.seconds(e*60)}static hours(e){return O.minutes(e*60)}static days(e){return O.hours(e*24)}};f(x,"NANOSECOND",x.nanoseconds(1)),f(x,"MICROSECOND",x.microseconds(1)),f(x,"MILLISECOND",x.milliseconds(1)),f(x,"SECOND",x.seconds(1)),f(x,"MINUTE",x.minutes(1)),f(x,"HOUR",x.hours(1)),f(x,"DAY",x.days(1)),f(x,"MAX",new x((1n<<63n)-1n)),f(x,"MIN",new x(0)),f(x,"ZERO",new x(0)),f(x,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new x(r.value)),s.z.string().transform(r=>new x(BigInt(r))),s.z.instanceof(Number).transform(r=>new x(r)),s.z.number().transform(r=>new x(r)),s.z.instanceof(x)]));let N=x;const C=class E{constructor(e){f(this,"value"),f(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof E?e:e instanceof st?e.period:e instanceof N?new E(e):["number","bigint"].includes(typeof e)?E.seconds(e):new E(e)}static fromMilliseconds(e){return e instanceof E?e:e instanceof st?e.period:e instanceof N?new E(e):["number","bigint"].includes(typeof e)?E.milliseconds(e):new E(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new E(e).valueOf()}greaterThan(e){return this.valueOf()>new E(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new E(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new E(e).valueOf()}remainder(e){return mi(this,e)}truncate(e){return new E(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(E.DAY),t=this.truncate(E.HOUR),n=this.truncate(E.MINUTE),i=this.truncate(E.SECOND),a=this.truncate(E.MILLISECOND),o=this.truncate(E.MICROSECOND),l=this.truncate(E.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),P=a.sub(i),D=o.sub(a),ee=l.sub(o);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),y.isZero||(B+=`${y.minutes}m `),d.isZero||(B+=`${d.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),ee.isZero||(B+=`${ee.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(E.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new E(e).valueOf()}add(e){return new E(this.valueOf()+new E(e).valueOf())}sub(e){return new E(this.valueOf()-new E(e).valueOf())}static nanoseconds(e=1){return new E(e)}static microseconds(e=1){return E.nanoseconds(Ze(e,1e3))}static milliseconds(e=1){return E.microseconds(Ze(e,1e3))}static seconds(e=1){return E.milliseconds(Ze(e,1e3))}static minutes(e=1){return E.seconds(Ze(e,60))}static hours(e){return E.minutes(Ze(e,60))}static days(e){return E.hours(Ze(e,24))}};f(C,"NANOSECOND",C.nanoseconds(1)),f(C,"MICROSECOND",C.microseconds(1)),f(C,"MILLISECOND",C.milliseconds(1)),f(C,"SECOND",C.seconds(1)),f(C,"MINUTE",C.minutes(1)),f(C,"HOUR",C.hours(1)),f(C,"DAY",C.days(1)),f(C,"MAX",new C((1n<<63n)-1n)),f(C,"MIN",new C(0)),f(C,"ZERO",new C(0)),f(C,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new C(r.value)),s.z.string().transform(r=>new C(BigInt(r))),s.z.instanceof(Number).transform(r=>new C(r)),s.z.number().transform(r=>new C(r)),s.z.instanceof(C)]));let I=C;const Tt=class ar extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ar(e).valueOf()}get period(){return I.seconds(1/this.valueOf())}sampleCount(e){return new I(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new F(t).valueOf()}span(e){return I.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new ar(e)}static khz(e){return ar.hz(e*1e3)}};f(Tt,"z",s.z.union([s.z.number().transform(r=>new Tt(r)),s.z.instanceof(Number).transform(r=>new Tt(r)),s.z.instanceof(Tt)]));let st=Tt;const q=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new it(e*this.valueOf())}};f(q,"UNKNOWN",new q(0)),f(q,"BIT128",new q(16)),f(q,"BIT64",new q(8)),f(q,"BIT32",new q(4)),f(q,"BIT16",new q(2)),f(q,"BIT8",new q(1)),f(q,"z",s.z.union([s.z.number().transform(r=>new q(r)),s.z.instanceof(Number).transform(r=>new q(r)),s.z.instanceof(q)]));let F=q;const ce=class or{constructor(e,t){f(this,"start"),f(this,"end"),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 I(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 or(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=I.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 I(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){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()}contains(e){return e instanceof or?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new or(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}};f(ce,"MAX",new ce(N.MIN,N.MAX)),f(ce,"MIN",new ce(N.MAX,N.MIN)),f(ce,"ZERO",new ce(N.ZERO,N.ZERO)),f(ce,"z",s.z.union([s.z.object({start:N.z,end:N.z}).transform(r=>new ce(r.start,r.end)),s.z.instanceof(ce)]));let W=ce;const p=class le extends String{constructor(e){if(e instanceof le||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=le.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(le.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=le.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(le.JSON)||this.equals(le.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(le.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=le.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return le.BIG_INT_TYPES.some(e=>e.equals(this))}};f(p,"UNKNOWN",new p("unknown")),f(p,"FLOAT64",new p("float64")),f(p,"FLOAT32",new p("float32")),f(p,"INT64",new p("int64")),f(p,"INT32",new p("int32")),f(p,"INT16",new p("int16")),f(p,"INT8",new p("int8")),f(p,"UINT64",new p("uint64")),f(p,"UINT32",new p("uint32")),f(p,"UINT16",new p("uint16")),f(p,"UINT8",new p("uint8")),f(p,"BOOLEAN",p.UINT8),f(p,"TIMESTAMP",new p("timestamp")),f(p,"UUID",new p("uuid")),f(p,"STRING",new p("string")),f(p,"JSON",new p("json")),f(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),f(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),f(p,"DENSITIES",new Map([[p.UINT8.toString(),F.BIT8],[p.UINT16.toString(),F.BIT16],[p.UINT32.toString(),F.BIT32],[p.UINT64.toString(),F.BIT64],[p.FLOAT32.toString(),F.BIT32],[p.FLOAT64.toString(),F.BIT64],[p.INT8.toString(),F.BIT8],[p.INT16.toString(),F.BIT16],[p.INT32.toString(),F.BIT32],[p.INT64.toString(),F.BIT64],[p.TIMESTAMP.toString(),F.BIT64],[p.STRING.toString(),F.UNKNOWN],[p.JSON.toString(),F.UNKNOWN],[p.UUID.toString(),F.BIT128]])),f(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),f(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),f(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let S=p;const V=class Z extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Z.bytes(this.valueOf()+e.valueOf())}sub(e){return Z.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Z(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Z.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Z.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Z.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Z.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Z.TERABYTE.valueOf()}toString(){const e=this.truncate(Z.TERABYTE),t=this.truncate(Z.GIGABYTE),n=this.truncate(Z.MEGABYTE),i=this.truncate(Z.KILOBYTE),a=this.truncate(Z.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new Z(e)}static kilobytes(e=1){return Z.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Z.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Z.megabytes(e.valueOf()*1e3)}static terabytes(e){return Z.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};f(V,"BYTE",new V(1)),f(V,"KILOBYTE",V.kilobytes(1)),f(V,"MEGABYTE",V.megabytes(1)),f(V,"GIGABYTE",V.gigabytes(1)),f(V,"TERABYTE",V.terabytes(1)),f(V,"ZERO",new V(0)),f(V,"z",s.z.union([s.z.number().transform(r=>new V(r)),s.z.instanceof(V)]));let it=V;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 wi=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof N||r instanceof I||r instanceof Date},kl=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):zt(t,-n).valueOf(),Al=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof ze?!0:wi(r),Te=-1,hn={[Symbol.iterator]:()=>hn,next:()=>({done:!0,value:void 0})},$l=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Rl=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),dn=10,Ot=class ue{constructor(e){f(this,"key",""),f(this,"isSynnaxSeries",!0),f(this,"dataType"),f(this,"sampleOffset"),f(this,"gl"),f(this,"_data"),f(this,"_timeRange"),f(this,"alignment",0n),f(this,"_cachedMin"),f(this,"_cachedMax"),f(this,"writePos",Te),f(this,"_refCount",0),f(this,"_cachedLength"),f(this,"_cachedIndexes"),Al(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=pi()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;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._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=wi(u),y=Array.isArray(u);if(t!=null)this.dataType=new S(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.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=u[0]}if(typeof d=="string")this.dataType=S.STRING;else if(typeof d=="number")this.dataType=S.FLOAT64;else if(typeof d=="bigint")this.dataType=S.INT64;else if(typeof d=="boolean")this.dataType=S.BOOLEAN;else if(d instanceof N||d instanceof Date||d instanceof N)this.dataType=S.TIMESTAMP;else if(typeof d=="object")this.dataType=S.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new S(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const P=d[0];(P instanceof N||P instanceof Date||P instanceof I)&&(d=d.map(D=>new N(D).valueOf())),this.dataType.equals(S.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(d.join(`
|
|
16
|
-
`)
|
|
17
|
-
`)):this.dataType.equals(S.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(d.map(D=>rt.encodeString(D)).join(`
|
|
18
|
-
`)
|
|
19
|
-
`)):this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,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 ue({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(t.span(o)).valueOf());return new ue({data:a,dataType:S.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
|
|
20
|
-
`)
|
|
21
|
-
`);return new ue({data:n,dataType:S.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>rt.encodeString(i)).join(`
|
|
22
|
-
`)
|
|
15
|
+
`).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,y)=>{const d=this.parseValue(u[y]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},ci=class{constructor(){It(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const n=new TextDecoder().decode(e);return t!=null?t.parse(n):n}};const rt=new ai,Cc=new oi,Pc=new ci,Dc=[rt],lt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:oi,CSV_CODEC:Cc,ENCODERS:Dc,JSONCodec:ai,JSON_CODEC:rt,TEXT_CODEC:Pc,TextCodec:ci},Symbol.toStringTag,{value:"Module"})),vr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const li=s.z.object({width:s.z.number(),height:s.z.number()}),jc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Mc=["width","height"];s.z.enum(Mc);const Bc=["start","center","end"],Uc=["signedWidth","signedHeight"];s.z.enum(Uc);const yr=s.z.object({x:s.z.number(),y:s.z.number()}),Zc=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Lc=["x","y"],ui=s.z.enum(Lc),hi=["top","right","bottom","left"];s.z.enum(hi);const _c=["left","right"],di=s.z.enum(_c),Yc=["top","bottom"],yi=s.z.enum(Yc),fi=["center"],ns=s.z.enum(fi),qc=[...hi,...fi],gi=s.z.enum(qc);s.z.enum(Bc);const Wc=["first","last"];s.z.enum(Wc);const Gc=s.z.object({lower:s.z.number(),upper:s.z.number()}),Vc=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Gc,vr]);s.z.union([Vc,vr]);s.z.union([ui,gi]);s.z.union([ui,gi,s.z.instanceof(String)]);const ut=r=>typeof r=="bigint"||r instanceof BigInt,Lr=(r,e)=>ut(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),Fc=(r,e)=>ut(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),ss=(r,e)=>ut(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),Jc=(r,e)=>ut(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),Kc=r=>ut(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,Ze=(r,e)=>ut(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),K=(r,e)=>{const t={};if(typeof r=="number"||typeof r=="bigint")e!=null?(t.lower=r,t.upper=e):(t.lower=typeof r=="bigint"?0n:0,t.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=r}else return is(r);return is(t)},is=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,as=(r,e)=>{const t=K(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},Kt=(r,e)=>{const t=K(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=K(e);return n.lower>=t.lower&&n.upper<=t.upper},Hc=(r,e,t)=>{const n=r.map(l=>K(l)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;ss(a,0)===!1;){const l=n.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(l!==-1){const u=n[l];let h;if(i>0?h=Lr(u.upper,o):h=Lr(o,u.lower),h>0){const y=Jc(Kc(a),h);if(o=Fc(o,i>0?y:-y),a=Lr(a,i>0?y:-y),ss(a,0))return o;continue}}if(i>0){const u=n.filter(h=>h.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=n.filter(h=>h.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},Xc=(r,e,t)=>{const n=r.map(o=>K(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?K([e,t]):K([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(l<u){const h=u-l;a=a+h}}return a};s.z.object({x:di.or(ns),y:yi.or(ns)});const Qc=s.z.object({x:di,y:yi}),el=Object.freeze({x:"left",y:"top"}),tl=(r,e)=>r.x===e.x&&r.y===e.y,os=s.z.union([s.z.number(),yr,vr,li,jc,Zc]),rl=(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}},cs=Object.freeze({x:0,y:0}),Ht=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Ht,left:Ht,width:Ht,height:Ht});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:yr,two:yr,root:Qc});const En=(r,e,t=0,n=0,i)=>{const a={one:{...cs},two:{...cs},root:i??el};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))},_r=r=>{const e=En(r);return{lower:e.one.x,upper:e.two.x}},Yr=r=>{const e=En(r);return{lower:e.one.y,upper:e.two.y}},nl=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var sl=Object.defineProperty,il=(r,e,t)=>e in r?sl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ge=(r,e,t)=>il(r,typeof e!="symbol"?e+"":e,t);const al=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:os,scale:os});const ol=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],cl=r=>(e,t,n,i)=>[e,i?n/r:n*r],ll=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const y=(n-i)*(h/u)+o;return[r,y]},ul=r=>(e,t,n)=>[r,n],hl=()=>(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)]},dl=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=al(n,i,a),[e,n]},un=class vt{constructor(){ge(this,"ops",[]),ge(this,"currBounds",null),ge(this,"currType",null),ge(this,"reversed",!1),this.ops=[]}static translate(e){return new vt().translate(e)}static magnify(e){return new vt().magnify(e)}static scale(e,t){return new vt().scale(e,t)}translate(e){const t=this.new(),n=ol(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=cl(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=K(e,t),i=this.new(),a=ll(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=K(e,t),i=this.new(),a=dl(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=K(e,t),i=this.new(),a=ul(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=hl();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 vt;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,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>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}};ge(un,"IDENTITY",new un);let ls=un;const us=class ye{constructor(e=new ls,t=new ls,n=null){ge(this,"x"),ge(this,"y"),ge(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ye().translate(e,t)}static translateX(e){return new ye().translateX(e)}static translateY(e){return new ye().translateY(e)}static clamp(e){return new ye().clamp(e)}static magnify(e){return new ye().magnify(e)}static scale(e){return new ye().scale(e)}static reBound(e){return new ye().reBound(e)}translate(e,t){const n=rl(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(nl(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!tl(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(_r(e)),t.y=t.y.scale(Yr(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(_r(e)),t.y=this.y.reBound(Yr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(_r(e)),t.y=this.y.clamp(Yr(e)),t}copy(){const e=new ye;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)}}box(e){return En(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};ge(us,"IDENTITY",new us);const hs=r=>[...new Set(r)],yl=r=>r!=null&&typeof r=="object"&&"toString"in r,fl=(r,e=!1)=>{const t=yl(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?gl(n):n},gl=r=>(e,t)=>r(t,e),Tr=0,qr=-1,Wr=1,pl=r=>r<Tr,ml=r=>r>Tr,wl=r=>r===Tr,bl=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},vl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([li,vl,yr,vr]);const Tl=s.z.bigint().or(s.z.string().transform(BigInt));var Ol=Object.defineProperty,zl=(r,e,t)=>e in r?Ol(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,f=(r,e,t)=>zl(r,typeof e!="symbol"?e+"":e,t);let El=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Sl="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",pi=El(Sl,11),Nl=Object.freeze(Object.defineProperty({__proto__:null,id:pi},Symbol.toStringTag,{value:"Module"})),Il=s.z.enum(["static","dynamic"]),mi=(r,e)=>{const t=new N(e);if(![I.DAY,I.HOUR,I.MINUTE,I.SECOND,I.MILLISECOND,I.MICROSECOND,I.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 I(n)},x=class O{constructor(e,t="UTC"){if(f(this,"value"),f(this,"encodeValue",!0),e==null)this.value=O.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*O.MILLISECOND.valueOf();else if(typeof e=="string")this.value=O.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=O.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=O.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=O.MAX:e=O.MIN)),this.value=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 O(BigInt(i.getTime())*O.MILLISECOND.valueOf()).truncate(O.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=O.hours(parseInt(n??"00")).add(O.minutes(parseInt(i??"00"))).add(O.seconds(parseInt(o??"00"))).add(O.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(O.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return O.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new O(BigInt(n.getTime())*O.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(O.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 I(BigInt(new Date().getTimezoneOffset())*O.MINUTE.valueOf())}static since(e){return new O().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new O(e).valueOf()}span(e){return this.range(e).span}range(e){return new W(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new O(e).valueOf()}afterEq(e){return this.valueOf()>=new O(e).valueOf()}before(e){return this.valueOf()<new O(e).valueOf()}beforeEq(e){return this.valueOf()<=new O(e).valueOf()}add(e){return new O(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new O(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(O.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return mi(this,e)}get isToday(){return this.truncate(I.DAY).equals(O.now().truncate(I.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new O(new Date)}static max(...e){let t=O.MIN;for(const n of e){const i=new O(n);i.after(t)&&(t=i)}return t}static min(...e){let t=O.MAX;for(const n of e){const i=new O(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new O(e)}static microseconds(e){return O.nanoseconds(e*1e3)}static milliseconds(e){return O.microseconds(e*1e3)}static seconds(e){return O.milliseconds(e*1e3)}static minutes(e){return O.seconds(e*60)}static hours(e){return O.minutes(e*60)}static days(e){return O.hours(e*24)}};f(x,"NANOSECOND",x.nanoseconds(1)),f(x,"MICROSECOND",x.microseconds(1)),f(x,"MILLISECOND",x.milliseconds(1)),f(x,"SECOND",x.seconds(1)),f(x,"MINUTE",x.minutes(1)),f(x,"HOUR",x.hours(1)),f(x,"DAY",x.days(1)),f(x,"MAX",new x((1n<<63n)-1n)),f(x,"MIN",new x(0)),f(x,"ZERO",new x(0)),f(x,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new x(r.value)),s.z.string().transform(r=>new x(BigInt(r))),s.z.instanceof(Number).transform(r=>new x(r)),s.z.number().transform(r=>new x(r)),s.z.instanceof(x)]));let N=x;const C=class E{constructor(e){f(this,"value"),f(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof E?e:e instanceof st?e.period:e instanceof N?new E(e):["number","bigint"].includes(typeof e)?E.seconds(e):new E(e)}static fromMilliseconds(e){return e instanceof E?e:e instanceof st?e.period:e instanceof N?new E(e):["number","bigint"].includes(typeof e)?E.milliseconds(e):new E(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new E(e).valueOf()}greaterThan(e){return this.valueOf()>new E(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new E(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new E(e).valueOf()}remainder(e){return mi(this,e)}truncate(e){return new E(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(E.DAY),t=this.truncate(E.HOUR),n=this.truncate(E.MINUTE),i=this.truncate(E.SECOND),a=this.truncate(E.MILLISECOND),o=this.truncate(E.MICROSECOND),l=this.truncate(E.NANOSECOND),u=e,h=t.sub(e),y=n.sub(t),d=i.sub(n),P=a.sub(i),D=o.sub(a),ee=l.sub(o);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),y.isZero||(B+=`${y.minutes}m `),d.isZero||(B+=`${d.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),ee.isZero||(B+=`${ee.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(E.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new E(e).valueOf()}add(e){return new E(this.valueOf()+new E(e).valueOf())}sub(e){return new E(this.valueOf()-new E(e).valueOf())}static nanoseconds(e=1){return new E(e)}static microseconds(e=1){return E.nanoseconds(Ze(e,1e3))}static milliseconds(e=1){return E.microseconds(Ze(e,1e3))}static seconds(e=1){return E.milliseconds(Ze(e,1e3))}static minutes(e=1){return E.seconds(Ze(e,60))}static hours(e){return E.minutes(Ze(e,60))}static days(e){return E.hours(Ze(e,24))}};f(C,"NANOSECOND",C.nanoseconds(1)),f(C,"MICROSECOND",C.microseconds(1)),f(C,"MILLISECOND",C.milliseconds(1)),f(C,"SECOND",C.seconds(1)),f(C,"MINUTE",C.minutes(1)),f(C,"HOUR",C.hours(1)),f(C,"DAY",C.days(1)),f(C,"MAX",new C((1n<<63n)-1n)),f(C,"MIN",new C(0)),f(C,"ZERO",new C(0)),f(C,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new C(r.value)),s.z.string().transform(r=>new C(BigInt(r))),s.z.instanceof(Number).transform(r=>new C(r)),s.z.number().transform(r=>new C(r)),s.z.instanceof(C)]));let I=C;const Tt=class ar extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ar(e).valueOf()}get period(){return I.seconds(1/this.valueOf())}sampleCount(e){return new I(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new F(t).valueOf()}span(e){return I.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new ar(e)}static khz(e){return ar.hz(e*1e3)}};f(Tt,"z",s.z.union([s.z.number().transform(r=>new Tt(r)),s.z.instanceof(Number).transform(r=>new Tt(r)),s.z.instanceof(Tt)]));let st=Tt;const q=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new it(e*this.valueOf())}};f(q,"UNKNOWN",new q(0)),f(q,"BIT128",new q(16)),f(q,"BIT64",new q(8)),f(q,"BIT32",new q(4)),f(q,"BIT16",new q(2)),f(q,"BIT8",new q(1)),f(q,"z",s.z.union([s.z.number().transform(r=>new q(r)),s.z.instanceof(Number).transform(r=>new q(r)),s.z.instanceof(q)]));let F=q;const ce=class or{constructor(e,t){f(this,"start"),f(this,"end"),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 I(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 or(this.end,this.start)}equals(e){return this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=I.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 I(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){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()}contains(e){return e instanceof or?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new or(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}};f(ce,"MAX",new ce(N.MIN,N.MAX)),f(ce,"MIN",new ce(N.MAX,N.MIN)),f(ce,"ZERO",new ce(N.ZERO,N.ZERO)),f(ce,"z",s.z.union([s.z.object({start:N.z,end:N.z}).transform(r=>new ce(r.start,r.end)),s.z.instanceof(ce)]));let W=ce;const p=class le extends String{constructor(e){if(e instanceof le||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=le.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(le.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=le.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(le.JSON)||this.equals(le.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(le.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=le.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}canSafelyCastTo(e){return this.equals(e)?!0:this.isVariable&&!e.isVariable||!this.isVariable&&e.isVariable?!1:this.isFloat&&e.isInteger||this.isInteger&&e.isFloat?this.density.valueOf()<e.density.valueOf():this.isFloat&&e.isFloat||this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf():!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return le.BIG_INT_TYPES.some(e=>e.equals(this))}};f(p,"UNKNOWN",new p("unknown")),f(p,"FLOAT64",new p("float64")),f(p,"FLOAT32",new p("float32")),f(p,"INT64",new p("int64")),f(p,"INT32",new p("int32")),f(p,"INT16",new p("int16")),f(p,"INT8",new p("int8")),f(p,"UINT64",new p("uint64")),f(p,"UINT32",new p("uint32")),f(p,"UINT16",new p("uint16")),f(p,"UINT8",new p("uint8")),f(p,"BOOLEAN",p.UINT8),f(p,"TIMESTAMP",new p("timestamp")),f(p,"UUID",new p("uuid")),f(p,"STRING",new p("string")),f(p,"JSON",new p("json")),f(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),f(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),f(p,"DENSITIES",new Map([[p.UINT8.toString(),F.BIT8],[p.UINT16.toString(),F.BIT16],[p.UINT32.toString(),F.BIT32],[p.UINT64.toString(),F.BIT64],[p.FLOAT32.toString(),F.BIT32],[p.FLOAT64.toString(),F.BIT64],[p.INT8.toString(),F.BIT8],[p.INT16.toString(),F.BIT16],[p.INT32.toString(),F.BIT32],[p.INT64.toString(),F.BIT64],[p.TIMESTAMP.toString(),F.BIT64],[p.STRING.toString(),F.UNKNOWN],[p.JSON.toString(),F.UNKNOWN],[p.UUID.toString(),F.BIT128]])),f(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),f(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),f(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let S=p;const V=class Z extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Z.bytes(this.valueOf()+e.valueOf())}sub(e){return Z.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Z(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Z.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Z.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Z.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Z.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Z.TERABYTE.valueOf()}toString(){const e=this.truncate(Z.TERABYTE),t=this.truncate(Z.GIGABYTE),n=this.truncate(Z.MEGABYTE),i=this.truncate(Z.KILOBYTE),a=this.truncate(Z.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),y=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!y.isZero||d==="")&&(d+=`${y.valueOf()}B`),d.trim()}static bytes(e=1){return new Z(e)}static kilobytes(e=1){return Z.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Z.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Z.megabytes(e.valueOf()*1e3)}static terabytes(e){return Z.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};f(V,"BYTE",new V(1)),f(V,"KILOBYTE",V.kilobytes(1)),f(V,"MEGABYTE",V.megabytes(1)),f(V,"GIGABYTE",V.gigabytes(1)),f(V,"TERABYTE",V.terabytes(1)),f(V,"ZERO",new V(0)),f(V,"z",s.z.union([s.z.number().transform(r=>new V(r)),s.z.instanceof(V)]));let it=V;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 wi=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof N||r instanceof I||r instanceof Date},kl=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):zt(t,-n).valueOf(),$l=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof ze?!0:wi(r),Te=-1,hn={[Symbol.iterator]:()=>hn,next:()=>({done:!0,value:void 0})},Al=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Rl=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),dn=10,Ot=class ue{constructor(e){f(this,"key",""),f(this,"isSynnaxSeries",!0),f(this,"dataType"),f(this,"sampleOffset"),f(this,"gl"),f(this,"_data"),f(this,"_timeRange"),f(this,"alignment",0n),f(this,"_cachedMin"),f(this,"_cachedMax"),f(this,"writePos",Te),f(this,"_refCount",0),f(this,"_cachedLength"),f(this,"_cachedIndexes"),$l(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=pi()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;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._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=wi(u),y=Array.isArray(u);if(t!=null)this.dataType=new S(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(y||h){let d=u;if(!h){if(u.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=u[0]}if(typeof d=="string")this.dataType=S.STRING;else if(typeof d=="number")this.dataType=S.FLOAT64;else if(typeof d=="bigint")this.dataType=S.INT64;else if(typeof d=="boolean")this.dataType=S.BOOLEAN;else if(d instanceof N||d instanceof Date||d instanceof N)this.dataType=S.TIMESTAMP;else if(typeof d=="object")this.dataType=S.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new S(u)}if(!y&&!h)this._data=u;else{let d=h?[u]:u;const P=d[0];(P instanceof N||P instanceof Date||P instanceof I)&&(d=d.map(D=>new N(D).valueOf())),this.dataType.equals(S.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
16
|
+
`)}
|
|
17
|
+
`)):this.dataType.equals(S.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(D=>rt.encodeString(D)).join(`
|
|
18
|
+
`)}
|
|
19
|
+
`)):this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,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 ue({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static generateTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(t.span(o)).valueOf());return new ue({data:a,dataType:S.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(`${e.join(`
|
|
20
|
+
`)}
|
|
21
|
+
`);return new ue({data:n,dataType:S.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(`${e.map(i=>rt.encodeString(i)).join(`
|
|
22
|
+
`)}
|
|
23
23
|
`);return new ue({data:n,dataType:S.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array 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 this._data instanceof ArrayBuffer||this._data instanceof SharedArrayBuffer?this._data:this._data.buffer}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(){if(!this.dataType.matches(S.STRING,S.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
|
|
24
24
|
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(S.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=S.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(S.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
|
|
25
|
-
`).slice(0,-1).map(t=>e.parse(rt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new it(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 it(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.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===dn&&(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]=kl(this.dataType,e,this.data[i],t);return new ue({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(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax==null&&(this._cachedMax=this.calcRawMax()),zt(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(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin==null&&(this._cachedMin=this.calcRawMin()),zt(this._cachedMin,this.sampleOffset))}get bounds(){return K(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return zt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return zt(n,this.sampleOffset)}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]===dn){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):ii(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=fl(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))throw new Error("Only FLOAT32 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.underlyingData,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Te}as(e){if(e==="string"){if(!this.dataType.equals(S.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(S.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:this.alignmentBounds,timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return K(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new xl(this);return this.dataType.equals(S.JSON)?new Cl(e):e}return new Pl(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ds(this,e,t??this.length)}subAlignmentIterator(e,t){return new ds(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ue({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 ue({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};f(Ot,"crudeZ",s.z.object({timeRange:W.z.optional(),dataType:S.z,alignment:Tl.optional(),data:s.z.union([$l,Rl,s.z.instanceof(ArrayBuffer)]),glBufferUsage:Il.optional().default("static").optional()})),f(Ot,"z",Ot.crudeZ.transform(r=>new Ot(r)));let ze=Ot,ds=class{constructor(e,t,n){f(this,"series"),f(this,"end"),f(this,"index"),this.series=e;const i=K(0,e.length);this.end=as(i,n),this.index=as(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class xl{constructor(e){if(f(this,"series"),f(this,"index"),f(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==dn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var ys,fs;class Cl{constructor(e){f(this,"wrapped"),f(this,ys,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:rt.decodeString(e.value)}}[(fs=Symbol.iterator,ys=Symbol.toStringTag,fs)](){return this}}var gs,ps;class Pl{constructor(e){f(this,"series"),f(this,"index"),f(this,gs,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(ps=Symbol.iterator,gs=Symbol.toStringTag,ps)](){return this}}const zt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);class bi{constructor(e){if(f(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new S(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?S.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?W.ZERO:new W(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?K(0n,0n):K(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const n of this.series)if(Kt(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 Gr(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return hn;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(Kt(o.alignmentBounds,e)){n+=Number(e-o.alignment);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(Kt(o.alignmentBounds,t)){i+=Number(t-o.alignment);break}}return new Gr(this,n,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return hn;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(Kt(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new Gr(this,n,n+t)}get byteLength(){return new it(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)}traverseAlignment(e,t){const n=this.series.map(i=>i.alignmentBounds);return Hc(n,e,t)}distance(e,t){const n=this.series.map(i=>i.alignmentBounds);return Xc(n,e,t)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Dl(this.series)}}var ms,ws;class Dl{constructor(e){f(this,"series"),f(this,"seriesIndex"),f(this,"internal"),f(this,ms,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(ws=Symbol.iterator,ms=Symbol.toStringTag,ws)](){return this}}class Gr{constructor(e,t,n){f(this,"series"),f(this,"index"),f(this,"end"),this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}s.z.object({key:s.z.string(),value:s.z.string()});var jl=Object.defineProperty,Ml=(r,e,t)=>e in r?jl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,cr=(r,e,t)=>Ml(r,typeof e!="symbol"?e+"":e,t);let Bl=class{constructor(e,t){cr(this,"handlers"),cr(this,"transform"),cr(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},Ul=class{constructor(e){cr(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const Pe=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Ul,Observer:Bl},Symbol.toStringTag,{value:"Module"})),Or=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),Zl=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Zl();const Ll=["MacOS","Windows","Linux","Docker"];s.z.enum(Ll);var _l=Object.defineProperty,Yl=(r,e,t)=>e in r?_l(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Et=(r,e,t)=>Yl(r,typeof e!="symbol"?e+"":e,t);const ql=(...r)=>r.map(vi).join(""),vi=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Wl=r=>r.endsWith("/")?r.slice(0,-1):r,yn=class fn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){Et(this,"protocol"),Et(this,"host"),Et(this,"port"),Et(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=vi(i)}replace(e){return new fn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new fn({...this,pathPrefix:ql(this.path,e)})}toString(){return Wl(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Et(yn,"UNKNOWN",new yn({host:"unknown",port:0}));let Gl=yn;var Vl=Object.defineProperty,Fl=(r,e,t)=>e in r?Vl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,lr=(r,e,t)=>Fl(r,typeof e!="symbol"?e+"":e,t);const Ae=class extends Number{};lr(Ae,"Absolute",255),lr(Ae,"Default",1),lr(Ae,"z",s.z.union([s.z.instanceof(Ae),s.z.number().int().min(0).max(255).transform(r=>new Ae(r)),s.z.instanceof(Number).transform(r=>new Ae(r))]));let Ti=Ae;const Oi=s.z.object({name:s.z.string(),key:s.z.string()}),Jl=r=>s.z.object({subject:Oi,resource:r,authority:Ti.z}),Kl=(...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}),at=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ti,filterTransfersByChannelKey:Kl,stateZ:Jl,subjectZ:Oi},Symbol.toStringTag,{value:"Module"})),zi=class St extends Error{constructor(){super(St.MESSAGE)}matches(e){return typeof e=="string"?e.includes(St.MESSAGE):e instanceof St||e.message.includes(St.MESSAGE)}};lr(zi,"MESSAGE","canceled");let Hl=zi;new Hl;const gn=s.z.string().regex(/^\d+\.\d+\.\d+$/),Mt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=gn.parse(r),i=gn.parse(e),[a,o,l]=n.split(".").map(Number),[u,h,y]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return qr;if(a>u)return Wr}if(t.checkMinor){if(o<h)return qr;if(o>h)return Wr}if(t.checkPatch){if(l<y)return qr;if(l>y)return Wr}return Tr},Xl=(r,e,t={})=>wl(Mt(r,e,t)),Ei=(r,e,t={})=>ml(Mt(r,e,t)),Ql=(r,e,t={})=>pl(Mt(r,e,t)),eu=({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}},tu=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(Mt).pop();if(a==null)return h=>{if(h.version==null&&(h.version=n),h.version!==i.version)return console.log(`${r} version ${h.version} is newer than latest version of ${i.version}.
|
|
25
|
+
`).slice(0,-1).map(t=>e.parse(rt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new it(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 it(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.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===dn&&(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]=kl(this.dataType,e,this.data[i],t);return new ue({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(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),zt(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(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),zt(this._cachedMin,this.sampleOffset))}get bounds(){return K(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return zt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return zt(n,this.sampleOffset)}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]===dn){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):ii(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=fl(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))throw new Error("Only FLOAT32 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.underlyingData,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Te}as(e){if(e==="string"){if(!this.dataType.equals(S.STRING))throw new Error(`cannot convert series of type ${this.dataType.toString()} to string`);return this}if(e==="number"){if(!this.dataType.isNumeric)throw new Error(`cannot convert series of type ${this.dataType.toString()} to number`);return this}if(e==="bigint"){if(!this.dataType.equals(S.INT64))throw new Error(`cannot convert series of type ${this.dataType.toString()} to bigint`);return this}throw new Error(`cannot convert series to ${e}`)}get digest(){var e;return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:this.alignmentBounds,timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return K(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new xl(this);return this.dataType.equals(S.JSON)?new Cl(e):e}return new Pl(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ds(this,e,t??this.length)}subAlignmentIterator(e,t){return new ds(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ue({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 ue({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};f(Ot,"crudeZ",s.z.object({timeRange:W.z.optional(),dataType:S.z,alignment:Tl.optional(),data:s.z.union([Al,Rl,s.z.instanceof(ArrayBuffer)]),glBufferUsage:Il.optional().default("static").optional()})),f(Ot,"z",Ot.crudeZ.transform(r=>new Ot(r)));let ze=Ot,ds=class{constructor(e,t,n){f(this,"series"),f(this,"end"),f(this,"index"),this.series=e;const i=K(0,e.length);this.end=as(i,n),this.index=as(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class xl{constructor(e){if(f(this,"series"),f(this,"index"),f(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==dn;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}[Symbol.iterator](){return this}}var ys,fs;class Cl{constructor(e){f(this,"wrapped"),f(this,ys,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:rt.decodeString(e.value)}}[(fs=Symbol.iterator,ys=Symbol.toStringTag,fs)](){return this}}var gs,ps;class Pl{constructor(e){f(this,"series"),f(this,"index"),f(this,gs,"SeriesIterator"),this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[(ps=Symbol.iterator,gs=Symbol.toStringTag,ps)](){return this}}const zt=(r,e)=>typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:e===0?r:r===0?e:Number(r)+Number(e);class bi{constructor(e){if(f(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new S(e).equals(this.dataType))throw new Error(`cannot convert series of type ${this.dataType.toString()} to ${e.toString()}`);return this}get dataType(){return this.series.length===0?S.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?W.ZERO:new W(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?K(0n,0n):K(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const n of this.series)if(Kt(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 Gr(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return hn;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(Kt(o.alignmentBounds,e)){n+=Number(e-o.alignment);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(Kt(o.alignmentBounds,t)){i+=Number(t-o.alignment);break}}return new Gr(this,n,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return hn;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(Kt(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new Gr(this,n,n+t)}get byteLength(){return new it(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)}traverseAlignment(e,t){const n=this.series.map(i=>i.alignmentBounds);return Hc(n,e,t)}distance(e,t){const n=this.series.map(i=>i.alignmentBounds);return Xc(n,e,t)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Dl(this.series)}}var ms,ws;class Dl{constructor(e){f(this,"series"),f(this,"seriesIndex"),f(this,"internal"),f(this,ms,"MultiSeriesIterator"),this.series=e,this.seriesIndex=0,this.internal=e[0][Symbol.iterator]()}next(){const e=this.internal.next();return e.done===!1?e:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[(ws=Symbol.iterator,ms=Symbol.toStringTag,ws)](){return this}}class Gr{constructor(e,t,n){f(this,"series"),f(this,"index"),f(this,"end"),this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}s.z.object({key:s.z.string(),value:s.z.string()});var jl=Object.defineProperty,Ml=(r,e,t)=>e in r?jl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,cr=(r,e,t)=>Ml(r,typeof e!="symbol"?e+"":e,t);let Bl=class{constructor(e,t){cr(this,"handlers"),cr(this,"transform"),cr(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},Ul=class{constructor(e){cr(this,"handlers"),this.handlers=e??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){this.handlers.forEach((t,n)=>n(e))}};const Pe=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Ul,Observer:Bl},Symbol.toStringTag,{value:"Module"})),Or=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),Zl=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Zl();const Ll=["MacOS","Windows","Linux","Docker"];s.z.enum(Ll);var _l=Object.defineProperty,Yl=(r,e,t)=>e in r?_l(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Et=(r,e,t)=>Yl(r,typeof e!="symbol"?e+"":e,t);const ql=(...r)=>r.map(vi).join(""),vi=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Wl=r=>r.endsWith("/")?r.slice(0,-1):r,yn=class fn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){Et(this,"protocol"),Et(this,"host"),Et(this,"port"),Et(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=vi(i)}replace(e){return new fn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new fn({...this,pathPrefix:ql(this.path,e)})}toString(){return Wl(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Et(yn,"UNKNOWN",new yn({host:"unknown",port:0}));let Gl=yn;var Vl=Object.defineProperty,Fl=(r,e,t)=>e in r?Vl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,lr=(r,e,t)=>Fl(r,typeof e!="symbol"?e+"":e,t);const $e=class extends Number{};lr($e,"Absolute",255),lr($e,"Default",1),lr($e,"z",s.z.union([s.z.instanceof($e),s.z.number().int().min(0).max(255).transform(r=>new $e(r)),s.z.instanceof(Number).transform(r=>new $e(r))]));let Ti=$e;const Oi=s.z.object({name:s.z.string(),key:s.z.string()}),Jl=r=>s.z.object({subject:Oi,resource:r,authority:Ti.z}),Kl=(...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}),at=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ti,filterTransfersByChannelKey:Kl,stateZ:Jl,subjectZ:Oi},Symbol.toStringTag,{value:"Module"})),zi=class St extends Error{constructor(){super(St.MESSAGE)}matches(e){return typeof e=="string"?e.includes(St.MESSAGE):e instanceof St||e.message.includes(St.MESSAGE)}};lr(zi,"MESSAGE","canceled");let Hl=zi;new Hl;const gn=s.z.string().regex(/^\d+\.\d+\.\d+$/),Mt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=gn.parse(r),i=gn.parse(e),[a,o,l]=n.split(".").map(Number),[u,h,y]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return qr;if(a>u)return Wr}if(t.checkMinor){if(o<h)return qr;if(o>h)return Wr}if(t.checkPatch){if(l<y)return qr;if(l>y)return Wr}return Tr},Xl=(r,e,t={})=>wl(Mt(r,e,t)),Ei=(r,e,t={})=>ml(Mt(r,e,t)),Ql=(r,e,t={})=>pl(Mt(r,e,t)),eu=({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}},tu=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(Mt).pop();if(a==null)return h=>{if(h.version??(h.version=n),h.version!==i.version)return console.log(`${r} version ${h.version} is newer than latest version of ${i.version}.
|
|
26
26
|
Returning default instead.
|
|
27
|
-
`),i;try{return t!=null?t.parse(h):h}catch(y){return console.log(`${r} failed to parse default. Exiting with default`),console.error(y),i}};const o=Object.keys(e).length;let l=!1;const u=h=>{try{if(o===0||Ei(h.version,a))return console.log(l?`${r} ${h.version} now up to date`:`${r} version ${h.version} is up to date with target version ${i.version}`),h;const y=h.version,d=e[y],P=d(h);return l=!0,u(P)}catch(y){return console.log(`${r} failed to migrate from ${h.version} to ${a}`),console.error(y),i}};return h=>{try{if(h.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),h.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),i;return u(h)}catch(y){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(y),i}}},bs=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Mt,createMigration:eu,migrator:tu,semVerNewer:Ei,semVerOlder:Ql,semVerZ:gn,versionsEqual:Xl},Symbol.toStringTag,{value:"Module"})),Ie="sy.",_e=class _e extends se{constructor(){super(...arguments);c(this,"type",_e.TYPE)}};c(_e,"TYPE"
|
|
27
|
+
`),i;try{return t!=null?t.parse(h):h}catch(y){return console.log(`${r} failed to parse default. Exiting with default`),console.error(y),i}};const o=Object.keys(e).length;let l=!1;const u=h=>{try{if(o===0||Ei(h.version,a))return console.log(l?`${r} ${h.version} now up to date`:`${r} version ${h.version} is up to date with target version ${i.version}`),h;const y=h.version,d=e[y],P=d(h);return l=!0,u(P)}catch(y){return console.log(`${r} failed to migrate from ${h.version} to ${a}`),console.error(y),i}};return h=>{try{if(h.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),h.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),i;return u(h)}catch(y){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(y),i}}},bs=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Mt,createMigration:eu,migrator:tu,semVerNewer:Ei,semVerOlder:Ql,semVerZ:gn,versionsEqual:Xl},Symbol.toStringTag,{value:"Module"})),Ie="sy.",_e=class _e extends se{constructor(){super(...arguments);c(this,"type",_e.TYPE)}};c(_e,"TYPE",`${Ie}validation`),c(_e,"matches",X(_e.TYPE));let M=_e;const Ye=class Ye extends M{constructor(t,n){super(`${t}: ${n}`);c(this,"type",Ye.TYPE);c(this,"field");c(this,"message");this.field=t,this.message=n}};c(Ye,"TYPE",`${M.TYPE}.field`),c(Ye,"matches",X(Ye.TYPE));let fr=Ye;const qe=class qe extends se{constructor(){super(...arguments);c(this,"type",qe.TYPE)}};c(qe,"TYPE",`${Ie}auth`),c(qe,"matches",X(qe.TYPE));let De=qe;const We=class We extends De{constructor(){super(...arguments);c(this,"type",We.TYPE)}};c(We,"TYPE",`${De.TYPE}.invalid-token`),c(We,"matches",X(We.TYPE));let At=We;const Ge=class Ge extends se{constructor(t){super(`
|
|
28
28
|
Unexpected error encountered:
|
|
29
29
|
|
|
30
30
|
${t}
|
|
31
31
|
|
|
32
32
|
Please report this to the Synnax team.
|
|
33
|
-
`);c(this,"type",Ge.TYPE)}};c(Ge,"TYPE",Ie+"unexpected"),c(Ge,"matches",X(Ge.TYPE));let Se=Ge;const Ve=class Ve extends se{constructor(){super(...arguments);c(this,"type",Ve.TYPE)}};c(Ve,"TYPE",Ie+"query"),c(Ve,"matches",X(Ve.TYPE));let re=Ve;const Fe=class Fe extends re{constructor(){super(...arguments);c(this,"type",Fe.TYPE)}};c(Fe,"TYPE",re.TYPE+".not_found"),c(Fe,"matches",X(Fe.TYPE));let pe=Fe;const Je=class Je extends re{constructor(){super(...arguments);c(this,"type",Je.TYPE)}};c(Je,"TYPE",re.TYPE+".multiple_results"),c(Je,"matches",X(Je.TYPE));let me=Je;const Ke=class Ke extends se{constructor(t,n){super(t);c(this,"type",Ke.TYPE);c(this,"path");this.path=n}};c(Ke,"TYPE",Ie+"route"),c(Ke,"matches",X(Ke.TYPE));let Rt=Ke;const He=class He extends se{constructor(){super(...arguments);c(this,"type",He.TYPE)}};c(He,"TYPE",Ie+"control"),c(He,"matches",X(He.TYPE));let ot=He;const Xe=class Xe extends ot{constructor(){super(...arguments);c(this,"type",Xe.TYPE)}};c(Xe,"TYPE",ot.TYPE+".unauthorized"),c(Xe,"matches",X(Xe.TYPE));let gr=Xe;const Qe=class Qe extends se{constructor(){super(...arguments);c(this,"type",Qe.TYPE)}};c(Qe,"TYPE",Ie+"contiguity"),c(Qe,"matches",X(Qe.TYPE));let pn=Qe;const ru=r=>{if(!r.type.startsWith(Ie))return null;if(r.type.startsWith(M.TYPE)){if(r.type===fr.TYPE){const e=r.data.split(": ");return e.length<2?new M(r.data):new fr(e[0],e[1])}return new M(r.data)}return r.type.startsWith(De.TYPE)?r.type.startsWith($t.TYPE)?new $t(r.data):new De(r.data):r.type.startsWith(Se.TYPE)?new Se(r.data):r.type.startsWith(re.TYPE)?r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(me.TYPE)?new me(r.data):new re(r.data):r.type.startsWith(ot.TYPE)?r.type.startsWith(gr.TYPE)?new gr(r.data):new ot(r.data):r.type.startsWith(Rt.TYPE)?new Rt(r.data,r.data):new Se(r.data)},nu=()=>{throw new Error("Not implemented")};Ks({encode:nu,decode:ru});const su=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ce?[t,new Ce({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Si{constructor(e,t){c(this,"key");c(this,"name");this.key=t,this.name=e}get ontologyID(){return new v({type:"group",key:this.key})}}const iu=s.z.string().uuid(),Ni=s.z.object({key:iu,name:s.z.string()}),Bt=s.z.union([s.z.literal("label"),s.z.literal("log"),s.z.literal("allow_all"),s.z.literal("builtin"),s.z.literal("cluster"),s.z.literal("channel"),s.z.literal("node"),s.z.literal("group"),s.z.literal("range"),s.z.literal("framer"),s.z.literal("range-alias"),s.z.literal("user"),s.z.literal("workspace"),s.z.literal("schematic"),s.z.literal("lineplot"),s.z.literal("rack"),s.z.literal("device"),s.z.literal("task"),s.z.literal("policy")]),au="builtin",ou="cluster",cu="node",H=s.z.object({type:Bt,key:s.z.string()}),Ii=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Bt.parse(e),key:t??""}}),Le=s.z.union([Ii,H]),et=class et{constructor(e){c(this,"type");c(this,"key");if(e instanceof et){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};c(et,"z",s.z.union([s.z.instanceof(et),Le.transform(e=>new et(e))]));let v=et;const lu=new v({type:"builtin",key:"root"}),ki=s.z.object({type:s.z.number()}),Ai=s.z.object({type:Bt,fields:s.z.record(ki)}),$i=s.z.object({id:v.z,name:s.z.string(),schema:Ai.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),uu=s.z.object({from:v.z,type:s.z.string(),to:v.z}),mn=r=>{const[e,t,n]=r.split("->");return{from:new v(e),type:t,to:new v(n)}},hu=s.z.object({group:Ni}),du=s.z.object({parent:H,key:s.z.string().uuid().optional(),name:s.z.string()}),yu=s.z.object({key:s.z.string(),name:s.z.string()}),fu=s.z.object({keys:s.z.array(s.z.string())});var ne;let gu=(ne=class{constructor(e){c(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,ne.ENDPOINT,{parent:e,name:t,key:n},du,hu)).group}async rename(e,t){await w(this.client,ne.ENDPOINT_RENAME,{key:e,name:t},yu,s.z.object({}))}async delete(e){await w(this.client,ne.ENDPOINT_DELETE,{keys:e},fu,s.z.object({}))}},c(ne,"ENDPOINT","/ontology/create-group"),c(ne,"ENDPOINT_RENAME","/ontology/rename-group"),c(ne,"ENDPOINT_DELETE","/ontology/delete-group"),ne),pu=class{constructor(e){c(this,"creator");this.creator=new gu(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 Si(e.name,e.key)}};const Vr={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},vs=s.z.object({id:H,children:H.array()}),mu=s.z.object({from:H,to:H,children:H.array()});let wu=class{constructor(e){c(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Vr.ADD_CHILDREN,{id:new v(e).payload,children:t.map(n=>new v(n).payload)},vs,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Vr.REMOVE_CHILDREN,{id:new v(e).payload,children:t.map(n=>new v(n).payload)},vs,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new v(e).payload,to:new v(t).payload,children:n.map(a=>new v(a).payload)};await w(this.client,Vr.MOVE_CHILDREN,i,mu,s.z.object({}))}};const bu="/ontology/retrieve",vu=s.z.object({ids:H.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),includeSchema:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),term:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:Bt.array().optional()}),Tu=s.z.object({resources:$i.array()}),ur=r=>b(r).map(e=>new v(e).payload);let Ri=class{constructor(e,t){c(this,"type","ontology");c(this,"groups");c(this,"client");c(this,"writer");c(this,"framer");this.client=e,this.writer=new wu(e),this.groups=new pu(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:ur(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new re(`No resource found with ID ${e.toString()}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:ur(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:ur(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await Ut.open(this.framer,this)}async openDependentTracker(e){return await zr.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,bu,e,vu,Tu);return t}};const Ts="sy_ontology_resource_set",Os="sy_ontology_resource_delete",zs="sy_ontology_relationship_set",Es="sy_ontology_relationship_delete";class Ut{constructor(e,t){c(this,"relationships");c(this,"resources");c(this,"resourceObs");c(this,"relationshipObs");c(this,"streamer");c(this,"client");c(this,"closePromise");this.relationshipObs=new Pe.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Pe.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(zs);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:mn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Es);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:mn(n)}))}async parseResourceSets(e){const t=e.get(Ts);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new v(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof re)return[];throw i}}parseResourceDeletes(e){const t=e.get(Os);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new v(n)}))}static async open(e,t){const n=await e.openStreamer([Ts,Os,zs,Es]);return new Ut(n,t)}}const Ss=r=>r==="from"?"to":"from";class zr extends Pe.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:o},l,u){super();c(this,"internal");c(this,"target");c(this,"relDir");c(this,"resourceType");c(this,"dependents");c(this,"client");c(this,"relType");c(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const i=t.find(a=>a.key.toString()==n.id.toString());return i==null||i.variant==="delete"?n:i.value}),this.notify(this.dependents)});c(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Ss(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Ss(this.relDir)].type===this.resourceType));if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)})});this.resourceType=o,this.internal=l,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(h=>h.id.type===this.resourceType)),this.client=u,this.relType=i,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,i){const a=await Ut.open(n,i);return new zr(t,a,i)}async close(){await this.internal.close()}}const Ou=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:au,CLUSTER_TYPE:ou,ChangeTracker:Ut,Client:Ri,DependentTracker:zr,ID:v,NODE_TYPE:cu,Root:lu,crudeIDZ:Le,idZ:H,parseIDs:ur,parseRelationship:mn,relationshipSchemaZ:uu,resourceSchemaZ:$i,resourceTypeZ:Bt,schemaFieldZ:ki,schemaZ:Ai,stringIDZ:Ii},Symbol.toStringTag,{value:"Module"})),te=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),Zt=s.z.string().uuid(),xi=s.z.object({key:Zt.optional(),subjects:Le.array().or(Le),objects:Le.array().or(Le),actions:dr.array().or(dr)}),Er=s.z.object({key:Zt,subjects:te(H),objects:te(H),actions:te(dr)}),Ci="policy",zu=r=>new v({type:Ci,key:r}),Pi="allow_all",Eu=new v({type:Pi,key:""}),Su=s.z.object({keys:Zt.array().optional(),subjects:H.array().optional()}),Nu=s.z.object({policies:te(Er)}),Iu="/access/policy/retrieve";let ku=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Iu,e,Su,Nu)).policies}};const Au=s.z.object({policies:Er.partial({key:!0}).array()}),$u=s.z.object({policies:Er.array()}),Ru=s.z.object({keys:Zt.array()}),xu=s.z.object({}),Cu="/access/policy/create",Pu="/access/policy/delete";let Du=class{constructor(e){c(this,"client");this.client=e}async create(e){const n=xi.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await w(this.client,Cu,{policies:n},Au,$u)).policies}async delete(e){await w(this.client,Pu,{keys:b(e)},Ru,xu)}},Di=class{constructor(e){c(this,"retriever");c(this,"writer");this.retriever=new ku(e),this.writer=new Du(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve({keys:b(e)});return t?n:n[0]}async retrieveFor(e){const t=b(e).map(n=>new v(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const ju=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Eu,ALLOW_ALL_ONTOLOGY_TYPE:Pi,Client:Di,ONTOLOGY_TYPE:Ci,keyZ:Zt,newPolicyZ:xi,ontologyID:zu,policyZ:Er},Symbol.toStringTag,{value:"Module"}));let ji=class{constructor(e){c(this,"policy");this.policy=new Di(e)}};const Mu=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:Oc,CREATE_ACTION:zc,Client:ji,DELETE_ACTION:Ec,RETRIEVE_ACTION:Sc,UPDATE_ACTION:Nc,actionZ:dr},Symbol.toStringTag,{value:"Module"})),ke=s.z.number(),Lt=s.z.object({name:s.z.string(),key:s.z.number(),rate:st.z,dataType:S.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional()}),Mi=Lt.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:st.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Bi="channel",Bu=r=>new v({type:Bi,key:r.toString()}),Uu=new Error("request for lock canceled");var Zu=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 l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class Lu{constructor(e,t=Uu){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=Ui(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return Zu(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]=[]),_u(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 _u(r,e){const t=Ui(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Ui(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Yu=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 l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class qu{constructor(e){this._semaphore=new Lu(1,e)}acquire(){return Yu(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 Sr=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=b(r);const a=i[0],o=typeof a;let l;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[o],{single:n,variant:l,normalized:i,actual:r}},Nr=(r,e,t,n)=>{if(n){if(t.length===0)throw new pe(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new me(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Wu=s.z.object({leaseholder:s.z.number().optional(),keys:s.z.number().array().optional(),names:s.z.string().array().optional(),search: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()}),Gu=s.z.object({channels:te(Lt)}),we=r=>Sr(r,{number:"keys",string:"names"}),mr=class mr{constructor(e){c(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=we(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 page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(mr.ENDPOINT,e,Wu,Gu);if(n!=null)throw n;return t.channels}};c(mr,"ENDPOINT","/channel/retrieve");let xt=mr;class Sn{constructor(e){c(this,"cache");c(this,"namesToKeys");c(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=Sr(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),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}=we(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 l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.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 Zi{constructor(e,t){c(this,"mu",new qu);c(this,"requests",new Map);c(this,"wrapped");c(this,"debouncedRun");this.wrapped=e,this.debouncedRun=bl(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=we(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 Li=async(r,e)=>{const{normalized:t}=we(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 re(`Could not find channels: ${JSON.stringify(i)}`);return n};class Nn{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:o=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:y,alias:d}){c(this,"_frameClient");c(this,"key");c(this,"name");c(this,"rate");c(this,"dataType");c(this,"leaseholder");c(this,"index");c(this,"isIndex");c(this,"internal");c(this,"alias");c(this,"virtual");this.key=a,this.name=n,this.rate=new st(t??0),this.dataType=new S(e),this.leaseholder=i,this.index=l,this.isIndex=o,this.internal=u,this.alias=d,this.virtual=h,this._frameClient=y??null}get framer(){if(this._frameClient==null)throw new M("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Lt.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal})}get ontologyID(){return new v({type:"channel",key:this.key.toString()})}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 Vu="/channel/retrieve-group",Fu=s.z.object({}),Ju=s.z.object({group:Ni});let _i=class{constructor(e,t,n,i){c(this,"type","channel");c(this,"frameClient");c(this,"client");c(this,"retriever");c(this,"writer");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=b(e),o=[];if(n){const l=await this.retriever.retrieve(a.map(h=>h.name)),u=new Set(l.map(h=>h.name));a=a.filter(h=>!u.has(h.name)),o=this.sugar(l)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return Nr("channel",e,i,n),n?i[0]:i}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=we(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new Sn(new Zi(new xt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Nn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Vu,{},Fu,Ju);return new Si(e.group.name,e.group.key)}};const Ku=s.z.object({channels:Mi.array()}),Hu=s.z.object({channels:Lt.array()}),Xu=s.z.object({keys:ke.array().optional(),names:s.z.string().array().optional()}),Qu=s.z.object({}),eh=s.z.object({keys:ke.array(),names:s.z.string().array()}),th=s.z.object({}),rh="/channel/create",nh="/channel/delete",sh="/channel/rename";let Yi=class{constructor(e,t){c(this,"client");c(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,rh,{channels:e},Ku,Hu);return this.cache.set(t),t}async delete(e){await w(this.client,nh,e,Xu,Qu),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,sh,{keys:e,names:t},eh,th),this.cache.rename(e,t)}};const ih=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:Sn,Channel:Nn,Client:_i,ClusterRetriever:xt,DebouncedBatchRetriever:Zi,ONTOLOGY_TYPE:Bi,Writer:Yi,analyzeChannelParams:we,keyZ:ke,newPayload:Mi,ontologyID:Bu,payload:Lt,retrieveRequired:Li},Symbol.toStringTag,{value:"Module"})),ht=s.z.string().uuid(),_t=s.z.object({key:ht,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),qi=_t.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Wi="user",ah=r=>new v({type:Wi,key:r}),oh=s.z.object({keys:ht.array().optional(),usernames:s.z.string().array().optional()}),ch=s.z.object({users:te(_t)}),lh="/user/retrieve";let uh=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,lh,e,oh,ch)).users}};const hh=s.z.object({users:qi.array()}),dh=s.z.object({users:_t.array()}),yh=s.z.object({key:ht,username:s.z.string().min(1)}),fh=s.z.object({}),gh=s.z.object({key:ht,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),ph=s.z.object({}),mh=s.z.object({keys:ht.array()}),wh=s.z.object({}),bh="/user/create",vh="/user/change-username",Th="/user/rename",Oh="/user/delete";let zh=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,bh,{users:b(e)},hh,dh)).users}async changeUsername(e,t){await w(this.client,vh,{key:e,username:t},yh,fh)}async rename(e,t,n){await w(this.client,Th,{key:e,firstName:t,lastName:n},gh,ph)}async delete(e){await w(this.client,Oh,{keys:b(e)},mh,wh)}},Gi=class{constructor(e){c(this,"reader");c(this,"writer");this.writer=new zh(e),this.reader=new uh(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.reader.retrieve({keys:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with key ${e} found`);if(n.length>1)throw new me(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with username ${e} found`);if(n.length>1)throw new me(`Multiple users found with username ${e}`);return n[0]}async rename(e,t,n){await this.writer.rename(e,t,n)}async delete(e){await this.writer.delete(e)}};const Eh=Object.freeze(Object.defineProperty({__proto__:null,Client:Gi,ONTOLOGY_TYPE:Wi,keyZ:ht,newUserZ:qi,ontologyID:ah,userZ:_t},Symbol.toStringTag,{value:"Module"})),Sh=s.z.object({username:s.z.string(),password:s.z.string()}),Nh=s.z.object({token:s.z.string(),user:_t}),Ns="/auth/login",Ih=3,kh="/auth/change-password",Ah=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),$h=s.z.object({});let Rh=class{constructor(e,t){c(this,"token");c(this,"client");c(this,"credentials");c(this,"authenticating");c(this,"authenticated");c(this,"user");c(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await w(this.client,kh,{username:this.credentials.username,password:this.credentials.password,newPassword:e},Ah,$h),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(Ns)){this.authenticating==null&&(this.authenticating=new Promise((l,u)=>{this.client.send(Ns,this.credentials,Sh,Nh).then(([h,y])=>{if(y!=null)return l(y);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(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 $t.matches(a)&&this.retryCount<Ih?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const xh=["disconnected","connecting","connected","failed"],Vi=s.z.enum(xh),Fi=s.z.object({status:Vi,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()}),Ch=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Is={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.33.0"},ks=(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}.
|
|
33
|
+
`);c(this,"type",Ge.TYPE)}};c(Ge,"TYPE",`${Ie}unexpected`),c(Ge,"matches",X(Ge.TYPE));let Se=Ge;const Ve=class Ve extends se{constructor(){super(...arguments);c(this,"type",Ve.TYPE)}};c(Ve,"TYPE",`${Ie}query`),c(Ve,"matches",X(Ve.TYPE));let re=Ve;const Fe=class Fe extends re{constructor(){super(...arguments);c(this,"type",Fe.TYPE)}};c(Fe,"TYPE",`${re.TYPE}.not_found`),c(Fe,"matches",X(Fe.TYPE));let pe=Fe;const Je=class Je extends re{constructor(){super(...arguments);c(this,"type",Je.TYPE)}};c(Je,"TYPE",`${re.TYPE}.multiple_results`),c(Je,"matches",X(Je.TYPE));let me=Je;const Ke=class Ke extends se{constructor(t,n){super(t);c(this,"type",Ke.TYPE);c(this,"path");this.path=n}};c(Ke,"TYPE",`${Ie}route`),c(Ke,"matches",X(Ke.TYPE));let Rt=Ke;const He=class He extends se{constructor(){super(...arguments);c(this,"type",He.TYPE)}};c(He,"TYPE",`${Ie}control`),c(He,"matches",X(He.TYPE));let ot=He;const Xe=class Xe extends ot{constructor(){super(...arguments);c(this,"type",Xe.TYPE)}};c(Xe,"TYPE",`${ot.TYPE}.unauthorized`),c(Xe,"matches",X(Xe.TYPE));let gr=Xe;const Qe=class Qe extends se{constructor(){super(...arguments);c(this,"type",Qe.TYPE)}};c(Qe,"TYPE",`${Ie}contiguity`),c(Qe,"matches",X(Qe.TYPE));let pn=Qe;const ru=r=>{if(!r.type.startsWith(Ie))return null;if(r.type.startsWith(M.TYPE)){if(r.type===fr.TYPE){const e=r.data.split(": ");return e.length<2?new M(r.data):new fr(e[0],e[1])}return new M(r.data)}return r.type.startsWith(De.TYPE)?r.type.startsWith(At.TYPE)?new At(r.data):new De(r.data):r.type.startsWith(Se.TYPE)?new Se(r.data):r.type.startsWith(re.TYPE)?r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(me.TYPE)?new me(r.data):new re(r.data):r.type.startsWith(ot.TYPE)?r.type.startsWith(gr.TYPE)?new gr(r.data):new ot(r.data):r.type.startsWith(Rt.TYPE)?new Rt(r.data,r.data):new Se(r.data)},nu=()=>{throw new Error("Not implemented")};Ks({encode:nu,decode:ru});const su=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ce?[t,new Ce({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Si{constructor(e,t){c(this,"key");c(this,"name");this.key=t,this.name=e}get ontologyID(){return new v({type:"group",key:this.key})}}const iu=s.z.string().uuid(),Ni=s.z.object({key:iu,name:s.z.string()}),Bt=s.z.union([s.z.literal("label"),s.z.literal("log"),s.z.literal("allow_all"),s.z.literal("builtin"),s.z.literal("cluster"),s.z.literal("channel"),s.z.literal("node"),s.z.literal("group"),s.z.literal("range"),s.z.literal("framer"),s.z.literal("range-alias"),s.z.literal("user"),s.z.literal("workspace"),s.z.literal("schematic"),s.z.literal("lineplot"),s.z.literal("rack"),s.z.literal("device"),s.z.literal("task"),s.z.literal("policy")]),au="builtin",ou="cluster",cu="node",H=s.z.object({type:Bt,key:s.z.string()}),Ii=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Bt.parse(e),key:t??""}}),Le=s.z.union([Ii,H]),et=class et{constructor(e){c(this,"type");c(this,"key");if(e instanceof et){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};c(et,"z",s.z.union([s.z.instanceof(et),Le.transform(e=>new et(e))]));let v=et;const lu=new v({type:"builtin",key:"root"}),ki=s.z.object({type:s.z.number()}),$i=s.z.object({type:Bt,fields:s.z.record(ki)}),Ai=s.z.object({id:v.z,name:s.z.string(),schema:$i.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),uu=s.z.object({from:v.z,type:s.z.string(),to:v.z}),mn=r=>{const[e,t,n]=r.split("->");return{from:new v(e),type:t,to:new v(n)}},hu=s.z.object({group:Ni}),du=s.z.object({parent:H,key:s.z.string().uuid().optional(),name:s.z.string()}),yu=s.z.object({key:s.z.string(),name:s.z.string()}),fu=s.z.object({keys:s.z.array(s.z.string())});var ne;let gu=(ne=class{constructor(e){c(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,ne.ENDPOINT,{parent:e,name:t,key:n},du,hu)).group}async rename(e,t){await w(this.client,ne.ENDPOINT_RENAME,{key:e,name:t},yu,s.z.object({}))}async delete(e){await w(this.client,ne.ENDPOINT_DELETE,{keys:e},fu,s.z.object({}))}},c(ne,"ENDPOINT","/ontology/create-group"),c(ne,"ENDPOINT_RENAME","/ontology/rename-group"),c(ne,"ENDPOINT_DELETE","/ontology/delete-group"),ne),pu=class{constructor(e){c(this,"creator");this.creator=new gu(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 Si(e.name,e.key)}};const Vr={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},vs=s.z.object({id:H,children:H.array()}),mu=s.z.object({from:H,to:H,children:H.array()});let wu=class{constructor(e){c(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Vr.ADD_CHILDREN,{id:new v(e).payload,children:t.map(n=>new v(n).payload)},vs,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Vr.REMOVE_CHILDREN,{id:new v(e).payload,children:t.map(n=>new v(n).payload)},vs,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new v(e).payload,to:new v(t).payload,children:n.map(a=>new v(a).payload)};await w(this.client,Vr.MOVE_CHILDREN,i,mu,s.z.object({}))}};const bu="/ontology/retrieve",vu=s.z.object({ids:H.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),includeSchema:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),term:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:Bt.array().optional()}),Tu=s.z.object({resources:Ai.array()}),ur=r=>b(r).map(e=>new v(e).payload);let Ri=class{constructor(e,t){c(this,"type","ontology");c(this,"groups");c(this,"client");c(this,"writer");c(this,"framer");this.client=e,this.writer=new wu(e),this.groups=new pu(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const n=await this.execRetrieve({ids:ur(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new re(`No resource found with ID ${e.toString()}`);return n[0]}async page(e,t,n){return await this.execRetrieve({offset:e,limit:t,...n})}async retrieveChildren(e,t){return await this.execRetrieve({ids:ur(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:ur(e),parents:!0,...t})}async addChildren(e,...t){return await this.writer.addChildren(e,...t)}async removeChildren(e,...t){return await this.writer.removeChildren(e,...t)}async moveChildren(e,t,...n){return await this.writer.moveChildren(e,t,...n)}async openChangeTracker(){return await Ut.open(this.framer,this)}async openDependentTracker(e){return await zr.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,bu,e,vu,Tu);return t}};const Ts="sy_ontology_resource_set",Os="sy_ontology_resource_delete",zs="sy_ontology_relationship_set",Es="sy_ontology_relationship_delete";class Ut{constructor(e,t){c(this,"relationships");c(this,"resources");c(this,"resourceObs");c(this,"relationshipObs");c(this,"streamer");c(this,"client");c(this,"closePromise");this.relationshipObs=new Pe.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Pe.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(zs);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:mn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Es);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:mn(n)}))}async parseResourceSets(e){const t=e.get(Ts);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new v(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof re)return[];throw i}}parseResourceDeletes(e){const t=e.get(Os);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new v(n)}))}static async open(e,t){const n=await e.openStreamer([Ts,Os,zs,Es]);return new Ut(n,t)}}const Ss=r=>r==="from"?"to":"from";class zr extends Pe.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:o},l,u){super();c(this,"internal");c(this,"target");c(this,"relDir");c(this,"resourceType");c(this,"dependents");c(this,"client");c(this,"relType");c(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const i=t.find(a=>a.key.toString()==n.id.toString());return i==null||i.variant==="delete"?n:i.value}),this.notify(this.dependents)});c(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Ss(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Ss(this.relDir)].type===this.resourceType));if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)})});this.resourceType=o,this.internal=l,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(h=>h.id.type===this.resourceType)),this.client=u,this.relType=i,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,i){const a=await Ut.open(n,i);return new zr(t,a,i)}async close(){await this.internal.close()}}const Ou=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:au,CLUSTER_TYPE:ou,ChangeTracker:Ut,Client:Ri,DependentTracker:zr,ID:v,NODE_TYPE:cu,Root:lu,crudeIDZ:Le,idZ:H,parseIDs:ur,parseRelationship:mn,relationshipSchemaZ:uu,resourceSchemaZ:Ai,resourceTypeZ:Bt,schemaFieldZ:ki,schemaZ:$i,stringIDZ:Ii},Symbol.toStringTag,{value:"Module"})),te=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),Zt=s.z.string().uuid(),xi=s.z.object({key:Zt.optional(),subjects:Le.array().or(Le),objects:Le.array().or(Le),actions:dr.array().or(dr)}),Er=s.z.object({key:Zt,subjects:te(H),objects:te(H),actions:te(dr)}),Ci="policy",zu=r=>new v({type:Ci,key:r}),Pi="allow_all",Eu=new v({type:Pi,key:""}),Su=s.z.object({keys:Zt.array().optional(),subjects:H.array().optional()}),Nu=s.z.object({policies:te(Er)}),Iu="/access/policy/retrieve";let ku=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Iu,e,Su,Nu)).policies}};const $u=s.z.object({policies:Er.partial({key:!0}).array()}),Au=s.z.object({policies:Er.array()}),Ru=s.z.object({keys:Zt.array()}),xu=s.z.object({}),Cu="/access/policy/create",Pu="/access/policy/delete";let Du=class{constructor(e){c(this,"client");this.client=e}async create(e){const n=xi.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await w(this.client,Cu,{policies:n},$u,Au)).policies}async delete(e){await w(this.client,Pu,{keys:b(e)},Ru,xu)}},Di=class{constructor(e){c(this,"retriever");c(this,"writer");this.retriever=new ku(e),this.writer=new Du(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve({keys:b(e)});return t?n:n[0]}async retrieveFor(e){const t=b(e).map(n=>new v(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const ju=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Eu,ALLOW_ALL_ONTOLOGY_TYPE:Pi,Client:Di,ONTOLOGY_TYPE:Ci,keyZ:Zt,newPolicyZ:xi,ontologyID:zu,policyZ:Er},Symbol.toStringTag,{value:"Module"}));let ji=class{constructor(e){c(this,"policy");this.policy=new Di(e)}};const Mu=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:Oc,CREATE_ACTION:zc,Client:ji,DELETE_ACTION:Ec,RETRIEVE_ACTION:Sc,UPDATE_ACTION:Nc,actionZ:dr},Symbol.toStringTag,{value:"Module"})),ke=s.z.number(),Lt=s.z.object({name:s.z.string(),key:s.z.number(),rate:st.z,dataType:S.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional()}),Mi=Lt.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:st.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Bi="channel",Bu=r=>new v({type:Bi,key:r.toString()}),Uu=new Error("request for lock canceled");var Zu=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 l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class Lu{constructor(e,t=Uu){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=Ui(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return Zu(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]=[]),_u(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 _u(r,e){const t=Ui(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Ui(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Yu=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 l(y){try{h(n.next(y))}catch(d){o(d)}}function u(y){try{h(n.throw(y))}catch(d){o(d)}}function h(y){y.done?a(y.value):i(y.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class qu{constructor(e){this._semaphore=new Lu(1,e)}acquire(){return Yu(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 Sr=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=b(r);const a=i[0],o=typeof a;let l;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[o],{single:n,variant:l,normalized:i,actual:r}},Nr=(r,e,t,n)=>{if(n){if(t.length===0)throw new pe(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new me(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Wu=s.z.object({leaseholder:s.z.number().optional(),keys:s.z.number().array().optional(),names:s.z.string().array().optional(),search: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()}),Gu=s.z.object({channels:te(Lt)}),we=r=>Sr(r,{number:"keys",string:"names"}),mr=class mr{constructor(e){c(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=we(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 page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(mr.ENDPOINT,e,Wu,Gu);if(n!=null)throw n;return t.channels}};c(mr,"ENDPOINT","/channel/retrieve");let xt=mr;class Sn{constructor(e){c(this,"cache");c(this,"namesToKeys");c(this,"wrapped");this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e,t){const{normalized:n}=Sr(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),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}=we(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 l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.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 Zi{constructor(e,t){c(this,"mu",new qu);c(this,"requests",new Map);c(this,"wrapped");c(this,"debouncedRun");this.wrapped=e,this.debouncedRun=bl(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,n){return await this.wrapped.page(e,t,n)}async retrieve(e){const{normalized:t,variant:n}=we(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 Li=async(r,e)=>{const{normalized:t}=we(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 re(`Could not find channels: ${JSON.stringify(i)}`);return n};class Nn{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:o=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:y,alias:d}){c(this,"_frameClient");c(this,"key");c(this,"name");c(this,"rate");c(this,"dataType");c(this,"leaseholder");c(this,"index");c(this,"isIndex");c(this,"internal");c(this,"alias");c(this,"virtual");this.key=a,this.name=n,this.rate=new st(t??0),this.dataType=new S(e),this.leaseholder=i,this.index=l,this.isIndex=o,this.internal=u,this.alias=d,this.virtual=h,this._frameClient=y??null}get framer(){if(this._frameClient==null)throw new M("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Lt.parse({key:this.key,name:this.name,rate:this.rate.valueOf(),dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal})}get ontologyID(){return new v({type:"channel",key:this.key.toString()})}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 Vu="/channel/retrieve-group",Fu=s.z.object({}),Ju=s.z.object({group:Ni});let _i=class{constructor(e,t,n,i){c(this,"type","channel");c(this,"frameClient");c(this,"client");c(this,"retriever");c(this,"writer");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=b(e),o=[];if(n){const l=await this.retriever.retrieve(a.map(h=>h.name)),u=new Set(l.map(h=>h.name));a=a.filter(h=>!u.has(h.name)),o=this.sugar(l)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return Nr("channel",e,i,n),n?i[0]:i}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=we(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new Sn(new Zi(new xt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Nn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Vu,{},Fu,Ju);return new Si(e.group.name,e.group.key)}};const Ku=s.z.object({channels:Mi.array()}),Hu=s.z.object({channels:Lt.array()}),Xu=s.z.object({keys:ke.array().optional(),names:s.z.string().array().optional()}),Qu=s.z.object({}),eh=s.z.object({keys:ke.array(),names:s.z.string().array()}),th=s.z.object({}),rh="/channel/create",nh="/channel/delete",sh="/channel/rename";let Yi=class{constructor(e,t){c(this,"client");c(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,rh,{channels:e},Ku,Hu);return this.cache.set(t),t}async delete(e){await w(this.client,nh,e,Xu,Qu),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,sh,{keys:e,names:t},eh,th),this.cache.rename(e,t)}};const ih=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:Sn,Channel:Nn,Client:_i,ClusterRetriever:xt,DebouncedBatchRetriever:Zi,ONTOLOGY_TYPE:Bi,Writer:Yi,analyzeChannelParams:we,keyZ:ke,newPayload:Mi,ontologyID:Bu,payload:Lt,retrieveRequired:Li},Symbol.toStringTag,{value:"Module"})),ht=s.z.string().uuid(),_t=s.z.object({key:ht,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),qi=_t.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Wi="user",ah=r=>new v({type:Wi,key:r}),oh=s.z.object({keys:ht.array().optional(),usernames:s.z.string().array().optional()}),ch=s.z.object({users:te(_t)}),lh="/user/retrieve";let uh=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,lh,e,oh,ch)).users}};const hh=s.z.object({users:qi.array()}),dh=s.z.object({users:_t.array()}),yh=s.z.object({key:ht,username:s.z.string().min(1)}),fh=s.z.object({}),gh=s.z.object({key:ht,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),ph=s.z.object({}),mh=s.z.object({keys:ht.array()}),wh=s.z.object({}),bh="/user/create",vh="/user/change-username",Th="/user/rename",Oh="/user/delete";let zh=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,bh,{users:b(e)},hh,dh)).users}async changeUsername(e,t){await w(this.client,vh,{key:e,username:t},yh,fh)}async rename(e,t,n){await w(this.client,Th,{key:e,firstName:t,lastName:n},gh,ph)}async delete(e){await w(this.client,Oh,{keys:b(e)},mh,wh)}},Gi=class{constructor(e){c(this,"reader");c(this,"writer");this.writer=new zh(e),this.reader=new uh(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.reader.retrieve({keys:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with key ${e} found`);if(n.length>1)throw new me(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:b(e)});if(t)return n;if(n.length===0)throw new pe(`No user with username ${e} found`);if(n.length>1)throw new me(`Multiple users found with username ${e}`);return n[0]}async rename(e,t,n){await this.writer.rename(e,t,n)}async delete(e){await this.writer.delete(e)}};const Eh=Object.freeze(Object.defineProperty({__proto__:null,Client:Gi,ONTOLOGY_TYPE:Wi,keyZ:ht,newUserZ:qi,ontologyID:ah,userZ:_t},Symbol.toStringTag,{value:"Module"})),Sh=s.z.object({username:s.z.string(),password:s.z.string()}),Nh=s.z.object({token:s.z.string(),user:_t}),Ns="/auth/login",Ih=3,kh="/auth/change-password",$h=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),Ah=s.z.object({});let Rh=class{constructor(e,t){c(this,"token");c(this,"client");c(this,"credentials");c(this,"authenticating");c(this,"authenticated");c(this,"user");c(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await w(this.client,kh,{username:this.credentials.username,password:this.credentials.password,newPassword:e},$h,Ah),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(Ns)){this.authenticating??(this.authenticating=new Promise((l,u)=>{this.client.send(Ns,this.credentials,Sh,Nh).then(([h,y])=>{if(y!=null)return l(y);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(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 At.matches(a)&&this.retryCount<Ih?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const xh=["disconnected","connecting","connected","failed"],Vi=s.z.enum(xh),Fi=s.z.object({status:Vi,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()}),Ch=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Is={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.34.0"},ks=(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}.
|
|
34
34
|
This may cause compatibility issues. We recommend updating the ${n}. For more information, see
|
|
35
|
-
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},tt=class tt{constructor(e,t=I.seconds(30),n,i){c(this,"_state");c(this,"pollFrequency",I.seconds(30));c(this,"client");c(this,"name");c(this,"interval");c(this,"clientVersion");c(this,"onChangeHandlers",[]);c(this,"versionWarned",!1);this._state={...Is},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(){var t;const e=this._state.status;try{const[n,i]=await this.client.send(tt.ENDPOINT,{},s.z.object({}),Ch);if(i!=null)throw i;const a=n.nodeVersion,o=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(ks(null,o,!0)),this.versionWarned=!0)):bs.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(ks(a,o,bs.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};c(tt,"ENDPOINT","/connectivity/check"),c(tt,"DEFAULT",Is),c(tt,"connectionStateZ",Fi);let Ct=tt;const Ph=Object.freeze(Object.defineProperty({__proto__:null,Checker:Ct,state:Fi,status:Vi},Symbol.toStringTag,{value:"Module"})),Dh=s.z.object({keys:ke.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),jh=s.z.object({}),Mh="/frame/delete";class Bh{constructor(e){c(this,"client");this.client=e}async delete(e){await w(this.client,Mh,e,Dh,jh)}}const
|
|
36
|
-
Got ${t.length} ${n}s and ${e.length} series.`)};class _{constructor(e=[],t=[]){c(this,"columns",[]);c(this,"series",[]);if(e instanceof _){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...b(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e;i.series??(i.series=[]),i.keys??(i.keys=[]);const a=i.series.map(o=>Ji(o))
|
|
35
|
+
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},tt=class tt{constructor(e,t=I.seconds(30),n,i){c(this,"_state");c(this,"pollFrequency",I.seconds(30));c(this,"client");c(this,"name");c(this,"interval");c(this,"clientVersion");c(this,"onChangeHandlers",[]);c(this,"versionWarned",!1);this._state={...Is},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(){var t;const e=this._state.status;try{const[n,i]=await this.client.send(tt.ENDPOINT,{},s.z.object({}),Ch);if(i!=null)throw i;const a=n.nodeVersion,o=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(ks(null,o,!0)),this.versionWarned=!0)):bs.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(ks(a,o,bs.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};c(tt,"ENDPOINT","/connectivity/check"),c(tt,"DEFAULT",Is),c(tt,"connectionStateZ",Fi);let Ct=tt;const Ph=Object.freeze(Object.defineProperty({__proto__:null,Checker:Ct,state:Fi,status:Vi},Symbol.toStringTag,{value:"Module"})),Dh=s.z.object({keys:ke.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),jh=s.z.object({}),Mh="/frame/delete";class Bh{constructor(e){c(this,"client");this.client=e}async delete(e){await w(this.client,Mh,e,Dh,jh)}}const $s=r=>{const e=b(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},As=(r,e)=>{const t=b(r);if(t.length===e.length)return;const n=$s(r);throw $s===null?new M("[Frame] - channel keys or names must be provided when constructing a frame."):new M(`[Frame] - ${n}s and series must be the same length.
|
|
36
|
+
Got ${t.length} ${n}s and ${e.length} series.`)};class _{constructor(e=[],t=[]){c(this,"columns",[]);c(this,"series",[]);if(e instanceof _){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...b(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e;i.series??(i.series=[]),i.keys??(i.keys=[]);const a=i.series.map(o=>Ji(o));As(i.keys,a),i.keys.forEach((o,l)=>this.push(o,a[l]))}else Object.entries(e).forEach(([i,a])=>{const o=parseInt(i);if(!isNaN(o))return this.push(o,...b(a));this.push(i,...b(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=b(t),a=b(e);As(a,i),i.forEach((o,l)=>this.push(a[l],o));return}throw new M(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
37
37
|
payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
|
|
38
38
|
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 Se("colType is not key");return this.columns??[]}get uniqueKeys(){return hs(this.keys)}get names(){if(this.colType==="key")throw new Se("colType is not name");return this.columns??[]}get uniqueNames(){return hs(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Ki(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 W.ZERO;const n=N.min(...this.series.map(a=>a.timeRange.start)),i=N.max(...this.series.map(a=>a.timeRange.end));return new W(n,i)}const t=this.get(e);return t==null?W.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 bi(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof _){if(this.colType!==null&&e.colType!==this.colType)throw new M("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 M("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new M("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new _([...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 _;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 _;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new it(this.series.reduce((e,t)=>e.add(t.byteLength),it.ZERO))}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const Ir=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(()=>[]),ze.crudeZ.array().optional().default([])])}),Ji=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new ze({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},Ki=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class kr{constructor(e){c(this,"adapter");c(this,"retriever");c(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new kr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=we(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const i=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(o=>{const l=i.find(u=>u.name===o);if(l==null)throw new Error(`Channel ${o} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}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 In{constructor(e){c(this,"adapter");c(this,"retriever");c(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new In(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,i]of Object.entries(e))t[await this.adaptToKey(n)]=i;return t}async update(e){const t=await Li(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new M(`
|
|
39
39
|
Received a single channel name or key but no series.
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
Received an array of channel names or keys but no array of series.
|
|
46
46
|
`);const o=[],l=[];for(let u=0;u<e.length;u++){const h=await this.fetchChannel(e[u]);if(u>=t.length)throw new M(`
|
|
47
47
|
Received an array of channel names or keys but not enough series.
|
|
48
|
-
`);const y=new ze({data:t[u],dataType:h.dataType});o.push(h.key),l.push(y)}return new _(o,l)}if(e instanceof _||e instanceof Map){const o=new _(e);if(this.adapter==null)return o;
|
|
48
|
+
`);const y=new ze({data:t[u],dataType:h.dataType});o.push(h.key),l.push(y)}return new _(o,l)}if(e instanceof _||e instanceof Map){const o=new _(e);if(this.adapter==null)return o;const l=o.columns.map(u=>{var y;const h=typeof u=="string"?(y=this.adapter)==null?void 0:y.get(u):u;if(h==null)throw new M(`
|
|
49
49
|
Channel ${u} was not provided in the list of channels when opening the writer
|
|
50
|
-
`);return h})
|
|
51
|
-
Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Ne.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const wn=new I(-1);var An=(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))(An||{}),Hi=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Hi||{});const Uh=s.z.object({command:s.z.nativeEnum(An),span:I.z.optional(),bounds:W.z.optional(),stamp:N.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),Zh=s.z.object({variant:s.z.nativeEnum(Hi),ack:s.z.boolean(),command:s.z.nativeEnum(An),error:jt.optional().nullable(),frame:Ir.optional()}),At=class At{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"value");this.stream=new kn("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,n,i,a={}){const o=await kr.open(n,t),l=await i.stream(At.ENDPOINT,Uh,Zh),u=new At(l,o);return await u.execute({command:0,keys:o.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=wn){return await this.execute({command:1,span:new I(e)})}async prev(e=wn){return await this.execute({command:2,span:new I(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 Lh(this)}async execute(e){for(this.stream.send(e),this.value=new _;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new _(t.frame)))}}};c(At,"ENDPOINT","/frame/iterate");let pr=At;class Lh{constructor(e){c(this,"iter");c(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const _h=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),Yh=s.z.object({frame:Ir,error:jt.optional().nullable()}),qh="/frame/stream";class Ar{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"downsampleFactor");this.stream=new kn("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,downsampleFactor:i}){const a=await kr.open(e,n),o=await t.stream(qh,_h,Yh),l=new Ar(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await o.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ne.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new _((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 Yt extends Pe.Observer{constructor(t,n){super(n);c(this,"streamer");c(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}var $n=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.Error=3]="Error",r[r.SetAuthority=4]="SetAuthority",r))($n||{}),ct=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(ct||{});const Wh=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in ct)return r;throw new Error(`invalid writer mode: ${r}`)}},Gh=new I(-1),Vh=s.z.object({start:N.z.optional(),controlSubject:at.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:at.Authority.z.array().optional(),mode:s.z.nativeEnum(ct).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:I.z.optional()}),Fh=s.z.object({command:s.z.nativeEnum($n),config:Vh.optional(),frame:Ir.optional()}),Jh=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum($n),error:jt.optional().nullable()});var Ee;let Xi=(Ee=class{constructor(e,t){c(this,"stream");c(this,"adapter");this.stream=new kn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=N.now(),authorities:a=at.Authority.Absolute,controlSubject:o,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:y=I.SECOND}){const d=await In.open(e,n),P=await t.stream(Ee.ENDPOINT,Fh,Jh),D=new Ee(P,d);return await D.execute({command:0,config:{start:new N(i),keys:d.keys,controlSubject:o,authorities:b(a),mode:Wh(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:y}}),D}async write(e,t){const n=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:n.toPayload()}),!0}async setAuthority(e,t){let n={keys:[],authorities:[]};if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),n={keys:Object.keys(a).map(o=>Number(o)),authorities:Object.values(a)}}return(await this.execute({command:4,config:n})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const e=await this.execute({command:3});return e.error!=null?On(e.error):null}async close(){await this.stream.closeAndAck()}async execute(e){for(this.stream.send(e);;){const t=await this.stream.receive();if(t.command===e.command)return t;console.warn("writer received unexpected response",t)}}get errorAccumulated(){return this.stream.received()}},c(Ee,"ENDPOINT","/frame/write"),Ee);const Qi="framer",Kh=r=>new v({type:Qi,key:r.toString()});let ea=class{constructor(e,t,n){c(this,"streamClient");c(this,"retriever");c(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new Bh(t)}async openIterator(e,t,n){return await pr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await Xi._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await Ar._open(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:ct.Persist});try{await o.write(a),await o.commit()}finally{await o.close()}return}const i=await this.openWriter({start:e,channels:t,mode:ct.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:I.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=we(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 _;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=we(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Hh=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Gh,AUTO_SPAN:wn,Client:ea,Frame:_,Iterator:pr,ONTOLOGY_TYPE:Qi,ObservableStreamer:Yt,Streamer:Ar,Writer:Xi,WriterMode:ct,frameZ:Ir,ontologyID:Kh,seriesFromPayload:Ji,seriesToPayload:Ki},Symbol.toStringTag,{value:"Module"})),Xh=at.Authority,Qh=at.stateZ(s.z.number()),ed=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`};class ta extends Yt{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].data);return this.merge(i),[i.transfers,!0]});c(this,"states");c(this,"codec");this.states=new Map,this.codec=new lt.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const td="sy_node_1_control";let ra=class{constructor(e){c(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(td);return new ta(e)}};const rd=Object.freeze(Object.defineProperty({__proto__:null,Authority:Xh,Client:ra,StateTracker:ta,stateZ:Qh,transferString:ed},Symbol.toStringTag,{value:"Module"}));let na=class{constructor(e,t,n){c(this,"tasks");c(this,"racks");c(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const nd=Object.freeze(Object.defineProperty({__proto__:null,Client:na},Symbol.toStringTag,{value:"Module"})),dt=s.z.number(),$r=s.z.object({key:dt,name:s.z.string()}),sa=$r.partial({key:!0}),ia="rack",sd=r=>new v({type:ia,key:r.toString()}),Rr=s.z.string(),qt=s.z.object({key:Rr,rack:dt,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:lt.JSON_CODEC.decodeString(r)))}),aa=qt.extend({properties:s.z.unknown().transform(r=>lt.JSON_CODEC.encodeString(r))}),oa="device",id=r=>new v({type:oa,key:r.toString()}),je=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=o=>{const l=[];return t!=null&&l.push(...o.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...o.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Yt(i,a)},ad=Object.freeze(Object.defineProperty({__proto__:null,openObservable:je},Symbol.toStringTag,{value:"Module"})),od="sy_device_set",cd="sy_device_delete",Fr="/hardware/device/retrieve",ld="/hardware/device/create",ud="/hardware/device/delete",hd=s.z.object({devices:aa.array()}),dd=s.z.object({devices:qt.array()}),yd=s.z.object({keys:Rr.array()}),fd=s.z.object({}),Jr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Rr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Kr=s.z.object({devices:te(qt)});let ca=class{constructor(e,t){c(this,"type","device");c(this,"client");c(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,Fr,{keys:b(e),...t},Jr,Kr);return Nr("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,Fr,{search:e,...t},Jr,Kr)).devices}async page(e,t,n){return(await w(this.client,Fr,{offset:e,limit:t,...n},Jr,Kr)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,ld,{devices:b(e)},hd,dd);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,ud,{keys:b(e)},yd,fd)}async openDeviceTracker(){return await je(this.frameClient,od,cd,gd)}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const gd=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(qt).map(t=>({variant:r,key:t.key,value:t})),pd=Object.freeze(Object.defineProperty({__proto__:null,Client:ca,ONTOLOGY_TYPE:oa,deviceKeyZ:Rr,deviceZ:qt,newDeviceZ:aa,ontologyID:id},Symbol.toStringTag,{value:"Module"})),Hr="/hardware/rack/retrieve",md="/hardware/rack/create",wd="/hardware/rack/delete",Xr=s.z.object({keys:dt.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Qr=s.z.object({racks:te($r)}),bd=s.z.object({racks:sa.array()}),vd=s.z.object({racks:$r.array()}),Td=s.z.object({keys:dt.array()}),Od=s.z.object({});let la=class{constructor(e,t,n){c(this,"type","rack");c(this,"client");c(this,"frameClient");c(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,wd,{keys:b(e)},Td,Od)}async create(e){const t=!Array.isArray(e),n=await w(this.client,md,{racks:b(e)},bd,vd),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,Hr,{search:e},Xr,Qr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Hr,{offset:e,limit:t},Xr,Qr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=Sr(e,{string:"names",number:"keys"}),a=await w(this.client,Hr,{[t]:n},Xr,Qr),o=this.sugar(a.racks);return Nr("Rack",e,o,i),i?o[0]:o}sugar(e){return e.map(({key:t,name:n})=>new ua(t,n,this.tasks))}};class ua{constructor(e,t,n){c(this,"key");c(this,"name");c(this,"tasks");this.key=e,this.name=t,this.tasks=n}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const zd=Object.freeze(Object.defineProperty({__proto__:null,Client:la,ONTOLOGY_TYPE:ia,Rack:ua,newRackZ:sa,ontologyID:sd,rackKeyZ:dt,rackZ:$r},Symbol.toStringTag,{value:"Module"})),Me=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),Pt=s.z.object({task:Me,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null())}),Wt=s.z.object({key:Me,name:s.z.string(),type:s.z.string(),internal:s.z.boolean().optional(),config:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:lt.JSON_CODEC.decodeString(r))),state:Pt.optional().nullable(),snapshot:s.z.boolean().optional()}),ha=Wt.omit({key:!0}).extend({key:Me.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>lt.JSON_CODEC.encodeString(r))}),Ed=s.z.object({task:Me,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r)))}),da="task",Sd=r=>new v({type:da,key:r.toString()}),kt="sy_task_state",Rs="sy_task_cmd",Xt=new Error("Task not created");class ya{constructor(e,t,n,i,a=!1,o=!1,l,u=null,h=null,y=null){c(this,"key");c(this,"name");c(this,"internal");c(this,"type");c(this,"config");c(this,"snapshot");c(this,"state");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=o,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=y}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return new v({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw Xt;const n=await this.frameClient.openWriter(Rs),i=Nl.id();return await n.write(Rs,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){if(this.frameClient==null)throw Xt;const i=await this.frameClient.openStreamer(kt),a=await this.executeCommand(e,t);let o;const l=new Promise(u=>setTimeout(()=>u(!1),new I(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=Pt.safeParse(u.at(-1).sy_task_state);if(h.success){if(o=h.data,o.key===a)break}else console.error(h.error)}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw Xt;return new Yt(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));if(!n.success)return[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Xt;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const Nd=s.z.object({rack:dt.optional(),keys:s.z.string().array().optional(),names:s.z.string().array().optional(),offset:s.z.number().optional(),limit:s.z.number().optional(),includeState:s.z.boolean().optional()}),Id=s.z.object({tasks:te(Wt)}),kd="/hardware/task/retrieve",Ad="/hardware/task/create",$d="/hardware/task/delete",Rd="/hardware/task/copy",xd=s.z.object({tasks:ha.array()}),Cd=s.z.object({tasks:Wt.array()}),Pd=s.z.object({keys:Me.array()}),Dd=s.z.object({}),jd=s.z.object({key:Me,name:s.z.string(),snapshot:s.z.boolean()}),Md=s.z.object({task:Wt});let fa=class{constructor(e,t,n,i){c(this,"type","task");c(this,"client");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e){const t=!Array.isArray(e),n=await w(this.client,Ad,{tasks:b(e)},xd,Cd),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,$d,{keys:b(e)},Pd,Dd)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:i,variant:a}=Sr(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=i;const l=await this.execRetrieve(o),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,Rd,{key:e,name:t,snapshot:n},jd,Md);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return Nr("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,kd,e,Nd,Id)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:o,internal:l,snapshot:u})=>new ya(t,n,i,a,l,u,o,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await je(this.frameClient,"sy_task_set","sy_task_delete",(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Yt(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const Bd=Object.freeze(Object.defineProperty({__proto__:null,Client:fa,ONTOLOGY_TYPE:da,Task:ya,commandZ:Ed,newTaskZ:ha,ontologyID:Sd,stateZ:Pt,taskKeyZ:Me,taskZ:Wt},Symbol.toStringTag,{value:"Module"})),yt=s.z.string().uuid(),Gt=s.z.object({key:yt,name:s.z.string().min(1),color:s.z.string()}),ga="label",Ud=r=>new v({type:ga,key:r}),Zd=s.z.object({keys:yt.array().optional(),for:H.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Ld=s.z.object({labels:te(Gt)});var $e;let pa=($e=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=b(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send($e.ENDPOINT,e,Zd,Ld);if(n!=null)throw n;return t.labels}},c($e,"ENDPOINT","/label/retrieve"),$e);const ma=Gt.extend({key:yt.optional()}),_d=s.z.object({labels:ma.array()}),Yd=s.z.object({labels:Gt.array()}),qd=s.z.object({keys:yt.array()}),wa=s.z.object({id:H,labels:yt.array(),replace:s.z.boolean().optional()}),Wd=wa.omit({replace:!0}),en=s.z.object({}),Gd="/label/create",Vd="/label/delete",Fd="/label/set",Jd="/label/remove";let ba=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Gd,{labels:b(e)},_d,Yd)).labels}async delete(e){await w(this.client,Vd,{keys:b(e)},qd,en)}async set(e,t,{replace:n}={}){await w(this.client,Fd,{id:e,labels:t,replace:n},wa,en)}async remove(e,t){await w(this.client,Jd,{id:e,labels:t},Wd,en)}};const Kd="sy_label_set",Hd="sy_label_delete";let va=class{constructor(e,t,n){c(this,"type","label");c(this,"retriever");c(this,"writer");c(this,"frameClient");c(this,"ontology");this.writer=new ba(e),this.retriever=new pa(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new v(e))}async label(e,t,n={}){await this.writer.set(new v(e),t,n)}async removeLabels(e,t){await this.writer.remove(new v(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await je(this.frameClient,Kd,Hd,Xd)}async trackLabelsOf(e){const t=new Pe.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new v({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new v(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var l,u;return{key:o.id.key,color:(l=o.data)==null?void 0:l.color,name:(u=o.data)==null?void 0:u.name}}))),t}};const Xd=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Gt).map(t=>({variant:r,key:t.key,value:t})),Qd=Object.freeze(Object.defineProperty({__proto__:null,Client:va,ONTOLOGY_TYPE:ga,Retriever:pa,Writer:ba,keyZ:yt,labelZ:Gt,newLabelPayloadZ:ma,ontologyID:Ud},Symbol.toStringTag,{value:"Module"})),Q=s.z.string().uuid(),Vt=s.z.object({key:Q,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),Ta=Vt.extend({key:s.z.string().uuid().optional()}),Oa=r=>{const e=b(r),t=e.length===0;let n=!1;return t||(n=Q.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},za="range",Ea="range-alias",ey=r=>new v({type:za,key:r}),ty=r=>new v({type:Ea,key:r}),ry="sy_range_alias_set",ny="sy_range_alias_delete",sy=s.z.object({range:Q,aliases:s.z.string().array()}),iy=s.z.object({aliases:s.z.record(s.z.string(),ke)}),ay=s.z.object({range:Q,aliases:s.z.record(ke.or(s.z.string()),s.z.string())}),oy=s.z.unknown(),cy=s.z.object({range:Q,channels:ke.array()}),ly=s.z.unknown(),uy=s.z.object({range:Q}),hy=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),he=class he{constructor(e,t,n){c(this,"frameClient");c(this,"cache",new Map);c(this,"client");c(this,"rangeKey");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 l=this.cache.get(o);l!=null?i[o]=l:t.push(o)});if(t.length===0)return i;const a=await w(this.client,he.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},sy,iy);return Object.entries(a.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,he.SET_ENDPOINT,{range:this.rangeKey,aliases:e},ay,oy)}async list(){return(await w(this.client,he.LIST_ENDPOINT,{range:this.rangeKey},uy,hy)).aliases}async delete(e){await w(this.client,he.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},cy,ly)}async openChangeTracker(){return await je(this.frameClient,ry,ny,fy(this.rangeKey))}};c(he,"SET_ENDPOINT","/range/alias/set"),c(he,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(he,"LIST_ENDPOINT","/range/alias/list"),c(he,"DELETE_ENDPOINT","/range/alias/delete");let bn=he;const dy=s.z.object({range:Q,channel:ke,alias:s.z.string()}),yy="---",fy=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(yy)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(dy).map(n=>({variant:e,key:n.alias,value:n})),gy=s.z.object({range:Q,keys:s.z.string().array()}),Rn=s.z.object({range:Q,key:s.z.string(),value:s.z.string()}),py=s.z.object({pairs:te(Rn)}),my=s.z.object({range:Q,pairs:Rn.array()}),wy=s.z.object({range:Q,keys:s.z.string().array()}),Oe=class Oe{constructor(e,t,n){c(this,"rangeKey");c(this,"client");c(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,Oe.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},gy,py);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;zn(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await w(this.client,Oe.SET_ENDPOINT,{range:this.rangeKey,pairs:n},my,s.z.unknown())}async delete(e){await w(this.client,Oe.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},wy,s.z.unknown())}async openTracker(){return await je(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):t.parseJSON(Rn).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};c(Oe,"GET_ENDPOINT","/range/kv/get"),c(Oe,"SET_ENDPOINT","/range/kv/set"),c(Oe,"DELETE_ENDPOINT","/range/kv/delete");let Dt=Oe;const tn=r=>new v({type:"range",key:r});class Sa{constructor(e,t=W.ZERO,n,i,a,o,l,u,h,y,d){c(this,"key");c(this,"name");c(this,"kv");c(this,"timeRange");c(this,"color");c(this,"channels");c(this,"aliaser");c(this,"frameClient");c(this,"labelClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=y,this.rangeClient=d}get ontologyID(){return new v({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new re(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(tn(this.key))}async addLabel(...e){await this.labelClient.label(tn(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(tn(this.key),e)}async openChildRangeTracker(){const e=new Pe.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new v({key:i.key,type:"range"});return{id:a,key:a.toString(),name:i.name,data:i.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Pe.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new v({key:t.key,type:"range"}),i={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const l=this.rangeClient.resourcesToRanges(o);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const by=s.z.object({keys:Q.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:W.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),vy="/range/retrieve",Ty=s.z.object({ranges:te(Vt)});let Na=class{constructor(e,t,n,i,a,o){c(this,"type","range");c(this,"frameClient");c(this,"writer");c(this,"unaryClient");c(this,"channels");c(this,"labelClient");c(this,"ontologyClient");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(b(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new W(e)});const{single:t,actual:n,variant:i,normalized:a,empty:o}=Oa(e);if(o)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new pe(`range matching ${n} not found`);if(l.length>1)throw new me(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new Dt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,vy,e,by,Ty);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents({key:e,type:"range"});if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new Sa(e.name,e.timeRange,e.key,e.color,this.frameClient,new Dt(e.key,this.unaryClient,this.frameClient),new bn(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await je(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugarMany(t.parseJSON(Vt)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,i;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new W((n=e.data)==null?void 0:n.timeRange),color:(i=e.data)==null?void 0:i.color})}};const Oy=s.z.object({ranges:Vt.array()}),zy=s.z.object({parent:H.optional(),ranges:Ta.array()}),Ey=s.z.object({keys:Q.array()}),Sy=s.z.object({}),Ny=s.z.object({key:Q,name:s.z.string()}),Iy=s.z.object({}),ky="/range/create",Ay="/range/delete",$y="/range/rename";let Ia=class{constructor(e){c(this,"client");this.client=e}async rename(e,t){await w(this.client,$y,{key:e,name:t},Ny,Iy)}async create(e,t){return(await w(this.client,ky,{ranges:e,...t},zy,Oy)).ranges}async delete(e){await w(this.client,Ay,{keys:e},Ey,Sy)}};const Ry=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:Ea,Client:Na,KV:Dt,ONTOLOGY_TYPE:za,Range:Sa,Writer:Ia,analyzeParams:Oa,keyZ:Q,newPayloadZ:Ta,payloadZ:Vt,rangeAliasOntologyID:ty,rangeOntologyID:ey},Symbol.toStringTag,{value:"Module"})),xy="/api/v1/";class Cy{constructor(e,t=!1){c(this,"url");c(this,"unary");c(this,"stream");c(this,"secure");this.secure=t,this.url=e.child(xy);const n=new lt.JSONCodec;this.unary=new dc(this.url,n,this.secure),this.stream=new Tc(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const xr=s.z.string().uuid(),Cr=s.z.object({key:s.z.string(),name:s.z.string(),data:Or.or(s.z.string().transform(r=>JSON.parse(r)))}),ka="lineplot",Py=r=>new v({type:ka,key:r}),Dy=s.z.object({keys:s.z.string().array()}),jy=s.z.object({linePlots:Cr.array()});let My=class{constructor(e){c(this,"ENDPOINT","/workspace/lineplot/retrieve");c(this,"client");this.client=e}async retrieve(e){const t=b(e);return(await w(this.client,this.ENDPOINT,{keys:t},Dy,jy)).linePlots}};const be=s.z.string().uuid(),Aa=r=>JSON.parse(r),xn=s.z.object({name:s.z.string(),key:be,layout:Or.or(s.z.string().transform(r=>Aa(r)))}),Cn=xn.omit({layout:!0}).extend({layout:s.z.string().transform(r=>Aa(r))}),$a="workspace",By=r=>new v({type:$a,key:r}),Uy=Cr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Zy=s.z.object({workspace:be,linePlots:Uy.array()}),Ly=s.z.object({linePlots:Cr.array()}),_y=s.z.object({keys:xr.array()}),Yy=s.z.object({}),qy=s.z.object({key:xr,name:s.z.string()}),Wy=s.z.object({}),Gy=s.z.object({key:xr,data:s.z.string()}),Vy=s.z.object({}),Fy="/workspace/lineplot/create",Jy="/workspace/lineplot/delete",Ky="/workspace/lineplot/rename",Hy="/workspace/lineplot/set-data";let Xy=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Fy,{workspace:e,linePlots:[n]},Zy,Ly)).linePlots[0]}async delete(e){const t=b(e);await w(this.client,Jy,{keys:t},_y,Yy)}async rename(e,t){await w(this.client,Ky,{key:e,name:t},qy,Wy)}async setData(e,t){await w(this.client,Hy,{key:e,data:JSON.stringify(t)},Gy,Vy)}},Ra=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new Xy(e),this.retriever=new My(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const Qy=Object.freeze(Object.defineProperty({__proto__:null,Client:Ra,ONTOLOGY_TYPE:ka,keyZ:xr,linePlotZ:Cr,ontologyID:Py},Symbol.toStringTag,{value:"Module"})),Pr=s.z.string().uuid(),xa=s.z.object({key:s.z.string(),name:s.z.string(),data:Or.or(s.z.string().transform(r=>JSON.parse(r)))}),Pn=s.z.object({key:s.z.string(),name:s.z.string(),data:s.z.string().transform(r=>JSON.parse(r))}),Ca="log",ef=r=>new v({type:Ca,key:r}),tf=s.z.object({keys:s.z.string().array()}),rf=s.z.object({logs:Pn.array()});let nf=class{constructor(e){c(this,"ENDPOINT","/workspace/log/retrieve");c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:b(e)},tf,rf)).logs}};const sf=xa.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),af=s.z.object({workspace:be,logs:sf.array()}),of=s.z.object({logs:Pn.array()}),cf=s.z.object({keys:Pr.array()}),lf=s.z.object({}),uf=s.z.object({key:Pr,name:s.z.string()}),hf=s.z.object({}),df=s.z.object({key:Pr,data:s.z.string()}),yf=s.z.object({}),ff="/workspace/log/create",gf="/workspace/log/delete",pf="/workspace/log/rename",mf="/workspace/log/set-data";let wf=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,ff,{workspace:e,logs:[n]},af,of)).logs[0]}async delete(e){const t=b(e);await w(this.client,gf,{keys:t},cf,lf)}async rename(e,t){await w(this.client,pf,{key:e,name:t},uf,hf)}async setData(e,t){await w(this.client,mf,{key:e,data:JSON.stringify(t)},df,yf)}},Pa=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new wf(e),this.retriever=new nf(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const bf=Object.freeze(Object.defineProperty({__proto__:null,Client:Pa,ONTOLOGY_TYPE:Ca,keyZ:Pr,logRemoteZ:Pn,logZ:xa,ontologyID:ef},Symbol.toStringTag,{value:"Module"})),vf=s.z.object({keys:be.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Tf=s.z.object({workspaces:te(Cn)});var Re;let Of=(Re=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=b(e);return await this.execute({keys:t})}async retrieveByAuthor(e){return await this.execute({author:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){return(await w(this.client,Re.ENDPOINT,e,vf,Tf)).workspaces}},c(Re,"ENDPOINT","/workspace/retrieve"),Re);const Ft=s.z.string().uuid(),Da=s.z.object({key:s.z.string(),name:s.z.string(),data:Or.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),Dr=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),ja="schematic",zf=r=>new v({type:ja,key:r}),Ef=s.z.object({keys:s.z.string().array()}),Sf=s.z.object({schematics:Dr.array()});class Nf{constructor(e){c(this,"ENDPOINT","/workspace/schematic/retrieve");c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:b(e)},Ef,Sf)).schematics}}const If=Da.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),kf=s.z.object({workspace:be,schematics:If.array()}),Af=s.z.object({schematics:Dr.array()}),$f=s.z.object({keys:Ft.array()}),Rf=s.z.object({}),xf=s.z.object({key:Ft,name:s.z.string()}),Cf=s.z.object({}),Pf=s.z.object({key:Ft,data:s.z.string()}),Df=s.z.object({}),jf=s.z.object({key:Ft,name:s.z.string(),snapshot:s.z.boolean()}),Mf=s.z.object({schematic:Dr}),Bf="/workspace/schematic/create",Uf="/workspace/schematic/delete",Zf="/workspace/schematic/rename",Lf="/workspace/schematic/set-data",_f="/workspace/schematic/copy";let Yf=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Bf,{workspace:e,schematics:[n]},kf,Af)).schematics[0]}async copy(e,t,n){return(await w(this.client,_f,{key:e,name:t,snapshot:n},jf,Mf)).schematic}async delete(e){const t=b(e);await w(this.client,Uf,{keys:t},$f,Rf)}async rename(e,t){await w(this.client,Zf,{key:e,name:t},xf,Cf)}async setData(e,t){await w(this.client,Lf,{key:e,data:JSON.stringify(t)},Pf,Df)}},Ma=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new Yf(e),this.retriever=new Nf(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async copy(e,t,n){return await this.writer.copy(e,t,n)}};const qf=Object.freeze(Object.defineProperty({__proto__:null,Client:Ma,ONTOLOGY_TYPE:ja,keyZ:Ft,ontologyID:zf,schematicRemoteZ:Dr,schematicZ:Da},Symbol.toStringTag,{value:"Module"})),Wf=xn.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Gf=s.z.object({workspaces:Wf.array()}),Vf=s.z.object({workspaces:Cn.array()}),Ff=s.z.object({keys:be.array()}),Jf=s.z.object({}),Kf=s.z.object({key:be,name:s.z.string()}),Hf=s.z.object({}),Xf=s.z.object({key:be,layout:s.z.string()}),Qf=s.z.object({}),eg="/workspace/create",tg="/workspace/delete",rg="/workspace/rename",ng="/workspace/set-layout";class sg{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,eg,{workspaces:b(e)},Gf,Vf)).workspaces}async delete(e){await w(this.client,tg,{keys:b(e)},Ff,Jf)}async rename(e,t){await w(this.client,rg,{key:e,name:t},Kf,Hf)}async setLayout(e,t){await w(this.client,ng,{key:e,layout:JSON.stringify(t)},Xf,Qf)}}class Ba{constructor(e){c(this,"type","workspace");c(this,"schematic");c(this,"linePlot");c(this,"log");c(this,"retriever");c(this,"writer");this.schematic=new Ma(e),this.linePlot=new Ra(e),this.retriever=new Of(e),this.log=new Pa(e),this.writer=new sg(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async rename(e,t){await this.writer.rename(e,t)}async setLayout(e,t){await this.writer.setLayout(e,t)}async delete(...e){await this.writer.delete(e)}}const ig=Object.freeze(Object.defineProperty({__proto__:null,Client:Ba,ONTOLOGY_TYPE:$a,keyZ:be,ontologyID:By,workspaceRemoteZ:Cn,workspaceZ:xn},Symbol.toStringTag,{value:"Module"})),Ua=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:I.z.default(I.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class Za extends ea{constructor(t){const n=Ua.parse(t),{host:i,port:a,username:o,password:l,connectivityPollFrequency:u,secure:h}=n,y=new Cy(new Gl({host:i,port:Number(a)}),h);y.use(su);let d;o!=null&&l!=null&&(d=new Rh(y.unary,{username:o,password:l}),y.use(d.middleware()));const P=new Sn(new xt(y.unary)),D=new Yi(y.unary,P);super(y.stream,y.unary,P);c(this,"createdAt");c(this,"props");c(this,"ranges");c(this,"channels");c(this,"auth");c(this,"user");c(this,"access");c(this,"connectivity");c(this,"ontology");c(this,"workspaces");c(this,"labels");c(this,"hardware");c(this,"control");c(this,"transport");c(this,"clientVersion","0.33.0");this.createdAt=N.now(),this.props=n,this.auth=d,this.transport=y,this.channels=new _i(this,P,y.unary,D),this.connectivity=new Ct(y.unary,u,this.clientVersion,n.name),this.control=new ra(this),this.ontology=new Ri(y.unary,this);const ee=new Ia(this.transport.unary);this.labels=new va(this.transport.unary,this,this.ontology),this.ranges=new Na(this,ee,this.transport.unary,P,this.labels,this.ontology),this.access=new ji(this.transport.unary),this.user=new Gi(this.transport.unary),this.workspaces=new Ba(this.transport.unary);const B=new ca(this.transport.unary,this),Dn=new fa(this.transport.unary,this,this.ontology,this.ranges),La=new la(this.transport.unary,this,Dn);this.hardware=new na(Dn,La,B)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(Za,"connectivity",Ct);const ag=at.Authority;exports.AuthError=De;exports.Authority=ag;exports.Channel=Nn;exports.ContiguityError=pn;exports.DataType=S;exports.Density=F;exports.Frame=_;exports.MultiSeries=bi;exports.MultipleFoundError=me;exports.NotFoundError=pe;exports.QueryError=re;exports.Rate=st;exports.RouteError=Rt;exports.Series=ze;exports.Synnax=Za;exports.TimeRange=W;exports.TimeSpan=I;exports.TimeStamp=N;exports.UnexpectedError=Se;exports.ValidationError=M;exports.access=Mu;exports.channel=ih;exports.connection=Ph;exports.control=rd;exports.device=pd;exports.framer=Hh;exports.hardware=nd;exports.label=Qd;exports.linePlot=Qy;exports.log=bf;exports.ontology=Ou;exports.policy=ju;exports.rack=zd;exports.ranger=Ry;exports.schematic=qf;exports.signals=ad;exports.synnaxPropsZ=Ua;exports.task=Bd;exports.user=Eh;exports.workspace=ig;
|
|
50
|
+
`);return h});return new _(l,o.series)}const n=[],i=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[l,u]=a[o],h=await this.fetchChannel(l),y=new ze({data:u,dataType:h.dataType});n.push(h.key),i.push(y)}return new _(n,i)}}class kn{constructor(e,t){c(this,"name");c(this,"stream");this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
|
|
51
|
+
Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Ne.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const wn=new I(-1);var $n=(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))($n||{}),Hi=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Hi||{});const Uh=s.z.object({command:s.z.nativeEnum($n),span:I.z.optional(),bounds:W.z.optional(),stamp:N.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),Zh=s.z.object({variant:s.z.nativeEnum(Hi),ack:s.z.boolean(),command:s.z.nativeEnum($n),error:jt.optional().nullable(),frame:Ir.optional()}),$t=class $t{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"value");this.stream=new kn("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,n,i,a={}){const o=await kr.open(n,t),l=await i.stream($t.ENDPOINT,Uh,Zh),u=new $t(l,o);return await u.execute({command:0,keys:o.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=wn){return await this.execute({command:1,span:new I(e)})}async prev(e=wn){return await this.execute({command:2,span:new I(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 Lh(this)}async execute(e){for(this.stream.send(e),this.value=new _;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new _(t.frame)))}}};c($t,"ENDPOINT","/frame/iterate");let pr=$t;class Lh{constructor(e){c(this,"iter");c(this,"open",!1);this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const _h=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),Yh=s.z.object({frame:Ir,error:jt.optional().nullable()}),qh="/frame/stream";class $r{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"downsampleFactor");this.stream=new kn("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,downsampleFactor:i}){const a=await kr.open(e,n),o=await t.stream(qh,_h,Yh),l=new $r(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await o.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ne.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new _((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 Yt extends Pe.Observer{constructor(t,n){super(n);c(this,"streamer");c(this,"closePromise");this.streamer=t,this.closePromise=this.stream()}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const t of this.streamer)this.notify(t)}}var An=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.Error=3]="Error",r[r.SetAuthority=4]="SetAuthority",r))(An||{}),ct=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(ct||{});const Wh=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in ct)return r;throw new Error(`invalid writer mode: ${r}`)}},Gh=new I(-1),Vh=s.z.object({start:N.z.optional(),controlSubject:at.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:at.Authority.z.array().optional(),mode:s.z.nativeEnum(ct).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:I.z.optional()}),Fh=s.z.object({command:s.z.nativeEnum(An),config:Vh.optional(),frame:Ir.optional()}),Jh=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(An),error:jt.optional().nullable()});var Ee;let Xi=(Ee=class{constructor(e,t){c(this,"stream");c(this,"adapter");this.stream=new kn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=N.now(),authorities:a=at.Authority.Absolute,controlSubject:o,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:y=I.SECOND}){const d=await In.open(e,n),P=await t.stream(Ee.ENDPOINT,Fh,Jh),D=new Ee(P,d);return await D.execute({command:0,config:{start:new N(i),keys:d.keys,controlSubject:o,authorities:b(a),mode:Wh(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:y}}),D}async write(e,t){const n=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:n.toPayload()}),!0}async setAuthority(e,t){let n;if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),n={keys:Object.keys(a).map(o=>Number(o)),authorities:Object.values(a)}}return(await this.execute({command:4,config:n})).ack}async commit(){return this.errorAccumulated?!1:(await this.execute({command:2})).ack}async error(){this.stream.send({command:3});const e=await this.execute({command:3});return e.error!=null?On(e.error):null}async close(){await this.stream.closeAndAck()}async execute(e){for(this.stream.send(e);;){const t=await this.stream.receive();if(t.command===e.command)return t;console.warn("writer received unexpected response",t)}}get errorAccumulated(){return this.stream.received()}},c(Ee,"ENDPOINT","/frame/write"),Ee);const Qi="framer",Kh=r=>new v({type:Qi,key:r.toString()});let ea=class{constructor(e,t,n){c(this,"streamClient");c(this,"retriever");c(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new Bh(t)}async openIterator(e,t,n){return await pr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await Xi._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await $r._open(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:ct.Persist});try{await o.write(a),await o.commit()}finally{await o.close()}return}const i=await this.openWriter({start:e,channels:t,mode:ct.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:I.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=we(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 _;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=we(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Hh=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Gh,AUTO_SPAN:wn,Client:ea,Frame:_,Iterator:pr,ONTOLOGY_TYPE:Qi,ObservableStreamer:Yt,Streamer:$r,Writer:Xi,WriterMode:ct,frameZ:Ir,ontologyID:Kh,seriesFromPayload:Ji,seriesToPayload:Ki},Symbol.toStringTag,{value:"Module"})),Xh=at.Authority,Qh=at.stateZ(s.z.number()),ed=r=>{var e,t;return r.to==null?`${(e=r.from)==null?void 0:e.resource} - ${(t=r.from)==null?void 0:t.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`};class ta extends Yt{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].data);return this.merge(i),[i.transfers,!0]});c(this,"states");c(this,"codec");this.states=new Map,this.codec=new lt.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const td="sy_node_1_control";let ra=class{constructor(e){c(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(td);return new ta(e)}};const rd=Object.freeze(Object.defineProperty({__proto__:null,Authority:Xh,Client:ra,StateTracker:ta,stateZ:Qh,transferString:ed},Symbol.toStringTag,{value:"Module"}));let na=class{constructor(e,t,n){c(this,"tasks");c(this,"racks");c(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const nd=Object.freeze(Object.defineProperty({__proto__:null,Client:na},Symbol.toStringTag,{value:"Module"})),dt=s.z.number(),Ar=s.z.object({key:dt,name:s.z.string()}),sa=Ar.partial({key:!0}),ia="rack",sd=r=>new v({type:ia,key:r.toString()}),Rr=s.z.string(),qt=s.z.object({key:Rr,rack:dt,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:lt.JSON_CODEC.decodeString(r)))}),aa=qt.extend({properties:s.z.unknown().transform(r=>lt.JSON_CODEC.encodeString(r))}),oa="device",id=r=>new v({type:oa,key:r.toString()}),je=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=o=>{const l=[];return t!=null&&l.push(...o.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...o.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Yt(i,a)},ad=Object.freeze(Object.defineProperty({__proto__:null,openObservable:je},Symbol.toStringTag,{value:"Module"})),od="sy_device_set",cd="sy_device_delete",Fr="/hardware/device/retrieve",ld="/hardware/device/create",ud="/hardware/device/delete",hd=s.z.object({devices:aa.array()}),dd=s.z.object({devices:qt.array()}),yd=s.z.object({keys:Rr.array()}),fd=s.z.object({}),Jr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Rr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Kr=s.z.object({devices:te(qt)});let ca=class{constructor(e,t){c(this,"type","device");c(this,"client");c(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,Fr,{keys:b(e),...t},Jr,Kr);return Nr("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,Fr,{search:e,...t},Jr,Kr)).devices}async page(e,t,n){return(await w(this.client,Fr,{offset:e,limit:t,...n},Jr,Kr)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,ld,{devices:b(e)},hd,dd);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,ud,{keys:b(e)},yd,fd)}async openDeviceTracker(){return await je(this.frameClient,od,cd,gd)}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}};const gd=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(qt).map(t=>({variant:r,key:t.key,value:t})),pd=Object.freeze(Object.defineProperty({__proto__:null,Client:ca,ONTOLOGY_TYPE:oa,deviceKeyZ:Rr,deviceZ:qt,newDeviceZ:aa,ontologyID:id},Symbol.toStringTag,{value:"Module"})),Hr="/hardware/rack/retrieve",md="/hardware/rack/create",wd="/hardware/rack/delete",Xr=s.z.object({keys:dt.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Qr=s.z.object({racks:te(Ar)}),bd=s.z.object({racks:sa.array()}),vd=s.z.object({racks:Ar.array()}),Td=s.z.object({keys:dt.array()}),Od=s.z.object({});let la=class{constructor(e,t,n){c(this,"type","rack");c(this,"client");c(this,"frameClient");c(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,wd,{keys:b(e)},Td,Od)}async create(e){const t=!Array.isArray(e),n=await w(this.client,md,{racks:b(e)},bd,vd),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,Hr,{search:e},Xr,Qr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Hr,{offset:e,limit:t},Xr,Qr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=Sr(e,{string:"names",number:"keys"}),a=await w(this.client,Hr,{[t]:n},Xr,Qr),o=this.sugar(a.racks);return Nr("Rack",e,o,i),i?o[0]:o}sugar(e){return e.map(({key:t,name:n})=>new ua(t,n,this.tasks))}};class ua{constructor(e,t,n){c(this,"key");c(this,"name");c(this,"tasks");this.key=e,this.name=t,this.tasks=n}async listTasks(){return await this.tasks.retrieve(this.key)}async retrieveTaskByName(e){return await this.tasks.retrieveByName(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const zd=Object.freeze(Object.defineProperty({__proto__:null,Client:la,ONTOLOGY_TYPE:ia,Rack:ua,newRackZ:sa,ontologyID:sd,rackKeyZ:dt,rackZ:Ar},Symbol.toStringTag,{value:"Module"})),Me=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),Pt=s.z.object({task:Me,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r))).or(s.z.array(s.z.unknown())).or(s.z.null())}),Wt=s.z.object({key:Me,name:s.z.string(),type:s.z.string(),internal:s.z.boolean().optional(),config:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:lt.JSON_CODEC.decodeString(r))),state:Pt.optional().nullable(),snapshot:s.z.boolean().optional()}),ha=Wt.omit({key:!0}).extend({key:Me.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>lt.JSON_CODEC.encodeString(r))}),Ed=s.z.object({task:Me,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(r=>r===""?{}:JSON.parse(r)))}),da="task",Sd=r=>new v({type:da,key:r.toString()}),kt="sy_task_state",Rs="sy_task_cmd",Xt=new Error("Task not created");class ya{constructor(e,t,n,i,a=!1,o=!1,l,u=null,h=null,y=null){c(this,"key");c(this,"name");c(this,"internal");c(this,"type");c(this,"config");c(this,"snapshot");c(this,"state");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=o,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=y}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return new v({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw Xt;const n=await this.frameClient.openWriter(Rs),i=Nl.id();return await n.write(Rs,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){if(this.frameClient==null)throw Xt;const i=await this.frameClient.openStreamer(kt),a=await this.executeCommand(e,t);let o;const l=new Promise(u=>setTimeout(()=>u(!1),new I(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=Pt.safeParse(u.at(-1).sy_task_state);if(h.success){if(o=h.data,o.key===a)break}else console.error(h.error)}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw Xt;return new Yt(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));if(!n.success)return[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Xt;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const Nd=s.z.object({rack:dt.optional(),keys:s.z.string().array().optional(),names:s.z.string().array().optional(),offset:s.z.number().optional(),limit:s.z.number().optional(),includeState:s.z.boolean().optional()}),Id=s.z.object({tasks:te(Wt)}),kd="/hardware/task/retrieve",$d="/hardware/task/create",Ad="/hardware/task/delete",Rd="/hardware/task/copy",xd=s.z.object({tasks:ha.array()}),Cd=s.z.object({tasks:Wt.array()}),Pd=s.z.object({keys:Me.array()}),Dd=s.z.object({}),jd=s.z.object({key:Me,name:s.z.string(),snapshot:s.z.boolean()}),Md=s.z.object({task:Wt});let fa=class{constructor(e,t,n,i){c(this,"type","task");c(this,"client");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e){const t=!Array.isArray(e),n=await w(this.client,$d,{tasks:b(e)},xd,Cd),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,Ad,{keys:b(e)},Pd,Dd)}async search(e){return await this.execRetrieve({keys:[e]})}async page(e,t){return await this.execRetrieve({offset:e,limit:t})}async list(e={}){return this.sugar(await this.execRetrieve(e))}async retrieve(e,t){const{single:n,normalized:i,variant:a}=Sr(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=i;const l=await this.execRetrieve(o),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,Rd,{key:e,name:t,snapshot:n},jd,Md);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return Nr("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,kd,e,Nd,Id)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:o,internal:l,snapshot:u})=>new ya(t,n,i,a,l,u,o,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await je(this.frameClient,"sy_task_set","sy_task_delete",(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Yt(await this.frameClient.openStreamer(kt),e=>{const t=e.get(kt);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const Bd=Object.freeze(Object.defineProperty({__proto__:null,Client:fa,ONTOLOGY_TYPE:da,Task:ya,commandZ:Ed,newTaskZ:ha,ontologyID:Sd,stateZ:Pt,taskKeyZ:Me,taskZ:Wt},Symbol.toStringTag,{value:"Module"})),yt=s.z.string().uuid(),Gt=s.z.object({key:yt,name:s.z.string().min(1),color:s.z.string()}),ga="label",Ud=r=>new v({type:ga,key:r}),Zd=s.z.object({keys:yt.array().optional(),for:H.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Ld=s.z.object({labels:te(Gt)});var Ae;let pa=(Ae=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=b(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Ae.ENDPOINT,e,Zd,Ld);if(n!=null)throw n;return t.labels}},c(Ae,"ENDPOINT","/label/retrieve"),Ae);const ma=Gt.extend({key:yt.optional()}),_d=s.z.object({labels:ma.array()}),Yd=s.z.object({labels:Gt.array()}),qd=s.z.object({keys:yt.array()}),wa=s.z.object({id:H,labels:yt.array(),replace:s.z.boolean().optional()}),Wd=wa.omit({replace:!0}),en=s.z.object({}),Gd="/label/create",Vd="/label/delete",Fd="/label/set",Jd="/label/remove";let ba=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Gd,{labels:b(e)},_d,Yd)).labels}async delete(e){await w(this.client,Vd,{keys:b(e)},qd,en)}async set(e,t,{replace:n}={}){await w(this.client,Fd,{id:e,labels:t,replace:n},wa,en)}async remove(e,t){await w(this.client,Jd,{id:e,labels:t},Wd,en)}};const Kd="sy_label_set",Hd="sy_label_delete";let va=class{constructor(e,t,n){c(this,"type","label");c(this,"retriever");c(this,"writer");c(this,"frameClient");c(this,"ontology");this.writer=new ba(e),this.retriever=new pa(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new v(e))}async label(e,t,n={}){await this.writer.set(new v(e),t,n)}async removeLabels(e,t){await this.writer.remove(new v(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await je(this.frameClient,Kd,Hd,Xd)}async trackLabelsOf(e){const t=new Pe.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new v({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new v(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var l,u;return{key:o.id.key,color:(l=o.data)==null?void 0:l.color,name:(u=o.data)==null?void 0:u.name}}))),t}};const Xd=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Gt).map(t=>({variant:r,key:t.key,value:t})),Qd=Object.freeze(Object.defineProperty({__proto__:null,Client:va,ONTOLOGY_TYPE:ga,Retriever:pa,Writer:ba,keyZ:yt,labelZ:Gt,newLabelPayloadZ:ma,ontologyID:Ud},Symbol.toStringTag,{value:"Module"})),Q=s.z.string().uuid(),Vt=s.z.object({key:Q,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),Ta=Vt.extend({key:s.z.string().uuid().optional()}),Oa=r=>{const e=b(r),t=e.length===0;let n=!1;return t||(n=Q.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},za="range",Ea="range-alias",ey=r=>new v({type:za,key:r}),ty=r=>new v({type:Ea,key:r}),ry="sy_range_alias_set",ny="sy_range_alias_delete",sy=s.z.object({range:Q,aliases:s.z.string().array()}),iy=s.z.object({aliases:s.z.record(s.z.string(),ke)}),ay=s.z.object({range:Q,aliases:s.z.record(ke.or(s.z.string()),s.z.string())}),oy=s.z.unknown(),cy=s.z.object({range:Q,channels:ke.array()}),ly=s.z.unknown(),uy=s.z.object({range:Q}),hy=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),he=class he{constructor(e,t,n){c(this,"frameClient");c(this,"cache",new Map);c(this,"client");c(this,"rangeKey");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 l=this.cache.get(o);l!=null?i[o]=l:t.push(o)});if(t.length===0)return i;const a=await w(this.client,he.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},sy,iy);return Object.entries(a.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,he.SET_ENDPOINT,{range:this.rangeKey,aliases:e},ay,oy)}async list(){return(await w(this.client,he.LIST_ENDPOINT,{range:this.rangeKey},uy,hy)).aliases}async delete(e){await w(this.client,he.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},cy,ly)}async openChangeTracker(){return await je(this.frameClient,ry,ny,fy(this.rangeKey))}};c(he,"SET_ENDPOINT","/range/alias/set"),c(he,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(he,"LIST_ENDPOINT","/range/alias/list"),c(he,"DELETE_ENDPOINT","/range/alias/delete");let bn=he;const dy=s.z.object({range:Q,channel:ke,alias:s.z.string()}),yy="---",fy=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(yy)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(dy).map(n=>({variant:e,key:n.alias,value:n})),gy=s.z.object({range:Q,keys:s.z.string().array()}),Rn=s.z.object({range:Q,key:s.z.string(),value:s.z.string()}),py=s.z.object({pairs:te(Rn)}),my=s.z.object({range:Q,pairs:Rn.array()}),wy=s.z.object({range:Q,keys:s.z.string().array()}),Oe=class Oe{constructor(e,t,n){c(this,"rangeKey");c(this,"client");c(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,Oe.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},gy,py);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;zn(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await w(this.client,Oe.SET_ENDPOINT,{range:this.rangeKey,pairs:n},my,s.z.unknown())}async delete(e){await w(this.client,Oe.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},wy,s.z.unknown())}async openTracker(){return await je(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):t.parseJSON(Rn).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};c(Oe,"GET_ENDPOINT","/range/kv/get"),c(Oe,"SET_ENDPOINT","/range/kv/set"),c(Oe,"DELETE_ENDPOINT","/range/kv/delete");let Dt=Oe;const tn=r=>new v({type:"range",key:r});class Sa{constructor(e,t=W.ZERO,n,i,a,o,l,u,h,y,d){c(this,"key");c(this,"name");c(this,"kv");c(this,"timeRange");c(this,"color");c(this,"channels");c(this,"aliaser");c(this,"frameClient");c(this,"labelClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=y,this.rangeClient=d}get ontologyID(){return new v({key:this.key,type:"range"})}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new re(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(tn(this.key))}async addLabel(...e){await this.labelClient.label(tn(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(tn(this.key),e)}async openChildRangeTracker(){const e=new Pe.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new v({key:i.key,type:"range"});return{id:a,key:a.toString(),name:i.name,data:i.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Pe.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new v({key:t.key,type:"range"}),i={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const l=this.rangeClient.resourcesToRanges(o);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const by=s.z.object({keys:Q.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:W.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),vy="/range/retrieve",Ty=s.z.object({ranges:te(Vt)});let Na=class{constructor(e,t,n,i,a,o){c(this,"type","range");c(this,"frameClient");c(this,"writer");c(this,"unaryClient");c(this,"channels");c(this,"labelClient");c(this,"ontologyClient");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(b(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new W(e)});const{single:t,actual:n,variant:i,normalized:a,empty:o}=Oa(e);if(o)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new pe(`range matching ${n} not found`);if(l.length>1)throw new me(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new Dt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,vy,e,by,Ty);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents({key:e,type:"range"});if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new Sa(e.name,e.timeRange,e.key,e.color,this.frameClient,new Dt(e.key,this.unaryClient,this.frameClient),new bn(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await je(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugarMany(t.parseJSON(Vt)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,i;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new W((n=e.data)==null?void 0:n.timeRange),color:(i=e.data)==null?void 0:i.color})}};const Oy=s.z.object({ranges:Vt.array()}),zy=s.z.object({parent:H.optional(),ranges:Ta.array()}),Ey=s.z.object({keys:Q.array()}),Sy=s.z.object({}),Ny=s.z.object({key:Q,name:s.z.string()}),Iy=s.z.object({}),ky="/range/create",$y="/range/delete",Ay="/range/rename";let Ia=class{constructor(e){c(this,"client");this.client=e}async rename(e,t){await w(this.client,Ay,{key:e,name:t},Ny,Iy)}async create(e,t){return(await w(this.client,ky,{ranges:e,...t},zy,Oy)).ranges}async delete(e){await w(this.client,$y,{keys:e},Ey,Sy)}};const Ry=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:Ea,Client:Na,KV:Dt,ONTOLOGY_TYPE:za,Range:Sa,Writer:Ia,analyzeParams:Oa,keyZ:Q,newPayloadZ:Ta,payloadZ:Vt,rangeAliasOntologyID:ty,rangeOntologyID:ey},Symbol.toStringTag,{value:"Module"})),xy="/api/v1/";class Cy{constructor(e,t=!1){c(this,"url");c(this,"unary");c(this,"stream");c(this,"secure");this.secure=t,this.url=e.child(xy);const n=new lt.JSONCodec;this.unary=new dc(this.url,n,this.secure),this.stream=new Tc(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const xr=s.z.string().uuid(),Cr=s.z.object({key:s.z.string(),name:s.z.string(),data:Or.or(s.z.string().transform(r=>JSON.parse(r)))}),ka="lineplot",Py=r=>new v({type:ka,key:r}),Dy=s.z.object({keys:s.z.string().array()}),jy=s.z.object({linePlots:Cr.array()});let My=class{constructor(e){c(this,"ENDPOINT","/workspace/lineplot/retrieve");c(this,"client");this.client=e}async retrieve(e){const t=b(e);return(await w(this.client,this.ENDPOINT,{keys:t},Dy,jy)).linePlots}};const be=s.z.string().uuid(),$a=r=>JSON.parse(r),xn=s.z.object({name:s.z.string(),key:be,layout:Or.or(s.z.string().transform(r=>$a(r)))}),Cn=xn.omit({layout:!0}).extend({layout:s.z.string().transform(r=>$a(r))}),Aa="workspace",By=r=>new v({type:Aa,key:r}),Uy=Cr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Zy=s.z.object({workspace:be,linePlots:Uy.array()}),Ly=s.z.object({linePlots:Cr.array()}),_y=s.z.object({keys:xr.array()}),Yy=s.z.object({}),qy=s.z.object({key:xr,name:s.z.string()}),Wy=s.z.object({}),Gy=s.z.object({key:xr,data:s.z.string()}),Vy=s.z.object({}),Fy="/workspace/lineplot/create",Jy="/workspace/lineplot/delete",Ky="/workspace/lineplot/rename",Hy="/workspace/lineplot/set-data";let Xy=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Fy,{workspace:e,linePlots:[n]},Zy,Ly)).linePlots[0]}async delete(e){const t=b(e);await w(this.client,Jy,{keys:t},_y,Yy)}async rename(e,t){await w(this.client,Ky,{key:e,name:t},qy,Wy)}async setData(e,t){await w(this.client,Hy,{key:e,data:JSON.stringify(t)},Gy,Vy)}},Ra=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new Xy(e),this.retriever=new My(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const Qy=Object.freeze(Object.defineProperty({__proto__:null,Client:Ra,ONTOLOGY_TYPE:ka,keyZ:xr,linePlotZ:Cr,ontologyID:Py},Symbol.toStringTag,{value:"Module"})),Pr=s.z.string().uuid(),xa=s.z.object({key:s.z.string(),name:s.z.string(),data:Or.or(s.z.string().transform(r=>JSON.parse(r)))}),Pn=s.z.object({key:s.z.string(),name:s.z.string(),data:s.z.string().transform(r=>JSON.parse(r))}),Ca="log",ef=r=>new v({type:Ca,key:r}),tf=s.z.object({keys:s.z.string().array()}),rf=s.z.object({logs:Pn.array()});let nf=class{constructor(e){c(this,"ENDPOINT","/workspace/log/retrieve");c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:b(e)},tf,rf)).logs}};const sf=xa.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),af=s.z.object({workspace:be,logs:sf.array()}),of=s.z.object({logs:Pn.array()}),cf=s.z.object({keys:Pr.array()}),lf=s.z.object({}),uf=s.z.object({key:Pr,name:s.z.string()}),hf=s.z.object({}),df=s.z.object({key:Pr,data:s.z.string()}),yf=s.z.object({}),ff="/workspace/log/create",gf="/workspace/log/delete",pf="/workspace/log/rename",mf="/workspace/log/set-data";let wf=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,ff,{workspace:e,logs:[n]},af,of)).logs[0]}async delete(e){const t=b(e);await w(this.client,gf,{keys:t},cf,lf)}async rename(e,t){await w(this.client,pf,{key:e,name:t},uf,hf)}async setData(e,t){await w(this.client,mf,{key:e,data:JSON.stringify(t)},df,yf)}},Pa=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new wf(e),this.retriever=new nf(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}};const bf=Object.freeze(Object.defineProperty({__proto__:null,Client:Pa,ONTOLOGY_TYPE:Ca,keyZ:Pr,logRemoteZ:Pn,logZ:xa,ontologyID:ef},Symbol.toStringTag,{value:"Module"})),vf=s.z.object({keys:be.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Tf=s.z.object({workspaces:te(Cn)});var Re;let Of=(Re=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=b(e);return await this.execute({keys:t})}async retrieveByAuthor(e){return await this.execute({author:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){return(await w(this.client,Re.ENDPOINT,e,vf,Tf)).workspaces}},c(Re,"ENDPOINT","/workspace/retrieve"),Re);const Ft=s.z.string().uuid(),Da=s.z.object({key:s.z.string(),name:s.z.string(),data:Or.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),Dr=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),ja="schematic",zf=r=>new v({type:ja,key:r}),Ef=s.z.object({keys:s.z.string().array()}),Sf=s.z.object({schematics:Dr.array()});class Nf{constructor(e){c(this,"ENDPOINT","/workspace/schematic/retrieve");c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:b(e)},Ef,Sf)).schematics}}const If=Da.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),kf=s.z.object({workspace:be,schematics:If.array()}),$f=s.z.object({schematics:Dr.array()}),Af=s.z.object({keys:Ft.array()}),Rf=s.z.object({}),xf=s.z.object({key:Ft,name:s.z.string()}),Cf=s.z.object({}),Pf=s.z.object({key:Ft,data:s.z.string()}),Df=s.z.object({}),jf=s.z.object({key:Ft,name:s.z.string(),snapshot:s.z.boolean()}),Mf=s.z.object({schematic:Dr}),Bf="/workspace/schematic/create",Uf="/workspace/schematic/delete",Zf="/workspace/schematic/rename",Lf="/workspace/schematic/set-data",_f="/workspace/schematic/copy";let Yf=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Bf,{workspace:e,schematics:[n]},kf,$f)).schematics[0]}async copy(e,t,n){return(await w(this.client,_f,{key:e,name:t,snapshot:n},jf,Mf)).schematic}async delete(e){const t=b(e);await w(this.client,Uf,{keys:t},Af,Rf)}async rename(e,t){await w(this.client,Zf,{key:e,name:t},xf,Cf)}async setData(e,t){await w(this.client,Lf,{key:e,data:JSON.stringify(t)},Pf,Df)}},Ma=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new Yf(e),this.retriever=new Nf(e)}async create(e,t){return await this.writer.create(e,t)}async rename(e,t){await this.writer.rename(e,t)}async setData(e,t){await this.writer.setData(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async delete(e){await this.writer.delete(e)}async copy(e,t,n){return await this.writer.copy(e,t,n)}};const qf=Object.freeze(Object.defineProperty({__proto__:null,Client:Ma,ONTOLOGY_TYPE:ja,keyZ:Ft,ontologyID:zf,schematicRemoteZ:Dr,schematicZ:Da},Symbol.toStringTag,{value:"Module"})),Wf=xn.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Gf=s.z.object({workspaces:Wf.array()}),Vf=s.z.object({workspaces:Cn.array()}),Ff=s.z.object({keys:be.array()}),Jf=s.z.object({}),Kf=s.z.object({key:be,name:s.z.string()}),Hf=s.z.object({}),Xf=s.z.object({key:be,layout:s.z.string()}),Qf=s.z.object({}),eg="/workspace/create",tg="/workspace/delete",rg="/workspace/rename",ng="/workspace/set-layout";class sg{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,eg,{workspaces:b(e)},Gf,Vf)).workspaces}async delete(e){await w(this.client,tg,{keys:b(e)},Ff,Jf)}async rename(e,t){await w(this.client,rg,{key:e,name:t},Kf,Hf)}async setLayout(e,t){await w(this.client,ng,{key:e,layout:JSON.stringify(t)},Xf,Qf)}}class Ba{constructor(e){c(this,"type","workspace");c(this,"schematic");c(this,"linePlot");c(this,"log");c(this,"retriever");c(this,"writer");this.schematic=new Ma(e),this.linePlot=new Ra(e),this.retriever=new Of(e),this.log=new Pa(e),this.writer=new sg(e)}async search(e){return await this.retriever.search(e)}async retrieveByAuthor(e){return await this.retriever.retrieveByAuthor(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async rename(e,t){await this.writer.rename(e,t)}async setLayout(e,t){await this.writer.setLayout(e,t)}async delete(...e){await this.writer.delete(e)}}const ig=Object.freeze(Object.defineProperty({__proto__:null,Client:Ba,ONTOLOGY_TYPE:Aa,keyZ:be,ontologyID:By,workspaceRemoteZ:Cn,workspaceZ:xn},Symbol.toStringTag,{value:"Module"})),Ua=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:I.z.default(I.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class Za extends ea{constructor(t){const n=Ua.parse(t),{host:i,port:a,username:o,password:l,connectivityPollFrequency:u,secure:h}=n,y=new Cy(new Gl({host:i,port:Number(a)}),h);y.use(su);let d;o!=null&&l!=null&&(d=new Rh(y.unary,{username:o,password:l}),y.use(d.middleware()));const P=new Sn(new xt(y.unary)),D=new Yi(y.unary,P);super(y.stream,y.unary,P);c(this,"createdAt");c(this,"props");c(this,"ranges");c(this,"channels");c(this,"auth");c(this,"user");c(this,"access");c(this,"connectivity");c(this,"ontology");c(this,"workspaces");c(this,"labels");c(this,"hardware");c(this,"control");c(this,"transport");c(this,"clientVersion","0.34.0");this.createdAt=N.now(),this.props=n,this.auth=d,this.transport=y,this.channels=new _i(this,P,y.unary,D),this.connectivity=new Ct(y.unary,u,this.clientVersion,n.name),this.control=new ra(this),this.ontology=new Ri(y.unary,this);const ee=new Ia(this.transport.unary);this.labels=new va(this.transport.unary,this,this.ontology),this.ranges=new Na(this,ee,this.transport.unary,P,this.labels,this.ontology),this.access=new ji(this.transport.unary),this.user=new Gi(this.transport.unary),this.workspaces=new Ba(this.transport.unary);const B=new ca(this.transport.unary,this),Dn=new fa(this.transport.unary,this,this.ontology,this.ranges),La=new la(this.transport.unary,this,Dn);this.hardware=new na(Dn,La,B)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(Za,"connectivity",Ct);const ag=at.Authority;exports.AuthError=De;exports.Authority=ag;exports.Channel=Nn;exports.ContiguityError=pn;exports.DataType=S;exports.Density=F;exports.Frame=_;exports.MultiSeries=bi;exports.MultipleFoundError=me;exports.NotFoundError=pe;exports.QueryError=re;exports.Rate=st;exports.RouteError=Rt;exports.Series=ze;exports.Synnax=Za;exports.TimeRange=W;exports.TimeSpan=I;exports.TimeStamp=N;exports.UnexpectedError=Se;exports.ValidationError=M;exports.access=Mu;exports.channel=ih;exports.connection=Ph;exports.control=rd;exports.device=pd;exports.framer=Hh;exports.hardware=nd;exports.label=Qd;exports.linePlot=Qy;exports.log=bf;exports.ontology=Ou;exports.policy=ju;exports.rack=zd;exports.ranger=Ry;exports.schematic=qf;exports.signals=ad;exports.synnaxPropsZ=Ua;exports.task=Bd;exports.user=Eh;exports.workspace=ig;
|