@synnaxlabs/client 0.32.0 → 0.33.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.
Files changed (56) hide show
  1. package/.turbo/turbo-build.log +7 -7
  2. package/dist/access/policy/payload.d.ts +40 -40
  3. package/dist/access/policy/retriever.d.ts +5 -5
  4. package/dist/channel/client.d.ts +1 -1
  5. package/dist/client.cjs +26 -26
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +2896 -2499
  8. package/dist/framer/deleter.d.ts.map +1 -1
  9. package/dist/framer/frame.d.ts.map +1 -1
  10. package/dist/framer/writer.d.ts.map +1 -1
  11. package/dist/hardware/task/ni/types.d.ts +13 -13
  12. package/dist/hardware/task/ni/types.d.ts.map +1 -1
  13. package/dist/index.d.ts +3 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/label/writer.d.ts +5 -5
  16. package/dist/ontology/client.d.ts +9 -9
  17. package/dist/ontology/payload.d.ts +43 -43
  18. package/dist/ontology/payload.d.ts.map +1 -1
  19. package/dist/ranger/client.d.ts.map +1 -1
  20. package/dist/ranger/payload.d.ts.map +1 -1
  21. package/dist/ranger/writer.d.ts +5 -5
  22. package/dist/ranger/writer.d.ts.map +1 -1
  23. package/dist/workspace/client.d.ts +2 -0
  24. package/dist/workspace/client.d.ts.map +1 -1
  25. package/dist/workspace/log/client.d.ts +16 -0
  26. package/dist/workspace/log/client.d.ts.map +1 -0
  27. package/dist/workspace/log/external.d.ts +3 -0
  28. package/dist/workspace/log/external.d.ts.map +1 -0
  29. package/dist/workspace/log/index.d.ts +2 -0
  30. package/dist/workspace/log/index.d.ts.map +1 -0
  31. package/dist/workspace/log/log.spec.d.ts +2 -0
  32. package/dist/workspace/log/log.spec.d.ts.map +1 -0
  33. package/dist/workspace/log/payload.d.ts +36 -0
  34. package/dist/workspace/log/payload.d.ts.map +1 -0
  35. package/dist/workspace/log/retriever.d.ts +9 -0
  36. package/dist/workspace/log/retriever.d.ts.map +1 -0
  37. package/dist/workspace/log/writer.d.ts +35 -0
  38. package/dist/workspace/log/writer.d.ts.map +1 -0
  39. package/package.json +12 -13
  40. package/src/access/policy/policy.spec.ts +6 -6
  41. package/src/channel/client.ts +1 -1
  42. package/src/control/state.ts +1 -1
  43. package/src/errors.spec.ts +19 -0
  44. package/src/hardware/task/ni/types.ts +13 -13
  45. package/src/index.ts +2 -2
  46. package/src/ontology/client.ts +1 -1
  47. package/src/ontology/payload.ts +1 -0
  48. package/src/workspace/client.ts +3 -0
  49. package/src/workspace/log/client.ts +51 -0
  50. package/src/workspace/log/external.ts +11 -0
  51. package/src/workspace/log/index.ts +10 -0
  52. package/src/workspace/log/log.spec.ts +78 -0
  53. package/src/workspace/log/payload.ts +36 -0
  54. package/src/workspace/log/retriever.ts +38 -0
  55. package/src/workspace/log/writer.ts +116 -0
  56. package/src/workspace/schematic/writer.ts +1 -1
package/dist/client.cjs CHANGED
@@ -1,51 +1,51 @@
1
- "use strict";var za=Object.defineProperty;var Ea=(r,e,t)=>e in r?za(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>Ea(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),T=r=>Array.isArray(r)?r:[r];var Sa=Object.defineProperty,Na=(r,e,t)=>e in r?Sa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>Na(r,typeof e!="symbol"?e+"":e,t);const Ia=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:e[0].toLowerCase()+e.slice(1)},ps=r=>{const e=(t,n=Vr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!$r(t))return t;n=$a(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&($r(l)?Sn(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&En(l)&&(l=[...l].map(h=>{let d=h;return $r(h)?Sn(d,n.keepTypesOnRecursion)||(d=e(h,n)):En(h)&&(d=e({key:h},n).key),d}))),i[u]=l}),i};return e},gs=ps(Ia),ka=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Aa=ps(ka),Vr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},$a=(r=Vr)=>(r.recursive==null?r=Vr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),En=r=>r!=null&&Array.isArray(r),$r=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Sn=(r,e)=>(e||[]).some(t=>r instanceof t),ms=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Ra=Object.defineProperty,xa=(r,e,t)=>e in r?Ra(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,wt=(r,e,t)=>xa(r,typeof e!="symbol"?e+"":e,t);let Ca=class{constructor(){wt(this,"contentType","application/json"),wt(this,"decoder"),wt(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=gs(t);return e!=null?e.parse(n):n}encodeString(r){const e=Aa(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):ms(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},Pa=class{constructor(){wt(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||!ms(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(`
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==null&&(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(c=>c.trim());if(t.length===0)return e!=null?e.parse({}):{};const i=t.split(",").map(c=>c.trim()),a={};return i.forEach(c=>{a[c]=[]}),n.forEach(c=>{const l=c.split(",").map(u=>u.trim());i.forEach((u,h)=>{const d=this.parseValue(l[h]);d!=null&&a[u].push(d)})}),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(){}},Da=class{constructor(){wt(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 Vt=new Ca;new Pa;new Da;const dr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ws=s.z.object({width:s.z.number(),height:s.z.number()}),ja=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Ma=["width","height"];s.z.enum(Ma);const Ba=["start","center","end"],Ua=["signedWidth","signedHeight"];s.z.enum(Ua);const ar=s.z.object({x:s.z.number(),y:s.z.number()}),Za=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),La=["x","y"],bs=s.z.enum(La),Ts=["top","right","bottom","left"];s.z.enum(Ts);const _a=["left","right"],vs=s.z.enum(_a),Ya=["top","bottom"],Os=s.z.enum(Ya),zs=["center"],Nn=s.z.enum(zs),qa=[...Ts,...zs],Es=s.z.enum(qa);s.z.enum(Ba);const Wa=["first","last"];s.z.enum(Wa);const Ga=s.z.object({lower:s.z.number(),upper:s.z.number()}),Fa=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Ga,dr]);s.z.union([Fa,dr]);s.z.union([bs,Es]);s.z.union([bs,Es,s.z.instanceof(String)]);const bt=(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 In(r);return In(t)},In=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:vs.or(Nn),y:Os.or(Nn)});const Va=s.z.object({x:vs,y:Os}),Ka=Object.freeze({x:"left",y:"top"}),Ja=(r,e)=>r.x===e.x&&r.y===e.y,kn=s.z.union([s.z.number(),ar,dr,ws,ja,Za]),Ha=(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}},An=Object.freeze({x:0,y:0}),qt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:qt,left:qt,width:qt,height:qt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:ar,two:ar,root:Va});const cn=(r,e,t=0,n=0,i)=>{const a={one:{...An},two:{...An},root:i??Ka};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))},Rr=r=>{const e=cn(r);return{lower:e.one.x,upper:e.two.x}},xr=r=>{const e=cn(r);return{lower:e.one.y,upper:e.two.y}},Xa=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Qa=Object.defineProperty,eo=(r,e,t)=>e in r?Qa(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,de=(r,e,t)=>eo(r,typeof e!="symbol"?e+"":e,t);const to=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:kn,scale:kn});const ro=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],no=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:c,upper:l}=r,u=a-i,h=l-c;if(t==="dimension")return[r,n*(h/u)];const d=(n-i)*(h/u)+c;return[r,d]},io=r=>(e,t,n)=>[r,n],ao=()=>(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)]},oo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=to(n,i,a),[e,n]},Kr=class ot{constructor(){de(this,"ops",[]),de(this,"currBounds",null),de(this,"currType",null),de(this,"reversed",!1),this.ops=[]}static translate(e){return new ot().translate(e)}static magnify(e){return new ot().magnify(e)}static scale(e,t){return new ot().scale(e,t)}translate(e){const t=this.new(),n=ro(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=no(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=bt(e,t),i=this.new(),a=so(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=bt(e,t),i=this.new(),a=oo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=bt(e,t),i=this.new(),a=io(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=ao();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 ot;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(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.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}};de(Kr,"IDENTITY",new Kr);let $n=Kr;const Rn=class le{constructor(e=new $n,t=new $n,n=null){de(this,"x"),de(this,"y"),de(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new le().translate(e,t)}static translateX(e){return new le().translateX(e)}static translateY(e){return new le().translateY(e)}static clamp(e){return new le().clamp(e)}static magnify(e){return new le().magnify(e)}static scale(e){return new le().scale(e)}static reBound(e){return new le().reBound(e)}translate(e,t){const n=Ha(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(Xa(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Ja(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(Rr(e)),t.y=t.y.scale(xr(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(Rr(e)),t.y=this.y.reBound(xr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Rr(e)),t.y=this.y.clamp(xr(e)),t}copy(){const e=new le;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 cn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};de(Rn,"IDENTITY",new Rn);const co=r=>r!=null&&typeof r=="object"&&"toString"in r,lo=(r,e=!1)=>{const t=co(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?uo(n):n},uo=r=>(e,t)=>r(t,e),ho=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ws,ho,ar,dr]);const yo=s.z.bigint().or(s.z.string().transform(BigInt));var fo=Object.defineProperty,po=(r,e,t)=>e in r?fo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>po(r,typeof e!="symbol"?e+"":e,t);let go=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const mo="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",wo=go(mo,11),bo=s.z.enum(["static","dynamic"]),Ss=(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 v{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=v.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*v.MILLISECOND.valueOf();else if(typeof e=="string")this.value=v.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=v.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=v.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=v.MAX:e=v.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(i.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let c="00",l="00";a!=null&&([c,l]=a.split("."));let u=v.hours(parseInt(n??"00",10)).add(v.minutes(parseInt(i??"00",10))).add(v.seconds(parseInt(c??"00",10))).add(v.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(v.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return v.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new v(BigInt(n.getTime())*v.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(v.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new L(BigInt(new Date().getTimezoneOffset())*v.MINUTE.valueOf())}static since(e){return new v().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new v(e).valueOf()}span(e){return this.range(e).span}range(e){return new ln(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return Ss(this,e)}get isToday(){return this.truncate(L.DAY).equals(v.now().truncate(L.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new v(new Date)}static max(...e){let t=v.MIN;for(const n of e){const i=new v(n);i.after(t)&&(t=i)}return t}static min(...e){let t=v.MAX;for(const n of e){const i=new v(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new v(e)}static microseconds(e){return v.nanoseconds(e*1e3)}static milliseconds(e){return v.microseconds(e*1e3)}static seconds(e){return v.milliseconds(e*1e3)}static minutes(e){return v.seconds(e*60)}static hours(e){return v.minutes(e*60)}static days(e){return v.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 N{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new N(e).valueOf()}greaterThan(e){return this.valueOf()>new N(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new N(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new N(e).valueOf()}remainder(e){return Ss(this,e)}truncate(e){return new N(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(N.DAY),t=this.truncate(N.HOUR),n=this.truncate(N.MINUTE),i=this.truncate(N.SECOND),a=this.truncate(N.MILLISECOND),c=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,h=t.sub(e),d=n.sub(t),y=i.sub(n),P=a.sub(i),D=c.sub(a),Q=l.sub(c);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),d.isZero||(B+=`${d.minutes}m `),y.isZero||(B+=`${y.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),Q.isZero||(B+=`${Q.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(N.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(N.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(N.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(N.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(N.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(N.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new N(e).valueOf()}add(e){return new N(this.valueOf()+new N(e).valueOf())}sub(e){return new N(this.valueOf()-new N(e).valueOf())}static nanoseconds(e=1){return new N(e)}static microseconds(e=1){return N.nanoseconds(e*1e3)}static milliseconds(e=1){return N.microseconds(e*1e3)}static seconds(e=1){return N.milliseconds(e*1e3)}static minutes(e){return N.seconds(e.valueOf()*60)}static hours(e){return N.minutes(e*60)}static days(e){return N.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 L=$;const Wt=class Kt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Kt(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 K(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 Kt(e)}static khz(e){return Kt.hz(e*1e3)}};m(Wt,"z",s.z.union([s.z.number().transform(r=>new Wt(r)),s.z.instanceof(Number).transform(r=>new Wt(r)),s.z.instanceof(Wt)]));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 Ns(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 K=Y;const se=class Jt{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 Jt(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 Jt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Jt(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(se,"MAX",new se(j.MIN,j.MAX)),m(se,"MIN",new se(j.MAX,j.MIN)),m(se,"ZERO",new se(j.ZERO,j.ZERO)),m(se,"z",s.z.union([s.z.object({start:j.z,end:j.z}).transform(r=>new se(r.start,r.end)),s.z.instanceof(se)]));let ln=se;const f=class ie extends String{constructor(e){if(e instanceof ie||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ie.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ie.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ie.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(ie.JSON)||this.equals(ie.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ie.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ie.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 ie.BIG_INT_TYPES.some(e=>e.equals(this))}};m(f,"UNKNOWN",new f("unknown")),m(f,"FLOAT64",new f("float64")),m(f,"FLOAT32",new f("float32")),m(f,"INT64",new f("int64")),m(f,"INT32",new f("int32")),m(f,"INT16",new f("int16")),m(f,"INT8",new f("int8")),m(f,"UINT64",new f("uint64")),m(f,"UINT32",new f("uint32")),m(f,"UINT16",new f("uint16")),m(f,"UINT8",new f("uint8")),m(f,"BOOLEAN",f.UINT8),m(f,"TIMESTAMP",new f("timestamp")),m(f,"UUID",new f("uuid")),m(f,"STRING",new f("string")),m(f,"JSON",new f("json")),m(f,"ARRAY_CONSTRUCTORS",new Map([[f.UINT8.toString(),Uint8Array],[f.UINT16.toString(),Uint16Array],[f.UINT32.toString(),Uint32Array],[f.UINT64.toString(),BigUint64Array],[f.FLOAT32.toString(),Float32Array],[f.FLOAT64.toString(),Float64Array],[f.INT8.toString(),Int8Array],[f.INT16.toString(),Int16Array],[f.INT32.toString(),Int32Array],[f.INT64.toString(),BigInt64Array],[f.TIMESTAMP.toString(),BigInt64Array],[f.STRING.toString(),Uint8Array],[f.JSON.toString(),Uint8Array],[f.UUID.toString(),Uint8Array]])),m(f,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,f.UINT8],[Uint16Array.name,f.UINT16],[Uint32Array.name,f.UINT32],[BigUint64Array.name,f.UINT64],[Float32Array.name,f.FLOAT32],[Float64Array.name,f.FLOAT64],[Int8Array.name,f.INT8],[Int16Array.name,f.INT16],[Int32Array.name,f.INT32],[BigInt64Array.name,f.INT64]])),m(f,"DENSITIES",new Map([[f.UINT8.toString(),K.BIT8],[f.UINT16.toString(),K.BIT16],[f.UINT32.toString(),K.BIT32],[f.UINT64.toString(),K.BIT64],[f.FLOAT32.toString(),K.BIT32],[f.FLOAT64.toString(),K.BIT64],[f.INT8.toString(),K.BIT8],[f.INT16.toString(),K.BIT16],[f.INT32.toString(),K.BIT32],[f.INT64.toString(),K.BIT64],[f.TIMESTAMP.toString(),K.BIT64],[f.STRING.toString(),K.UNKNOWN],[f.JSON.toString(),K.UNKNOWN],[f.UUID.toString(),K.BIT128]])),m(f,"ALL",[f.UNKNOWN,f.FLOAT64,f.FLOAT32,f.INT64,f.INT32,f.INT16,f.INT8,f.UINT64,f.UINT32,f.UINT16,f.UINT8,f.TIMESTAMP,f.UUID,f.STRING,f.JSON]),m(f,"BIG_INT_TYPES",[f.INT64,f.UINT64,f.TIMESTAMP]),m(f,"z",s.z.union([s.z.string().transform(r=>new f(r)),s.z.instanceof(f)]));let R=f;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),c=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),d=a.sub(i);let y="";return c.isZero||(y+=`${c.terabytes}TB `),l.isZero||(y+=`${l.gigabytes}GB `),u.isZero||(y+=`${u.megabytes}MB `),h.isZero||(y+=`${h.kilobytes}KB `),(!d.isZero||y==="")&&(y+=`${d.valueOf()}B`),y.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 Ns=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 Is=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof j||r instanceof L||r instanceof Date},To=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):lt(t,-n),vo=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Eo?!0:Is(r),Ne=-1,Oo=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),zo=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),ct=class ue{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",Ne),m(this,"_refCount",0),m(this,"_cachedLength"),vo(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=wo()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const y=u;this.key=y.key,this.dataType=y.dataType,this.sampleOffset=y.sampleOffset,this.gl=y.gl,this._data=y._data,this._timeRange=y._timeRange,this.alignment=y.alignment,this._cachedMin=y._cachedMin,this._cachedMax=y._cachedMax,this.writePos=y.writePos,this._refCount=y._refCount,this._cachedLength=y._cachedLength;return}const h=Is(u),d=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(d||h){let y=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.");y=u[0]}if(typeof y=="string")this.dataType=R.STRING;else if(typeof y=="number")this.dataType=R.FLOAT64;else if(typeof y=="bigint")this.dataType=R.INT64;else if(typeof y=="boolean")this.dataType=R.BOOLEAN;else if(y instanceof j||y instanceof Date||y instanceof j)this.dataType=R.TIMESTAMP;else if(typeof y=="object")this.dataType=R.JSON;else throw new Error(`cannot infer data type of ${typeof y} when constructing a Series from a JS array`)}else this.dataType=new R(u)}if(!d&&!h)this._data=u;else{let y=h?[u]:u;const P=y[0];(P instanceof j||P instanceof Date||P instanceof L)&&(y=y.map(D=>new j(D).valueOf())),this.dataType.equals(R.STRING)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.join(`
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
4
  `)+`
5
- `)):this.dataType.equals(R.JSON)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.map(D=>Vt.encodeString(D)).join(`
5
+ `)):this.dataType.equals(R.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(d.map(D=>Qt.encodeString(D)).join(`
6
6
  `)+`
7
- `)):this._data=new this.dataType.Array(y).buffer}this.key=l,this.alignment=c,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 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 c=0;c<e;c++)a[c]=BigInt(n.add(t.span(c)).valueOf());return new ue({data:a,dataType:R.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
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
8
  `)+`
9
- `);return new ue({data:n,dataType:R.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>Vt.encodeString(i)).join(`
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
10
  `)+`
11
- `);return new ue({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");if(this.writePos===Ne)return 0;const t=this.capacity-this.writePos,n=t<e.length?e.slice(0,t):e;return this.underlyingData.set(n.data,this.writePos),this.maybeRecomputeMinMax(n),this._cachedLength=void 0,this.writePos+=n.length,n.length}get buffer(){return this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Ne?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.buffer).split(`
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.buffer.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i),c=>c.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.buffer).split(`
13
- `).slice(0,-1).map(t=>e.parse(Vt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Ns(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ne?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ne?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;return this.data.forEach(t=>{t===10&&e++}),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]=To(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(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()),lt(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()),lt(this._cachedMin,this.sampleOffset))}get bounds(){return bt(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 lt(this.max,-this.min)}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 lt(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+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):gs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=lo(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<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!==Ne){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ne}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 bt(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 So(this);return this.dataType.equals(R.JSON)?new No(e):e}return new Io(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(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)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:ln.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(ct,"crudeZ",s.z.object({timeRange:ln.z.optional(),dataType:R.z,alignment:yo.optional(),data:s.z.union([Oo,zo,s.z.instanceof(ArrayBuffer)]),glBufferUsage:bo.optional().default("static").optional()})),m(ct,"z",ct.crudeZ.transform(r=>new ct(r)));let Eo=ct;class So{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]!==10;)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 xn,Cn;class No{constructor(e){m(this,"wrapped"),m(this,xn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Vt.decodeString(e.value)}}[(Cn=Symbol.iterator,xn=Symbol.toStringTag,Cn)](){return this}}var Pn,Dn;class Io{constructor(e){m(this,"series"),m(this,"index"),m(this,Pn,"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)}}[(Dn=Symbol.iterator,Pn=Symbol.toStringTag,Dn)](){return this}}const lt=(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 ks=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",ko=ks(),As=["MacOS","Windows","Linux","Docker"],Ao=s.z.enum(As);let Cr;const $o=()=>{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"},Ro=(r={})=>{const{force:e,default:t}=r;return e??Cr??(Cr=$o(),Cr??t)},$s=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:As,RUNTIME:ko,detect:ks,getOS:Ro,osZ:Ao},Symbol.toStringTag,{value:"Module"}));var xo=Object.defineProperty,Co=(r,e,t)=>e in r?xo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ut=(r,e,t)=>Co(r,typeof e!="symbol"?e+"":e,t);const Po=(...r)=>r.map(Rs).join(""),Rs=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Do=r=>r.endsWith("/")?r.slice(0,-1):r,jo=(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("&"),Jr=class Hr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){ut(this,"protocol"),ut(this,"host"),ut(this,"port"),ut(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Rs(i)}replace(e){return new Hr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Hr({...this,pathPrefix:Po(this.path,e)})}toString(){return Do(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};ut(Jr,"UNKNOWN",new Jr({host:"unknown",port:0}));let Mo=Jr;var Bo=Object.defineProperty,Uo=(r,e,t)=>e in r?Bo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ht=(r,e,t)=>Uo(r,typeof e!="symbol"?e+"":e,t);const je=class extends Number{};Ht(je,"Absolute",255),Ht(je,"Default",1),Ht(je,"z",s.z.union([s.z.instanceof(je),s.z.number().int().min(0).max(255).transform(r=>new je(r)),s.z.instanceof(Number).transform(r=>new je(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const xs=class ht extends Error{constructor(){super(ht.MESSAGE)}matches(e){return typeof e=="string"?e.includes(ht.MESSAGE):e instanceof ht||e.message.includes(ht.MESSAGE)}};Ht(xs,"MESSAGE","canceled");let Zo=xs;new Zo;s.z.string().regex(/^\d+\.\d+\.\d+$/);const H=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 ne extends Error{constructor(e){super(e),k(this,"discriminator","FreighterError"),k(this,"type","")}}const Lo=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},jn="unknown",Mn="nil",_o="freighter",Rt=s.z.object({type:s.z.string(),data:s.z.string()});class Yo{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Mn,data:""};if(Lo(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:jn,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Mn)return null;if(e.type===jn)return new Bn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Bn(e.data)}}const Cs=new Yo,Ps=({encode:r,decode:e})=>Cs.register({encode:r,decode:e}),un=r=>Cs.decode(r);class Bn extends ne{constructor(e){super(e),k(this,"type","unknown")}}const fr="freighter.",Xt=class Ds extends ne{constructor(){super("EOF"),k(this,"type",Ds.TYPE)}};k(Xt,"TYPE",fr+"eof"),k(Xt,"matches",H(Xt.TYPE));let Oe=Xt;const Qt=class js extends ne{constructor(){super("StreamClosed"),k(this,"type",js.TYPE)}};k(Qt,"TYPE",fr+"stream_closed"),k(Qt,"matches",H(Qt.TYPE));let Qe=Qt;const er=class Ms extends ne{constructor(e={}){const{message:t="Unreachable",url:n=Mo.UNKNOWN}=e;super(t),k(this,"type",Ms.TYPE),k(this,"url"),this.url=n}};k(er,"TYPE",fr+"unreachable"),k(er,"matches",H(er.TYPE));let Re=er;const qo=r=>{if(!r.type.startsWith(_o))return null;if(Oe.matches(r))return{type:Oe.TYPE,data:"EOF"};if(Qe.matches(r))return{type:Qe.TYPE,data:"StreamClosed"};if(Re.matches(r))return{type:Re.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Wo=r=>{if(!r.type.startsWith(fr))return null;switch(r.type){case Oe.TYPE:return new Oe;case Qe.TYPE:return new Qe;case Re.TYPE:return new Re;default:throw new Error(`Unknown error type: ${r.data}`)}};Ps({encode:qo,decode:Wo});let Bs=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 c=this.middleware[n];return n++,await c(a,i)};return await i(e)}};const Us="Content-Type",Un=r=>{if($s.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 Go extends Bs{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=Un(this.endpoint.protocol),new Proxy(this,{get:(i,a,c)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,c)})}get headers(){return{[Us]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const c=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:c.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const d={...h,params:{}};l.headers={...this.headers,...h.params};let y;try{y=await Un(h.protocol)(h.target,l)}catch(D){let Q=D;return Q.message==="Load failed"&&(Q=new Re({url:c})),[d,Q]}const P=await y.arrayBuffer();if(y!=null&&y.ok)return i!=null&&(a=this.encoder.decode(P,i)),[d,null];try{if(y.status!==400)return[d,new Error(y.statusText)];const D=this.encoder.decode(P,Rt),Q=un(D);return[d,Q]}catch(D){return[d,new Error(`[freighter] - failed to decode error: ${y.statusText}: ${D.message}`)]}});return[a,u]}}const w=async(r,e,t,n,i)=>{const[a,c]=await r.send(e,t,n,i);if(c!=null)throw c;return a},Fo=()=>$s.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Vo=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Rt)});class Ko{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 Oe;if(this.sendClosed)throw new Qe;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=un(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,Vo)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:ec(e)?Oe.TYPE:Qe.TYPE,data:""}})}}const Jo="freighterctx",Ho=1e3,Xo=1001,Qo=[Ho,Xo],ec=r=>Qo.includes(r.code),Zs=class Ls extends Bs{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=Fo();let a;const[,c]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=Ls.MESSAGE_TYPE;const d=await this.wrapSocket(u,t,n);return d instanceof Error?[h,d]:(a=d,[h,null])});if(c!=null)throw c;return a}buildURL(e,t){const n=jo({[Us]:this.encoder.contentType,...t.params},Jo);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new Ko(e,this.encoder,t,n))},e.onerror=a=>{const c=a;i(new Error(c.message))}})}};k(Zs,"MESSAGE_TYPE","arraybuffer");let tc=Zs;const or=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),rc="all",nc="create",sc="delete",ic="retrieve",ac="update",oc=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:e[0].toLowerCase()+e.slice(1)},_s=r=>{const e=(t,n=Xr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(c=>e(c,n));if(!Pr(t))return t;n=uc(n);const i={},a=t;return Object.keys(a).forEach(c=>{let l=a[c];const u=r(c);n.recursive&&(Pr(l)?Ln(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&Zn(l)&&(l=[...l].map(h=>{let d=h;return Pr(h)?Ln(d,n.keepTypesOnRecursion)||(d=e(h,n)):Zn(h)&&(d=e({key:h},n).key),d}))),i[u]=l}),i};return e},Ys=_s(oc),cc=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),lc=_s(cc),Xr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},uc=(r=Xr)=>(r.recursive==null?r=Xr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),Zn=r=>r!=null&&Array.isArray(r),Pr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ln=(r,e)=>(e||[]).some(t=>r instanceof t),hn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var hc=Object.defineProperty,yc=(r,e,t)=>e in r?hc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Tt=(r,e,t)=>yc(r,typeof e!="symbol"?e+"":e,t);let qs=class{constructor(){Tt(this,"contentType","application/json"),Tt(this,"decoder"),Tt(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=Ys(n);return t!=null?t.parse(i):i}encodeString(e){const t=lc(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):hn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Ws=class{constructor(){Tt(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||!hn(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(c=>JSON.stringify(i[c]??""));n.push(a.join(","))}),n.join(`
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
+ `).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(`
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()),c={};return a.forEach(l=>{c[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,d)=>{const y=this.parseValue(u[d]);y!=null&&c[h].push(y)})}),t!=null?t.parse(c):c}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(){}},Gs=class{constructor(){Tt(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 Xe=new qs,dc=new Ws,fc=new Gs,pc=[Xe],nt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ws,CSV_CODEC:dc,ENCODERS:pc,JSONCodec:qs,JSON_CODEC:Xe,TEXT_CODEC:fc,TextCodec:Gs},Symbol.toStringTag,{value:"Module"})),pr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Fs=s.z.object({width:s.z.number(),height:s.z.number()}),gc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),mc=["width","height"];s.z.enum(mc);const wc=["start","center","end"],bc=["signedWidth","signedHeight"];s.z.enum(bc);const cr=s.z.object({x:s.z.number(),y:s.z.number()}),Tc=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),vc=["x","y"],Vs=s.z.enum(vc),Ks=["top","right","bottom","left"];s.z.enum(Ks);const Oc=["left","right"],Js=s.z.enum(Oc),zc=["top","bottom"],Hs=s.z.enum(zc),Xs=["center"],_n=s.z.enum(Xs),Ec=[...Ks,...Xs],Qs=s.z.enum(Ec);s.z.enum(wc);const Sc=["first","last"];s.z.enum(Sc);const Nc=s.z.object({lower:s.z.number(),upper:s.z.number()}),Ic=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Nc,pr]);s.z.union([Ic,pr]);s.z.union([Vs,Qs]);s.z.union([Vs,Qs,s.z.instanceof(String)]);const vt=(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 Yn(r);return Yn(t)},Yn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Js.or(_n),y:Hs.or(_n)});const kc=s.z.object({x:Js,y:Hs}),Ac=Object.freeze({x:"left",y:"top"}),$c=(r,e)=>r.x===e.x&&r.y===e.y,qn=s.z.union([s.z.number(),cr,pr,Fs,gc,Tc]),Rc=(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}},Wn=Object.freeze({x:0,y:0}),Gt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Gt,left:Gt,width:Gt,height:Gt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:cr,two:cr,root:kc});const yn=(r,e,t=0,n=0,i)=>{const a={one:{...Wn},two:{...Wn},root:i??Ac};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))},Dr=r=>{const e=yn(r);return{lower:e.one.x,upper:e.two.x}},jr=r=>{const e=yn(r);return{lower:e.one.y,upper:e.two.y}},xc=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Cc=Object.defineProperty,Pc=(r,e,t)=>e in r?Cc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,fe=(r,e,t)=>Pc(r,typeof e!="symbol"?e+"":e,t);const Dc=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:qn,scale:qn});const jc=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Mc=r=>(e,t,n,i)=>[e,i?n/r:n*r],Bc=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,h=l-c;if(t==="dimension")return[r,n*(h/u)];const d=(n-i)*(h/u)+c;return[r,d]},Uc=r=>(e,t,n)=>[r,n],Zc=()=>(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)]},Lc=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Dc(n,i,a),[e,n]},Qr=class yt{constructor(){fe(this,"ops",[]),fe(this,"currBounds",null),fe(this,"currType",null),fe(this,"reversed",!1),this.ops=[]}static translate(e){return new yt().translate(e)}static magnify(e){return new yt().magnify(e)}static scale(e,t){return new yt().scale(e,t)}translate(e){const t=this.new(),n=jc(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Mc(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=vt(e,t),i=this.new(),a=Bc(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=vt(e,t),i=this.new(),a=Lc(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=vt(e,t),i=this.new(),a=Uc(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Zc();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 yt;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(([c,l])=>i>=c&&i<=l))return;const a=e.ops.findIndex((c,l)=>c.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(Qr,"IDENTITY",new Qr);let Gn=Qr;const Fn=class he{constructor(e=new Gn,t=new Gn,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 he().translate(e,t)}static translateX(e){return new he().translateX(e)}static translateY(e){return new he().translateY(e)}static clamp(e){return new he().clamp(e)}static magnify(e){return new he().magnify(e)}static scale(e){return new he().scale(e)}static reBound(e){return new he().reBound(e)}translate(e,t){const n=Rc(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(xc(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!$c(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(Dr(e)),t.y=t.y.scale(jr(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(Dr(e)),t.y=this.y.reBound(jr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Dr(e)),t.y=this.y.clamp(jr(e)),t}copy(){const e=new he;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 yn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};fe(Fn,"IDENTITY",new Fn);const Vn=r=>[...new Set(r)],_c=r=>r!=null&&typeof r=="object"&&"toString"in r,Yc=(r,e=!1)=>{const t=_c(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?qc(n):n},qc=r=>(e,t)=>r(t,e),gr=0,Mr=-1,Br=1,Wc=r=>r<gr,Gc=r=>r>gr,Fc=r=>r===gr,Vc=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Kc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Fs,Kc,cr,pr]);const Jc=s.z.bigint().or(s.z.string().transform(BigInt));var Hc=Object.defineProperty,Xc=(r,e,t)=>e in r?Hc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,g=(r,e,t)=>Xc(r,typeof e!="symbol"?e+"":e,t);let Qc=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const el="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ei=Qc(el,11),tl=Object.freeze(Object.defineProperty({__proto__:null,id:ei},Symbol.toStringTag,{value:"Module"})),rl=s.z.enum(["static","dynamic"]),ti=(r,e)=>{const t=new S(e);if(![E.DAY,E.HOUR,E.MINUTE,E.SECOND,E.MILLISECOND,E.MICROSECOND,E.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof S?new S(n):new E(n)},x=class O{constructor(e,t="UTC"){if(g(this,"value"),g(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 c="00",l="00";a!=null&&([c,l]=a.split("."));let u=O.hours(parseInt(n??"00",10)).add(O.minutes(parseInt(i??"00",10))).add(O.seconds(parseInt(c??"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 E(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 ti(this,e)}get isToday(){return this.truncate(E.DAY).equals(O.now().truncate(E.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)}};g(x,"NANOSECOND",x.nanoseconds(1)),g(x,"MICROSECOND",x.microseconds(1)),g(x,"MILLISECOND",x.milliseconds(1)),g(x,"SECOND",x.seconds(1)),g(x,"MINUTE",x.minutes(1)),g(x,"HOUR",x.hours(1)),g(x,"DAY",x.days(1)),g(x,"MAX",new x((1n<<63n)-1n)),g(x,"MIN",new x(0)),g(x,"ZERO",new x(0)),g(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 S=x;const C=class I{constructor(e){g(this,"value"),g(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new I(e).valueOf()}greaterThan(e){return this.valueOf()>new I(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new I(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new I(e).valueOf()}remainder(e){return ti(this,e)}truncate(e){return new I(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(I.DAY),t=this.truncate(I.HOUR),n=this.truncate(I.MINUTE),i=this.truncate(I.SECOND),a=this.truncate(I.MILLISECOND),c=this.truncate(I.MICROSECOND),l=this.truncate(I.NANOSECOND),u=e,h=t.sub(e),d=n.sub(t),y=i.sub(n),P=a.sub(i),D=c.sub(a),Q=l.sub(c);let B="";return u.isZero||(B+=`${u.days}d `),h.isZero||(B+=`${h.hours}h `),d.isZero||(B+=`${d.minutes}m `),y.isZero||(B+=`${y.seconds}s `),P.isZero||(B+=`${P.milliseconds}ms `),D.isZero||(B+=`${D.microseconds}µs `),Q.isZero||(B+=`${Q.nanoseconds}ns`),B.trim()}get days(){return Number(this.valueOf())/Number(I.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(I.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(I.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(I.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(I.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(I.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new I(e).valueOf()}add(e){return new I(this.valueOf()+new I(e).valueOf())}sub(e){return new I(this.valueOf()-new I(e).valueOf())}static nanoseconds(e=1){return new I(e)}static microseconds(e=1){return I.nanoseconds(e*1e3)}static milliseconds(e=1){return I.microseconds(e*1e3)}static seconds(e=1){return I.milliseconds(e*1e3)}static minutes(e){return I.seconds(e.valueOf()*60)}static hours(e){return I.minutes(e*60)}static days(e){return I.hours(e*24)}};g(C,"NANOSECOND",C.nanoseconds(1)),g(C,"MICROSECOND",C.microseconds(1)),g(C,"MILLISECOND",C.milliseconds(1)),g(C,"SECOND",C.seconds(1)),g(C,"MINUTE",C.minutes(1)),g(C,"HOUR",C.hours(1)),g(C,"DAY",C.days(1)),g(C,"MAX",new C((1n<<63n)-1n)),g(C,"MIN",new C(0)),g(C,"ZERO",new C(0)),g(C,"z",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 E=C;const dt=class tr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new tr(e).valueOf()}get period(){return E.seconds(1/this.valueOf())}sampleCount(e){return new E(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new V(t).valueOf()}span(e){return E.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new tr(e)}static khz(e){return tr.hz(e*1e3)}};g(dt,"z",s.z.union([s.z.number().transform(r=>new dt(r)),s.z.instanceof(Number).transform(r=>new dt(r)),s.z.instanceof(dt)]));let mr=dt;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 Et(e*this.valueOf())}};g(q,"UNKNOWN",new q(0)),g(q,"BIT128",new q(16)),g(q,"BIT64",new q(8)),g(q,"BIT32",new q(4)),g(q,"BIT16",new q(2)),g(q,"BIT8",new q(1)),g(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 V=q;const ae=class rr{constructor(e,t){g(this,"start"),g(this,"end"),typeof e=="object"&&"start"in e?(this.start=new S(e.start),this.end=new S(e.end)):(this.start=new S(e),this.end=new S(t))}get span(){return new E(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new rr(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=E.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const i=S.max(n.start,e.start),a=S.min(n.end,e.end);return a.before(i)?!1:new E(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 rr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new rr(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}};g(ae,"MAX",new ae(S.MIN,S.MAX)),g(ae,"MIN",new ae(S.MAX,S.MIN)),g(ae,"ZERO",new ae(S.ZERO,S.ZERO)),g(ae,"z",s.z.union([s.z.object({start:S.z,end:S.z}).transform(r=>new ae(r.start,r.end)),s.z.instanceof(ae)]));let W=ae;const p=class oe extends String{constructor(e){if(e instanceof oe||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=oe.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(oe.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=oe.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(oe.JSON)||this.equals(oe.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(oe.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=oe.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 oe.BIG_INT_TYPES.some(e=>e.equals(this))}};g(p,"UNKNOWN",new p("unknown")),g(p,"FLOAT64",new p("float64")),g(p,"FLOAT32",new p("float32")),g(p,"INT64",new p("int64")),g(p,"INT32",new p("int32")),g(p,"INT16",new p("int16")),g(p,"INT8",new p("int8")),g(p,"UINT64",new p("uint64")),g(p,"UINT32",new p("uint32")),g(p,"UINT16",new p("uint16")),g(p,"UINT8",new p("uint8")),g(p,"BOOLEAN",p.UINT8),g(p,"TIMESTAMP",new p("timestamp")),g(p,"UUID",new p("uuid")),g(p,"STRING",new p("string")),g(p,"JSON",new p("json")),g(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),g(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),g(p,"DENSITIES",new Map([[p.UINT8.toString(),V.BIT8],[p.UINT16.toString(),V.BIT16],[p.UINT32.toString(),V.BIT32],[p.UINT64.toString(),V.BIT64],[p.FLOAT32.toString(),V.BIT32],[p.FLOAT64.toString(),V.BIT64],[p.INT8.toString(),V.BIT8],[p.INT16.toString(),V.BIT16],[p.INT32.toString(),V.BIT32],[p.INT64.toString(),V.BIT64],[p.TIMESTAMP.toString(),V.BIT64],[p.STRING.toString(),V.UNKNOWN],[p.JSON.toString(),V.UNKNOWN],[p.UUID.toString(),V.BIT128]])),g(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),g(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),g(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let z=p;const F=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),c=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),d=a.sub(i);let y="";return c.isZero||(y+=`${c.terabytes}TB `),l.isZero||(y+=`${l.gigabytes}GB `),u.isZero||(y+=`${u.megabytes}MB `),h.isZero||(y+=`${h.kilobytes}KB `),(!d.isZero||y==="")&&(y+=`${d.valueOf()}B`),y.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}};g(F,"BYTE",new F(1)),g(F,"KILOBYTE",F.kilobytes(1)),g(F,"MEGABYTE",F.megabytes(1)),g(F,"GIGABYTE",F.gigabytes(1)),g(F,"TERABYTE",F.terabytes(1)),g(F,"ZERO",new F(0)),g(F,"z",s.z.union([s.z.number().transform(r=>new F(r)),s.z.instanceof(F)]));let Et=F;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 ri=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof S||r instanceof E||r instanceof Date},nl=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):pt(t,-n),sl=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof be?!0:ri(r),Ie=-1,il=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),al=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),ft=class ye{constructor(e){g(this,"key",""),g(this,"isSynnaxSeries",!0),g(this,"dataType"),g(this,"sampleOffset"),g(this,"gl"),g(this,"_data"),g(this,"_timeRange"),g(this,"alignment",0n),g(this,"_cachedMin"),g(this,"_cachedMax"),g(this,"writePos",Ie),g(this,"_refCount",0),g(this,"_cachedLength"),sl(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=ei()}=e,u=e.data??[];if(u instanceof ye||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const y=u;this.key=y.key,this.dataType=y.dataType,this.sampleOffset=y.sampleOffset,this.gl=y.gl,this._data=y._data,this._timeRange=y._timeRange,this.alignment=y.alignment,this._cachedMin=y._cachedMin,this._cachedMax=y._cachedMax,this.writePos=y.writePos,this._refCount=y._refCount,this._cachedLength=y._cachedLength;return}const h=ri(u),d=Array.isArray(u);if(t!=null)this.dataType=new z(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(d||h){let y=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.");y=u[0]}if(typeof y=="string")this.dataType=z.STRING;else if(typeof y=="number")this.dataType=z.FLOAT64;else if(typeof y=="bigint")this.dataType=z.INT64;else if(typeof y=="boolean")this.dataType=z.BOOLEAN;else if(y instanceof S||y instanceof Date||y instanceof S)this.dataType=z.TIMESTAMP;else if(typeof y=="object")this.dataType=z.JSON;else throw new Error(`cannot infer data type of ${typeof y} when constructing a Series from a JS array`)}else this.dataType=new z(u)}if(!d&&!h)this._data=u;else{let y=h?[u]:u;const P=y[0];(P instanceof S||P instanceof Date||P instanceof E)&&(y=y.map(D=>new S(D).valueOf())),this.dataType.equals(z.STRING)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.join(`
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
16
  `)+`
17
- `)):this.dataType.equals(z.JSON)?(this._cachedLength=y.length,this._data=new TextEncoder().encode(y.map(D=>Xe.encodeString(D)).join(`
17
+ `)):this.dataType.equals(S.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(d.map(D=>rt.encodeString(D)).join(`
18
18
  `)+`
19
- `)):this._data=new this.dataType.Array(y).buffer}this.key=l,this.alignment=c,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 z(t).Array(e),a=new ye({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 c=0;c<e;c++)a[c]=BigInt(n.add(t.span(c)).valueOf());return new ye({data:a,dataType:z.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
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
20
  `)+`
21
- `);return new ye({data:n,dataType:z.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>Xe.encodeString(i)).join(`
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
22
  `)+`
23
- `);return new ye({data:n,dataType:z.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");if(this.writePos===Ie)return 0;const t=this.capacity-this.writePos,n=t<e.length?e.slice(0,t):e;return this.underlyingData.set(n.data,this.writePos),this.maybeRecomputeMinMax(n),this._cachedLength=void 0,this.writePos+=n.length,n.length}get buffer(){return this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Ie?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(z.STRING,z.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
24
- `).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(z.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=z.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.buffer.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i),c=>c.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(z.JSON))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.buffer).split(`
25
- `).slice(0,-1).map(t=>e.parse(Xe.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new Et(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Ie?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Ie?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;return this.data.forEach(t=>{t===10&&e++}),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]=nl(this.dataType,e,this.data[i],t);return new ye({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(z.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()),pt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(z.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()),pt(this._cachedMin,this.sampleOffset))}get bounds(){return vt(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 pt(this.max,-this.min)}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 pt(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,i=0;for(let c=0;c<this.data.length;c++)if(this.data[c]===10){if(e===0){i=c;break}n=c+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(z.STRING)?new TextDecoder().decode(a):Ys(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Yc(e);for(;t<=n;){const a=Math.floor((t+n)/2),c=i(this.at(a,!0),e);if(c===0)return a;c<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(z.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!==Ie){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),c=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,c.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Ie}as(e){if(e==="string"){if(!this.dataType.equals(z.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(z.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 vt(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 ol(this);return this.dataType.equals(z.JSON)?new cl(e):e}return new ll(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(e,t);return new ye({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new ye({data:this.buffer,dataType:this.dataType,timeRange:W.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};g(ft,"crudeZ",s.z.object({timeRange:W.z.optional(),dataType:z.z,alignment:Jc.optional(),data:s.z.union([il,al,s.z.instanceof(ArrayBuffer)]),glBufferUsage:rl.optional().default("static").optional()})),g(ft,"z",ft.crudeZ.transform(r=>new ft(r)));let be=ft;class ol{constructor(e){if(g(this,"series"),g(this,"index"),g(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==10;)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 Kn,Jn;class cl{constructor(e){g(this,"wrapped"),g(this,Kn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Xe.decodeString(e.value)}}[(Jn=Symbol.iterator,Kn=Symbol.toStringTag,Jn)](){return this}}var Hn,Xn;class ll{constructor(e){g(this,"series"),g(this,"index"),g(this,Hn,"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)}}[(Xn=Symbol.iterator,Hn=Symbol.toStringTag,Xn)](){return this}}const pt=(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 ni{constructor(e){if(g(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 z(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?z.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)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}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}`)}get byteLength(){return new Et(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)}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new ul(this.series)}}var Qn,es;class ul{constructor(e){g(this,"series"),g(this,"seriesIndex"),g(this,"internal"),g(this,Qn,"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())}[(es=Symbol.iterator,Qn=Symbol.toStringTag,es)](){return this}}s.z.object({key:s.z.string(),value:s.z.string()});var hl=Object.defineProperty,yl=(r,e,t)=>e in r?hl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,nr=(r,e,t)=>yl(r,typeof e!="symbol"?e+"":e,t);let dl=class{constructor(e,t){nr(this,"handlers"),nr(this,"transform"),nr(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))}},fl=class{constructor(e){nr(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 xe=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:fl,Observer:dl},Symbol.toStringTag,{value:"Module"})),dn=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),pl=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";pl();const gl=["MacOS","Windows","Linux","Docker"];s.z.enum(gl);var ml=Object.defineProperty,wl=(r,e,t)=>e in r?ml(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,gt=(r,e,t)=>wl(r,typeof e!="symbol"?e+"":e,t);const bl=(...r)=>r.map(si).join(""),si=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Tl=r=>r.endsWith("/")?r.slice(0,-1):r,en=class tn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){gt(this,"protocol"),gt(this,"host"),gt(this,"port"),gt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=si(i)}replace(e){return new tn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new tn({...this,pathPrefix:bl(this.path,e)})}toString(){return Tl(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};gt(en,"UNKNOWN",new en({host:"unknown",port:0}));let vl=en;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,sr=(r,e,t)=>zl(r,typeof e!="symbol"?e+"":e,t);const ke=class extends Number{};sr(ke,"Absolute",255),sr(ke,"Default",1),sr(ke,"z",s.z.union([s.z.instanceof(ke),s.z.number().int().min(0).max(255).transform(r=>new ke(r)),s.z.instanceof(Number).transform(r=>new ke(r))]));let ii=ke;const ai=s.z.object({name:s.z.string(),key:s.z.string()}),El=r=>s.z.object({subject:ai,resource:r,authority:ii.z}),Sl=(...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}),et=Object.freeze(Object.defineProperty({__proto__:null,Authority:ii,filterTransfersByChannelKey:Sl,stateZ:El,subjectZ:ai},Symbol.toStringTag,{value:"Module"})),oi=class mt extends Error{constructor(){super(mt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(mt.MESSAGE):e instanceof mt||e.message.includes(mt.MESSAGE)}};sr(oi,"MESSAGE","canceled");let Nl=oi;new Nl;const rn=s.z.string().regex(/^\d+\.\d+\.\d+$/),xt=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=rn.parse(r),i=rn.parse(e),[a,c,l]=n.split(".").map(Number),[u,h,d]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return Mr;if(a>u)return Br}if(t.checkMinor){if(c<h)return Mr;if(c>h)return Br}if(t.checkPatch){if(l<d)return Mr;if(l>d)return Br}return gr},Il=(r,e,t={})=>Fc(xt(r,e,t)),ci=(r,e,t={})=>Gc(xt(r,e,t)),kl=(r,e,t={})=>Wc(xt(r,e,t)),Al=({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}},$l=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(xt).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}.
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
+ `).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}.
26
26
  Returning default instead.
27
- `),i;try{return t!=null?t.parse(h):h}catch(d){return console.log(`${r} failed to parse default. Exiting with default`),console.error(d),i}};const c=Object.keys(e).length;let l=!1;const u=h=>{try{if(c===0||ci(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 d=h.version,y=e[d],P=y(h);return l=!0,u(P)}catch(d){return console.log(`${r} failed to migrate from ${h.version} to ${a}`),console.error(d),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(d){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(d),i}}},ts=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:xt,createMigration:Al,migrator:$l,semVerNewer:ci,semVerOlder:kl,semVerZ:rn,versionsEqual:Il},Symbol.toStringTag,{value:"Module"})),ze="sy.",Be=class Be extends ne{constructor(){super(...arguments);o(this,"type",Be.TYPE)}};o(Be,"TYPE",ze+"validation"),o(Be,"matches",H(Be.TYPE));let M=Be;const Ue=class Ue extends M{constructor(t,n){super(t+": "+n);o(this,"type",Ue.TYPE);o(this,"field");o(this,"message");this.field=t,this.message=n}};o(Ue,"TYPE",M.TYPE+".field"),o(Ue,"matches",H(Ue.TYPE));let lr=Ue;const Ze=class Ze extends ne{constructor(){super(...arguments);o(this,"type",Ze.TYPE)}};o(Ze,"TYPE",ze+"auth"),o(Ze,"matches",H(Ze.TYPE));let Ce=Ze;const Le=class Le extends Ce{constructor(){super(...arguments);o(this,"type",Le.TYPE)}};o(Le,"TYPE",Ce.TYPE+".invalid-token"),o(Le,"matches",H(Le.TYPE));let St=Le;const _e=class _e extends ne{constructor(t){super(`
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 $t=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
- `);o(this,"type",_e.TYPE)}};o(_e,"TYPE",ze+"unexpected"),o(_e,"matches",H(_e.TYPE));let ve=_e;const Ye=class Ye extends ne{constructor(){super(...arguments);o(this,"type",Ye.TYPE)}};o(Ye,"TYPE",ze+"query"),o(Ye,"matches",H(Ye.TYPE));let te=Ye;const qe=class qe extends te{constructor(){super(...arguments);o(this,"type",qe.TYPE)}};o(qe,"TYPE",te.TYPE+".not_found"),o(qe,"matches",H(qe.TYPE));let pe=qe;const We=class We extends te{constructor(){super(...arguments);o(this,"type",We.TYPE)}};o(We,"TYPE",te.TYPE+".multiple_results"),o(We,"matches",H(We.TYPE));let ge=We;const Ge=class Ge extends ne{constructor(t,n){super(t);o(this,"type",Ge.TYPE);o(this,"path");this.path=n}};o(Ge,"TYPE",ze+"route"),o(Ge,"matches",H(Ge.TYPE));let Nt=Ge;const Fe=class Fe extends ne{constructor(){super(...arguments);o(this,"type",Fe.TYPE)}};o(Fe,"TYPE",ze+"control"),o(Fe,"matches",H(Fe.TYPE));let tt=Fe;const Ve=class Ve extends tt{constructor(){super(...arguments);o(this,"type",Ve.TYPE)}};o(Ve,"TYPE",tt.TYPE+".unauthorized"),o(Ve,"matches",H(Ve.TYPE));let ur=Ve;const Ke=class Ke extends ne{constructor(){super(...arguments);o(this,"type",Ke.TYPE)}};o(Ke,"TYPE",ze+"contiguity"),o(Ke,"matches",H(Ke.TYPE));let nn=Ke;const Rl=r=>{if(!r.type.startsWith(ze))return null;if(r.type.startsWith(M.TYPE)){if(r.type===lr.TYPE){const e=r.data.split(": ");return e.length<2?new M(r.data):new lr(e[0],e[1])}return new M(r.data)}return r.type.startsWith(Ce.TYPE)?r.type.startsWith(St.TYPE)?new St(r.data):new Ce(r.data):r.type.startsWith(ve.TYPE)?new ve(r.data):r.type.startsWith(te.TYPE)?r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(ge.TYPE)?new ge(r.data):new te(r.data):r.type.startsWith(tt.TYPE)?r.type.startsWith(ur.TYPE)?new ur(r.data):new tt(r.data):r.type.startsWith(Nt.TYPE)?new Nt(r.data,r.data):new ve(r.data)},xl=()=>{throw new Error("Not implemented")};Ps({encode:xl,decode:Rl});const Cl=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Re?[t,new Re({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class li{constructor(e,t){o(this,"key");o(this,"name");this.key=t,this.name=e}get ontologyID(){return new b({type:"group",key:this.key})}}const Pl=s.z.string().uuid(),ui=s.z.object({key:Pl,name:s.z.string()}),Ct=s.z.union([s.z.literal("label"),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")]),Dl="builtin",jl="cluster",Ml="node",J=s.z.object({type:Ct,key:s.z.string()}),hi=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Ct.parse(e),key:t??""}}),Me=s.z.union([hi,J]),Je=class Je{constructor(e){o(this,"type");o(this,"key");if(e instanceof Je){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}}};o(Je,"z",s.z.union([s.z.instanceof(Je),Me.transform(e=>new Je(e))]));let b=Je;const Bl=new b({type:"builtin",key:"root"}),yi=s.z.object({type:s.z.number()}),di=s.z.object({type:Ct,fields:s.z.record(yi)}),fi=s.z.object({id:b.z,name:s.z.string(),schema:di.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),Ul=s.z.object({from:b.z,type:s.z.string(),to:b.z}),sn=r=>{const[e,t,n]=r.split("->");return{from:new b(e),type:t,to:new b(n)}},Zl=s.z.object({group:ui}),Ll=s.z.object({parent:J,key:s.z.string().uuid().optional(),name:s.z.string()}),_l=s.z.object({key:s.z.string(),name:s.z.string()}),Yl=s.z.object({keys:s.z.array(s.z.string())});var re;let ql=(re=class{constructor(e){o(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,re.ENDPOINT,{parent:e,name:t,key:n},Ll,Zl)).group}async rename(e,t){await w(this.client,re.ENDPOINT_RENAME,{key:e,name:t},_l,s.z.object({}))}async delete(e){await w(this.client,re.ENDPOINT_DELETE,{keys:e},Yl,s.z.object({}))}},o(re,"ENDPOINT","/ontology/create-group"),o(re,"ENDPOINT_RENAME","/ontology/rename-group"),o(re,"ENDPOINT_DELETE","/ontology/delete-group"),re),Wl=class{constructor(e){o(this,"creator");this.creator=new ql(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 li(e.name,e.key)}};const Ur={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},rs=s.z.object({id:J,children:J.array()}),Gl=s.z.object({from:J,to:J,children:J.array()});let Fl=class{constructor(e){o(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Ur.ADD_CHILDREN,{id:new b(e).payload,children:t.map(n=>new b(n).payload)},rs,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Ur.REMOVE_CHILDREN,{id:new b(e).payload,children:t.map(n=>new b(n).payload)},rs,s.z.object({}))}async moveChildren(e,t,...n){const i={from:new b(e).payload,to:new b(t).payload,children:n.map(a=>new b(a).payload)};await w(this.client,Ur.MOVE_CHILDREN,i,Gl,s.z.object({}))}};const Vl="/ontology/retrieve",Kl=s.z.object({ids:J.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:Ct.array().optional()}),Jl=s.z.object({resources:fi.array()}),ir=r=>T(r).map(e=>new b(e).payload);let pi=class{constructor(e,t){o(this,"type","ontology");o(this,"groups");o(this,"client");o(this,"writer");o(this,"framer");this.client=e,this.writer=new Fl(e),this.groups=new Wl(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:ir(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new te(`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:ir(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:ir(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 Pt.open(this.framer,this)}async openDependentTracker(e){return await wr.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,Vl,e,Kl,Jl);return t}};const ns="sy_ontology_resource_set",ss="sy_ontology_resource_delete",is="sy_ontology_relationship_set",as="sy_ontology_relationship_delete";class Pt{constructor(e,t){o(this,"relationships");o(this,"resources");o(this,"resourceObs");o(this,"relationshipObs");o(this,"streamer");o(this,"client");o(this,"closePromise");this.relationshipObs=new xe.Observer,this.relationships=this.relationshipObs,this.resourceObs=new xe.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),c=this.parseRelationshipDeletes(e);a.concat(c).length>0&&this.relationshipObs.notify(a.concat(c))}parseRelationshipSets(e){const t=e.get(is);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:sn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(as);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:sn(n)}))}async parseResourceSets(e){const t=e.get(ns);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new b(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof te)return[];throw i}}parseResourceDeletes(e){const t=e.get(ss);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new b(n)}))}static async open(e,t){const n=await e.openStreamer([ns,ss,is,as]);return new Pt(n,t)}}const os=r=>r==="from"?"to":"from";class wr extends xe.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:c},l,u){super();o(this,"internal");o(this,"target");o(this,"relDir");o(this,"resourceType");o(this,"dependents");o(this,"client");o(this,"relType");o(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)});o(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[os(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(c=>c.key.to.toString()===a.id.toString()&&c.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[os(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=c,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 Pt.open(n,i);return new wr(t,a,i)}async close(){await this.internal.close()}}const Hl=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Dl,CLUSTER_TYPE:jl,ChangeTracker:Pt,Client:pi,DependentTracker:wr,ID:b,NODE_TYPE:Ml,Root:Bl,crudeIDZ:Me,idZ:J,parseIDs:ir,parseRelationship:sn,relationshipSchemaZ:Ul,resourceSchemaZ:fi,resourceTypeZ:Ct,schemaFieldZ:yi,schemaZ:di,stringIDZ:hi},Symbol.toStringTag,{value:"Module"})),ee=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),Dt=s.z.string().uuid(),gi=s.z.object({key:Dt.optional(),subjects:Me.array().or(Me),objects:Me.array().or(Me),actions:or.array().or(or)}),br=s.z.object({key:Dt,subjects:ee(J),objects:ee(J),actions:ee(or)}),mi="policy",Xl=r=>new b({type:mi,key:r}),wi="allow_all",Ql=new b({type:wi,key:""}),eu=s.z.object({keys:Dt.array().optional(),subjects:J.array().optional()}),tu=s.z.object({policies:ee(br)}),ru="/access/policy/retrieve";let nu=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,ru,e,eu,tu)).policies}};const su=s.z.object({policies:br.partial({key:!0}).array()}),iu=s.z.object({policies:br.array()}),au=s.z.object({keys:Dt.array()}),ou=s.z.object({}),cu="/access/policy/create",lu="/access/policy/delete";let uu=class{constructor(e){o(this,"client");this.client=e}async create(e){const n=gi.array().parse(T(e)).map(a=>({objects:T(a.objects),actions:T(a.actions),subjects:T(a.subjects)}));return(await w(this.client,cu,{policies:n},su,iu)).policies}async delete(e){await w(this.client,lu,{keys:T(e)},au,ou)}},bi=class{constructor(e){o(this,"retriever");o(this,"writer");this.retriever=new nu(e),this.writer=new uu(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:T(e)});return t?n:n[0]}async retrieveFor(e){const t=T(e).map(n=>new b(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const hu=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Ql,ALLOW_ALL_ONTOLOGY_TYPE:wi,Client:bi,ONTOLOGY_TYPE:mi,keyZ:Dt,newPolicyZ:gi,ontologyID:Xl,policyZ:br},Symbol.toStringTag,{value:"Module"}));let Ti=class{constructor(e){o(this,"policy");this.policy=new bi(e)}};const yu=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:rc,CREATE_ACTION:nc,Client:Ti,DELETE_ACTION:sc,RETRIEVE_ACTION:ic,UPDATE_ACTION:ac,actionZ:or},Symbol.toStringTag,{value:"Module"})),Ee=s.z.number(),jt=s.z.object({name:s.z.string(),key:s.z.number(),rate:mr.z,dataType:z.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()}),vi=jt.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:mr.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Oi="channel",du=r=>new b({type:Oi,key:r.toString()}),fu=new Error("request for lock canceled");var pu=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(d){try{h(n.next(d))}catch(y){c(y)}}function u(d){try{h(n.throw(d))}catch(y){c(y)}}function h(d){d.done?a(d.value):i(d.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class gu{constructor(e,t=fu){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},c=zi(this._queue,l=>t<=l.priority);c===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(c+1,0,a)})}runExclusive(e){return pu(this,arguments,void 0,function*(t,n=1,i=0){const[a,c]=yield this.acquire(n,i);try{return yield t(a)}finally{c()}})}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]=[]),mu(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 mu(r,e){const t=zi(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function zi(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var wu=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(c){c(a)})}return new(t||(t=Promise))(function(a,c){function l(d){try{h(n.next(d))}catch(y){c(y)}}function u(d){try{h(n.throw(d))}catch(y){c(y)}}function h(d){d.done?a(d.value):i(d.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class bu{constructor(e){this._semaphore=new gu(1,e)}acquire(){return wu(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 Tr=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=T(r);const a=i[0],c=typeof a;let l;return c==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[c],{single:n,variant:l,normalized:i,actual:r}},vr=(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 ge(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Tu=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:z.z.array().optional(),notDataTypes:z.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),vu=s.z.object({channels:ee(jt)}),me=r=>Tr(r,{number:"keys",string:"names"}),yr=class yr{constructor(e){o(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const n=me(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(c=>c!==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(yr.ENDPOINT,e,Tu,vu);if(n!=null)throw n;return t.channels}};o(yr,"ENDPOINT","/channel/retrieve");let It=yr;class fn{constructor(e){o(this,"cache");o(this,"namesToKeys");o(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}=Tr(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 c=await this.wrapped.retrieve(a,t);return this.set(c),i.concat(c)}delete(e){const{variant:t,normalized:n}=me(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(c=>this.cache.delete(c)),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],c=this.cache.get(n);if(c==null)return;this.cache.delete(n);const l=this.namesToKeys.get(c.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(c.name)),c.name=a,this.cache.set(n,c);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 Ei{constructor(e,t){o(this,"mu",new bu);o(this,"requests",new Map);o(this,"wrapped");o(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Vc(()=>{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}=me(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,c)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:c}),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 Si=async(r,e)=>{const{normalized:t}=me(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(c=>c.name===a||c.key===a)==null&&i.push(a)}),i.length>0)throw new te(`Could not find channels: ${JSON.stringify(i)}`);return n};class pn{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:c=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:d,alias:y}){o(this,"_frameClient");o(this,"key");o(this,"name");o(this,"rate");o(this,"dataType");o(this,"leaseholder");o(this,"index");o(this,"isIndex");o(this,"internal");o(this,"alias");o(this,"virtual");this.key=a,this.name=n,this.rate=new mr(t??0),this.dataType=new z(e),this.leaseholder=i,this.index=l,this.isIndex=c,this.internal=u,this.alias=y,this.virtual=h,this._frameClient=d??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 jt.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 b({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 Ou="/channel/retrieve-group",zu=s.z.object({}),Eu=s.z.object({group:ui});let Ni=class{constructor(e,t,n,i){o(this,"type","channel");o(this,"frameClient");o(this,"client");o(this,"retriever");o(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=T(e),c=[];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)),c=this.sugar(l)}return c=c.concat(this.sugar(await this.writer.create(a))),i?c[0]:c}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return vr("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}=me(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(T(e),T(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 fn(new Ei(new It(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new pn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Ou,{},zu,Eu);return new li(e.group.name,e.group.key)}};const Su=s.z.object({channels:vi.array()}),Nu=s.z.object({channels:jt.array()}),Iu=s.z.object({keys:Ee.array().optional(),names:s.z.string().array().optional()}),ku=s.z.object({}),Au=s.z.object({keys:Ee.array(),names:s.z.string().array()}),$u=s.z.object({}),Ru="/channel/create",xu="/channel/delete",Cu="/channel/rename";let Ii=class{constructor(e,t){o(this,"client");o(this,"cache");this.client=e,this.cache=t}async create(e){const{channels:t}=await w(this.client,Ru,{channels:e},Su,Nu);return this.cache.set(t),t}async delete(e){await w(this.client,xu,e,Iu,ku),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Cu,{keys:e,names:t},Au,$u),this.cache.rename(e,t)}};const Pu=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:fn,Channel:pn,Client:Ni,ClusterRetriever:It,DebouncedBatchRetriever:Ei,ONTOLOGY_TYPE:Oi,Writer:Ii,analyzeChannelParams:me,keyZ:Ee,newPayload:vi,ontologyID:du,payload:jt,retrieveRequired:Si},Symbol.toStringTag,{value:"Module"})),st=s.z.string().uuid(),Mt=s.z.object({key:st,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),ki=Mt.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Ai="user",Du=r=>new b({type:Ai,key:r}),ju=s.z.object({keys:st.array().optional(),usernames:s.z.string().array().optional()}),Mu=s.z.object({users:ee(Mt)}),Bu="/user/retrieve";let Uu=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Bu,e,ju,Mu)).users}};const Zu=s.z.object({users:ki.array()}),Lu=s.z.object({users:Mt.array()}),_u=s.z.object({key:st,username:s.z.string().min(1)}),Yu=s.z.object({}),qu=s.z.object({key:st,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Wu=s.z.object({}),Gu=s.z.object({keys:st.array()}),Fu=s.z.object({}),Vu="/user/create",Ku="/user/change-username",Ju="/user/rename",Hu="/user/delete";let Xu=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,Vu,{users:T(e)},Zu,Lu)).users}async changeUsername(e,t){await w(this.client,Ku,{key:e,username:t},_u,Yu)}async rename(e,t,n){await w(this.client,Ju,{key:e,firstName:t,lastName:n},qu,Wu)}async delete(e){await w(this.client,Hu,{keys:T(e)},Gu,Fu)}},$i=class{constructor(e){o(this,"reader");o(this,"writer");this.writer=new Xu(e),this.reader=new Uu(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:T(e)});if(t)return n;if(n.length===0)throw new pe(`No user with key ${e} found`);if(n.length>1)throw new ge(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:T(e)});if(t)return n;if(n.length===0)throw new pe(`No user with username ${e} found`);if(n.length>1)throw new ge(`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 Qu=Object.freeze(Object.defineProperty({__proto__:null,Client:$i,ONTOLOGY_TYPE:Ai,keyZ:st,newUserZ:ki,ontologyID:Du,userZ:Mt},Symbol.toStringTag,{value:"Module"})),eh=s.z.object({username:s.z.string(),password:s.z.string()}),th=s.z.object({token:s.z.string(),user:Mt}),cs="/auth/login",rh=3,nh="/auth/change-password",sh=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),ih=s.z.object({});let ah=class{constructor(e,t){o(this,"token");o(this,"client");o(this,"credentials");o(this,"authenticating");o(this,"authenticated");o(this,"user");o(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,nh,{username:this.credentials.username,password:this.credentials.password,newPassword:e},sh,ih),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(cs)){this.authenticating==null&&(this.authenticating=new Promise((l,u)=>{this.client.send(cs,this.credentials,eh,th).then(([h,d])=>{if(d!=null)return l(d);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(null)}).catch(u)}));const c=await this.authenticating;if(c!=null)return[t,c]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return St.matches(a)&&this.retryCount<rh?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const oh=["disconnected","connecting","connected","failed"],Ri=s.z.enum(oh),xi=s.z.object({status:Ri,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()}),ls={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.32.0"},us=(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($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}.
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`},He=class He{constructor(e,t=E.seconds(30),n,i){o(this,"_state");o(this,"pollFrequency",E.seconds(30));o(this,"client");o(this,"name");o(this,"interval");o(this,"clientVersion");o(this,"onChangeHandlers",[]);o(this,"versionWarned",!1);this._state={...ls},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(He.ENDPOINT,{},s.z.object({}),ch);if(i!=null)throw i;const a=n.nodeVersion,c=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(us(null,c,!0)),this.versionWarned=!0)):ts.versionsEqual(c,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(us(a,c,ts.semVerNewer(c,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)}};o(He,"ENDPOINT","/connectivity/check"),o(He,"DEFAULT",ls),o(He,"connectionStateZ",xi);let kt=He;const lh=Object.freeze(Object.defineProperty({__proto__:null,Checker:kt,state:xi,status:Ri},Symbol.toStringTag,{value:"Module"})),uh=s.z.object({keys:Ee.array().optional(),bounds:W.z,names:s.z.string().array().optional()}),hh=s.z.object({}),yh="/frame/delete";class dh{constructor(e){o(this,"client");this.client=e}async delete(e){await w(this.client,yh,e,uh,hh)}}const hs=r=>{const e=T(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ys=(r,e)=>{const t=T(r);if(t.length===e.length)return;const n=hs(r);throw hs===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=[]){o(this,"columns",[]);o(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,...T(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(c=>Ci(c));ys(i.keys,a),i.keys.forEach((c,l)=>this.push(c,a[l]))}else Object.entries(e).forEach(([i,a])=>{const c=parseInt(i);if(isNaN(c))this.push(i,...T(a));else return this.push(c,...T(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=T(t),a=T(e);ys(a,i),i.forEach((c,l)=>this.push(a[l],c));return}throw new M(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
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 As=r=>{const e=b(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},$s=(r,e)=>{const t=b(r);if(t.length===e.length)return;const n=As(r);throw As===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));$s(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))this.push(i,...b(a));else return this.push(o,...b(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=b(t),a=b(e);$s(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
- name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new ve("colType is not key");return this.columns??[]}get uniqueKeys(){return Vn(this.keys)}get names(){if(this.colType==="key")throw new ve("colType is not name");return this.columns??[]}get uniqueNames(){return Vn(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Pi(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=S.min(...this.series.map(a=>a.timeRange.start)),i=S.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 ni(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 Et(this.series.reduce((e,t)=>e.add(t.byteLength),Et.ZERO))}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const Or=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(()=>[]),be.crudeZ.array().optional().default([])])}),Ci=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new be({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},Pi=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class zr{constructor(e){o(this,"adapter");o(this,"retriever");o(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new zr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=me(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(c=>{const l=i.find(u=>u.name===c);if(l==null)throw new Error(`Channel ${c} 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 gn{constructor(e){o(this,"adapter");o(this,"retriever");o(this,"keys");this.retriever=e,this.adapter=null,this.keys=[]}static async open(e,t){const n=new gn(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 Si(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(`
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.
40
- `);if(Array.isArray(t)){if(t.some(u=>u instanceof be||Array.isArray(u)))throw new M(`
40
+ `);if(Array.isArray(t)){if(t.some(u=>u instanceof ze||Array.isArray(u)))throw new M(`
41
41
  Received a single channel name or key but multiple series.
42
- `);t=t}const c=await this.fetchChannel(e),l=new be({data:t,dataType:c.dataType});return new _(c.key,l)}if(Array.isArray(e)){if(t==null)throw new M(`
42
+ `);t=t}const o=await this.fetchChannel(e),l=new ze({data:t,dataType:o.dataType});return new _(o.key,l)}if(Array.isArray(e)){if(t==null)throw new M(`
43
43
  Received an array of channel names or keys but no series.
44
44
  `);if(!Array.isArray(t))throw new M(`
45
45
  Received an array of channel names or keys but no array of series.
46
- `);const c=[],l=[];for(let u=0;u<e.length;u++){const h=await this.fetchChannel(e[u]);if(u>=t.length)throw new M(`
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 d=new be({data:t[u],dataType:h.dataType});c.push(h.key),l.push(d)}return new _(c,l)}if(e instanceof _||e instanceof Map){const c=new _(e);if(this.adapter==null)return c;let l=[];return l=c.columns.map(u=>{var d;const h=typeof u=="string"?(d=this.adapter)==null?void 0:d.get(u):u;if(h==null)throw new M(`
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;let l=[];return 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}),new _(l,c.series)}const n=[],i=[],a=Object.entries(e);for(let c=0;c<a.length;c++){const[l,u]=a[c],h=await this.fetchChannel(l),d=new be({data:u,dataType:h.dataType});n.push(h.key),i.push(d)}return new _(n,i)}}class mn{constructor(e,t){o(this,"name");o(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(Oe.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const an=new E(-1);var wn=(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))(wn||{}),Di=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Di||{});const fh=s.z.object({command:s.z.nativeEnum(wn),span:E.z.optional(),bounds:W.z.optional(),stamp:S.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),ph=s.z.object({variant:s.z.nativeEnum(Di),ack:s.z.boolean(),command:s.z.nativeEnum(wn),error:Rt.optional().nullable(),frame:Or.optional()}),zt=class zt{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"value");this.stream=new mn("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,n,i,a={}){const c=await zr.open(n,t),l=await i.stream(zt.ENDPOINT,fh,ph),u=new zt(l,c);return await u.execute({command:0,keys:c.keys,bounds:new W(e),chunkSize:a.chunkSize??1e5}),u}async next(e=an){return await this.execute({command:1,span:new E(e)})}async prev(e=an){return await this.execute({command:2,span:new E(e)})}async seekFirst(){return await this.execute({command:3})}async seekLast(){return await this.execute({command:4})}async seekLE(e){return await this.execute({command:5,stamp:new S(e)})}async seekGE(e){return await this.execute({command:6,stamp:new S(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new gh(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)))}}};o(zt,"ENDPOINT","/frame/iterate");let hr=zt;class gh{constructor(e){o(this,"iter");o(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 mh=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),wh=s.z.object({frame:Or,error:Rt.optional().nullable()}),bh="/frame/stream";class Er{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"downsampleFactor");this.stream=new mn("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 zr.open(e,n),c=await t.stream(bh,mh,wh),l=new Er(c,a);c.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await c.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Oe.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 Bt extends xe.Observer{constructor(t,n){super(n);o(this,"streamer");o(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 bn=(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))(bn||{}),rt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(rt||{});const Th=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in rt)return r;throw new Error(`invalid writer mode: ${r}`)}},vh=new E(-1),Oh=s.z.object({start:S.z.optional(),controlSubject:et.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:et.Authority.z.array().optional(),mode:s.z.nativeEnum(rt).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:E.z.optional()}),zh=s.z.object({command:s.z.nativeEnum(bn),config:Oh.optional(),frame:Or.optional()}),Eh=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(bn),error:Rt.optional().nullable()});var Te;let ji=(Te=class{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new mn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=S.now(),authorities:a=et.Authority.Absolute,controlSubject:c,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:d=E.SECOND}){const y=await gn.open(e,n),P=await t.stream(Te.ENDPOINT,zh,Eh),D=new Te(P,y);return await D.execute({command:0,config:{start:new S(i),keys:y.keys,controlSubject:c,authorities:T(a),mode:Th(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:d}}),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(c=>Number(c)),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?un(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()}},o(Te,"ENDPOINT","/frame/write"),Te);const Mi="framer",Sh=r=>new b({type:Mi,key:r.toString()});let Bi=class{constructor(e,t,n){o(this,"streamClient");o(this,"retriever");o(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new dh(t)}async openIterator(e,t,n){return await hr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ji._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await Er._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,c=await this.openWriter({start:e,channels:Object.keys(a),mode:rt.Persist});try{await c.write(a),await c.commit()}finally{await c.close()}return}const i=await this.openWriter({start:e,channels:t,mode:rt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=me(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}=me(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const Nh=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:vh,AUTO_SPAN:an,Client:Bi,Frame:_,Iterator:hr,ONTOLOGY_TYPE:Mi,ObservableStreamer:Bt,Streamer:Er,Writer:ji,WriterMode:rt,frameZ:Or,ontologyID:Sh,seriesFromPayload:Ci,seriesToPayload:Pi},Symbol.toStringTag,{value:"Module"})),Ih=et.Authority,kh=et.stateZ(s.z.number()),Ah=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 Ui extends Bt{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});o(this,"states");o(this,"codec");this.states=new Map,this.codec=new nt.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 $h="sy_node_1_control";let Zi=class{constructor(e){o(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer($h);return new Ui(e)}};const Rh=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ih,Client:Zi,StateTracker:Ui,stateZ:kh,transferString:Ah},Symbol.toStringTag,{value:"Module"}));let Li=class{constructor(e,t,n){o(this,"tasks");o(this,"racks");o(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const xh=Object.freeze(Object.defineProperty({__proto__:null,Client:Li},Symbol.toStringTag,{value:"Module"})),it=s.z.number(),Sr=s.z.object({key:it,name:s.z.string()}),_i=Sr.partial({key:!0}),Yi="rack",Ch=r=>new b({type:Yi,key:r.toString()}),Nr=s.z.string(),Ut=s.z.object({key:Nr,rack:it,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===""?{}:nt.JSON_CODEC.decodeString(r)))}),qi=Ut.extend({properties:s.z.unknown().transform(r=>nt.JSON_CODEC.encodeString(r))}),Wi="device",Ph=r=>new b({type:Wi,key:r.toString()}),Pe=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=c=>{const l=[];return t!=null&&l.push(...c.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...c.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Bt(i,a)},Dh=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Pe},Symbol.toStringTag,{value:"Module"})),jh="sy_device_set",Mh="sy_device_delete",Zr="/hardware/device/retrieve",Bh="/hardware/device/create",Uh="/hardware/device/delete",Zh=s.z.object({devices:qi.array()}),Lh=s.z.object({devices:Ut.array()}),_h=s.z.object({keys:Nr.array()}),Yh=s.z.object({}),Lr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Nr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),_r=s.z.object({devices:ee(Ut)});let Gi=class{constructor(e,t){o(this,"type","device");o(this,"client");o(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,Zr,{keys:T(e),...t},Lr,_r);return vr("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,Zr,{search:e,...t},Lr,_r)).devices}async page(e,t,n){return(await w(this.client,Zr,{offset:e,limit:t,...n},Lr,_r)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Bh,{devices:T(e)},Zh,Lh);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,Uh,{keys:T(e)},_h,Yh)}async openDeviceTracker(){return await Pe(this.frameClient,jh,Mh,qh)}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 qh=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(Ut).map(t=>({variant:r,key:t.key,value:t})),Wh=Object.freeze(Object.defineProperty({__proto__:null,Client:Gi,ONTOLOGY_TYPE:Wi,deviceKeyZ:Nr,deviceZ:Ut,newDeviceZ:qi,ontologyID:Ph},Symbol.toStringTag,{value:"Module"})),Yr="/hardware/rack/retrieve",Gh="/hardware/rack/create",Fh="/hardware/rack/delete",qr=s.z.object({keys:it.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Wr=s.z.object({racks:ee(Sr)}),Vh=s.z.object({racks:_i.array()}),Kh=s.z.object({racks:Sr.array()}),Jh=s.z.object({keys:it.array()}),Hh=s.z.object({});let Fi=class{constructor(e,t,n){o(this,"type","rack");o(this,"client");o(this,"frameClient");o(this,"tasks");this.client=e,this.frameClient=t,this.tasks=n}async delete(e){await w(this.client,Fh,{keys:T(e)},Jh,Hh)}async create(e){const t=!Array.isArray(e),n=await w(this.client,Gh,{racks:T(e)},Vh,Kh),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,Yr,{search:e},qr,Wr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Yr,{offset:e,limit:t},qr,Wr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=Tr(e,{string:"names",number:"keys"}),a=await w(this.client,Yr,{[t]:n},qr,Wr),c=this.sugar(a.racks);return vr("Rack",e,c,i),i?c[0]:c}sugar(e){return e.map(({key:t,name:n})=>new Vi(t,n,this.tasks))}};class Vi{constructor(e,t,n){o(this,"key");o(this,"name");o(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 Xh=Object.freeze(Object.defineProperty({__proto__:null,Client:Fi,ONTOLOGY_TYPE:Yi,Rack:Vi,newRackZ:_i,ontologyID:Ch,rackKeyZ:it,rackZ:Sr},Symbol.toStringTag,{value:"Module"})),De=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),At=s.z.object({task:De,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())}),Zt=s.z.object({key:De,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===""?{}:nt.JSON_CODEC.decodeString(r))),state:At.optional().nullable(),snapshot:s.z.boolean().optional()}),Ki=Zt.omit({key:!0}).extend({key:De.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>nt.JSON_CODEC.encodeString(r))}),Qh=s.z.object({task:De,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)))}),Ji="task",ey=r=>new b({type:Ji,key:r.toString()}),Ot="sy_task_state",ds="sy_task_cmd",Ft=new Error("Task not created");class Hi{constructor(e,t,n,i,a=!1,c=!1,l,u=null,h=null,d=null){o(this,"key");o(this,"name");o(this,"internal");o(this,"type");o(this,"config");o(this,"snapshot");o(this,"state");o(this,"frameClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=c,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=d}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 b({type:"task",key:this.key})}async executeCommand(e,t){if(this.frameClient==null)throw Ft;const n=await this.frameClient.openWriter(ds),i=tl.id();return await n.write(ds,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){if(this.frameClient==null)throw Ft;const i=await this.frameClient.openStreamer(Ot),a=await this.executeCommand(e,t);let c;const l=new Promise(u=>setTimeout(()=>u(!1),new E(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=At.safeParse(u.at(-1).sy_task_state);if(h.success){if(c=h.data,c.key===a)break}else console.error(h.error)}return i.close(),c}async openStateObserver(){if(this.frameClient==null)throw Ft;return new Bt(await this.frameClient.openStreamer(Ot),e=>{const t=e.get(Ot);if(t.length===0)return[null,!1];const n=At.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 Ft;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const ty=s.z.object({rack:it.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()}),ry=s.z.object({tasks:ee(Zt)}),ny="/hardware/task/retrieve",sy="/hardware/task/create",iy="/hardware/task/delete",ay="/hardware/task/copy",oy=s.z.object({tasks:Ki.array()}),cy=s.z.object({tasks:Zt.array()}),ly=s.z.object({keys:De.array()}),uy=s.z.object({}),hy=s.z.object({key:De,name:s.z.string(),snapshot:s.z.boolean()}),yy=s.z.object({task:Zt});let Xi=class{constructor(e,t,n,i){o(this,"type","task");o(this,"client");o(this,"frameClient");o(this,"ontologyClient");o(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,sy,{tasks:T(e)},oy,cy),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,iy,{keys:T(e)},ly,uy)}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}=Tr(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),c={...t};a==="rack"?c.rack=e:c.keys=i;const l=await this.execRetrieve(c),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,ay,{key:e,name:t,snapshot:n},hy,yy);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return vr("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,ny,e,ty,ry)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:c,internal:l,snapshot:u})=>new Hi(t,n,i,a,l,u,c,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await Pe(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 Bt(await this.frameClient.openStreamer(Ot),e=>{const t=e.get(Ot);if(t.length===0)return[null,!1];const n=At.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const dy=Object.freeze(Object.defineProperty({__proto__:null,Client:Xi,ONTOLOGY_TYPE:Ji,Task:Hi,commandZ:Qh,newTaskZ:Ki,ontologyID:ey,stateZ:At,taskKeyZ:De,taskZ:Zt},Symbol.toStringTag,{value:"Module"})),at=s.z.string().uuid(),Lt=s.z.object({key:at,name:s.z.string().min(1),color:s.z.string()}),Qi="label",fy=r=>new b({type:Qi,key:r}),py=s.z.object({keys:at.array().optional(),for:J.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),gy=s.z.object({labels:ee(Lt)});var Ae;let ea=(Ae=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=T(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,py,gy);if(n!=null)throw n;return t.labels}},o(Ae,"ENDPOINT","/label/retrieve"),Ae);const ta=Lt.extend({key:at.optional()}),my=s.z.object({labels:ta.array()}),wy=s.z.object({labels:Lt.array()}),by=s.z.object({keys:at.array()}),ra=s.z.object({id:J,labels:at.array(),replace:s.z.boolean().optional()}),Ty=ra.omit({replace:!0}),Gr=s.z.object({}),vy="/label/create",Oy="/label/delete",zy="/label/set",Ey="/label/remove";let na=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,vy,{labels:T(e)},my,wy)).labels}async delete(e){await w(this.client,Oy,{keys:T(e)},by,Gr)}async set(e,t,{replace:n}={}){await w(this.client,zy,{id:e,labels:t,replace:n},ra,Gr)}async remove(e,t){await w(this.client,Ey,{id:e,labels:t},Ty,Gr)}};const Sy="sy_label_set",Ny="sy_label_delete";let sa=class{constructor(e,t,n){o(this,"type","label");o(this,"retriever");o(this,"writer");o(this,"frameClient");o(this,"ontology");this.writer=new na(e),this.retriever=new ea(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 b(e))}async label(e,t,n={}){await this.writer.set(new b(e),t,n)}async removeLabels(e,t){await this.writer.remove(new b(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 Pe(this.frameClient,Sy,Ny,Iy)}async trackLabelsOf(e){const t=new xe.Observer,n=(await this.retrieveFor(e)).map(a=>({id:new b({key:a.key,type:"label"}),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new b(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(c=>{var l,u;return{key:c.id.key,color:(l=c.data)==null?void 0:l.color,name:(u=c.data)==null?void 0:u.name}}))),t}};const Iy=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Lt).map(t=>({variant:r,key:t.key,value:t})),ky=Object.freeze(Object.defineProperty({__proto__:null,Client:sa,ONTOLOGY_TYPE:Qi,Retriever:ea,Writer:na,keyZ:at,labelZ:Lt,newLabelPayloadZ:ta,ontologyID:fy},Symbol.toStringTag,{value:"Module"})),X=s.z.string().uuid(),_t=s.z.object({key:X,name:s.z.string().min(1),timeRange:W.z,color:s.z.string().optional()}),ia=_t.extend({key:s.z.string().uuid().optional()}),aa=r=>{const e=T(r),t=e.length===0;let n=!1;return t||(n=X.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},oa="range",ca="range-alias",Ay=r=>new b({type:oa,key:r}),$y=r=>new b({type:ca,key:r}),Ry="sy_range_alias_set",xy="sy_range_alias_delete",Cy=s.z.object({range:X,aliases:s.z.string().array()}),Py=s.z.object({aliases:s.z.record(s.z.string(),Ee)}),Dy=s.z.object({range:X,aliases:s.z.record(Ee.or(s.z.string()),s.z.string())}),jy=s.z.unknown(),My=s.z.object({range:X,channels:Ee.array()}),By=s.z.unknown(),Uy=s.z.object({range:X}),Zy=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),ce=class ce{constructor(e,t,n){o(this,"frameClient");o(this,"cache",new Map);o(this,"client");o(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 c=this.cache.get(e);if(c!=null)return c;t.push(e)}else e.forEach(c=>{const l=this.cache.get(c);l!=null?i[c]=l:t.push(c)});if(t.length===0)return i;const a=await w(this.client,ce.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Cy,Py);return Object.entries(a.aliases).forEach(([c,l])=>this.cache.set(c,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,ce.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Dy,jy)}async list(){return(await w(this.client,ce.LIST_ENDPOINT,{range:this.rangeKey},Uy,Zy)).aliases}async delete(e){await w(this.client,ce.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},My,By)}async openChangeTracker(){return await Pe(this.frameClient,Ry,xy,Yy(this.rangeKey))}};o(ce,"SET_ENDPOINT","/range/alias/set"),o(ce,"RESOLVE_ENDPOINT","/range/alias/resolve"),o(ce,"LIST_ENDPOINT","/range/alias/list"),o(ce,"DELETE_ENDPOINT","/range/alias/delete");let on=ce;const Ly=s.z.object({range:X,channel:Ee,alias:s.z.string()}),_y="---",Yy=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(_y)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Ly).map(n=>({variant:e,key:n.alias,value:n})),qy=s.z.object({range:X,keys:s.z.string().array()}),Tn=s.z.object({range:X,key:s.z.string(),value:s.z.string()}),Wy=s.z.object({pairs:ee(Tn)}),Gy=s.z.object({range:X,pairs:Tn.array()}),Fy=s.z.object({range:X,keys:s.z.string().array()}),we=class we{constructor(e,t,n){o(this,"rangeKey");o(this,"client");o(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,we.GET_ENDPOINT,{range:this.rangeKey,keys:T(e)},qy,Wy);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;hn(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,we.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Gy,s.z.unknown())}async delete(e){await w(this.client,we.DELETE_ENDPOINT,{range:this.rangeKey,keys:T(e)},Fy,s.z.unknown())}async openTracker(){return await Pe(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(Tn).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};o(we,"GET_ENDPOINT","/range/kv/get"),o(we,"SET_ENDPOINT","/range/kv/set"),o(we,"DELETE_ENDPOINT","/range/kv/delete");let $t=we;const Fr=r=>new b({type:"range",key:r});class la{constructor(e,t=W.ZERO,n,i,a,c,l,u,h,d,y){o(this,"key");o(this,"name");o(this,"kv");o(this,"timeRange");o(this,"color");o(this,"channels");o(this,"aliaser");o(this,"frameClient");o(this,"labelClient");o(this,"ontologyClient");o(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=c,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=d,this.rangeClient=y}get ontologyID(){return new b({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 te(`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(Fr(this.key))}async addLabel(...e){await this.labelClient.label(Fr(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(Fr(this.key),e)}async openChildRangeTracker(){const e=new xe.Observer,t=(await this.retrieveChildren()).map(i=>{const a=new b({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 xe.Observer,t=await this.retrieveParent();if(t==null)return null;const n=new b({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(c=>{const l=this.rangeClient.resourcesToRanges(c);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const Vy=s.z.object({keys:X.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()}),Ky="/range/retrieve",Jy=s.z.object({ranges:ee(_t)});let ua=class{constructor(e,t,n,i,a,c){o(this,"type","range");o(this,"frameClient");o(this,"writer");o(this,"unaryClient");o(this,"channels");o(this,"labelClient");o(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=c}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(T(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(T(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:c}=aa(e);if(c)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 ge(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new $t(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,Ky,e,Vy,Jy);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 la(e.name,e.timeRange,e.key,e.color,this.frameClient,new $t(e.key,this.unaryClient,this.frameClient),new on(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 Pe(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(_t)).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 Hy=s.z.object({ranges:_t.array()}),Xy=s.z.object({parent:J.optional(),ranges:ia.array()}),Qy=s.z.object({keys:X.array()}),ed=s.z.object({}),td=s.z.object({key:X,name:s.z.string()}),rd=s.z.object({}),nd="/range/create",sd="/range/delete",id="/range/rename";let ha=class{constructor(e){o(this,"client");this.client=e}async rename(e,t){await w(this.client,id,{key:e,name:t},td,rd)}async create(e,t){return(await w(this.client,nd,{ranges:e,...t},Xy,Hy)).ranges}async delete(e){await w(this.client,sd,{keys:e},Qy,ed)}};const ad=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:ca,Client:ua,KV:$t,ONTOLOGY_TYPE:oa,Range:la,Writer:ha,analyzeParams:aa,keyZ:X,newPayloadZ:ia,payloadZ:_t,rangeAliasOntologyID:$y,rangeOntologyID:Ay},Symbol.toStringTag,{value:"Module"})),od="/api/v1/";class cd{constructor(e,t=!1){o(this,"url");o(this,"unary");o(this,"stream");o(this,"secure");this.secure=t,this.url=e.child(od);const n=new nt.JSONCodec;this.unary=new Go(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 Ir=s.z.string().uuid(),kr=s.z.object({key:s.z.string(),name:s.z.string(),data:dn.or(s.z.string().transform(r=>JSON.parse(r)))}),ya="lineplot",ld=r=>new b({type:ya,key:r}),ud=s.z.object({keys:s.z.string().array()}),hd=s.z.object({linePlots:kr.array()});let yd=class{constructor(e){o(this,"ENDPOINT","/workspace/lineplot/retrieve");o(this,"client");this.client=e}async retrieve(e){const t=T(e);return(await w(this.client,this.ENDPOINT,{keys:t},ud,hd)).linePlots}};const Se=s.z.string().uuid(),da=r=>JSON.parse(r),vn=s.z.object({name:s.z.string(),key:Se,layout:dn.or(s.z.string().transform(r=>da(r)))}),On=vn.omit({layout:!0}).extend({layout:s.z.string().transform(r=>da(r))}),fa="workspace",dd=r=>new b({type:fa,key:r}),fd=kr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),pd=s.z.object({workspace:Se,linePlots:fd.array()}),gd=s.z.object({linePlots:kr.array()}),md=s.z.object({keys:Ir.array()}),wd=s.z.object({}),bd=s.z.object({key:Ir,name:s.z.string()}),Td=s.z.object({}),vd=s.z.object({key:Ir,data:s.z.string()}),Od=s.z.object({}),zd="/workspace/lineplot/create",Ed="/workspace/lineplot/delete",Sd="/workspace/lineplot/rename",Nd="/workspace/lineplot/set-data";let Id=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,zd,{workspace:e,linePlots:[n]},pd,gd)).linePlots[0]}async delete(e){const t=T(e);await w(this.client,Ed,{keys:t},md,wd)}async rename(e,t){await w(this.client,Sd,{key:e,name:t},bd,Td)}async setData(e,t){await w(this.client,Nd,{key:e,data:JSON.stringify(t)},vd,Od)}},pa=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Id(e),this.retriever=new yd(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 kd=Object.freeze(Object.defineProperty({__proto__:null,Client:pa,ONTOLOGY_TYPE:ya,keyZ:Ir,linePlotZ:kr,ontologyID:ld},Symbol.toStringTag,{value:"Module"})),Ad=s.z.object({keys:Se.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),$d=s.z.object({workspaces:ee(On)});var $e;let Rd=($e=class{constructor(e){o(this,"client");this.client=e}async retrieve(e){const t=T(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,$e.ENDPOINT,e,Ad,$d)).workspaces}},o($e,"ENDPOINT","/workspace/retrieve"),$e);const Yt=s.z.string().uuid(),ga=s.z.object({key:s.z.string(),name:s.z.string(),data:dn.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),Ar=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),ma="schematic",xd=r=>new b({type:ma,key:r}),Cd=s.z.object({keys:s.z.string().array()}),Pd=s.z.object({schematics:Ar.array()});class Dd{constructor(e){o(this,"ENDPOINT","/workspace/schematic/retrieve");o(this,"client");this.client=e}async retrieve(e){return(await w(this.client,this.ENDPOINT,{keys:T(e)},Cd,Pd)).schematics}}const jd=ga.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Md=s.z.object({workspace:Se,schematics:jd.array()}),Bd=s.z.object({schematics:Ar.array()}),Ud=s.z.object({keys:Yt.array()}),Zd=s.z.object({}),Ld=s.z.object({key:Yt,name:s.z.string()}),fs=s.z.object({}),_d=s.z.object({key:Yt,data:s.z.string()});s.z.object({});const Yd=s.z.object({key:Yt,name:s.z.string(),snapshot:s.z.boolean()}),qd=s.z.object({schematic:Ar}),Wd="/workspace/schematic/create",Gd="/workspace/schematic/delete",Fd="/workspace/schematic/rename",Vd="/workspace/schematic/set-data",Kd="/workspace/schematic/copy";let Jd=class{constructor(e){o(this,"client");this.client=e}async create(e,t){const n={...t,data:JSON.stringify(t.data)};return(await w(this.client,Wd,{workspace:e,schematics:[n]},Md,Bd)).schematics[0]}async copy(e,t,n){return(await w(this.client,Kd,{key:e,name:t,snapshot:n},Yd,qd)).schematic}async delete(e){const t=T(e);await w(this.client,Gd,{keys:t},Ud,Zd)}async rename(e,t){await w(this.client,Fd,{key:e,name:t},Ld,fs)}async setData(e,t){await w(this.client,Vd,{key:e,data:JSON.stringify(t)},_d,fs)}},wa=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Jd(e),this.retriever=new Dd(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 Hd=Object.freeze(Object.defineProperty({__proto__:null,Client:wa,ONTOLOGY_TYPE:ma,keyZ:Yt,ontologyID:xd,schematicRemoteZ:Ar,schematicZ:ga},Symbol.toStringTag,{value:"Module"})),Xd=vn.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Qd=s.z.object({workspaces:Xd.array()}),ef=s.z.object({workspaces:On.array()}),tf=s.z.object({keys:Se.array()}),rf=s.z.object({}),nf=s.z.object({key:Se,name:s.z.string()}),sf=s.z.object({}),af=s.z.object({key:Se,layout:s.z.string()}),of=s.z.object({}),cf="/workspace/create",lf="/workspace/delete",uf="/workspace/rename",hf="/workspace/set-layout";class yf{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,cf,{workspaces:T(e)},Qd,ef)).workspaces}async delete(e){await w(this.client,lf,{keys:T(e)},tf,rf)}async rename(e,t){await w(this.client,uf,{key:e,name:t},nf,sf)}async setLayout(e,t){await w(this.client,hf,{key:e,layout:JSON.stringify(t)},af,of)}}class ba{constructor(e){o(this,"type","workspace");o(this,"schematic");o(this,"linePlot");o(this,"retriever");o(this,"writer");this.schematic=new wa(e),this.linePlot=new pa(e),this.retriever=new Rd(e),this.writer=new yf(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 df=Object.freeze(Object.defineProperty({__proto__:null,Client:ba,ONTOLOGY_TYPE:fa,keyZ:Se,ontologyID:dd,workspaceRemoteZ:On,workspaceZ:vn},Symbol.toStringTag,{value:"Module"})),Ta=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:E.z.default(E.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class va extends Bi{constructor(t){const n=Ta.parse(t),{host:i,port:a,username:c,password:l,connectivityPollFrequency:u,secure:h}=n,d=new cd(new vl({host:i,port:Number(a)}),h);d.use(Cl);let y;c!=null&&l!=null&&(y=new ah(d.unary,{username:c,password:l}),d.use(y.middleware()));const P=new fn(new It(d.unary)),D=new Ii(d.unary,P);super(d.stream,d.unary,P);o(this,"createdAt");o(this,"props");o(this,"ranges");o(this,"channels");o(this,"auth");o(this,"user");o(this,"access");o(this,"connectivity");o(this,"ontology");o(this,"workspaces");o(this,"labels");o(this,"hardware");o(this,"control");o(this,"transport");o(this,"clientVersion","0.32.0");this.createdAt=S.now(),this.props=n,this.auth=y,this.transport=d,this.channels=new Ni(this,P,d.unary,D),this.connectivity=new kt(d.unary,u,this.clientVersion,n.name),this.control=new Zi(this),this.ontology=new pi(d.unary,this);const Q=new ha(this.transport.unary);this.labels=new sa(this.transport.unary,this,this.ontology),this.ranges=new ua(this,Q,this.transport.unary,P,this.labels,this.ontology),this.access=new Ti(this.transport.unary),this.user=new $i(this.transport.unary),this.workspaces=new ba(this.transport.unary);const B=new Gi(this.transport.unary,this),zn=new Xi(this.transport.unary,this,this.ontology,this.ranges),Oa=new Fi(this.transport.unary,this,zn);this.hardware=new Li(zn,Oa,B)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}o(va,"connectivity",kt);const ff=et.Authority;exports.AuthError=Ce;exports.Authority=ff;exports.Channel=pn;exports.ContiguityError=nn;exports.DataType=z;exports.Density=V;exports.Frame=_;exports.MultiSeries=ni;exports.MultipleFoundError=ge;exports.NotFoundError=pe;exports.QueryError=te;exports.Rate=mr;exports.RouteError=Nt;exports.Series=be;exports.Synnax=va;exports.TimeRange=W;exports.TimeSpan=E;exports.TimeStamp=S;exports.UnexpectedError=ve;exports.ValidationError=M;exports.access=yu;exports.channel=Pu;exports.connection=lh;exports.control=Rh;exports.device=Wh;exports.framer=Nh;exports.hardware=xh;exports.label=ky;exports.linePlot=kd;exports.ontology=Hl;exports.policy=hu;exports.rack=Xh;exports.ranger=ad;exports.schematic=Hd;exports.signals=Dh;exports.synnaxPropsZ=Ta;exports.task=dy;exports.user=Qu;exports.workspace=df;
50
+ `);return h}),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 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;