@synnaxlabs/client 0.24.0 → 0.25.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 (78) hide show
  1. package/.turbo/turbo-build.log +10 -11
  2. package/dist/auth/auth.d.ts +2 -2
  3. package/dist/channel/client.d.ts +8 -8
  4. package/dist/channel/creator.d.ts +1 -1
  5. package/dist/channel/payload.d.ts +1 -1
  6. package/dist/channel/retriever.d.ts +4 -4
  7. package/dist/channel/retriever.d.ts.map +1 -1
  8. package/dist/channel/writer.d.ts +3 -3
  9. package/dist/client.cjs +21 -21
  10. package/dist/client.d.ts +11 -11
  11. package/dist/client.js +2570 -3296
  12. package/dist/connection/checker.d.ts +2 -2
  13. package/dist/control/client.d.ts +1 -1
  14. package/dist/control/state.d.ts +5 -5
  15. package/dist/errors.d.ts +12 -12
  16. package/dist/errors.d.ts.map +1 -1
  17. package/dist/framer/adapter.d.ts +3 -3
  18. package/dist/framer/client.d.ts +7 -7
  19. package/dist/framer/deleter.d.ts +2 -2
  20. package/dist/framer/frame.d.ts +2 -2
  21. package/dist/framer/iterator.d.ts +4 -4
  22. package/dist/framer/streamProxy.d.ts +1 -1
  23. package/dist/framer/streamer.d.ts +5 -5
  24. package/dist/framer/writer.d.ts +6 -6
  25. package/dist/hardware/client.d.ts +2 -2
  26. package/dist/hardware/device/client.d.ts +7 -7
  27. package/dist/hardware/device/client.d.ts.map +1 -1
  28. package/dist/hardware/rack/client.d.ts +5 -5
  29. package/dist/hardware/task/client.d.ts +10 -10
  30. package/dist/hardware/task/client.d.ts.map +1 -1
  31. package/dist/index.d.ts +1 -2
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/label/client.d.ts +6 -6
  34. package/dist/label/payload.d.ts +1 -1
  35. package/dist/label/payload.d.ts.map +1 -1
  36. package/dist/label/retriever.d.ts +2 -2
  37. package/dist/label/writer.d.ts +3 -3
  38. package/dist/ontology/client.d.ts +6 -6
  39. package/dist/ontology/group/client.d.ts +2 -2
  40. package/dist/ontology/group/writer.d.ts +2 -2
  41. package/dist/ontology/group/writer.d.ts.map +1 -1
  42. package/dist/ontology/payload.d.ts +7 -7
  43. package/dist/ontology/payload.d.ts.map +1 -1
  44. package/dist/ontology/writer.d.ts +1 -1
  45. package/dist/ranger/active.d.ts +1 -1
  46. package/dist/ranger/alias.d.ts +6 -6
  47. package/dist/ranger/client.d.ts +10 -10
  48. package/dist/ranger/kv.d.ts +2 -2
  49. package/dist/ranger/payload.d.ts +1 -1
  50. package/dist/ranger/range.d.ts +8 -8
  51. package/dist/ranger/range.d.ts.map +1 -1
  52. package/dist/ranger/writer.d.ts +1 -1
  53. package/dist/signals/observable.d.ts +4 -4
  54. package/dist/signals/observable.d.ts.map +1 -1
  55. package/dist/transport.d.ts +1 -1
  56. package/dist/util/retrieve.d.ts +1 -1
  57. package/dist/util/retrieve.d.ts.map +1 -1
  58. package/dist/util/zod.d.ts.map +1 -1
  59. package/dist/workspace/client.d.ts +6 -6
  60. package/dist/workspace/lineplot/client.d.ts +3 -3
  61. package/dist/workspace/lineplot/payload.d.ts +1 -1
  62. package/dist/workspace/lineplot/retriever.d.ts +1 -1
  63. package/dist/workspace/lineplot/writer.d.ts +3 -3
  64. package/dist/workspace/payload.d.ts +1 -1
  65. package/dist/workspace/retriever.d.ts +1 -1
  66. package/dist/workspace/schematic/client.d.ts +3 -3
  67. package/dist/workspace/schematic/payload.d.ts +1 -1
  68. package/dist/workspace/schematic/retriever.d.ts +1 -1
  69. package/dist/workspace/schematic/writer.d.ts +3 -3
  70. package/dist/workspace/writer.d.ts +3 -3
  71. package/package.json +11 -12
  72. package/src/errors.spec.ts +0 -1
  73. package/src/framer/writer.spec.ts +29 -1
  74. package/src/hardware/task/client.ts +2 -2
  75. package/src/hardware/task/task.spec.ts +2 -2
  76. package/src/index.ts +1 -2
  77. package/src/ontology/group/writer.ts +1 -1
  78. package/src/ontology/ontology.spec.ts +1 -1
package/dist/client.cjs CHANGED
@@ -1,37 +1,37 @@
1
- "use strict";var Hi=Object.defineProperty;var Xi=(r,e,t)=>e in r?Hi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>(Xi(r,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod");var Qi=Object.defineProperty,eo=(r,e,t)=>e in r?Qi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,k=(r,e,t)=>(eo(r,typeof e!="symbol"?e+"":e,t),t),te=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},O={},gr={};Object.defineProperty(gr,"__esModule",{value:!0});function to(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"$"+n}).toLowerCase().replace(/(\$)(\w)/g,function(e,t,n){return n.toUpperCase()}):""}gr.default=to;var mr={};Object.defineProperty(mr,"__esModule",{value:!0});function ro(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}mr.default=ro;var wr={};Object.defineProperty(wr,"__esModule",{value:!0});function no(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"$"+n}).toLowerCase().replace(/(\$)(\w?)/g,function(e,t,n){return n.toUpperCase()}):""}wr.default=no;var gn={};Object.defineProperty(gn,"__esModule",{value:!0});function so(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}gn.default=so;var mn={};Object.defineProperty(mn,"__esModule",{value:!0});function ao(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}mn.default=ao;var wn={};Object.defineProperty(wn,"__esModule",{value:!0});function io(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}wn.default=io;var vn={};Object.defineProperty(vn,"__esModule",{value:!0});function oo(r){if(r===void 0&&(r=""),!r)return"";var e=String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,a){return n+"_"+a.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return e.charAt(0).toUpperCase()+e.slice(1)}vn.default=oo;var bn={};Object.defineProperty(bn,"__esModule",{value:!0});function co(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(e,t,n,a){return t+n.charAt(0).toUpperCase()+n.slice(1)+a}):""}bn.default=co;var vr={};Object.defineProperty(vr,"__esModule",{value:!0});function uo(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}vr.default=uo;var On={},qe={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.belongToTypes=r.isValidObject=r.isArrayObject=r.validateOptions=r.DefaultOption=void 0,r.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},r.validateOptions=function(e){return e===void 0&&(e=r.DefaultOption),e.recursive==null?e=r.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},r.isArrayObject=function(e){return e!=null&&Array.isArray(e)},r.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},r.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}})(qe);var lo=te&&te.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(On,"__esModule",{value:!0});var he=qe;function Yt(r,e){if(e===void 0&&(e=he.DefaultOption),!he.isValidObject(r))return null;e=he.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=n.toLowerCase();e.recursive&&(he.isValidObject(a)?he.belongToTypes(a,e.keepTypesOnRecursion)||(a=Yt(a,e)):e.recursiveInArray&&he.isArrayObject(a)&&(a=lo(a).map(function(o){var u=o;if(he.isValidObject(o))he.belongToTypes(u,e.keepTypesOnRecursion)||(u=Yt(o,e));else if(he.isArrayObject(o)){var l=Yt({key:o},e);u=l.key}return u}))),t[i]=a}),t}On.default=Yt;var Tn={},ho=te&&te.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Tn,"__esModule",{value:!0});var fe=qe;function Kt(r,e){if(e===void 0&&(e=fe.DefaultOption),!fe.isValidObject(r))return null;e=fe.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=n.toUpperCase();e.recursive&&(fe.isValidObject(a)?fe.belongToTypes(a,e.keepTypesOnRecursion)||(a=Kt(a,e)):e.recursiveInArray&&fe.isArrayObject(a)&&(a=ho(a).map(function(o){var u=o;if(fe.isValidObject(o))fe.belongToTypes(u,e.keepTypesOnRecursion)||(u=Kt(o,e));else if(fe.isArrayObject(o)){var l=Kt({key:o},e);u=l.key}return u}))),t[i]=a}),t}Tn.default=Kt;var zn={},fo=te&&te.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(zn,"__esModule",{value:!0});var de=qe,yo=gr;function Wt(r,e){if(e===void 0&&(e=de.DefaultOption),!de.isValidObject(r))return null;e=de.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=yo.default(n);e.recursive&&(de.isValidObject(a)?de.belongToTypes(a,e.keepTypesOnRecursion)||(a=Wt(a,e)):e.recursiveInArray&&de.isArrayObject(a)&&(a=fo(a).map(function(o){var u=o;if(de.isValidObject(o))de.belongToTypes(u,e.keepTypesOnRecursion)||(u=Wt(o,e));else if(de.isArrayObject(o)){var l=Wt({key:o},e);u=l.key}return u}))),t[i]=a}),t}zn.default=Wt;var En={},po=te&&te.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(En,"__esModule",{value:!0});var ye=qe,go=mr;function Vt(r,e){if(e===void 0&&(e=ye.DefaultOption),!ye.isValidObject(r))return null;e=ye.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=go.default(n);e.recursive&&(ye.isValidObject(a)?ye.belongToTypes(a,e.keepTypesOnRecursion)||(a=Vt(a,e)):e.recursiveInArray&&ye.isArrayObject(a)&&(a=po(a).map(function(o){var u=o;if(ye.isValidObject(o))ye.belongToTypes(u,e.keepTypesOnRecursion)||(u=Vt(o,e));else if(ye.isArrayObject(o)){var l=Vt({key:o},e);u=l.key}return u}))),t[i]=a}),t}En.default=Vt;var Sn={},mo=te&&te.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Sn,"__esModule",{value:!0});var pe=qe,wo=wr;function Ft(r,e){if(e===void 0&&(e=pe.DefaultOption),!pe.isValidObject(r))return null;e=pe.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=wo.default(n);e.recursive&&(pe.isValidObject(a)?pe.belongToTypes(a,e.keepTypesOnRecursion)||(a=Ft(a,e)):e.recursiveInArray&&pe.isArrayObject(a)&&(a=mo(a).map(function(o){var u=o;if(pe.isValidObject(o))pe.belongToTypes(u,e.keepTypesOnRecursion)||(u=Ft(o,e));else if(pe.isArrayObject(o)){var l=Ft({key:o},e);u=l.key}return u}))),t[i]=a}),t}Sn.default=Ft;var Nn={},vo=te&&te.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Nn,"__esModule",{value:!0});var ge=qe,bo=vr;function Jt(r,e){if(e===void 0&&(e=ge.DefaultOption),!ge.isValidObject(r))return null;e=ge.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=bo.default(n);e.recursive&&(ge.isValidObject(a)?ge.belongToTypes(a,e.keepTypesOnRecursion)||(a=Jt(a,e)):e.recursiveInArray&&ge.isArrayObject(a)&&(a=vo(a).map(function(o){var u=o;if(ge.isValidObject(o))ge.belongToTypes(u,e.keepTypesOnRecursion)||(u=Jt(o,e));else if(ge.isArrayObject(o)){var l=Jt({key:o},e);u=l.key}return u}))),t[i]=a}),t}Nn.default=Jt;Object.defineProperty(O,"__esModule",{value:!0});O.kebabKeys=O.pascalKeys=O.snakeKeys=O.camelKeys=O.upperKeys=O.lowerKeys=O.toLowerCase=O.toUpperCase=O.toKebabCase=O.toHeaderCase=O.toSentenceCase=O.toTextCase=O.toPathCase=O.toDotCase=O.toPascalCase=O.toSnakeCase=O.toCamelCase=void 0;var ks=gr;O.toCamelCase=ks.default;var $s=mr;O.toSnakeCase=$s.default;var Cs=wr;O.toPascalCase=Cs.default;var Rs=gn;O.toDotCase=Rs.default;var js=mn;O.toPathCase=js.default;var xs=wn;O.toTextCase=xs.default;var Ps=vn;O.toSentenceCase=Ps.default;var Ds=bn;O.toHeaderCase=Ds.default;var Zs=vr;O.toKebabCase=Zs.default;var Ms=On;O.lowerKeys=Ms.default;var Us=Tn;O.upperKeys=Us.default;var Ls=zn;O.camelKeys=Ls.default;var Bs=En;O.snakeKeys=Bs.default;var _s=Sn;O.pascalKeys=_s.default;var qs=Nn;O.kebabKeys=qs.default;var Ys=function(r){return String(r||"").toLowerCase()};O.toLowerCase=Ys;var Ks=function(r){return String(r||"").toUpperCase()};O.toUpperCase=Ks;var Oo={toCamelCase:ks.default,toSnakeCase:$s.default,toPascalCase:Cs.default,toDotCase:Rs.default,toPathCase:js.default,toTextCase:xs.default,toSentenceCase:Ps.default,toHeaderCase:Ds.default,toKebabCase:Zs.default,toUpperCase:Ks,toLowerCase:Ys,lowerKeys:Ms.default,upperKeys:Us.default,camelKeys:Ls.default,snakeKeys:Bs.default,pascalKeys:_s.default,kebabKeys:qs.default};O.default=Oo;var Ws=O;const Vs={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},To=r=>Ws.snakeKeys(r,Vs),zo=r=>Ws.camelKeys(r,Vs),Fs=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Eo=Object.defineProperty,So=(r,e,t)=>e in r?Eo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Et=(r,e,t)=>(So(r,typeof e!="symbol"?e+"":e,t),t);let No=class{constructor(){Et(this,"contentType","application/json"),Et(this,"decoder"),Et(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=zo(JSON.parse(r));return e!=null?e.parse(t):t}encodeString(r){return JSON.stringify(To(r),(e,t)=>ArrayBuffer.isView(t)?Array.from(t):Fs(t)&&"encode_value"in t?typeof t.value=="bigint"?t.value.toString():t.value:typeof t=="bigint"?t.toString():t)}static registerCustomType(){}},Ao=class{constructor(){Et(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||!Fs(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 a=e.map(i=>JSON.stringify(n[i]??""));t.push(a.join(","))}),t.join(`
2
- `)}decodeString(r,e){const[t,...n]=r.trim().split(`
3
- `).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const a=t.split(",").map(o=>o.trim()),i={};return a.forEach(o=>{i[o]=[]}),n.forEach(o=>{const u=o.split(",").map(l=>l.trim());a.forEach((l,y)=>{const g=this.parseValue(u[y]);g!=null&&i[l].push(g)})}),e!=null?e.parse(i):i}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(){}},Io=class{constructor(){Et(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}};new No;new Ao;new Io;const br=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Js=s.z.object({width:s.z.number(),height:s.z.number()}),ko=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),$o=["width","height"];s.z.enum($o);const Co=["start","center","end"],Ro=["signedWidth","signedHeight"];s.z.enum(Ro);const ur=s.z.object({x:s.z.number(),y:s.z.number()}),jo=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),xo=["x","y"],Gs=s.z.enum(xo),Hs=["top","right","bottom","left"];s.z.enum(Hs);const Po=["left","right"],Xs=s.z.enum(Po),Do=["top","bottom"],Qs=s.z.enum(Do),ea=["center"],ts=s.z.enum(ea),Zo=[...Hs,...ea],ta=s.z.enum(Zo);s.z.enum(Co);const Mo=["first","last"];s.z.enum(Mo);const Uo=s.z.object({lower:s.z.number(),upper:s.z.number()}),Lo=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Uo,br]);s.z.union([Lo,br]);s.z.union([Gs,ta]);s.z.union([Gs,ta,s.z.instanceof(String)]);const Mr=(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 rs(r);return rs(t)},rs=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Xs.or(ts),y:Qs.or(ts)});const Bo=s.z.object({x:Xs,y:Qs}),_o=Object.freeze({x:"left",y:"top"}),qo=(r,e)=>r.x===e.x&&r.y===e.y,ns=s.z.union([s.z.number(),ur,br,Js,ko,jo]),Yo=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},ss=Object.freeze({x:0,y:0}),Bt=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Bt,left:Bt,width:Bt,height:Bt});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:ur,two:ur,root:Bo});const An=(r,e,t=0,n=0,a)=>{const i={one:{...ss},two:{...ss},root:a??_o};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:r,y:e},i.two={x:i.one.x+t,y:i.one.y+n},i}return"one"in r&&"two"in r&&"root"in r?{...r,root:a??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(i.one={x:r.left,y:r.top},i.two={x:r.right,y:r.bottom},i):(i.one=r,e==null?i.two={x:i.one.x+t,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+t}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},Ur=r=>{const e=An(r);return{lower:e.one.x,upper:e.two.x}},Lr=r=>{const e=An(r);return{lower:e.one.y,upper:e.two.y}},Ko=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var Wo=Object.defineProperty,Vo=(r,e,t)=>e in r?Wo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ne=(r,e,t)=>(Vo(r,typeof e!="symbol"?e+"":e,t),t);const Fo=(r,e,t)=>(e!=null&&(r=Math.max(r,e)),t!=null&&(r=Math.min(r,t)),r);s.z.object({offset:ns,scale:ns});const Jo=r=>(e,t,n,a)=>t==="dimension"?[e,n]:[e,a?n-r:n+r],Go=r=>(e,t,n,a)=>[e,a?n/r:n*r],Ho=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:a,upper:i}=e,{lower:o,upper:u}=r,l=i-a,y=u-o;if(t==="dimension")return[r,n*(y/l)];const g=(n-a)*(y/l)+o;return[r,g]},Xo=r=>(e,t,n)=>[r,n],Qo=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:a}=r;return[r,a-(t-n)]},ec=r=>(e,t,n)=>{const{lower:a,upper:i}=r;return n=Fo(n,a,i),[e,n]},rn=class wt{constructor(){Ne(this,"ops",[]),Ne(this,"currBounds",null),Ne(this,"currType",null),Ne(this,"reversed",!1),this.ops=[]}static translate(e){return new wt().translate(e)}static magnify(e){return new wt().magnify(e)}static scale(e,t){return new wt().scale(e,t)}translate(e){const t=this.new(),n=Jo(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Go(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Mr(e,t),a=this.new(),i=Ho(n);return i.type="scale",a.ops.push(i),a}clamp(e,t){const n=Mr(e,t),a=this.new(),i=ec(n);return i.type="clamp",a.ops.push(i),a}reBound(e,t){const n=Mr(e,t),a=this.new(),i=Xo(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=Qo();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 wt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||t.some(([o,u])=>a>=o&&a<=u))return;const i=e.ops.findIndex((o,u)=>o.type==="scale"&&u>a);i!==-1&&t.push([a,i])}),t.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}};Ne(rn,"IDENTITY",new rn);let as=rn;const is=class ze{constructor(e=new as,t=new as,n=null){Ne(this,"x"),Ne(this,"y"),Ne(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ze().translate(e,t)}static translateX(e){return new ze().translateX(e)}static translateY(e){return new ze().translateY(e)}static clamp(e){return new ze().clamp(e)}static magnify(e){return new ze().magnify(e)}static scale(e){return new ze().scale(e)}static reBound(e){return new ze().reBound(e)}translate(e,t){const n=Yo(e,t),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}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(Ko(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!qo(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Ur(e)),t.y=t.y.scale(Lr(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(Ur(e)),t.y=this.y.reBound(Lr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Ur(e)),t.y=this.y.clamp(Lr(e)),t}copy(){const e=new ze;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 An(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};Ne(is,"IDENTITY",new is);s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const ra=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",tc=ra(),na=["MacOS","Windows","Linux","Docker"],rc=s.z.enum(na);let Br;const nc=()=>{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"},sc=(r={})=>{const{force:e,default:t}=r;return e??Br??(Br=nc(),Br??t)},sa=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:na,RUNTIME:tc,detect:ra,getOS:sc,osZ:rc},Symbol.toStringTag,{value:"Module"})),ac=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Js,ac,ur,br]);var ic=Object.defineProperty,oc=(r,e,t)=>e in r?ic(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>(oc(r,typeof e!="symbol"?e+"":e,t),t);const aa=(r,e)=>{const t=new q(e);if(![Y.DAY,Y.HOUR,Y.MINUTE,Y.SECOND,Y.MILLISECOND,Y.MICROSECOND,Y.NANOSECOND].some(a=>a.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 q?new q(n):new Y(n)},$=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 a=new Date(e,t-1,n,0,0,0,0);return new v(BigInt(a.getTime())*v.MILLISECOND.valueOf()).truncate(v.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,a,i]=e.split(":");let o="00",u="00";i!=null&&([o,u]=i.split("."));let l=v.hours(parseInt(n??"00",10)).add(v.minutes(parseInt(a??"00",10))).add(v.seconds(parseInt(o??"00",10))).add(v.milliseconds(parseInt(u??"00",10)));return t==="local"&&(l=l.add(v.utcOffset)),l.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 Y(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 cc(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 aa(this,e)}get isToday(){return this.truncate(Y.DAY).equals(v.now().truncate(Y.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 a=new v(n);a.after(t)&&(t=a)}return t}static min(...e){let t=v.MAX;for(const n of e){const a=new v(n);a.before(t)&&(t=a)}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($,"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 q=$;const C=class A{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 A(e).valueOf()}greaterThan(e){return this.valueOf()>new A(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new A(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new A(e).valueOf()}remainder(e){return aa(this,e)}truncate(e){return new A(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(A.DAY),t=this.truncate(A.HOUR),n=this.truncate(A.MINUTE),a=this.truncate(A.SECOND),i=this.truncate(A.MILLISECOND),o=this.truncate(A.MICROSECOND),u=this.truncate(A.NANOSECOND),l=e,y=t.sub(e),g=n.sub(t),p=a.sub(n),D=i.sub(a),P=o.sub(i),ee=u.sub(o);let Z="";return l.isZero||(Z+=`${l.days}d `),y.isZero||(Z+=`${y.hours}h `),g.isZero||(Z+=`${g.minutes}m `),p.isZero||(Z+=`${p.seconds}s `),D.isZero||(Z+=`${D.milliseconds}ms `),P.isZero||(Z+=`${P.microseconds}µs `),ee.isZero||(Z+=`${ee.nanoseconds}ns`),Z.trim()}get days(){return Number(this.valueOf())/Number(A.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(A.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(A.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(A.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(A.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(A.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new A(e).valueOf()}add(e){return new A(this.valueOf()+new A(e).valueOf())}sub(e){return new A(this.valueOf()-new A(e).valueOf())}static nanoseconds(e=1){return new A(e)}static microseconds(e=1){return A.nanoseconds(e*1e3)}static milliseconds(e=1){return A.microseconds(e*1e3)}static seconds(e=1){return A.milliseconds(e*1e3)}static minutes(e){return A.seconds(e.valueOf()*60)}static hours(e){return A.minutes(e*60)}static days(e){return A.hours(e*24)}};m(C,"NANOSECOND",C.nanoseconds(1)),m(C,"MICROSECOND",C.microseconds(1)),m(C,"MILLISECOND",C.milliseconds(1)),m(C,"SECOND",C.seconds(1)),m(C,"MINUTE",C.minutes(1)),m(C,"HOUR",C.hours(1)),m(C,"DAY",C.days(1)),m(C,"MAX",new C((1n<<63n)-1n)),m(C,"MIN",new C(0)),m(C,"ZERO",new C(0)),m(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 Y=C;const _t=class Gt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Gt(e).valueOf()}get period(){return Y.seconds(1/this.valueOf())}sampleCount(e){return new Y(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new H(t).valueOf()}span(e){return Y.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Gt(e)}static khz(e){return Gt.hz(e*1e3)}};m(_t,"z",s.z.union([s.z.number().transform(r=>new _t(r)),s.z.instanceof(Number).transform(r=>new _t(r)),s.z.instanceof(_t)]));const B=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new uc(e*this.valueOf())}};m(B,"UNKNOWN",new B(0)),m(B,"BIT128",new B(16)),m(B,"BIT64",new B(8)),m(B,"BIT32",new B(4)),m(B,"BIT16",new B(2)),m(B,"BIT8",new B(1)),m(B,"z",s.z.union([s.z.number().transform(r=>new B(r)),s.z.instanceof(Number).transform(r=>new B(r)),s.z.instanceof(B)]));let H=B;const ae=class Ht{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new q(e.start),this.end=new q(e.end)):(this.start=new q(e),this.end=new q(t))}get span(){return new Y(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}swap(){return new Ht(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=Y.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 a=q.max(n.start,e.start),i=q.min(n.end,e.end);return i.before(a)?!1:new Y(i.sub(a)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=t.valueOf()&&a<=t.valueOf()}contains(e){return e instanceof Ht?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new Ht(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(ae,"MAX",new ae(q.MIN,q.MAX)),m(ae,"MIN",new ae(q.MAX,q.MIN)),m(ae,"ZERO",new ae(q.ZERO,q.ZERO)),m(ae,"z",s.z.union([s.z.object({start:q.z,end:q.z}).transform(r=>new ae(r.start,r.end)),s.z.instanceof(ae)]));let cc=ae;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()}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(),H.BIT8],[f.UINT16.toString(),H.BIT16],[f.UINT32.toString(),H.BIT32],[f.UINT64.toString(),H.BIT64],[f.FLOAT32.toString(),H.BIT32],[f.FLOAT64.toString(),H.BIT64],[f.INT8.toString(),H.BIT8],[f.INT16.toString(),H.BIT16],[f.INT32.toString(),H.BIT32],[f.INT64.toString(),H.BIT64],[f.TIMESTAMP.toString(),H.BIT64],[f.STRING.toString(),H.UNKNOWN],[f.JSON.toString(),H.UNKNOWN],[f.UUID.toString(),H.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)]));const K=class M extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return M.bytes(this.valueOf()+e.valueOf())}sub(e){return M.bytes(this.valueOf()-e.valueOf())}truncate(e){return new M(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return M.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/M.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/M.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/M.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/M.TERABYTE.valueOf()}toString(){const e=this.truncate(M.TERABYTE),t=this.truncate(M.GIGABYTE),n=this.truncate(M.MEGABYTE),a=this.truncate(M.KILOBYTE),i=this.truncate(M.BYTE),o=e,u=t.sub(e),l=n.sub(t),y=a.sub(n),g=i.sub(a);let p="";return o.isZero||(p+=`${o.terabytes}TB `),u.isZero||(p+=`${u.gigabytes}GB `),l.isZero||(p+=`${l.megabytes}MB `),y.isZero||(p+=`${y.kilobytes}KB `),(!g.isZero||p==="")&&(p+=`${g.valueOf()}B`),p.trim()}static bytes(e=1){return new M(e)}static kilobytes(e=1){return M.bytes(e.valueOf()*1e3)}static megabytes(e=1){return M.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return M.megabytes(e.valueOf()*1e3)}static terabytes(e){return M.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(K,"BYTE",new K(1)),m(K,"KILOBYTE",K.kilobytes(1)),m(K,"MEGABYTE",K.megabytes(1)),m(K,"GIGABYTE",K.gigabytes(1)),m(K,"TERABYTE",K.terabytes(1)),m(K,"ZERO",new K(0)),m(K,"z",s.z.union([s.z.number().transform(r=>new K(r)),s.z.instanceof(K)]));let uc=K;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)]);var lc=Object.defineProperty,hc=(r,e,t)=>e in r?lc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,vt=(r,e,t)=>(hc(r,typeof e!="symbol"?e+"":e,t),t);const fc=(...r)=>r.map(ia).join(""),ia=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),dc=r=>r.endsWith("/")?r.slice(0,-1):r,yc=(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("&"),nn=class sn{constructor({host:e,port:t,protocol:n="",pathPrefix:a=""}){vt(this,"protocol"),vt(this,"host"),vt(this,"port"),vt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=ia(a)}replace(e){return new sn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new sn({...this,pathPrefix:fc(this.path,e)})}toString(){return dc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};vt(nn,"UNKNOWN",new nn({host:"unknown",port:0}));let pc=nn;var gc=Object.defineProperty,mc=(r,e,t)=>e in r?gc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,_r=(r,e,t)=>(mc(r,typeof e!="symbol"?e+"":e,t),t);const Ke=class extends Number{};_r(Ke,"Absolute",255),_r(Ke,"Default",1),_r(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))]));s.z.object({name:s.z.string(),key:s.z.string()});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);let se=class extends Error{constructor(e){super(e),k(this,"discriminator","FreighterError"),k(this,"type","")}};const wc=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},os="unknown",cs="nil",vc="freighter",Dt=s.z.object({type:s.z.string(),data:s.z.string()});class bc{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:cs,data:""};if(wc(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:os,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===cs)return null;if(e.type===os)return new us(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new us(e.data)}}const oa=new bc,ca=({encode:r,decode:e})=>oa.register({encode:r,decode:e}),In=r=>oa.decode(r);class us extends se{constructor(e){super(e),k(this,"type","unknown")}}const Or="freighter.",Xt=class ua extends se{constructor(){super("EOF"),k(this,"type",ua.TYPE)}};k(Xt,"TYPE",Or+"eof"),k(Xt,"matches",X(Xt.TYPE));let Ce=Xt;const Qt=class la extends se{constructor(){super("StreamClosed"),k(this,"type",la.TYPE)}};k(Qt,"TYPE",Or+"stream_closed"),k(Qt,"matches",X(Qt.TYPE));let ct=Qt;const er=class ha extends se{constructor(e={}){const{message:t="Unreachable",url:n=pc.UNKNOWN}=e;super(t),k(this,"type",ha.TYPE),k(this,"url"),this.url=n}};k(er,"TYPE",Or+"unreachable"),k(er,"matches",X(er.TYPE));let Ue=er;const Oc=r=>{if(!r.type.startsWith(vc))return null;if(Ce.matches(r))return{type:Ce.TYPE,data:"EOF"};if(ct.matches(r))return{type:ct.TYPE,data:"StreamClosed"};if(Ue.matches(r))return{type:Ue.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Tc=r=>{if(!r.type.startsWith(Or))return null;switch(r.type){case Ce.TYPE:return new Ce;case ct.TYPE:return new ct;case Ue.TYPE:return new Ue;default:throw new Error(`Unknown error type: ${r.data}`)}};ca({encode:Oc,decode:Tc});class fa{constructor(){k(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const a=async i=>{if(n===this.middleware.length)return await t(i);const o=this.middleware[n];return n++,await o(i,a)};return await a(e)}}const da="Content-Type",ls=r=>{if(sa.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(a,i)=>await e(a,{...i,agent:n})};class zc extends fa{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=ls(this.endpoint.protocol),new Proxy(this,{get:(a,i,o)=>i==="endpoint"?this.endpoint:Reflect.get(a,i,o)})}get headers(){return{[da]:this.encoder.contentType}}async send(e,t,n,a){t=n==null?void 0:n.parse(t);let i=null;const o=this.endpoint.child(e),u={};u.method="POST",u.body=this.encoder.encode(t??{});const[,l]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async y=>{const g={...y,params:{}};u.headers={...this.headers,...y.params};let p;try{p=await ls(y.protocol)(y.target,u)}catch(P){let ee=P;return ee.message==="Load failed"&&(ee=new Ue({url:o})),[g,ee]}const D=await p.arrayBuffer();if(p!=null&&p.ok)return a!=null&&(i=this.encoder.decode(D,a)),[g,null];try{if(p.status!==400)return[g,new Error(p.statusText)];const P=this.encoder.decode(D,Dt),ee=In(P);return[g,ee]}catch(P){return[g,new Error(`[freighter] - failed to decode error: ${p.statusText}: ${P.message}`)]}});return[i,l]}}const w=async(r,e,t,n,a)=>{const[i,o]=await r.send(e,t,n,a);if(o!=null)throw o;return i},Ec=()=>sa.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Sc=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(Dt)});class Nc{constructor(e,t,n,a){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=a,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}send(e){if(this.serverClosed!=null)return new Ce;if(this.sendClosed)throw new ct;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=In(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,Sc)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:Cc(e)?Ce.TYPE:ct.TYPE,data:""}})}}const Ac="freighterctx",Ic=1e3,kc=1001,$c=[Ic,kc],Cc=r=>$c.includes(r.code),ya=class pa extends fa{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 a=Ec();let i;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async u=>{const l=a(this.buildURL(e,u)),y={...u,params:{}};l.binaryType=pa.MESSAGE_TYPE;const g=await this.wrapSocket(l,t,n);return g instanceof Error?[y,g]:(i=g,[y,null])});if(o!=null)throw o;return i}buildURL(e,t){const n=yc({[da]:this.encoder.contentType,...t.params},Ac);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(a=>{e.onopen=()=>{a(new Nc(e,this.encoder,t,n))},e.onerror=i=>{const o=i;a(new Error(o.message))}})}};k(ya,"MESSAGE_TYPE","arraybuffer");let Rc=ya;var re=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},T={},Tr={};Object.defineProperty(Tr,"__esModule",{value:!0});function jc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"$"+n}).toLowerCase().replace(/(\$)(\w)/g,function(e,t,n){return n.toUpperCase()}):""}Tr.default=jc;var zr={};Object.defineProperty(zr,"__esModule",{value:!0});function xc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"_").toLowerCase():""}zr.default=xc;var Er={};Object.defineProperty(Er,"__esModule",{value:!0});function Pc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"$").replace(/[^A-Za-z0-9]+/g,"$").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"$"+n}).toLowerCase().replace(/(\$)(\w?)/g,function(e,t,n){return n.toUpperCase()}):""}Er.default=Pc;var kn={};Object.defineProperty(kn,"__esModule",{value:!0});function Dc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,".").toLowerCase():""}kn.default=Dc;var $n={};Object.defineProperty($n,"__esModule",{value:!0});function Zc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"/").toLowerCase():""}$n.default=Zc;var Cn={};Object.defineProperty(Cn,"__esModule",{value:!0});function Mc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase():""}Cn.default=Mc;var Rn={};Object.defineProperty(Rn,"__esModule",{value:!0});function Uc(r){if(r===void 0&&(r=""),!r)return"";var e=String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(t,n,a){return n+"_"+a.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase();return e.charAt(0).toUpperCase()+e.slice(1)}Rn.default=Uc;var jn={};Object.defineProperty(jn,"__esModule",{value:!0});function Lc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g," ").toLowerCase().replace(/( ?)(\w+)( ?)/g,function(e,t,n,a){return t+n.charAt(0).toUpperCase()+n.slice(1)+a}):""}jn.default=Lc;var Sr={};Object.defineProperty(Sr,"__esModule",{value:!0});function Bc(r){return r===void 0&&(r=""),r?String(r).replace(/^[^A-Za-z0-9]*|[^A-Za-z0-9]*$/g,"").replace(/([a-z])([A-Z])/g,function(e,t,n){return t+"_"+n.toLowerCase()}).replace(/[^A-Za-z0-9]+|_+/g,"-").toLowerCase():""}Sr.default=Bc;var xn={},Ye={};(function(r){Object.defineProperty(r,"__esModule",{value:!0}),r.belongToTypes=r.isValidObject=r.isArrayObject=r.validateOptions=r.DefaultOption=void 0,r.DefaultOption={recursive:!1,recursiveInArray:!1,keepTypesOnRecursion:[]},r.validateOptions=function(e){return e===void 0&&(e=r.DefaultOption),e.recursive==null?e=r.DefaultOption:e.recursiveInArray==null&&(e.recursiveInArray=!1),e},r.isArrayObject=function(e){return e!=null&&Array.isArray(e)},r.isValidObject=function(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)},r.belongToTypes=function(e,t){return(t||[]).some(function(n){return e instanceof n})}})(Ye);var _c=re&&re.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(xn,"__esModule",{value:!0});var me=Ye;function tr(r,e){if(e===void 0&&(e=me.DefaultOption),!me.isValidObject(r))return null;e=me.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=n.toLowerCase();e.recursive&&(me.isValidObject(a)?me.belongToTypes(a,e.keepTypesOnRecursion)||(a=tr(a,e)):e.recursiveInArray&&me.isArrayObject(a)&&(a=_c(a).map(function(o){var u=o;if(me.isValidObject(o))me.belongToTypes(u,e.keepTypesOnRecursion)||(u=tr(o,e));else if(me.isArrayObject(o)){var l=tr({key:o},e);u=l.key}return u}))),t[i]=a}),t}xn.default=tr;var Pn={},qc=re&&re.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Pn,"__esModule",{value:!0});var we=Ye;function rr(r,e){if(e===void 0&&(e=we.DefaultOption),!we.isValidObject(r))return null;e=we.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=n.toUpperCase();e.recursive&&(we.isValidObject(a)?we.belongToTypes(a,e.keepTypesOnRecursion)||(a=rr(a,e)):e.recursiveInArray&&we.isArrayObject(a)&&(a=qc(a).map(function(o){var u=o;if(we.isValidObject(o))we.belongToTypes(u,e.keepTypesOnRecursion)||(u=rr(o,e));else if(we.isArrayObject(o)){var l=rr({key:o},e);u=l.key}return u}))),t[i]=a}),t}Pn.default=rr;var Dn={},Yc=re&&re.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Dn,"__esModule",{value:!0});var ve=Ye,Kc=Tr;function nr(r,e){if(e===void 0&&(e=ve.DefaultOption),!ve.isValidObject(r))return null;e=ve.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=Kc.default(n);e.recursive&&(ve.isValidObject(a)?ve.belongToTypes(a,e.keepTypesOnRecursion)||(a=nr(a,e)):e.recursiveInArray&&ve.isArrayObject(a)&&(a=Yc(a).map(function(o){var u=o;if(ve.isValidObject(o))ve.belongToTypes(u,e.keepTypesOnRecursion)||(u=nr(o,e));else if(ve.isArrayObject(o)){var l=nr({key:o},e);u=l.key}return u}))),t[i]=a}),t}Dn.default=nr;var Zn={},Wc=re&&re.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Zn,"__esModule",{value:!0});var be=Ye,Vc=zr;function sr(r,e){if(e===void 0&&(e=be.DefaultOption),!be.isValidObject(r))return null;e=be.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=Vc.default(n);e.recursive&&(be.isValidObject(a)?be.belongToTypes(a,e.keepTypesOnRecursion)||(a=sr(a,e)):e.recursiveInArray&&be.isArrayObject(a)&&(a=Wc(a).map(function(o){var u=o;if(be.isValidObject(o))be.belongToTypes(u,e.keepTypesOnRecursion)||(u=sr(o,e));else if(be.isArrayObject(o)){var l=sr({key:o},e);u=l.key}return u}))),t[i]=a}),t}Zn.default=sr;var Mn={},Fc=re&&re.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Mn,"__esModule",{value:!0});var Oe=Ye,Jc=Er;function ar(r,e){if(e===void 0&&(e=Oe.DefaultOption),!Oe.isValidObject(r))return null;e=Oe.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=Jc.default(n);e.recursive&&(Oe.isValidObject(a)?Oe.belongToTypes(a,e.keepTypesOnRecursion)||(a=ar(a,e)):e.recursiveInArray&&Oe.isArrayObject(a)&&(a=Fc(a).map(function(o){var u=o;if(Oe.isValidObject(o))Oe.belongToTypes(u,e.keepTypesOnRecursion)||(u=ar(o,e));else if(Oe.isArrayObject(o)){var l=ar({key:o},e);u=l.key}return u}))),t[i]=a}),t}Mn.default=ar;var Un={},Gc=re&&re.__spreadArrays||function(){for(var r=0,e=0,t=arguments.length;e<t;e++)r+=arguments[e].length;for(var n=Array(r),a=0,e=0;e<t;e++)for(var i=arguments[e],o=0,u=i.length;o<u;o++,a++)n[a]=i[o];return n};Object.defineProperty(Un,"__esModule",{value:!0});var Te=Ye,Hc=Sr;function ir(r,e){if(e===void 0&&(e=Te.DefaultOption),!Te.isValidObject(r))return null;e=Te.validateOptions(e);var t={};return Object.keys(r).forEach(function(n){var a=r[n],i=Hc.default(n);e.recursive&&(Te.isValidObject(a)?Te.belongToTypes(a,e.keepTypesOnRecursion)||(a=ir(a,e)):e.recursiveInArray&&Te.isArrayObject(a)&&(a=Gc(a).map(function(o){var u=o;if(Te.isValidObject(o))Te.belongToTypes(u,e.keepTypesOnRecursion)||(u=ir(o,e));else if(Te.isArrayObject(o)){var l=ir({key:o},e);u=l.key}return u}))),t[i]=a}),t}Un.default=ir;Object.defineProperty(T,"__esModule",{value:!0});T.kebabKeys=T.pascalKeys=T.snakeKeys=T.camelKeys=T.upperKeys=T.lowerKeys=T.toLowerCase=T.toUpperCase=T.toKebabCase=T.toHeaderCase=T.toSentenceCase=T.toTextCase=T.toPathCase=T.toDotCase=T.toPascalCase=T.toSnakeCase=T.toCamelCase=void 0;var ga=Tr;T.toCamelCase=ga.default;var ma=zr;T.toSnakeCase=ma.default;var wa=Er;T.toPascalCase=wa.default;var va=kn;T.toDotCase=va.default;var ba=$n;T.toPathCase=ba.default;var Oa=Cn;T.toTextCase=Oa.default;var Ta=Rn;T.toSentenceCase=Ta.default;var za=jn;T.toHeaderCase=za.default;var Ea=Sr;T.toKebabCase=Ea.default;var Sa=xn;T.lowerKeys=Sa.default;var Na=Pn;T.upperKeys=Na.default;var Aa=Dn;T.camelKeys=Aa.default;var Ia=Zn;T.snakeKeys=Ia.default;var ka=Mn;T.pascalKeys=ka.default;var $a=Un;T.kebabKeys=$a.default;var Ca=function(r){return String(r||"").toLowerCase()};T.toLowerCase=Ca;var Ra=function(r){return String(r||"").toUpperCase()};T.toUpperCase=Ra;var Xc={toCamelCase:ga.default,toSnakeCase:ma.default,toPascalCase:wa.default,toDotCase:va.default,toPathCase:ba.default,toTextCase:Oa.default,toSentenceCase:Ta.default,toHeaderCase:za.default,toKebabCase:Ea.default,toUpperCase:Ra,toLowerCase:Ca,lowerKeys:Sa.default,upperKeys:Na.default,camelKeys:Aa.default,snakeKeys:Ia.default,pascalKeys:ka.default,kebabKeys:$a.default};T.default=Xc;var ja=T;const xa={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Qc=r=>ja.snakeKeys(r,xa),lr=r=>ja.camelKeys(r,xa),eu=r=>r!=null&&typeof r=="object"&&"toString"in r,tu=(r,e=!1)=>{const t=eu(r)?"stringer":typeof r;let n;switch(t){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?ru(n):n},ru=r=>(e,t)=>r(t,e),Nr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Pa=s.z.object({width:s.z.number(),height:s.z.number()}),nu=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),su=["width","height"];s.z.enum(su);const au=["start","center","end"],iu=["signedWidth","signedHeight"];s.z.enum(iu);const hr=s.z.object({x:s.z.number(),y:s.z.number()}),ou=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),cu=["x","y"],Da=s.z.enum(cu),Za=["top","right","bottom","left"];s.z.enum(Za);const uu=["left","right"],Ma=s.z.enum(uu),lu=["top","bottom"],Ua=s.z.enum(lu),La=["center"],hs=s.z.enum(La),hu=[...Za,...La],Ba=s.z.enum(hu);s.z.enum(au);const fu=["first","last"];s.z.enum(fu);const du=s.z.object({lower:s.z.number(),upper:s.z.number()}),yu=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([du,Nr]);s.z.union([yu,Nr]);s.z.union([Da,Ba]);s.z.union([Da,Ba,s.z.instanceof(String)]);const St=(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 fs(r);return fs(t)},fs=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Ma.or(hs),y:Ua.or(hs)});const pu=s.z.object({x:Ma,y:Ua}),gu=Object.freeze({x:"left",y:"top"}),mu=(r,e)=>r.x===e.x&&r.y===e.y,ds=s.z.union([s.z.number(),hr,Nr,Pa,nu,ou]),wu=(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}},ys=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:hr,two:hr,root:pu});const Ln=(r,e,t=0,n=0,a)=>{const i={one:{...ys},two:{...ys},root:a??gu};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:r,y:e},i.two={x:i.one.x+t,y:i.one.y+n},i}return"one"in r&&"two"in r&&"root"in r?{...r,root:a??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(i.one={x:r.left,y:r.top},i.two={x:r.right,y:r.bottom},i):(i.one=r,e==null?i.two={x:i.one.x+t,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+t}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},qr=r=>{const e=Ln(r);return{lower:e.one.x,upper:e.two.x}},Yr=r=>{const e=Ln(r);return{lower:e.one.y,upper:e.two.y}},vu=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,bu=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Pa,bu,hr,Nr]);var Ou=Object.defineProperty,Tu=(r,e,t)=>e in r?Ou(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ae=(r,e,t)=>(Tu(r,typeof e!="symbol"?e+"":e,t),t);const zu=(r,e,t)=>(e!=null&&(r=Math.max(r,e)),t!=null&&(r=Math.min(r,t)),r);s.z.object({offset:ds,scale:ds});const Eu=r=>(e,t,n,a)=>t==="dimension"?[e,n]:[e,a?n-r:n+r],Su=r=>(e,t,n,a)=>[e,a?n/r:n*r],Nu=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:a,upper:i}=e,{lower:o,upper:u}=r,l=i-a,y=u-o;if(t==="dimension")return[r,n*(y/l)];const g=(n-a)*(y/l)+o;return[r,g]},Au=r=>(e,t,n)=>[r,n],Iu=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:a}=r;return[r,a-(t-n)]},ku=r=>(e,t,n)=>{const{lower:a,upper:i}=r;return n=zu(n,a,i),[e,n]},an=class bt{constructor(){Ae(this,"ops",[]),Ae(this,"currBounds",null),Ae(this,"currType",null),Ae(this,"reversed",!1),this.ops=[]}static translate(e){return new bt().translate(e)}static magnify(e){return new bt().magnify(e)}static scale(e,t){return new bt().scale(e,t)}translate(e){const t=this.new(),n=Eu(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Su(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=St(e,t),a=this.new(),i=Nu(n);return i.type="scale",a.ops.push(i),a}clamp(e,t){const n=St(e,t),a=this.new(),i=ku(n);return i.type="clamp",a.ops.push(i),a}reBound(e,t){const n=St(e,t),a=this.new(),i=Au(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=Iu();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 bt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||t.some(([o,u])=>a>=o&&a<=u))return;const i=e.ops.findIndex((o,u)=>o.type==="scale"&&u>a);i!==-1&&t.push([a,i])}),t.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}};Ae(an,"IDENTITY",new an);let ps=an;const gs=class Ee{constructor(e=new ps,t=new ps,n=null){Ae(this,"x"),Ae(this,"y"),Ae(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new Ee().translate(e,t)}static translateX(e){return new Ee().translateX(e)}static translateY(e){return new Ee().translateY(e)}static clamp(e){return new Ee().clamp(e)}static magnify(e){return new Ee().magnify(e)}static scale(e){return new Ee().scale(e)}static reBound(e){return new Ee().reBound(e)}translate(e,t){const n=wu(e,t),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}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(vu(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!mu(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(qr(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(qr(e)),t.y=this.y.reBound(Yr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(qr(e)),t.y=this.y.clamp(Yr(e)),t}copy(){const e=new Ee;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 Ln(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};Ae(gs,"IDENTITY",new gs);var $u=Object.defineProperty,Cu=(r,e,t)=>e in r?$u(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,d=(r,e,t)=>(Cu(r,typeof e!="symbol"?e+"":e,t),t);let Ru="_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",ju=(r=21)=>{let e="",t=r;for(;t--;)e+=Ru[Math.random()*64|0];return e};const _a=(r,e)=>{const t=new E(e);if(![N.DAY,N.HOUR,N.MINUTE,N.SECOND,N.MILLISECOND,N.MICROSECOND,N.NANOSECOND].some(a=>a.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 E?new E(n):new N(n)},R=class b{constructor(e,t="UTC"){if(d(this,"value"),d(this,"encodeValue",!0),e==null)this.value=b.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*b.MILLISECOND.valueOf();else if(typeof e=="string")this.value=b.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=b.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const a=new Date(e,t-1,n,0,0,0,0);return new b(BigInt(a.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,a,i]=e.split(":");let o="00",u="00";i!=null&&([o,u]=i.split("."));let l=b.hours(parseInt(n??"00",10)).add(b.minutes(parseInt(a??"00",10))).add(b.seconds(parseInt(o??"00",10))).add(b.milliseconds(parseInt(u??"00",10)));return t==="local"&&(l=l.add(b.utcOffset)),l.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new b(BigInt(n.getTime())*b.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(b.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 N(BigInt(new Date().getTimezoneOffset())*b.MINUTE.valueOf())}static since(e){return new b().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new b(e).valueOf()}span(e){return this.range(e).span}range(e){return new F(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 b(e).valueOf()}afterEq(e){return this.valueOf()>=new b(e).valueOf()}before(e){return this.valueOf()<new b(e).valueOf()}beforeEq(e){return this.valueOf()<=new b(e).valueOf()}add(e){return new b(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new b(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return _a(this,e)}get isToday(){return this.truncate(N.DAY).equals(b.now().truncate(N.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new b(new Date)}static max(...e){let t=b.MIN;for(const n of e){const a=new b(n);a.after(t)&&(t=a)}return t}static min(...e){let t=b.MAX;for(const n of e){const a=new b(n);a.before(t)&&(t=a)}return t}static nanoseconds(e){return new b(e)}static microseconds(e){return b.nanoseconds(e*1e3)}static milliseconds(e){return b.microseconds(e*1e3)}static seconds(e){return b.milliseconds(e*1e3)}static minutes(e){return b.seconds(e*60)}static hours(e){return b.minutes(e*60)}static days(e){return b.hours(e*24)}};d(R,"NANOSECOND",R.nanoseconds(1)),d(R,"MICROSECOND",R.microseconds(1)),d(R,"MILLISECOND",R.milliseconds(1)),d(R,"SECOND",R.seconds(1)),d(R,"MINUTE",R.minutes(1)),d(R,"HOUR",R.hours(1)),d(R,"DAY",R.days(1)),d(R,"MAX",new R((1n<<63n)-1n)),d(R,"MIN",new R(0)),d(R,"ZERO",new R(0)),d(R,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new R(r.value)),s.z.string().transform(r=>new R(BigInt(r))),s.z.instanceof(Number).transform(r=>new R(r)),s.z.number().transform(r=>new R(r)),s.z.instanceof(R)]));let E=R;const j=class I{constructor(e){d(this,"value"),d(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 _a(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),a=this.truncate(I.SECOND),i=this.truncate(I.MILLISECOND),o=this.truncate(I.MICROSECOND),u=this.truncate(I.NANOSECOND),l=e,y=t.sub(e),g=n.sub(t),p=a.sub(n),D=i.sub(a),P=o.sub(i),ee=u.sub(o);let Z="";return l.isZero||(Z+=`${l.days}d `),y.isZero||(Z+=`${y.hours}h `),g.isZero||(Z+=`${g.minutes}m `),p.isZero||(Z+=`${p.seconds}s `),D.isZero||(Z+=`${D.milliseconds}ms `),P.isZero||(Z+=`${P.microseconds}µs `),ee.isZero||(Z+=`${ee.nanoseconds}ns`),Z.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)}};d(j,"NANOSECOND",j.nanoseconds(1)),d(j,"MICROSECOND",j.microseconds(1)),d(j,"MILLISECOND",j.milliseconds(1)),d(j,"SECOND",j.seconds(1)),d(j,"MINUTE",j.minutes(1)),d(j,"HOUR",j.hours(1)),d(j,"DAY",j.days(1)),d(j,"MAX",new j((1n<<63n)-1n)),d(j,"MIN",new j(0)),d(j,"ZERO",new j(0)),d(j,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new j(r.value)),s.z.string().transform(r=>new j(BigInt(r))),s.z.instanceof(Number).transform(r=>new j(r)),s.z.number().transform(r=>new j(r)),s.z.instanceof(j)]));let N=j;const Ot=class or extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new or(e).valueOf()}get period(){return N.seconds(1/this.valueOf())}sampleCount(e){return new N(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new V(t).valueOf()}span(e){return N.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new or(e)}static khz(e){return or.hz(e*1e3)}};d(Ot,"z",s.z.union([s.z.number().transform(r=>new Ot(r)),s.z.instanceof(Number).transform(r=>new Ot(r)),s.z.instanceof(Ot)]));let Ar=Ot;const _=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new kt(e*this.valueOf())}};d(_,"UNKNOWN",new _(0)),d(_,"BIT128",new _(16)),d(_,"BIT64",new _(8)),d(_,"BIT32",new _(4)),d(_,"BIT16",new _(2)),d(_,"BIT8",new _(1)),d(_,"z",s.z.union([s.z.number().transform(r=>new _(r)),s.z.instanceof(Number).transform(r=>new _(r)),s.z.instanceof(_)]));let V=_;const oe=class cr{constructor(e,t){d(this,"start"),d(this,"end"),typeof e=="object"&&"start"in e?(this.start=new E(e.start),this.end=new E(e.end)):(this.start=new E(e),this.end=new E(t))}get span(){return new N(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}swap(){return new cr(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=N.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 a=E.max(n.start,e.start),i=E.min(n.end,e.end);return i.before(a)?!1:new N(i.sub(a)).greaterThanOrEqual(t)}roughlyEquals(e,t){let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=t.valueOf()&&a<=t.valueOf()}contains(e){return e instanceof cr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new cr(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}};d(oe,"MAX",new oe(E.MIN,E.MAX)),d(oe,"MIN",new oe(E.MAX,E.MIN)),d(oe,"ZERO",new oe(E.ZERO,E.ZERO)),d(oe,"z",s.z.union([s.z.object({start:E.z,end:E.z}).transform(r=>new oe(r.start,r.end)),s.z.instanceof(oe)]));let F=oe;const h=class ce extends String{constructor(e){if(e instanceof ce||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ce.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ce.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ce.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()}toString(){return this.valueOf()}get isVariable(){return this.equals(ce.JSON)||this.equals(ce.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ce.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ce.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 ce.BIG_INT_TYPES.some(e=>e.equals(this))}};d(h,"UNKNOWN",new h("unknown")),d(h,"FLOAT64",new h("float64")),d(h,"FLOAT32",new h("float32")),d(h,"INT64",new h("int64")),d(h,"INT32",new h("int32")),d(h,"INT16",new h("int16")),d(h,"INT8",new h("int8")),d(h,"UINT64",new h("uint64")),d(h,"UINT32",new h("uint32")),d(h,"UINT16",new h("uint16")),d(h,"UINT8",new h("uint8")),d(h,"BOOLEAN",h.UINT8),d(h,"TIMESTAMP",new h("timestamp")),d(h,"UUID",new h("uuid")),d(h,"STRING",new h("string")),d(h,"JSON",new h("json")),d(h,"ARRAY_CONSTRUCTORS",new Map([[h.UINT8.toString(),Uint8Array],[h.UINT16.toString(),Uint16Array],[h.UINT32.toString(),Uint32Array],[h.UINT64.toString(),BigUint64Array],[h.FLOAT32.toString(),Float32Array],[h.FLOAT64.toString(),Float64Array],[h.INT8.toString(),Int8Array],[h.INT16.toString(),Int16Array],[h.INT32.toString(),Int32Array],[h.INT64.toString(),BigInt64Array],[h.TIMESTAMP.toString(),BigInt64Array],[h.STRING.toString(),Uint8Array],[h.JSON.toString(),Uint8Array],[h.UUID.toString(),Uint8Array]])),d(h,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,h.UINT8],[Uint16Array.name,h.UINT16],[Uint32Array.name,h.UINT32],[BigUint64Array.name,h.UINT64],[Float32Array.name,h.FLOAT32],[Float64Array.name,h.FLOAT64],[Int8Array.name,h.INT8],[Int16Array.name,h.INT16],[Int32Array.name,h.INT32],[BigInt64Array.name,h.INT64]])),d(h,"DENSITIES",new Map([[h.UINT8.toString(),V.BIT8],[h.UINT16.toString(),V.BIT16],[h.UINT32.toString(),V.BIT32],[h.UINT64.toString(),V.BIT64],[h.FLOAT32.toString(),V.BIT32],[h.FLOAT64.toString(),V.BIT64],[h.INT8.toString(),V.BIT8],[h.INT16.toString(),V.BIT16],[h.INT32.toString(),V.BIT32],[h.INT64.toString(),V.BIT64],[h.TIMESTAMP.toString(),V.BIT64],[h.STRING.toString(),V.UNKNOWN],[h.JSON.toString(),V.UNKNOWN],[h.UUID.toString(),V.BIT128]])),d(h,"ALL",[h.UNKNOWN,h.FLOAT64,h.FLOAT32,h.INT64,h.INT32,h.INT16,h.INT8,h.UINT64,h.UINT32,h.UINT16,h.UINT8,h.TIMESTAMP,h.UUID,h.STRING,h.JSON]),d(h,"BIG_INT_TYPES",[h.INT64,h.UINT64,h.TIMESTAMP]),d(h,"z",s.z.union([s.z.string().transform(r=>new h(r)),s.z.instanceof(h)]));let S=h;const W=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),a=this.truncate(U.KILOBYTE),i=this.truncate(U.BYTE),o=e,u=t.sub(e),l=n.sub(t),y=a.sub(n),g=i.sub(a);let p="";return o.isZero||(p+=`${o.terabytes}TB `),u.isZero||(p+=`${u.gigabytes}GB `),l.isZero||(p+=`${l.megabytes}MB `),y.isZero||(p+=`${y.kilobytes}KB `),(!g.isZero||p==="")&&(p+=`${g.valueOf()}B`),p.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}};d(W,"BYTE",new W(1)),d(W,"KILOBYTE",W.kilobytes(1)),d(W,"MEGABYTE",W.megabytes(1)),d(W,"GIGABYTE",W.gigabytes(1)),d(W,"TERABYTE",W.terabytes(1)),d(W,"ZERO",new W(0)),d(W,"z",s.z.union([s.z.number().transform(r=>new W(r)),s.z.instanceof(W)]));let kt=W;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 qa=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof E||r instanceof N||r instanceof Date},xu=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):Tt(t,-n),Pu=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Ze?!0:qa(r),Pe=-1;let Ze=class Se{constructor(e){d(this,"key",""),d(this,"isSynnaxSeries",!0),d(this,"dataType"),d(this,"sampleOffset"),d(this,"gl"),d(this,"_data"),d(this,"_timeRange"),d(this,"alignment",0n),d(this,"_cachedMin"),d(this,"_cachedMax"),d(this,"writePos",Pe),d(this,"_refCount",0),d(this,"_cachedLength"),Pu(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,key:u=ju()}=e,{data:l}=e;if(l instanceof Se||typeof l=="object"&&"isSynnaxSeries"in l&&l.isSynnaxSeries===!0){const p=l;this.key=p.key,this.dataType=p.dataType,this.sampleOffset=p.sampleOffset,this.gl=p.gl,this._data=p._data,this._timeRange=p._timeRange,this.alignment=p.alignment,this._cachedMin=p._cachedMin,this._cachedMax=p._cachedMax,this.writePos=p.writePos,this._refCount=p._refCount,this._cachedLength=p._cachedLength;return}const y=qa(l),g=Array.isArray(l);if(t!=null)this.dataType=new S(t);else{if(l instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(g||y){let p=l;if(!y){if(l.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");p=l[0]}if(typeof p=="string")this.dataType=S.STRING;else if(typeof p=="number")this.dataType=S.FLOAT64;else if(typeof p=="bigint")this.dataType=S.INT64;else if(typeof p=="boolean")this.dataType=S.BOOLEAN;else if(p instanceof E||p instanceof Date||p instanceof E)this.dataType=S.TIMESTAMP;else if(typeof p=="object")this.dataType=S.JSON;else throw new Error(`cannot infer data type of ${typeof p} when constructing a Series from a JS array`)}else this.dataType=new S(l)}if(!g&&!y)this._data=l;else{let p=y?[l]:l;const D=p[0];(D instanceof E||D instanceof Date||D instanceof N)&&(p=p.map(P=>new E(P).valueOf())),this.dataType.equals(S.STRING)?(this._cachedLength=p.length,this._data=new TextEncoder().encode(p.join(`
1
+ "use strict";var Si=Object.defineProperty;var Ni=(r,e,t)=>e in r?Si(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>Ni(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod");var Ii=Object.defineProperty,Ai=(r,e,t)=>e in r?Ii(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,I=(r,e,t)=>Ai(r,typeof e!="symbol"?e+"":e,t);const ki=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)},Un=r=>{const e=(t,n=Or)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(a=>e(a,n));if(!sr(t))return null;n=Ci(n);const i={};return Object.keys(t).forEach(a=>{let c=t[a];const l=r(a);n.recursive&&(sr(c)?tn(c,n.keepTypesOnRecursion)||(c=e(c,n)):n.recursiveInArray&&en(c)&&(c=[...c].map(u=>{let f=u;return sr(u)?tn(f,n.keepTypesOnRecursion)||(f=e(u,n)):en(u)&&(f=e({key:u},n).key),f}))),i[l]=c}),i};return e},Ri=Un(ki),$i=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),xi=Un($i),Or={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Ci=(r=Or)=>(r.recursive==null?r=Or:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),en=r=>r!=null&&Array.isArray(r),sr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),tn=(r,e)=>(e||[]).some(t=>r instanceof t),Bn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Pi=Object.defineProperty,ji=(r,e,t)=>e in r?Pi(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ct=(r,e,t)=>ji(r,typeof e!="symbol"?e+"":e,t);let Di=class{constructor(){ct(this,"contentType","application/json"),ct(this,"decoder"),ct(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=Ri(n);return t!=null?t.parse(i):i}encodeString(e){const t=xi(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Bn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Mi=class{constructor(){ct(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||!Bn(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(`
2
+ `)}decodeString(e,t){const[n,...i]=e.trim().split(`
3
+ `).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(f=>f.trim());a.forEach((f,g)=>{const p=this.parseValue(u[g]);p!=null&&c[f].push(p)})}),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(){}},Zi=class{constructor(){ct(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}};new Di;new Mi;new Zi;const Wt=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ln=s.z.object({width:s.z.number(),height:s.z.number()}),Ui=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Bi=["width","height"];s.z.enum(Bi);const Li=["start","center","end"],qi=["signedWidth","signedHeight"];s.z.enum(qi);const Mt=s.z.object({x:s.z.number(),y:s.z.number()}),Yi=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Wi=["x","y"],qn=s.z.enum(Wi),Yn=["top","right","bottom","left"];s.z.enum(Yn);const Fi=["left","right"],Wn=s.z.enum(Fi),_i=["top","bottom"],Fn=s.z.enum(_i),_n=["center"],rn=s.z.enum(_n),Gi=[...Yn,..._n],Gn=s.z.enum(Gi);s.z.enum(Li);const Ki=["first","last"];s.z.enum(Ki);const Ji=s.z.object({lower:s.z.number(),upper:s.z.number()}),Vi=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Ji,Wt]);s.z.union([Vi,Wt]);s.z.union([qn,Gn]);s.z.union([qn,Gn,s.z.instanceof(String)]);const ir=(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 nn(r);return nn(t)},nn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:Wn.or(rn),y:Fn.or(rn)});const Hi=s.z.object({x:Wn,y:Fn}),Xi=Object.freeze({x:"left",y:"top"}),Qi=(r,e)=>r.x===e.x&&r.y===e.y,sn=s.z.union([s.z.number(),Mt,Wt,Ln,Ui,Yi]),ea=(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}),St=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:St,left:St,width:St,height:St});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Mt,two:Mt,root:Hi});const Mr=(r,e,t=0,n=0,i)=>{const a={one:{...an},two:{...an},root:i??Xi};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))},ar=r=>{const e=Mr(r);return{lower:e.one.x,upper:e.two.x}},or=r=>{const e=Mr(r);return{lower:e.one.y,upper:e.two.y}},ta=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r;var ra=Object.defineProperty,na=(r,e,t)=>e in r?ra(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ue=(r,e,t)=>na(r,typeof e!="symbol"?e+"":e,t);const sa=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:sn,scale:sn});const ia=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],aa=r=>(e,t,n,i)=>[e,i?n/r:n*r],oa=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,f=l-c;if(t==="dimension")return[r,n*(f/u)];const g=(n-i)*(f/u)+c;return[r,g]},ca=r=>(e,t,n)=>[r,n],la=()=>(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)]},ua=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=sa(n,i,a),[e,n]},zr=class et{constructor(){ue(this,"ops",[]),ue(this,"currBounds",null),ue(this,"currType",null),ue(this,"reversed",!1),this.ops=[]}static translate(e){return new et().translate(e)}static magnify(e){return new et().magnify(e)}static scale(e,t){return new et().scale(e,t)}translate(e){const t=this.new(),n=ia(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=aa(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=ir(e,t),i=this.new(),a=oa(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=ir(e,t),i=this.new(),a=ua(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=ir(e,t),i=this.new(),a=ca(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=la();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 et;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}};ue(zr,"IDENTITY",new zr);let on=zr;const cn=class oe{constructor(e=new on,t=new on,n=null){ue(this,"x"),ue(this,"y"),ue(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new oe().translate(e,t)}static translateX(e){return new oe().translateX(e)}static translateY(e){return new oe().translateY(e)}static clamp(e){return new oe().clamp(e)}static magnify(e){return new oe().magnify(e)}static scale(e){return new oe().scale(e)}static reBound(e){return new oe().reBound(e)}translate(e,t){const n=ea(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(ta(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Qi(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(ar(e)),t.y=t.y.scale(or(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(ar(e)),t.y=this.y.reBound(or(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(ar(e)),t.y=this.y.clamp(or(e)),t}copy(){const e=new oe;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 Mr(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};ue(cn,"IDENTITY",new cn);const ha=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ln,ha,Mt,Wt]);var ya=Object.defineProperty,da=(r,e,t)=>e in r?ya(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>da(r,typeof e!="symbol"?e+"":e,t);const Kn=(r,e)=>{const t=new L(e);if(![q.DAY,q.HOUR,q.MINUTE,q.SECOND,q.MILLISECOND,q.MICROSECOND,q.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 L?new L(n):new q(n)},A=class b{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=b.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*b.MILLISECOND.valueOf();else if(typeof e=="string")this.value=b.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=b.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.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 b(BigInt(i.getTime())*b.MILLISECOND.valueOf()).truncate(b.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=b.hours(parseInt(n??"00",10)).add(b.minutes(parseInt(i??"00",10))).add(b.seconds(parseInt(c??"00",10))).add(b.milliseconds(parseInt(l??"00",10)));return t==="local"&&(u=u.add(b.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new b(BigInt(n.getTime())*b.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(b.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 q(BigInt(new Date().getTimezoneOffset())*b.MINUTE.valueOf())}static since(e){return new b().span(e)}date(){return new Date(this.milliseconds())}equals(e){return this.valueOf()===new b(e).valueOf()}span(e){return this.range(e).span}range(e){return new fa(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 b(e).valueOf()}afterEq(e){return this.valueOf()>=new b(e).valueOf()}before(e){return this.valueOf()<new b(e).valueOf()}beforeEq(e){return this.valueOf()<=new b(e).valueOf()}add(e){return new b(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new b(this.valueOf()-BigInt(e.valueOf()))}milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}toString(){return this.date().toISOString()}remainder(e){return Kn(this,e)}get isToday(){return this.truncate(q.DAY).equals(b.now().truncate(q.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new b(new Date)}static max(...e){let t=b.MIN;for(const n of e){const i=new b(n);i.after(t)&&(t=i)}return t}static min(...e){let t=b.MAX;for(const n of e){const i=new b(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new b(e)}static microseconds(e){return b.nanoseconds(e*1e3)}static milliseconds(e){return b.microseconds(e*1e3)}static seconds(e){return b.milliseconds(e*1e3)}static minutes(e){return b.seconds(e*60)}static hours(e){return b.minutes(e*60)}static days(e){return b.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 L=A;const k=class S{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 S(e).valueOf()}greaterThan(e){return this.valueOf()>new S(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new S(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new S(e).valueOf()}remainder(e){return Kn(this,e)}truncate(e){return new S(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(S.DAY),t=this.truncate(S.HOUR),n=this.truncate(S.MINUTE),i=this.truncate(S.SECOND),a=this.truncate(S.MILLISECOND),c=this.truncate(S.MICROSECOND),l=this.truncate(S.NANOSECOND),u=e,f=t.sub(e),g=n.sub(t),p=i.sub(n),P=a.sub(i),C=c.sub(a),X=l.sub(c);let j="";return u.isZero||(j+=`${u.days}d `),f.isZero||(j+=`${f.hours}h `),g.isZero||(j+=`${g.minutes}m `),p.isZero||(j+=`${p.seconds}s `),P.isZero||(j+=`${P.milliseconds}ms `),C.isZero||(j+=`${C.microseconds}µs `),X.isZero||(j+=`${X.nanoseconds}ns`),j.trim()}get days(){return Number(this.valueOf())/Number(S.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(S.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(S.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(S.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(S.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(S.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new S(e).valueOf()}add(e){return new S(this.valueOf()+new S(e).valueOf())}sub(e){return new S(this.valueOf()-new S(e).valueOf())}static nanoseconds(e=1){return new S(e)}static microseconds(e=1){return S.nanoseconds(e*1e3)}static milliseconds(e=1){return S.microseconds(e*1e3)}static seconds(e=1){return S.milliseconds(e*1e3)}static minutes(e){return S.seconds(e.valueOf()*60)}static hours(e){return S.minutes(e*60)}static days(e){return S.hours(e*24)}};m(k,"NANOSECOND",k.nanoseconds(1)),m(k,"MICROSECOND",k.microseconds(1)),m(k,"MILLISECOND",k.milliseconds(1)),m(k,"SECOND",k.seconds(1)),m(k,"MINUTE",k.minutes(1)),m(k,"HOUR",k.hours(1)),m(k,"DAY",k.days(1)),m(k,"MAX",new k((1n<<63n)-1n)),m(k,"MIN",new k(0)),m(k,"ZERO",new k(0)),m(k,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new k(r.value)),s.z.string().transform(r=>new k(BigInt(r))),s.z.instanceof(Number).transform(r=>new k(r)),s.z.number().transform(r=>new k(r)),s.z.instanceof(k)]));let q=k;const Nt=class At extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new At(e).valueOf()}get period(){return q.seconds(1/this.valueOf())}sampleCount(e){return new q(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new J(t).valueOf()}span(e){return q.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new At(e)}static khz(e){return At.hz(e*1e3)}};m(Nt,"z",s.z.union([s.z.number().transform(r=>new Nt(r)),s.z.instanceof(Number).transform(r=>new Nt(r)),s.z.instanceof(Nt)]));const U=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new pa(e*this.valueOf())}};m(U,"UNKNOWN",new U(0)),m(U,"BIT128",new U(16)),m(U,"BIT64",new U(8)),m(U,"BIT32",new U(4)),m(U,"BIT16",new U(2)),m(U,"BIT8",new U(1)),m(U,"z",s.z.union([s.z.number().transform(r=>new U(r)),s.z.instanceof(Number).transform(r=>new U(r)),s.z.instanceof(U)]));let J=U;const re=class kt{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new L(e.start),this.end=new L(e.end)):(this.start=new L(e),this.end=new L(t))}get span(){return new q(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}swap(){return new kt(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=q.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=L.max(n.start,e.start),a=L.min(n.end,e.end);return a.before(i)?!1:new q(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 kt?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new kt(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(re,"MAX",new re(L.MIN,L.MAX)),m(re,"MIN",new re(L.MAX,L.MIN)),m(re,"ZERO",new re(L.ZERO,L.ZERO)),m(re,"z",s.z.union([s.z.object({start:L.z,end:L.z}).transform(r=>new re(r.start,r.end)),s.z.instanceof(re)]));let fa=re;const y=class ne extends String{constructor(e){if(e instanceof ne||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}else{const t=ne.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}}throw super(ne.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=ne.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()}toString(){return this.valueOf()}get isVariable(){return this.equals(ne.JSON)||this.equals(ne.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(ne.UUID)}get isInteger(){return this.toString().startsWith("int")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=ne.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 ne.BIG_INT_TYPES.some(e=>e.equals(this))}};m(y,"UNKNOWN",new y("unknown")),m(y,"FLOAT64",new y("float64")),m(y,"FLOAT32",new y("float32")),m(y,"INT64",new y("int64")),m(y,"INT32",new y("int32")),m(y,"INT16",new y("int16")),m(y,"INT8",new y("int8")),m(y,"UINT64",new y("uint64")),m(y,"UINT32",new y("uint32")),m(y,"UINT16",new y("uint16")),m(y,"UINT8",new y("uint8")),m(y,"BOOLEAN",y.UINT8),m(y,"TIMESTAMP",new y("timestamp")),m(y,"UUID",new y("uuid")),m(y,"STRING",new y("string")),m(y,"JSON",new y("json")),m(y,"ARRAY_CONSTRUCTORS",new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]])),m(y,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]])),m(y,"DENSITIES",new Map([[y.UINT8.toString(),J.BIT8],[y.UINT16.toString(),J.BIT16],[y.UINT32.toString(),J.BIT32],[y.UINT64.toString(),J.BIT64],[y.FLOAT32.toString(),J.BIT32],[y.FLOAT64.toString(),J.BIT64],[y.INT8.toString(),J.BIT8],[y.INT16.toString(),J.BIT16],[y.INT32.toString(),J.BIT32],[y.INT64.toString(),J.BIT64],[y.TIMESTAMP.toString(),J.BIT64],[y.STRING.toString(),J.UNKNOWN],[y.JSON.toString(),J.UNKNOWN],[y.UUID.toString(),J.BIT128]])),m(y,"ALL",[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON]),m(y,"BIG_INT_TYPES",[y.INT64,y.UINT64,y.TIMESTAMP]),m(y,"z",s.z.union([s.z.string().transform(r=>new y(r)),s.z.instanceof(y)]));const Y=class D extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return D.bytes(this.valueOf()+e.valueOf())}sub(e){return D.bytes(this.valueOf()-e.valueOf())}truncate(e){return new D(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return D.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/D.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/D.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/D.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/D.TERABYTE.valueOf()}toString(){const e=this.truncate(D.TERABYTE),t=this.truncate(D.GIGABYTE),n=this.truncate(D.MEGABYTE),i=this.truncate(D.KILOBYTE),a=this.truncate(D.BYTE),c=e,l=t.sub(e),u=n.sub(t),f=i.sub(n),g=a.sub(i);let p="";return c.isZero||(p+=`${c.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),u.isZero||(p+=`${u.megabytes}MB `),f.isZero||(p+=`${f.kilobytes}KB `),(!g.isZero||p==="")&&(p+=`${g.valueOf()}B`),p.trim()}static bytes(e=1){return new D(e)}static kilobytes(e=1){return D.bytes(e.valueOf()*1e3)}static megabytes(e=1){return D.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return D.megabytes(e.valueOf()*1e3)}static terabytes(e){return D.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(Y,"BYTE",new Y(1)),m(Y,"KILOBYTE",Y.kilobytes(1)),m(Y,"MEGABYTE",Y.megabytes(1)),m(Y,"GIGABYTE",Y.gigabytes(1)),m(Y,"TERABYTE",Y.terabytes(1)),m(Y,"ZERO",new Y(0)),m(Y,"z",s.z.union([s.z.number().transform(r=>new Y(r)),s.z.instanceof(Y)]));let pa=Y;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)]);s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const Jn=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",ga=Jn(),Vn=["MacOS","Windows","Linux","Docker"],ma=s.z.enum(Vn);let cr;const wa=()=>{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"},ba=(r={})=>{const{force:e,default:t}=r;return e??cr??(cr=wa(),cr??t)},Hn=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Vn,RUNTIME:ga,detect:Jn,getOS:ba,osZ:ma},Symbol.toStringTag,{value:"Module"}));var va=Object.defineProperty,Ta=(r,e,t)=>e in r?va(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,tt=(r,e,t)=>Ta(r,typeof e!="symbol"?e+"":e,t);const Oa=(...r)=>r.map(Xn).join(""),Xn=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),za=r=>r.endsWith("/")?r.slice(0,-1):r,Ea=(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("&"),Er=class Sr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){tt(this,"protocol"),tt(this,"host"),tt(this,"port"),tt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Xn(i)}replace(e){return new Sr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Sr({...this,pathPrefix:Oa(this.path,e)})}toString(){return za(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};tt(Er,"UNKNOWN",new Er({host:"unknown",port:0}));let Sa=Er;var Na=Object.defineProperty,Ia=(r,e,t)=>e in r?Na(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Rt=(r,e,t)=>Ia(r,typeof e!="symbol"?e+"":e,t);const ke=class extends Number{};Rt(ke,"Absolute",255),Rt(ke,"Default",1),Rt(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))]));s.z.object({name:s.z.string(),key:s.z.string()});const Qn=class rt extends Error{constructor(){super(rt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(rt.MESSAGE):e instanceof rt||e.message.includes(rt.MESSAGE)}};Rt(Qn,"MESSAGE","canceled");let Aa=Qn;new Aa;s.z.string().regex(/^\d+\.\d+\.\d+$/);const V=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);let te=class extends Error{constructor(e){super(e),I(this,"discriminator","FreighterError"),I(this,"type","")}};const ka=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},ln="unknown",un="nil",Ra="freighter",vt=s.z.object({type:s.z.string(),data:s.z.string()});class $a{constructor(){I(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:un,data:""};if(ka(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:ln,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===un)return null;if(e.type===ln)return new hn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new hn(e.data)}}const es=new $a,ts=({encode:r,decode:e})=>es.register({encode:r,decode:e}),Zr=r=>es.decode(r);class hn extends te{constructor(e){super(e),I(this,"type","unknown")}}const Ft="freighter.",$t=class rs extends te{constructor(){super("EOF"),I(this,"type",rs.TYPE)}};I($t,"TYPE",Ft+"eof"),I($t,"matches",V($t.TYPE));let ge=$t;const xt=class ns extends te{constructor(){super("StreamClosed"),I(this,"type",ns.TYPE)}};I(xt,"TYPE",Ft+"stream_closed"),I(xt,"matches",V(xt.TYPE));let We=xt;const Ct=class ss extends te{constructor(e={}){const{message:t="Unreachable",url:n=Sa.UNKNOWN}=e;super(t),I(this,"type",ss.TYPE),I(this,"url"),this.url=n}};I(Ct,"TYPE",Ft+"unreachable"),I(Ct,"matches",V(Ct.TYPE));let Se=Ct;const xa=r=>{if(!r.type.startsWith(Ra))return null;if(ge.matches(r))return{type:ge.TYPE,data:"EOF"};if(We.matches(r))return{type:We.TYPE,data:"StreamClosed"};if(Se.matches(r))return{type:Se.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Ca=r=>{if(!r.type.startsWith(Ft))return null;switch(r.type){case ge.TYPE:return new ge;case We.TYPE:return new We;case Se.TYPE:return new Se;default:throw new Error(`Unknown error type: ${r.data}`)}};ts({encode:xa,decode:Ca});class is{constructor(){I(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 as="Content-Type",yn=r=>{if(Hn.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 Pa extends is{constructor(e,t,n=!1){return super(),I(this,"endpoint"),I(this,"encoder"),I(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=yn(this.endpoint.protocol),new Proxy(this,{get:(i,a,c)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,c)})}get headers(){return{[as]: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 f=>{const g={...f,params:{}};l.headers={...this.headers,...f.params};let p;try{p=await yn(f.protocol)(f.target,l)}catch(C){let X=C;return X.message==="Load failed"&&(X=new Se({url:c})),[g,X]}const P=await p.arrayBuffer();if(p!=null&&p.ok)return i!=null&&(a=this.encoder.decode(P,i)),[g,null];try{if(p.status!==400)return[g,new Error(p.statusText)];const C=this.encoder.decode(P,vt),X=Zr(C);return[g,X]}catch(C){return[g,new Error(`[freighter] - failed to decode error: ${p.statusText}: ${C.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},ja=()=>Hn.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Da=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close")]),payload:s.z.unknown().optional(),error:s.z.optional(vt)});class Ma{constructor(e,t,n,i){I(this,"encoder"),I(this,"reqSchema"),I(this,"resSchema"),I(this,"ws"),I(this,"serverClosed"),I(this,"sendClosed"),I(this,"receiveDataQueue",[]),I(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 ge;if(this.sendClosed)throw new We;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=Zr(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,Da)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:qa(e)?ge.TYPE:We.TYPE,data:""}})}}const Za="freighterctx",Ua=1e3,Ba=1001,La=[Ua,Ba],qa=r=>La.includes(r.code),os=class cs extends is{constructor(e,t,n=!1){super(),I(this,"baseUrl"),I(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=ja();let a;const[,c]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),f={...l,params:{}};u.binaryType=cs.MESSAGE_TYPE;const g=await this.wrapSocket(u,t,n);return g instanceof Error?[f,g]:(a=g,[f,null])});if(c!=null)throw c;return a}buildURL(e,t){const n=Ea({[as]:this.encoder.contentType,...t.params},Za);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{i(new Ma(e,this.encoder,t,n))},e.onerror=a=>{const c=a;i(new Error(c.message))}})}};I(os,"MESSAGE_TYPE","arraybuffer");let Ya=os;const Wa=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)},ls=r=>{const e=(t,n=Nr)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(a=>e(a,n));if(!lr(t))return null;n=Ga(n);const i={};return Object.keys(t).forEach(a=>{let c=t[a];const l=r(a);n.recursive&&(lr(c)?fn(c,n.keepTypesOnRecursion)||(c=e(c,n)):n.recursiveInArray&&dn(c)&&(c=[...c].map(u=>{let f=u;return lr(u)?fn(f,n.keepTypesOnRecursion)||(f=e(u,n)):dn(u)&&(f=e({key:u},n).key),f}))),i[l]=c}),i};return e},Zt=ls(Wa),Fa=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),_a=ls(Fa),Nr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Ga=(r=Nr)=>(r.recursive==null?r=Nr:r.recursiveInArray==null&&(r.recursiveInArray=!1),r),dn=r=>r!=null&&Array.isArray(r),lr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),fn=(r,e)=>(e||[]).some(t=>r instanceof t),Ka=r=>r!=null&&typeof r=="object"&&"toString"in r,Ja=(r,e=!1)=>{const t=Ka(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?Va(n):n},Va=r=>(e,t)=>r(t,e),_t=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const us=s.z.object({width:s.z.number(),height:s.z.number()}),Ha=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Xa=["width","height"];s.z.enum(Xa);const Qa=["start","center","end"],eo=["signedWidth","signedHeight"];s.z.enum(eo);const Ut=s.z.object({x:s.z.number(),y:s.z.number()}),to=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),ro=["x","y"],hs=s.z.enum(ro),ys=["top","right","bottom","left"];s.z.enum(ys);const no=["left","right"],ds=s.z.enum(no),so=["top","bottom"],fs=s.z.enum(so),ps=["center"],pn=s.z.enum(ps),io=[...ys,...ps],gs=s.z.enum(io);s.z.enum(Qa);const ao=["first","last"];s.z.enum(ao);const oo=s.z.object({lower:s.z.number(),upper:s.z.number()}),co=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([oo,_t]);s.z.union([co,_t]);s.z.union([hs,gs]);s.z.union([hs,gs,s.z.instanceof(String)]);const lt=(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 gn(r);return gn(t)},gn=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r;s.z.object({x:ds.or(pn),y:fs.or(pn)});const lo=s.z.object({x:ds,y:fs}),uo=Object.freeze({x:"left",y:"top"}),ho=(r,e)=>r.x===e.x&&r.y===e.y,mn=s.z.union([s.z.number(),Ut,_t,us,Ha,to]),yo=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},wn=Object.freeze({x:0,y:0}),It=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:It,left:It,width:It,height:It});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Ut,two:Ut,root:lo});const Ur=(r,e,t=0,n=0,i)=>{const a={one:{...wn},two:{...wn},root:i??uo};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))},ur=r=>{const e=Ur(r);return{lower:e.one.x,upper:e.two.x}},hr=r=>{const e=Ur(r);return{lower:e.one.y,upper:e.two.y}},fo=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,po=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([us,po,Ut,_t]);var go=Object.defineProperty,mo=(r,e,t)=>e in r?go(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,he=(r,e,t)=>mo(r,typeof e!="symbol"?e+"":e,t);const wo=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:mn,scale:mn});const bo=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],vo=r=>(e,t,n,i)=>[e,i?n/r:n*r],To=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:c,upper:l}=r,u=a-i,f=l-c;if(t==="dimension")return[r,n*(f/u)];const g=(n-i)*(f/u)+c;return[r,g]},Oo=r=>(e,t,n)=>[r,n],zo=()=>(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)]},Eo=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=wo(n,i,a),[e,n]},Ir=class nt{constructor(){he(this,"ops",[]),he(this,"currBounds",null),he(this,"currType",null),he(this,"reversed",!1),this.ops=[]}static translate(e){return new nt().translate(e)}static magnify(e){return new nt().magnify(e)}static scale(e,t){return new nt().scale(e,t)}translate(e){const t=this.new(),n=bo(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=vo(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=lt(e,t),i=this.new(),a=To(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=lt(e,t),i=this.new(),a=Eo(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=lt(e,t),i=this.new(),a=Oo(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=zo();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 nt;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}};he(Ir,"IDENTITY",new Ir);let bn=Ir;const vn=class ce{constructor(e=new bn,t=new bn,n=null){he(this,"x"),he(this,"y"),he(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ce().translate(e,t)}static translateX(e){return new ce().translateX(e)}static translateY(e){return new ce().translateY(e)}static clamp(e){return new ce().clamp(e)}static magnify(e){return new ce().magnify(e)}static scale(e){return new ce().scale(e)}static reBound(e){return new ce().reBound(e)}translate(e,t){const n=yo(e,t),i=this.copy();return i.x=this.x.translate(n.x),i.y=this.y.translate(n.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(fo(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!ho(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(ur(e)),t.y=t.y.scale(hr(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(ur(e)),t.y=this.y.reBound(hr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(ur(e)),t.y=this.y.clamp(hr(e)),t}copy(){const e=new ce;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 Ur(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}};he(vn,"IDENTITY",new vn);var So=Object.defineProperty,No=(r,e,t)=>e in r?So(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,d=(r,e,t)=>No(r,typeof e!="symbol"?e+"":e,t);let Io=(r,e=21)=>(t=e)=>{let n="",i=t;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Ao="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",ms=Io(Ao,11),ko=Object.freeze(Object.defineProperty({__proto__:null,id:ms},Symbol.toStringTag,{value:"Module"})),ws=(r,e)=>{const t=new O(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 O?new O(n):new E(n)},R=class v{constructor(e,t="UTC"){if(d(this,"value"),d(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 E(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 _(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 ws(this,e)}get isToday(){return this.truncate(E.DAY).equals(v.now().truncate(E.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)}};d(R,"NANOSECOND",R.nanoseconds(1)),d(R,"MICROSECOND",R.microseconds(1)),d(R,"MILLISECOND",R.milliseconds(1)),d(R,"SECOND",R.seconds(1)),d(R,"MINUTE",R.minutes(1)),d(R,"HOUR",R.hours(1)),d(R,"DAY",R.days(1)),d(R,"MAX",new R((1n<<63n)-1n)),d(R,"MIN",new R(0)),d(R,"ZERO",new R(0)),d(R,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new R(r.value)),s.z.string().transform(r=>new R(BigInt(r))),s.z.instanceof(Number).transform(r=>new R(r)),s.z.number().transform(r=>new R(r)),s.z.instanceof(R)]));let O=R;const $=class N{constructor(e){d(this,"value"),d(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 ws(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,f=t.sub(e),g=n.sub(t),p=i.sub(n),P=a.sub(i),C=c.sub(a),X=l.sub(c);let j="";return u.isZero||(j+=`${u.days}d `),f.isZero||(j+=`${f.hours}h `),g.isZero||(j+=`${g.minutes}m `),p.isZero||(j+=`${p.seconds}s `),P.isZero||(j+=`${P.milliseconds}ms `),C.isZero||(j+=`${C.microseconds}µs `),X.isZero||(j+=`${X.nanoseconds}ns`),j.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)}};d($,"NANOSECOND",$.nanoseconds(1)),d($,"MICROSECOND",$.microseconds(1)),d($,"MILLISECOND",$.milliseconds(1)),d($,"SECOND",$.seconds(1)),d($,"MINUTE",$.minutes(1)),d($,"HOUR",$.hours(1)),d($,"DAY",$.days(1)),d($,"MAX",new $((1n<<63n)-1n)),d($,"MIN",new $(0)),d($,"ZERO",new $(0)),d($,"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 E=$;const st=class Pt extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Pt(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 F(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 Pt(e)}static khz(e){return Pt.hz(e*1e3)}};d(st,"z",s.z.union([s.z.number().transform(r=>new st(r)),s.z.instanceof(Number).transform(r=>new st(r)),s.z.instanceof(st)]));let Gt=st;const B=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new dt(e*this.valueOf())}};d(B,"UNKNOWN",new B(0)),d(B,"BIT128",new B(16)),d(B,"BIT64",new B(8)),d(B,"BIT32",new B(4)),d(B,"BIT16",new B(2)),d(B,"BIT8",new B(1)),d(B,"z",s.z.union([s.z.number().transform(r=>new B(r)),s.z.instanceof(Number).transform(r=>new B(r)),s.z.instanceof(B)]));let F=B;const se=class jt{constructor(e,t){d(this,"start"),d(this,"end"),typeof e=="object"&&"start"in e?(this.start=new O(e.start),this.end=new O(e.end)):(this.start=new O(e),this.end=new O(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}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=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=O.max(n.start,e.start),a=O.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 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}};d(se,"MAX",new se(O.MIN,O.MAX)),d(se,"MIN",new se(O.MAX,O.MIN)),d(se,"ZERO",new se(O.ZERO,O.ZERO)),d(se,"z",s.z.union([s.z.object({start:O.z,end:O.z}).transform(r=>new se(r.start,r.end)),s.z.instanceof(se)]));let _=se;const h=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()}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))}};d(h,"UNKNOWN",new h("unknown")),d(h,"FLOAT64",new h("float64")),d(h,"FLOAT32",new h("float32")),d(h,"INT64",new h("int64")),d(h,"INT32",new h("int32")),d(h,"INT16",new h("int16")),d(h,"INT8",new h("int8")),d(h,"UINT64",new h("uint64")),d(h,"UINT32",new h("uint32")),d(h,"UINT16",new h("uint16")),d(h,"UINT8",new h("uint8")),d(h,"BOOLEAN",h.UINT8),d(h,"TIMESTAMP",new h("timestamp")),d(h,"UUID",new h("uuid")),d(h,"STRING",new h("string")),d(h,"JSON",new h("json")),d(h,"ARRAY_CONSTRUCTORS",new Map([[h.UINT8.toString(),Uint8Array],[h.UINT16.toString(),Uint16Array],[h.UINT32.toString(),Uint32Array],[h.UINT64.toString(),BigUint64Array],[h.FLOAT32.toString(),Float32Array],[h.FLOAT64.toString(),Float64Array],[h.INT8.toString(),Int8Array],[h.INT16.toString(),Int16Array],[h.INT32.toString(),Int32Array],[h.INT64.toString(),BigInt64Array],[h.TIMESTAMP.toString(),BigInt64Array],[h.STRING.toString(),Uint8Array],[h.JSON.toString(),Uint8Array],[h.UUID.toString(),Uint8Array]])),d(h,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,h.UINT8],[Uint16Array.name,h.UINT16],[Uint32Array.name,h.UINT32],[BigUint64Array.name,h.UINT64],[Float32Array.name,h.FLOAT32],[Float64Array.name,h.FLOAT64],[Int8Array.name,h.INT8],[Int16Array.name,h.INT16],[Int32Array.name,h.INT32],[BigInt64Array.name,h.INT64]])),d(h,"DENSITIES",new Map([[h.UINT8.toString(),F.BIT8],[h.UINT16.toString(),F.BIT16],[h.UINT32.toString(),F.BIT32],[h.UINT64.toString(),F.BIT64],[h.FLOAT32.toString(),F.BIT32],[h.FLOAT64.toString(),F.BIT64],[h.INT8.toString(),F.BIT8],[h.INT16.toString(),F.BIT16],[h.INT32.toString(),F.BIT32],[h.INT64.toString(),F.BIT64],[h.TIMESTAMP.toString(),F.BIT64],[h.STRING.toString(),F.UNKNOWN],[h.JSON.toString(),F.UNKNOWN],[h.UUID.toString(),F.BIT128]])),d(h,"ALL",[h.UNKNOWN,h.FLOAT64,h.FLOAT32,h.INT64,h.INT32,h.INT16,h.INT8,h.UINT64,h.UINT32,h.UINT16,h.UINT8,h.TIMESTAMP,h.UUID,h.STRING,h.JSON]),d(h,"BIG_INT_TYPES",[h.INT64,h.UINT64,h.TIMESTAMP]),d(h,"z",s.z.union([s.z.string().transform(r=>new h(r)),s.z.instanceof(h)]));let z=h;const W=class M extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return M.bytes(this.valueOf()+e.valueOf())}sub(e){return M.bytes(this.valueOf()-e.valueOf())}truncate(e){return new M(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return M.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/M.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/M.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/M.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/M.TERABYTE.valueOf()}toString(){const e=this.truncate(M.TERABYTE),t=this.truncate(M.GIGABYTE),n=this.truncate(M.MEGABYTE),i=this.truncate(M.KILOBYTE),a=this.truncate(M.BYTE),c=e,l=t.sub(e),u=n.sub(t),f=i.sub(n),g=a.sub(i);let p="";return c.isZero||(p+=`${c.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),u.isZero||(p+=`${u.megabytes}MB `),f.isZero||(p+=`${f.kilobytes}KB `),(!g.isZero||p==="")&&(p+=`${g.valueOf()}B`),p.trim()}static bytes(e=1){return new M(e)}static kilobytes(e=1){return M.bytes(e.valueOf()*1e3)}static megabytes(e=1){return M.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return M.megabytes(e.valueOf()*1e3)}static terabytes(e){return M.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};d(W,"BYTE",new W(1)),d(W,"KILOBYTE",W.kilobytes(1)),d(W,"MEGABYTE",W.megabytes(1)),d(W,"GIGABYTE",W.gigabytes(1)),d(W,"TERABYTE",W.terabytes(1)),d(W,"ZERO",new W(0)),d(W,"z",s.z.union([s.z.number().transform(r=>new W(r)),s.z.instanceof(W)]));let dt=W;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 bs=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof O||r instanceof E||r instanceof Date},Ro=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t)-BigInt(n):it(t,-n),$o=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Oe?!0:bs(r),ve=-1;let Oe=class le{constructor(e){d(this,"key",""),d(this,"isSynnaxSeries",!0),d(this,"dataType"),d(this,"sampleOffset"),d(this,"gl"),d(this,"_data"),d(this,"_timeRange"),d(this,"alignment",0n),d(this,"_cachedMin"),d(this,"_cachedMax"),d(this,"writePos",ve),d(this,"_refCount",0),d(this,"_cachedLength"),$o(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:c=0n,key:l=ms()}=e,{data:u}=e;if(u instanceof le||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const p=u;this.key=p.key,this.dataType=p.dataType,this.sampleOffset=p.sampleOffset,this.gl=p.gl,this._data=p._data,this._timeRange=p._timeRange,this.alignment=p.alignment,this._cachedMin=p._cachedMin,this._cachedMax=p._cachedMax,this.writePos=p.writePos,this._refCount=p._refCount,this._cachedLength=p._cachedLength;return}const f=bs(u),g=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(g||f){let p=u;if(!f){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.");p=u[0]}if(typeof p=="string")this.dataType=z.STRING;else if(typeof p=="number")this.dataType=z.FLOAT64;else if(typeof p=="bigint")this.dataType=z.INT64;else if(typeof p=="boolean")this.dataType=z.BOOLEAN;else if(p instanceof O||p instanceof Date||p instanceof O)this.dataType=z.TIMESTAMP;else if(typeof p=="object")this.dataType=z.JSON;else throw new Error(`cannot infer data type of ${typeof p} when constructing a Series from a JS array`)}else this.dataType=new z(u)}if(!g&&!f)this._data=u;else{let p=f?[u]:u;const P=p[0];(P instanceof O||P instanceof Date||P instanceof E)&&(p=p.map(C=>new O(C).valueOf())),this.dataType.equals(z.STRING)?(this._cachedLength=p.length,this._data=new TextEncoder().encode(p.join(`
4
4
  `)+`
5
- `)):this.dataType.equals(S.JSON)?(this._cachedLength=p.length,this._data=new TextEncoder().encode(p.map(P=>JSON.stringify(P)).join(`
5
+ `)):this.dataType.equals(z.JSON)?(this._cachedLength=p.length,this._data=new TextEncoder().encode(p.map(C=>JSON.stringify(C)).join(`
6
6
  `)+`
7
- `)):this._data=new this.dataType.Array(p).buffer}this.key=u,this.alignment=o,this.sampleOffset=a??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new S(t).Array(e),i=new Se({data:a.buffer,dataType:t,...n});return i.writePos=0,i}static generateTimestamps(e,t,n){const a=n.spanRange(t.span(e)),i=new BigInt64Array(e);for(let o=0;o<e;o++)i[o]=BigInt(n.add(t.span(o)).valueOf());return new Se({data:i,dataType:S.TIMESTAMP,timeRange:a})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
7
+ `)):this._data=new this.dataType.Array(p).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 le({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 le({data:a,dataType:z.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(e.join(`
8
8
  `)+`
9
- `);return new Se({data:n,dataType:S.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(a=>JSON.stringify(a)).join(`
9
+ `);return new le({data:n,dataType:z.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(e.map(i=>JSON.stringify(i)).join(`
10
10
  `)+`
11
- `);return new Se({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");if(this.writePos===Pe)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===Pe?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.equals(S.STRING))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(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 a=this.buffer.slice(n*e,(n+1)*e),i=Array.from(new Uint8Array(a),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=i}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.buffer).split(`
13
- `).slice(0,-1).map(t=>e.parse(lr(JSON.parse(t))))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new kt(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Pe?this.byteCapacity:this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Pe?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 a=0;a<this.length;a++)n[a]=xu(this.dataType,e,this.data[a],t);return new Se({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()),Tt(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()),Tt(this._cachedMin,this.sampleOffset))}get bounds(){return St(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 Tt(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 Tt(n,this.sampleOffset)}atVariable(e,t){e<0&&(e=this.length+e);let n=0,a=0;for(let o=0;o<this.data.length;o++)if(this.data[o]===10){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}const i=this.data.slice(n,a);return this.dataType.equals(S.STRING)?new TextDecoder().decode(i):lr(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1;const a=tu(e);for(;t<=n;){const i=Math.floor((t+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?t=i+1:n=i-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:a}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Pe){a===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(a).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,i,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Pe}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 St(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 Du(this);return this.dataType.equals(S.JSON)?new Zu(e):e}return new Mu(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(e,t);return new Se({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new Se({data:this.buffer,dataType:this.dataType,timeRange:F.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};class Du{constructor(e){if(d(this,"series"),d(this,"index"),d(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 Ya;class Zu{constructor(e){d(this,"wrapped"),d(this,Ya,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:lr(JSON.parse(e.value))}}[Symbol.iterator](){return this}}Ya=Symbol.toStringTag;var Ka;class Mu{constructor(e){d(this,"series"),d(this,"index"),d(this,Ka,"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)}}[Symbol.iterator](){return this}}Ka=Symbol.toStringTag;const Tt=(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 Wa{constructor(e){if(d(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?F.ZERO:new F(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 kt(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 Uu(this.series)}}var Va;class Uu{constructor(e){d(this,"series"),d(this,"seriesIndex"),d(this,"internal"),d(this,Va,"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())}[Symbol.iterator](){return this}}Va=Symbol.toStringTag;const z=r=>Array.isArray(r)?r:[r],Re=s.z.number(),Zt=s.z.object({name:s.z.string(),key:s.z.number(),rate:Ar.z,dataType:S.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),alias:s.z.string().optional()}),Fa=Zt.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:Ar.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Lu=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Bu=new Error("request for lock canceled");var _u=function(r,e,t,n){function a(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function u(g){try{y(n.next(g))}catch(p){o(p)}}function l(g){try{y(n.throw(g))}catch(p){o(p)}}function y(g){g.done?i(g.value):a(g.value).then(u,l)}y((n=n.apply(r,e||[])).next())})};class qu{constructor(e,t=Bu){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,a)=>{const i={resolve:n,reject:a,weight:e,priority:t},o=Ja(this._queue,u=>t<=u.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return _u(this,arguments,void 0,function*(t,n=1,a=0){const[i,o]=yield this.acquire(n,a);try{return yield t(i)}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]=[]),Yu(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 a=n.findIndex(i=>i.priority<=e);(a===-1?n:n.splice(0,a)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Yu(r,e){const t=Ja(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Ja(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Ku=function(r,e,t,n){function a(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function u(g){try{y(n.next(g))}catch(p){o(p)}}function l(g){try{y(n.throw(g))}catch(p){o(p)}}function y(g){g.done?i(g.value):a(g.value).then(u,l)}y((n=n.apply(r,e||[])).next())})};class Wu{constructor(e){this._semaphore=new qu(1,e)}acquire(){return Ku(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 je="sy.",We=class We extends se{constructor(){super(...arguments);c(this,"type",We.TYPE)}};c(We,"TYPE",je+"validation"),c(We,"matches",X(We.TYPE));let x=We;const Ve=class Ve extends x{constructor(t,n){super(t+": "+n);c(this,"type",Ve.TYPE);c(this,"field");c(this,"message");this.field=t,this.message=n}};c(Ve,"TYPE",x.TYPE+".field"),c(Ve,"matches",X(Ve.TYPE));let fr=Ve;const Fe=class Fe extends se{constructor(){super(...arguments);c(this,"type",Fe.TYPE)}};c(Fe,"TYPE",je+"auth"),c(Fe,"matches",X(Fe.TYPE));let Le=Fe;const Je=class Je extends Le{constructor(){super(...arguments);c(this,"type",Je.TYPE)}};c(Je,"TYPE",Le.TYPE+".invalid-token"),c(Je,"matches",X(Je.TYPE));let $t=Je;const Ge=class Ge extends se{constructor(t){super(`
11
+ `);return new le({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===ve)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===ve?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.equals(z.STRING))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(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(`
13
+ `).slice(0,-1).map(t=>e.parse(Zt(JSON.parse(t))))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new dt(this.buffer.byteLength)}get capacity(){return this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity: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;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]=Ro(this.dataType,e,this.data[i],t);return new le({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()),it(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()),it(this._cachedMin,this.sampleOffset))}get bounds(){return lt(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 it(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 it(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):Zt(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Ja(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!==ve){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=ve}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 lt(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 xo(this);return this.dataType.equals(z.JSON)?new Co(e):e}return new Po(this)}slice(e,t){if(e<=0&&(t==null||t>=this.length))return this;const n=this.data.slice(e,t);return new le({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}reAlign(e){return new le({data:this.buffer,dataType:this.dataType,timeRange:_.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};class xo{constructor(e){if(d(this,"series"),d(this,"index"),d(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 Tn,On;class Co{constructor(e){d(this,"wrapped"),d(this,Tn,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:Zt(JSON.parse(e.value))}}[(On=Symbol.iterator,Tn=Symbol.toStringTag,On)](){return this}}var zn,En;class Po{constructor(e){d(this,"series"),d(this,"index"),d(this,zn,"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)}}[(En=Symbol.iterator,zn=Symbol.toStringTag,En)](){return this}}const it=(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 vs{constructor(e){if(d(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?_.ZERO:new _(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 dt(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 jo(this.series)}}var Sn,Nn;class jo{constructor(e){d(this,"series"),d(this,"seriesIndex"),d(this,"internal"),d(this,Sn,"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())}[(Nn=Symbol.iterator,Sn=Symbol.toStringTag,Nn)](){return this}}const T=r=>Array.isArray(r)?r:[r],me=s.z.number(),Tt=s.z.object({name:s.z.string(),key:s.z.number(),rate:Gt.z,dataType:z.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),alias:s.z.string().optional()}),Ts=Tt.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:Gt.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1)}),Do=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Mo=new Error("request for lock canceled");var Zo=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(g){try{f(n.next(g))}catch(p){c(p)}}function u(g){try{f(n.throw(g))}catch(p){c(p)}}function f(g){g.done?a(g.value):i(g.value).then(l,u)}f((n=n.apply(r,e||[])).next())})};class Uo{constructor(e,t=Mo){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=Os(this._queue,l=>t<=l.priority);c===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(c+1,0,a)})}runExclusive(e){return Zo(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]=[]),Bo(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 Bo(r,e){const t=Os(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Os(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var Lo=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(g){try{f(n.next(g))}catch(p){c(p)}}function u(g){try{f(n.throw(g))}catch(p){c(p)}}function f(g){g.done?a(g.value):i(g.value).then(l,u)}f((n=n.apply(r,e||[])).next())})};class qo{constructor(e){this._semaphore=new Uo(1,e)}acquire(){return Lo(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 we="sy.",Re=class Re extends te{constructor(){super(...arguments);o(this,"type",Re.TYPE)}};o(Re,"TYPE",we+"validation"),o(Re,"matches",V(Re.TYPE));let x=Re;const $e=class $e extends x{constructor(t,n){super(t+": "+n);o(this,"type",$e.TYPE);o(this,"field");o(this,"message");this.field=t,this.message=n}};o($e,"TYPE",x.TYPE+".field"),o($e,"matches",V($e.TYPE));let Bt=$e;const xe=class xe extends te{constructor(){super(...arguments);o(this,"type",xe.TYPE)}};o(xe,"TYPE",we+"auth"),o(xe,"matches",V(xe.TYPE));let Ne=xe;const Ce=class Ce extends Ne{constructor(){super(...arguments);o(this,"type",Ce.TYPE)}};o(Ce,"TYPE",Ne.TYPE+".invalid-token"),o(Ce,"matches",V(Ce.TYPE));let ft=Ce;const Pe=class Pe extends te{constructor(t){super(`
14
14
  Unexpected error encountered:
15
15
 
16
16
  ${t}
17
17
 
18
18
  Please report this to the Synnax team.
19
- `);c(this,"type",Ge.TYPE)}};c(Ge,"TYPE",je+"unexpected"),c(Ge,"matches",X(Ge.TYPE));let $e=Ge;const He=class He extends se{constructor(){super(...arguments);c(this,"type",He.TYPE)}};c(He,"TYPE",je+"query"),c(He,"matches",X(He.TYPE));let Q=He;const Xe=class Xe extends Q{constructor(){super(...arguments);c(this,"type",Xe.TYPE)}};c(Xe,"TYPE",Q.TYPE+".not_found"),c(Xe,"matches",X(Xe.TYPE));let Be=Xe;const Qe=class Qe extends Q{constructor(){super(...arguments);c(this,"type",Qe.TYPE)}};c(Qe,"TYPE",Q.TYPE+".multiple_results"),c(Qe,"matches",X(Qe.TYPE));let _e=Qe;const et=class et extends se{constructor(t,n){super(t);c(this,"type",et.TYPE);c(this,"path");this.path=n}};c(et,"TYPE",je+"route"),c(et,"matches",X(et.TYPE));let Ct=et;const tt=class tt extends se{constructor(){super(...arguments);c(this,"type",tt.TYPE)}};c(tt,"TYPE",je+"control"),c(tt,"matches",X(tt.TYPE));let ut=tt;const rt=class rt extends ut{constructor(){super(...arguments);c(this,"type",rt.TYPE)}};c(rt,"TYPE",ut.TYPE+".unauthorized"),c(rt,"matches",X(rt.TYPE));let dr=rt;const nt=class nt extends se{constructor(){super(...arguments);c(this,"type",nt.TYPE)}};c(nt,"TYPE",je+"contiguity"),c(nt,"matches",X(nt.TYPE));let on=nt;const Vu=r=>{if(!r.type.startsWith(je))return null;if(r.type.startsWith(x.TYPE)){if(r.type===fr.TYPE){const e=r.data.split(": ");return e.length<2?new x(r.data):new fr(e[0],e[1])}return new x(r.data)}return r.type.startsWith(Le.TYPE)?r.type.startsWith($t.TYPE)?new $t(r.data):new Le(r.data):r.type.startsWith($e.TYPE)?new $e(r.data):r.type.startsWith(Q.TYPE)?r.type.startsWith(Be.TYPE)?new Be(r.data):r.type.startsWith(_e.TYPE)?new _e(r.data):new Q(r.data):r.type.startsWith(ut.TYPE)?r.type.startsWith(dr.TYPE)?new dr(r.data):new ut(r.data):r.type.startsWith(Ct.TYPE)?new Ct(r.data,r.data):new $e(r.data)},Fu=()=>{throw new Error("Not implemented")};ca({encode:Fu,decode:Vu});const Ju=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ue?[t,new Ue({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]},Bn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Gu=Object.defineProperty,Hu=(r,e,t)=>e in r?Gu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Nt=(r,e,t)=>(Hu(r,typeof e!="symbol"?e+"":e,t),t);class Ga{constructor(){Nt(this,"contentType","application/json"),Nt(this,"decoder"),Nt(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=lr(JSON.parse(e));return t!=null?t.parse(n):n}encodeString(e){return JSON.stringify(Qc(e),(t,n)=>ArrayBuffer.isView(n)?Array.from(n):Bn(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}}let Ha=class{constructor(){Nt(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||!Bn(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(a=>{const i=t.map(o=>JSON.stringify(a[o]??""));n.push(i.join(","))}),n.join(`
20
- `)}decodeString(e,t){const[n,...a]=e.trim().split(`
21
- `).map(u=>u.trim());if(n.length===0)return t!=null?t.parse({}):{};const i=n.split(",").map(u=>u.trim()),o={};return i.forEach(u=>{o[u]=[]}),a.forEach(u=>{const l=u.split(",").map(y=>y.trim());i.forEach((y,g)=>{const p=this.parseValue(l[g]);p!=null&&o[y].push(p)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}};class Xa{constructor(){Nt(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 Qa=new Ga,Xu=new Ha,Qu=new Xa,el=[Qa],ht=Object.freeze(Object.defineProperty({__proto__:null,CSVEncoderDecoder:Ha,CSV_ECD:Xu,ENCODERS:el,JSONEncoderDecoder:Ga,JSON_ECD:Qa,TEXT_ECD:Qu,TextEncoderDecoder:Xa},Symbol.toStringTag,{value:"Module"}));var tl=Object.defineProperty,rl=(r,e,t)=>e in r?tl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,cn=(r,e,t)=>(rl(r,typeof e!="symbol"?e+"":e,t),t);class nl{constructor(e,t){cn(this,"handlers"),cn(this,"transform"),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,a]=this.transform(e);if(!a)return;t=n}this.handlers.forEach((n,a)=>a(t))}}let sl=class{constructor(e){cn(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 un=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:sl,Observer:nl},Symbol.toStringTag,{value:"Module"})),_n=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),al=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";al();const il=["MacOS","Windows","Linux","Docker"];s.z.enum(il);const ms=r=>[...new Set(r)];var ol=Object.defineProperty,cl=(r,e,t)=>e in r?ol(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,zt=(r,e,t)=>(cl(r,typeof e!="symbol"?e+"":e,t),t);const ul=(...r)=>r.map(ei).join(""),ei=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),ll=r=>r.endsWith("/")?r.slice(0,-1):r,ln=class hn{constructor({host:e,port:t,protocol:n="",pathPrefix:a=""}){zt(this,"protocol"),zt(this,"host"),zt(this,"port"),zt(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=ei(a)}replace(e){return new hn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new hn({...this,pathPrefix:ul(this.path,e)})}toString(){return ll(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};zt(ln,"UNKNOWN",new ln({host:"unknown",port:0}));let hl=ln;var fl=Object.defineProperty,dl=(r,e,t)=>e in r?fl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Kr=(r,e,t)=>(dl(r,typeof e!="symbol"?e+"":e,t),t);const De=class extends Number{};Kr(De,"Absolute",255),Kr(De,"Default",1),Kr(De,"z",s.z.union([s.z.instanceof(De),s.z.number().int().min(0).max(255).transform(r=>new De(r)),s.z.instanceof(Number).transform(r=>new De(r))]));let ti=De;const ri=s.z.object({name:s.z.string(),key:s.z.string()}),yl=r=>s.z.object({subject:ri,resource:r,authority:ti.z}),pl=(...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}),lt=Object.freeze(Object.defineProperty({__proto__:null,Authority:ti,filterTransfersByChannelKey:pl,stateZ:yl,subjectZ:ri},Symbol.toStringTag,{value:"Module"}));s.z.string().regex(/^\d+\.\d+\.\d+$/);const Ir=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let a=z(r);const i=a[0],o=typeof i;let u;return o==="string"&&t&&!isNaN(parseInt(i))&&"number"in e?(u=e.number,a=a.map(l=>parseInt(l))):u=e[o],{single:n,variant:u,normalized:a,actual:r}},kr=(r,e,t,n)=>{if(n){if(t.length===0)throw new Be(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new _e(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},ft=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),gl=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()}),ml=s.z.object({channels:ft(Zt)}),Ie=r=>Ir(r,{number:"keys",string:"names"}),pr=class pr{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=Ie(e),{variant:a}=n;let{normalized:i}=n;return a==="keys"&&i.indexOf(0)!==-1&&(i=i.filter(o=>o!==0)),i.length===0?[]:await this.execute({[a]:i,...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(pr.ENDPOINT,e,gl,ml);if(n!=null)throw n;return t.channels}};c(pr,"ENDPOINT","/channel/retrieve");let Rt=pr;class qn{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}=Ir(e,{string:"names",number:"keys"}),a=[],i=[];if(n.forEach(u=>{const l=this.get(u);l!=null?a.push(...l):i.push(u)}),i.length===0)return a;const o=await this.wrapped.retrieve(i,t);return this.set(o),a.concat(o)}delete(e){const{variant:t,normalized:n}=Ie(e);t==="names"?n.forEach(a=>{const i=this.namesToKeys.get(a);i!=null&&(i.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(a))}):n.forEach(a=>{const i=this.cache.get(a);i!=null&&(this.cache.delete(a),this.namesToKeys.delete(i.name))})}rename(e,t){e.forEach((n,a)=>{const i=t[a],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const u=this.namesToKeys.get(o.name);u!=null&&(u.delete(n),u.size===0&&this.namesToKeys.delete(o.name)),o.name=i,this.cache.set(n,o);const l=this.namesToKeys.get(i);l==null?this.namesToKeys.set(i,new Set([n])):l.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 a=this.cache.get(e);return a==null?void 0:[a]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(a=>{const i=this.cache.get(a);i!=null&&n.push(i)}),n.length!==0)return n}}class ni{constructor(e,t){c(this,"mu",new Wu);c(this,"requests",new Map);c(this,"wrapped");c(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Lu(()=>{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}=Ie(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((i,o)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:i,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(a=>e.add(a)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,a)=>n.resolve(t.filter(i=>a.includes(i.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const si=async(r,e)=>{const{normalized:t}=Ie(e),n=await r.retrieve(t),a=[];if(t.forEach(i=>{n.find(o=>o.name===i||o.key===i)==null&&a.push(i)}),a.length>0)throw new Q(`Could not find channels: ${JSON.stringify(a)}`);return n};class ai{constructor(e,t){c(this,"key");c(this,"name");this.key=t,this.name=e}get ontologyID(){return new J({type:"group",key:this.key})}}const wl=s.z.string().uuid(),ii=s.z.object({key:wl,name:s.z.string()}),oi=s.z.union([s.z.literal("label"),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("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")]),ne=s.z.object({type:oi,key:s.z.string()}),ci=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:e,key:t}}),ui=s.z.union([ci,ne]),st=class st{constructor(e){c(this,"type");c(this,"key");if(e instanceof st)this.type=e.type,this.key=e.key;else if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n}else this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}get payload(){return{type:this.type,key:this.key}}};c(st,"z",s.z.union([ui,s.z.instanceof(st)]).transform(e=>new st(e)));let J=st;const vl=new J({type:"builtin",key:"root"}),li=s.z.object({type:s.z.number()}),hi=s.z.object({type:oi,fields:s.z.record(li)}),fi=s.z.object({id:J.z,name:s.z.string(),schema:hi.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),bl=s.z.object({from:J.z,type:s.z.string(),to:J.z}),fn=r=>{const[e,t,n]=r.split("->");return{from:new J(e),type:t,to:new J(n)}},Ol=s.z.object({group:ii}),Tl=s.z.object({parent:ne,key:s.z.string().uuid().optional(),name:s.z.string()}),zl=s.z.object({key:s.z.string(),name:s.z.string()}),El=s.z.object({keys:s.z.array(s.z.string())});var le;let Sl=(le=class{constructor(e){c(this,"client");this.client=e}async create(e,t,n){const[a,i]=await this.client.send(le.ENDPOINT,{parent:e,name:t,key:n},Tl,Ol);if(i!=null)throw i;return a.group}async rename(e,t){const n={key:e,name:t},[,a]=await this.client.send(le.ENDPOINT_RENAME,n,zl,s.z.object({}));if(a!=null)throw a}async delete(e){const t={keys:e},[,n]=await this.client.send(le.ENDPOINT_DELETE,t,El,s.z.object({}));if(n!=null)throw n}},c(le,"ENDPOINT","/ontology/create-group"),c(le,"ENDPOINT_RENAME","/ontology/rename-group"),c(le,"ENDPOINT_DELETE","/ontology/delete-group"),le),Nl=class{constructor(e){c(this,"creator");this.creator=new Sl(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 ai(e.name,e.key)}};const Wr={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},ws=s.z.object({id:ne,children:ne.array()}),Al=s.z.object({from:ne,to:ne,children:ne.array()});let Il=class{constructor(e){c(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Wr.ADD_CHILDREN,{id:e,children:t},ws,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Wr.REMOVE_CHILDREN,{id:e,children:t},ws,s.z.object({}))}async moveChildren(e,t,...n){const a={from:e,to:t,children:n};await w(this.client,Wr.MOVE_CHILDREN,a,Al,s.z.object({}))}};const kl="/ontology/retrieve",$l=s.z.object({ids:ne.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()}),Cl=s.z.object({resources:fi.array()}),Vr=r=>z(r).map(e=>new J(e).payload);let di=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 Il(e),this.groups=new Nl(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:Vr(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new Q(`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:Vr(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:Vr(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 $r.open(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,kl,e,$l,Cl);return t}};const vs="sy_ontology_resource_set",bs="sy_ontology_resource_delete",Os="sy_ontology_relationship_set",Ts="sy_ontology_relationship_delete";class $r{constructor(e,t){c(this,"resourceObs");c(this,"relationshipObs");c(this,"relationships");c(this,"resources");c(this,"streamer");c(this,"client");c(this,"closePromise");this.relationshipObs=new un.Observer,this.relationships=this.relationshipObs,this.resourceObs=new un.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 i=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);i.concat(o).length>0&&this.relationshipObs.notify(i.concat(o))}parseRelationshipSets(e){const t=e.get(Os);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:fn(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Ts);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:fn(n)}))}async parseResourceSets(e){const t=e.get(vs);if(t.length===0)return[];const n=Array.from(t.as("string")).map(a=>new J(a));try{return(await this.client.retrieve(n)).map(i=>({variant:"set",key:i.id,value:i}))}catch(a){if(a instanceof Q)return[];throw a}}parseResourceDeletes(e){const t=e.get(bs);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new J(n)}))}static async open(e,t){const n=await e.openStreamer([vs,bs,Os,Ts]);return new $r(n,t)}}const Rl=Object.freeze(Object.defineProperty({__proto__:null,ChangeTracker:$r,Client:di,ID:J,Root:vl,crudeIDZ:ui,idZ:ne,parseRelationship:fn,relationshipSchemaZ:bl,resourceSchemaZ:fi,schemaFieldZ:li,schemaZ:hi,stringIDZ:ci},Symbol.toStringTag,{value:"Module"}));class Yn{constructor({dataType:e,rate:t,name:n,leaseholder:a=0,key:i=0,isIndex:o=!1,index:u=0,internal:l=!1,frameClient:y,alias:g}){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");this.key=i,this.name=n,this.rate=new Ar(t??0),this.dataType=new S(e),this.leaseholder=a,this.index=u,this.isIndex=o,this.internal=l,this.alias=g,this._frameClient=y??null}get framer(){if(this._frameClient==null)throw new x("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Zt.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 J({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 jl="/channel/retrieve-group",xl=s.z.object({}),Pl=s.z.object({group:ii});let yi=class{constructor(e,t,n,a){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=a}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,a=!Array.isArray(e);let i=z(e),o=[];if(n){const u=await this.retriever.retrieve(i.map(y=>y.name)),l=new Set(u.map(y=>y.name));i=i.filter(y=>!l.has(y.name)),o=this.sugar(u)}return o=o.concat(this.sugar(await this.writer.create(i))),a?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),a=this.sugar(await this.retriever.retrieve(e,t));return kr("channel",e,a,n),n?a[0]:a}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:n}=Ie(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(z(e),z(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 qn(new ni(new Rt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Yn({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,jl,{},xl,Pl);return new ai(e.group.name,e.group.key)}};const Dl=s.z.object({channels:Fa.array()}),Zl=s.z.object({channels:Zt.array()}),Ml=s.z.object({keys:Re.array().optional(),names:s.z.string().array().optional()}),Ul=s.z.object({}),Ll=s.z.object({keys:Re.array(),names:s.z.string().array()}),Bl=s.z.object({}),_l="/channel/create",ql="/channel/delete",Yl="/channel/rename";let pi=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,_l,{channels:e},Dl,Zl);return this.cache.set(t),t}async delete(e){await w(this.client,ql,e,Ml,Ul),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Yl,{keys:e,names:t},Ll,Bl),this.cache.rename(e,t)}};const Kl=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:qn,Channel:Yn,Client:yi,ClusterRetriever:Rt,DebouncedBatchRetriever:ni,Writer:pi,analyzeChannelParams:Ie,keyZ:Re,newPayload:Fa,payload:Zt,retrieveRequired:si},Symbol.toStringTag,{value:"Module"})),Wl=s.z.object({key:s.z.string(),username:s.z.string()}),Vl=s.z.object({username:s.z.string(),password:s.z.string()}),Fl=s.z.object({token:s.z.string(),user:Wl}),zs="/auth/login",Jl=3;let Gl=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}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(zs)){this.authenticating==null&&(this.authenticating=new Promise((u,l)=>{this.client.send(zs,this.credentials,Vl,Fl).then(([y,g])=>{if(g!=null)return u(g);this.token=y==null?void 0:y.token,this.user=y==null?void 0:y.user,this.authenticated=!0,u(null)}).catch(l)}));const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[a,i]=await n(t);return $t.matches(i)&&this.retryCount<Jl?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[a,i])};return e}};const Hl=["disconnected","connecting","connected","failed"],gi=s.z.enum(Hl),mi=s.z.object({status:gi,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string()}),Xl=s.z.object({clusterKey:s.z.string()}),Es={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected"},at=class at{constructor(e,t=N.seconds(30),n){c(this,"_state");c(this,"pollFrequency",N.seconds(30));c(this,"client");c(this,"name");c(this,"interval");c(this,"onChangeHandlers",[]);this._state={...Es},this.client=e,this.pollFrequency=t,this.name=n,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,a]=await this.client.send(at.ENDPOINT,{},s.z.object({}),Xl);if(a!=null)throw a;this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey}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(at,"ENDPOINT","/connectivity/check"),c(at,"DEFAULT",Es),c(at,"connectionStateZ",mi);let jt=at;const Ql=Object.freeze(Object.defineProperty({__proto__:null,Checker:jt,state:mi,status:gi},Symbol.toStringTag,{value:"Module"})),eh=s.z.object({keys:Re.array().optional(),names:s.z.string().array().optional(),bounds:F.z}),th=s.z.object({}),rh="/frame/delete";class nh{constructor(e){c(this,"client");this.client=e}async delete(e){await w(this.client,rh,e,eh,th)}}const Ss=r=>{const e=z(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Ns=(r,e)=>{const t=z(r);if(t.length===e.length)return;const n=Ss(r);throw Ss===null?new x("[Frame] - channel keys or names must be provided when constructing a frame."):new x(`[Frame] - ${n}s and arrays must be the same length.
22
- Got ${t.length} ${n}s and ${e.length} arrays.`)};class L{constructor(e=[],t=[]){c(this,"columns",[]);c(this,"series",[]);if(e instanceof L){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((a,i)=>this.push(i,...z(a)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const a=e,i=a.series.map(o=>vi(o));Ns(a.keys,i),a.keys.forEach((o,u)=>this.push(o,i[u]))}else Object.entries(e).forEach(([a,i])=>{const o=parseInt(a);if(isNaN(o))this.push(a,...z(i));else return this.push(o,...z(i))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const a=z(t),i=z(e);Ns(i,a),a.forEach((o,u)=>this.push(i[u],o));return}throw new x(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
19
+ `);o(this,"type",Pe.TYPE)}};o(Pe,"TYPE",we+"unexpected"),o(Pe,"matches",V(Pe.TYPE));let pe=Pe;const je=class je extends te{constructor(){super(...arguments);o(this,"type",je.TYPE)}};o(je,"TYPE",we+"query"),o(je,"matches",V(je.TYPE));let H=je;const De=class De extends H{constructor(){super(...arguments);o(this,"type",De.TYPE)}};o(De,"TYPE",H.TYPE+".not_found"),o(De,"matches",V(De.TYPE));let Ie=De;const Me=class Me extends H{constructor(){super(...arguments);o(this,"type",Me.TYPE)}};o(Me,"TYPE",H.TYPE+".multiple_results"),o(Me,"matches",V(Me.TYPE));let Ae=Me;const Ze=class Ze extends te{constructor(t,n){super(t);o(this,"type",Ze.TYPE);o(this,"path");this.path=n}};o(Ze,"TYPE",we+"route"),o(Ze,"matches",V(Ze.TYPE));let pt=Ze;const Ue=class Ue extends te{constructor(){super(...arguments);o(this,"type",Ue.TYPE)}};o(Ue,"TYPE",we+"control"),o(Ue,"matches",V(Ue.TYPE));let Fe=Ue;const Be=class Be extends Fe{constructor(){super(...arguments);o(this,"type",Be.TYPE)}};o(Be,"TYPE",Fe.TYPE+".unauthorized"),o(Be,"matches",V(Be.TYPE));let Lt=Be;const Le=class Le extends te{constructor(){super(...arguments);o(this,"type",Le.TYPE)}};o(Le,"TYPE",we+"contiguity"),o(Le,"matches",V(Le.TYPE));let Ar=Le;const Yo=r=>{if(!r.type.startsWith(we))return null;if(r.type.startsWith(x.TYPE)){if(r.type===Bt.TYPE){const e=r.data.split(": ");return e.length<2?new x(r.data):new Bt(e[0],e[1])}return new x(r.data)}return r.type.startsWith(Ne.TYPE)?r.type.startsWith(ft.TYPE)?new ft(r.data):new Ne(r.data):r.type.startsWith(pe.TYPE)?new pe(r.data):r.type.startsWith(H.TYPE)?r.type.startsWith(Ie.TYPE)?new Ie(r.data):r.type.startsWith(Ae.TYPE)?new Ae(r.data):new H(r.data):r.type.startsWith(Fe.TYPE)?r.type.startsWith(Lt.TYPE)?new Lt(r.data):new Fe(r.data):r.type.startsWith(pt.TYPE)?new pt(r.data,r.data):new pe(r.data)},Wo=()=>{throw new Error("Not implemented")};ts({encode:Wo,decode:Yo});const Fo=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Se?[t,new Se({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]},Br=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var _o=Object.defineProperty,Go=(r,e,t)=>e in r?_o(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,ut=(r,e,t)=>Go(r,typeof e!="symbol"?e+"":e,t);class zs{constructor(){ut(this,"contentType","application/json"),ut(this,"decoder"),ut(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=Zt(n);return t!=null?t.parse(i):i}encodeString(e){const t=_a(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Br(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}}let Es=class{constructor(){ut(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||!Br(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(`
20
+ `)}decodeString(e,t){const[n,...i]=e.trim().split(`
21
+ `).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(f=>f.trim());a.forEach((f,g)=>{const p=this.parseValue(u[g]);p!=null&&c[f].push(p)})}),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(){}},Ss=class{constructor(){ut(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 Ns=new zs,Ko=new Es,Jo=new Ss,Vo=[Ns],Ge=Object.freeze(Object.defineProperty({__proto__:null,CSVEncoderDecoder:Es,CSV_ECD:Ko,ENCODERS:Vo,JSONEncoderDecoder:zs,JSON_ECD:Ns,TEXT_ECD:Jo,TextEncoderDecoder:Ss},Symbol.toStringTag,{value:"Module"}));var Ho=Object.defineProperty,Xo=(r,e,t)=>e in r?Ho(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,kr=(r,e,t)=>Xo(r,typeof e!="symbol"?e+"":e,t);class Qo{constructor(e,t){kr(this,"handlers"),kr(this,"transform"),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))}}let ec=class{constructor(e){kr(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 Rr=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:ec,Observer:Qo},Symbol.toStringTag,{value:"Module"})),Lr=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),tc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";tc();const rc=["MacOS","Windows","Linux","Docker"];s.z.enum(rc);const In=r=>[...new Set(r)];var nc=Object.defineProperty,sc=(r,e,t)=>e in r?nc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,at=(r,e,t)=>sc(r,typeof e!="symbol"?e+"":e,t);const ic=(...r)=>r.map(Is).join(""),Is=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),ac=r=>r.endsWith("/")?r.slice(0,-1):r,$r=class xr{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){at(this,"protocol"),at(this,"host"),at(this,"port"),at(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Is(i)}replace(e){return new xr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new xr({...this,pathPrefix:ic(this.path,e)})}toString(){return ac(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};at($r,"UNKNOWN",new $r({host:"unknown",port:0}));let oc=$r;var cc=Object.defineProperty,lc=(r,e,t)=>e in r?cc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dt=(r,e,t)=>lc(r,typeof e!="symbol"?e+"":e,t);const Te=class extends Number{};Dt(Te,"Absolute",255),Dt(Te,"Default",1),Dt(Te,"z",s.z.union([s.z.instanceof(Te),s.z.number().int().min(0).max(255).transform(r=>new Te(r)),s.z.instanceof(Number).transform(r=>new Te(r))]));let As=Te;const ks=s.z.object({name:s.z.string(),key:s.z.string()}),uc=r=>s.z.object({subject:ks,resource:r,authority:As.z}),hc=(...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}),_e=Object.freeze(Object.defineProperty({__proto__:null,Authority:As,filterTransfersByChannelKey:hc,stateZ:uc,subjectZ:ks},Symbol.toStringTag,{value:"Module"})),Rs=class ot extends Error{constructor(){super(ot.MESSAGE)}matches(e){return typeof e=="string"?e.includes(ot.MESSAGE):e instanceof ot||e.message.includes(ot.MESSAGE)}};Dt(Rs,"MESSAGE","canceled");let yc=Rs;new yc;s.z.string().regex(/^\d+\.\d+\.\d+$/);const Kt=(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}},Jt=(r,e,t,n)=>{if(n){if(t.length===0)throw new Ie(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new Ae(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Ke=r=>s.z.union([s.z.null().transform(()=>[]),r.array()]),dc=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()}),fc=s.z.object({channels:Ke(Tt)}),ye=r=>Kt(r,{number:"keys",string:"names"}),Yt=class Yt{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=ye(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(Yt.ENDPOINT,e,dc,fc);if(n!=null)throw n;return t.channels}};o(Yt,"ENDPOINT","/channel/retrieve");let gt=Yt;class qr{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}=Kt(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}=ye(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 $s{constructor(e,t){o(this,"mu",new qo);o(this,"requests",new Map);o(this,"wrapped");o(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Do(()=>{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}=ye(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 xs=async(r,e)=>{const{normalized:t}=ye(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 H(`Could not find channels: ${JSON.stringify(i)}`);return n};class Cs{constructor(e,t){o(this,"key");o(this,"name");this.key=t,this.name=e}get ontologyID(){return new G({type:"group",key:this.key})}}const pc=s.z.string().uuid(),Ps=s.z.object({key:pc,name:s.z.string()}),js=s.z.union([s.z.literal("label"),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("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")]),ee=s.z.object({type:js,key:s.z.string()}),Ds=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:e,key:t}}),Ms=s.z.union([Ds,ee]),qe=class qe{constructor(e){o(this,"type");o(this,"key");if(e instanceof qe)this.type=e.type,this.key=e.key;else if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n}else this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}get payload(){return{type:this.type,key:this.key}}};o(qe,"z",s.z.union([Ms,s.z.instanceof(qe)]).transform(e=>new qe(e)));let G=qe;const gc=new G({type:"builtin",key:"root"}),Zs=s.z.object({type:s.z.number()}),Us=s.z.object({type:js,fields:s.z.record(Zs)}),Bs=s.z.object({id:G.z,name:s.z.string(),schema:Us.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),mc=s.z.object({from:G.z,type:s.z.string(),to:G.z}),Cr=r=>{const[e,t,n]=r.split("->");return{from:new G(e),type:t,to:new G(n)}},wc=s.z.object({group:Ps}),bc=s.z.object({parent:ee,key:s.z.string().uuid().optional(),name:s.z.string()}),vc=s.z.object({key:s.z.string(),name:s.z.string()}),Tc=s.z.object({keys:s.z.array(s.z.string())});var Q;let Oc=(Q=class{constructor(e){o(this,"client");this.client=e}async create(e,t,n){const[i,a]=await this.client.send(Q.ENDPOINT,{parent:e,name:t,key:n},bc,wc);if(a!=null)throw a;return i.group}async rename(e,t){const n={key:e,name:t},[,i]=await this.client.send(Q.ENDPOINT_RENAME,n,vc,s.z.object({}));if(i!=null)throw i}async delete(e){const t={keys:e},[,n]=await this.client.send(Q.ENDPOINT_DELETE,t,Tc,s.z.object({}));if(n!=null)throw n}},o(Q,"ENDPOINT","/ontology/create-group"),o(Q,"ENDPOINT_RENAME","/ontology/rename-group"),o(Q,"ENDPOINT_DELETE","/ontology/delete-group"),Q),zc=class{constructor(e){o(this,"creator");this.creator=new Oc(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 Cs(e.name,e.key)}};const yr={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},An=s.z.object({id:ee,children:ee.array()}),Ec=s.z.object({from:ee,to:ee,children:ee.array()});let Sc=class{constructor(e){o(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,yr.ADD_CHILDREN,{id:e,children:t},An,s.z.object({}))}async removeChildren(e,...t){await w(this.client,yr.REMOVE_CHILDREN,{id:e,children:t},An,s.z.object({}))}async moveChildren(e,t,...n){const i={from:e,to:t,children:n};await w(this.client,yr.MOVE_CHILDREN,i,Ec,s.z.object({}))}};const Nc="/ontology/retrieve",Ic=s.z.object({ids:ee.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()}),Ac=s.z.object({resources:Bs.array()}),dr=r=>T(r).map(e=>new G(e).payload);let Ls=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 Sc(e),this.groups=new zc(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:dr(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new H(`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:dr(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:dr(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 Vt.open(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,Nc,e,Ic,Ac);return t}};const kn="sy_ontology_resource_set",Rn="sy_ontology_resource_delete",$n="sy_ontology_relationship_set",xn="sy_ontology_relationship_delete";class Vt{constructor(e,t){o(this,"resourceObs");o(this,"relationshipObs");o(this,"relationships");o(this,"resources");o(this,"streamer");o(this,"client");o(this,"closePromise");this.relationshipObs=new Rr.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Rr.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($n);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:Cr(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(xn);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:Cr(n)}))}async parseResourceSets(e){const t=e.get(kn);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new G(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof H)return[];throw i}}parseResourceDeletes(e){const t=e.get(Rn);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new G(n)}))}static async open(e,t){const n=await e.openStreamer([kn,Rn,$n,xn]);return new Vt(n,t)}}const kc=Object.freeze(Object.defineProperty({__proto__:null,ChangeTracker:Vt,Client:Ls,ID:G,Root:gc,crudeIDZ:Ms,idZ:ee,parseRelationship:Cr,relationshipSchemaZ:mc,resourceSchemaZ:Bs,schemaFieldZ:Zs,schemaZ:Us,stringIDZ:Ds},Symbol.toStringTag,{value:"Module"}));class Yr{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:c=!1,index:l=0,internal:u=!1,frameClient:f,alias:g}){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");this.key=a,this.name=n,this.rate=new Gt(t??0),this.dataType=new z(e),this.leaseholder=i,this.index=l,this.isIndex=c,this.internal=u,this.alias=g,this._frameClient=f??null}get framer(){if(this._frameClient==null)throw new x("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Tt.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 G({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 Rc="/channel/retrieve-group",$c=s.z.object({}),xc=s.z.object({group:Ps});let qs=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(f=>f.name)),u=new Set(l.map(f=>f.name));a=a.filter(f=>!u.has(f.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 Jt("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}=ye(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 qr(new $s(new gt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new Yr({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Rc,{},$c,xc);return new Cs(e.group.name,e.group.key)}};const Cc=s.z.object({channels:Ts.array()}),Pc=s.z.object({channels:Tt.array()}),jc=s.z.object({keys:me.array().optional(),names:s.z.string().array().optional()}),Dc=s.z.object({}),Mc=s.z.object({keys:me.array(),names:s.z.string().array()}),Zc=s.z.object({}),Uc="/channel/create",Bc="/channel/delete",Lc="/channel/rename";let Ys=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,Uc,{channels:e},Cc,Pc);return this.cache.set(t),t}async delete(e){await w(this.client,Bc,e,jc,Dc),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Lc,{keys:e,names:t},Mc,Zc),this.cache.rename(e,t)}};const qc=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:qr,Channel:Yr,Client:qs,ClusterRetriever:gt,DebouncedBatchRetriever:$s,Writer:Ys,analyzeChannelParams:ye,keyZ:me,newPayload:Ts,payload:Tt,retrieveRequired:xs},Symbol.toStringTag,{value:"Module"})),Yc=s.z.object({key:s.z.string(),username:s.z.string()}),Wc=s.z.object({username:s.z.string(),password:s.z.string()}),Fc=s.z.object({token:s.z.string(),user:Yc}),Cn="/auth/login",_c=3;let Gc=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}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(Cn)){this.authenticating==null&&(this.authenticating=new Promise((l,u)=>{this.client.send(Cn,this.credentials,Wc,Fc).then(([f,g])=>{if(g!=null)return l(g);this.token=f==null?void 0:f.token,this.user=f==null?void 0:f.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 ft.matches(a)&&this.retryCount<_c?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const Kc=["disconnected","connecting","connected","failed"],Ws=s.z.enum(Kc),Fs=s.z.object({status:Ws,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string()}),Jc=s.z.object({clusterKey:s.z.string()}),Pn={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected"},Ye=class Ye{constructor(e,t=E.seconds(30),n){o(this,"_state");o(this,"pollFrequency",E.seconds(30));o(this,"client");o(this,"name");o(this,"interval");o(this,"onChangeHandlers",[]);this._state={...Pn},this.client=e,this.pollFrequency=t,this.name=n,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(Ye.ENDPOINT,{},s.z.object({}),Jc);if(i!=null)throw i;this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey}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(Ye,"ENDPOINT","/connectivity/check"),o(Ye,"DEFAULT",Pn),o(Ye,"connectionStateZ",Fs);let mt=Ye;const Vc=Object.freeze(Object.defineProperty({__proto__:null,Checker:mt,state:Fs,status:Ws},Symbol.toStringTag,{value:"Module"})),Hc=s.z.object({keys:me.array().optional(),names:s.z.string().array().optional(),bounds:_.z}),Xc=s.z.object({}),Qc="/frame/delete";class el{constructor(e){o(this,"client");this.client=e}async delete(e){await w(this.client,Qc,e,Hc,Xc)}}const jn=r=>{const e=T(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},Dn=(r,e)=>{const t=T(r);if(t.length===e.length)return;const n=jn(r);throw jn===null?new x("[Frame] - channel keys or names must be provided when constructing a frame."):new x(`[Frame] - ${n}s and arrays must be the same length.
22
+ Got ${t.length} ${n}s and ${e.length} arrays.`)};class Z{constructor(e=[],t=[]){o(this,"columns",[]);o(this,"series",[]);if(e instanceof Z){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,a=i.series.map(c=>Gs(c));Dn(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);Dn(a,i),i.forEach((c,l)=>this.push(a[l],c));return}throw new x(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
23
23
  payload, a list of lazy arrays, a lazy array, a map, or a record keyed by channel
24
- 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 $e("colType is not key");return this.columns??[]}get uniqueKeys(){return ms(this.keys)}get names(){if(this.colType==="key")throw new $e("colType is not name");return this.columns??[]}get uniqueNames(){return ms(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>bi(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 F.ZERO;const n=E.min(...this.series.map(i=>i.timeRange.start)),a=E.max(...this.series.map(i=>i.timeRange.end));return new F(n,a)}const t=this.get(e);return t==null?F.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 Wa(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof L){if(this.colType!==null&&e.colType!==this.colType)throw new x("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 x("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new x("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new L([...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 L;return this.forEach((n,a,i)=>t.push(...e(n,a,i))),t}forEach(e){this.columns.forEach((t,n)=>{const a=this.series[n];e(t,a,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(a=>{n[a]=this.get(a).at(e,t)}),n}filter(e){const t=new L;return this.columns.forEach((n,a)=>{const i=this.series[a];e(n,i,a)&&t.push(n,i)}),t}get byteLength(){return new kt(this.series.reduce((e,t)=>e.add(t.byteLength),kt.ZERO))}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const wi=s.z.object({timeRange:F.z.optional(),alignment:s.z.bigint().or(s.z.string().transform(r=>BigInt(r))).optional(),dataType:S.z,data:s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer)}),Cr=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(()=>[]),wi.array().optional().default([])])}),vi=r=>{const{dataType:e,data:t,timeRange:n,alignment:a}=r;return new Ze({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:a})},bi=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class Rr{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 Rr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=Ie(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const a=await this.retriever.retrieve(n),i=new Map;this.adapter=i,n.forEach(o=>{const u=a.find(l=>l.name===o);if(u==null)throw new Error(`Channel ${o} not found`);i.set(u.key,u.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,a)=>{if(typeof n=="number"){const i=t.get(n);if(i==null)throw new Error(`Channel ${n} not found`);return[i,a]}return[n,a]})}}class Kn{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 Kn(e);return await n.update(t),n}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 adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new x(`
24
+ 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 pe("colType is not key");return this.columns??[]}get uniqueKeys(){return In(this.keys)}get names(){if(this.colType==="key")throw new pe("colType is not name");return this.columns??[]}get uniqueNames(){return In(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Ks(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 _.ZERO;const n=O.min(...this.series.map(a=>a.timeRange.start)),i=O.max(...this.series.map(a=>a.timeRange.end));return new _(n,i)}const t=this.get(e);return t==null?_.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 vs(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof Z){if(this.colType!==null&&e.colType!==this.colType)throw new x("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 x("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new x("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new Z([...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 Z;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 Z;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new dt(this.series.reduce((e,t)=>e.add(t.byteLength),dt.ZERO))}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const _s=s.z.object({timeRange:_.z.optional(),alignment:s.z.bigint().or(s.z.string().transform(r=>BigInt(r))).optional(),dataType:z.z,data:s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer)}),Ht=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(()=>[]),_s.array().optional().default([])])}),Gs=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new Oe({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},Ks=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});class Xt{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 Xt(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=ye(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 Wr{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 Wr(e);return await n.update(t),n}async update(e){const t=await xs(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 adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new x(`
25
25
  Received a single channel name or key but no series.
26
- `);if(Array.isArray(t)){if(t.some(l=>l instanceof Ze||Array.isArray(l)))throw new x(`
26
+ `);if(Array.isArray(t)){if(t.some(u=>u instanceof Oe||Array.isArray(u)))throw new x(`
27
27
  Received a single channel name or key but multiple series.
28
- `);t=t}const o=await this.fetchChannel(e),u=new Ze({data:t,dataType:o.dataType});return new L(o.key,u)}if(Array.isArray(e)){if(t==null)throw new x(`
28
+ `);t=t}const c=await this.fetchChannel(e),l=new Oe({data:t,dataType:c.dataType});return new Z(c.key,l)}if(Array.isArray(e)){if(t==null)throw new x(`
29
29
  Received an array of channel names or keys but no series.
30
30
  `);if(!Array.isArray(t))throw new x(`
31
31
  Received an array of channel names or keys but no array of series.
32
- `);const o=[],u=[];for(let l=0;l<e.length;l++){const y=await this.fetchChannel(e[l]);if(l>=t.length)throw new x(`
32
+ `);const c=[],l=[];for(let u=0;u<e.length;u++){const f=await this.fetchChannel(e[u]);if(u>=t.length)throw new x(`
33
33
  Received an array of channel names or keys but not enough series.
34
- `);const g=new Ze({data:t[l],dataType:y.dataType});o.push(y.key),u.push(g)}return new L(o,u)}if(e instanceof L||e instanceof Map){const o=new L(e);if(this.adapter==null)return o;let u=[];return u=o.columns.map(l=>{var g;const y=typeof l=="string"?(g=this.adapter)==null?void 0:g.get(l):l;if(y==null)throw new x(`
35
- Channel ${l} was not provided in the list of channels when opening the writer
36
- `);return y}),new L(u,o.series)}const n=[],a=[],i=Object.entries(e);for(let o=0;o<i.length;o++){const[u,l]=i[o],y=await this.fetchChannel(u),g=new Ze({data:l,dataType:y.dataType});n.push(y.key),a.push(g)}return new L(n,a)}}class Wn{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.
37
- Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Ce.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const dn=new N(-1);var Vn=(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))(Vn||{}),Oi=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Oi||{});const sh=s.z.object({command:s.z.nativeEnum(Vn),span:N.z.optional(),bounds:F.z.optional(),stamp:E.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),ah=s.z.object({variant:s.z.nativeEnum(Oi),ack:s.z.boolean(),command:s.z.nativeEnum(Vn),error:Dt.optional().nullable(),frame:Cr.optional()}),It=class It{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"value");this.stream=new Wn("Iterator",e),this.value=new L,this.adapter=t}static async _open(e,t,n,a,i={}){const o=await Rr.open(n,t),u=await a.stream(It.ENDPOINT,sh,ah),l=new It(u,o);return await l.execute({command:0,keys:o.keys,bounds:new F(e),chunkSize:i.chunkSize??1e5}),l}async next(e=dn){return await this.execute({command:1,span:new N(e)})}async prev(e=dn){return await this.execute({command:2,span:new N(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 E(e)})}async seekGE(e){return await this.execute({command:6,stamp:new E(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new ih(this)}async execute(e){for(this.stream.send(e),this.value=new L;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new L(t.frame)))}}};c(It,"ENDPOINT","/frame/iterate");let yr=It;class ih{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 oh=s.z.object({start:E.z.optional(),keys:s.z.number().array()}),ch=s.z.object({frame:Cr,error:Dt.optional().nullable()}),uh="/frame/stream";class jr{constructor(e,t){c(this,"stream");c(this,"adapter");this.stream=new Wn("Streamer",e),this.adapter=t}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,from:a}){const i=await Rr.open(e,n),o=await t.stream(uh,oh,ch),u=new jr(o,i);return o.send({start:new E(a),keys:i.keys}),u}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ce.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new L((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Mt extends un.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 Fn=(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))(Fn||{}),xt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.PersistOnly=2]="PersistOnly",r[r.StreamOnly=3]="StreamOnly",r))(xt||{});const lh=new N(-1),hh=s.z.object({start:E.z.optional(),controlSubject:lt.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:lt.Authority.z.array().optional(),mode:s.z.nativeEnum(xt).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:N.z.optional()}),fh=s.z.object({command:s.z.nativeEnum(Fn),config:hh.optional(),frame:Cr.optional()}),dh=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Fn),error:Dt.optional().nullable()});var Me;let Ti=(Me=class{constructor(e,t){c(this,"stream");c(this,"adapter");this.stream=new Wn("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:a=E.now(),authorities:i=lt.Authority.Absolute,controlSubject:o,mode:u=1,errOnUnauthorized:l=!1,enableAutoCommit:y=!1,autoIndexPersistInterval:g=N.SECOND}){const p=await Kn.open(e,n),D=await t.stream(Me.ENDPOINT,fh,dh),P=new Me(D,p);return await P.execute({command:0,config:{start:new E(a),keys:p.keys,controlSubject:o,authorities:z(i),mode:u,errOnUnauthorized:l,enableAutoCommit:y,autoIndexPersistInterval:g}}),P}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){return(await this.execute({command:4,config:{keys:Object.keys(e).map(n=>Number(n)),authorities:Object.values(e)}})).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?In(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(Me,"ENDPOINT","/frame/write"),Me),zi=class{constructor(e,t,n){c(this,"streamClient");c(this,"retriever");c(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new nh(t)}async openIterator(e,t,n){return await yr._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await Ti._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await jr._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const i=t,o=await this.openWriter({start:e,channels:Object.keys(i),mode:xt.PersistOnly});try{await o.write(i),await o.commit()}finally{await o.close()}return}const a=await this.openWriter({start:e,channels:t,mode:xt.PersistOnly,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:N.MAX});try{await a.write(t,n)}finally{await a.close()}}async read(e,t){const{single:n}=Ie(t),a=await this.readFrame(e,t);return n?a.get(t):a}async readFrame(e,t){const n=await this.openIterator(e,t),a=new L;try{for await(const i of n)a.push(i)}finally{await n.close()}return a}async delete(e,t){const{normalized:n,variant:a}=Ie(e);return a==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const yh=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:lh,AUTO_SPAN:dn,Client:zi,Frame:L,Iterator:yr,ObservableStreamer:Mt,Streamer:jr,Writer:Ti,WriterMode:xt,frameZ:Cr,series:wi,seriesFromPayload:vi,seriesToPayload:bi},Symbol.toStringTag,{value:"Module"})),ph=lt.Authority,gh=lt.stateZ(s.z.number()),mh=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 Ei extends Mt{constructor(t){super(t,n=>{const a=this.ecd.decode(n.series[0].buffer);return this.merge(a),[a.transfers,!0]});c(this,"states");c(this,"ecd");this.states=new Map,this.ecd=new ht.JSONEncoderDecoder}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 wh="sy_node_1_control";let Si=class{constructor(e){c(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(wh);return new Ei(e)}};const vh=Object.freeze(Object.defineProperty({__proto__:null,Authority:ph,Client:Si,StateTracker:Ei,stateZ:gh,transferString:mh},Symbol.toStringTag,{value:"Module"}));let Ni=class{constructor(e,t,n){c(this,"tasks");c(this,"racks");c(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const bh=Object.freeze(Object.defineProperty({__proto__:null,Client:Ni},Symbol.toStringTag,{value:"Module"})),dt=s.z.number(),xr=s.z.object({key:dt,name:s.z.string()}),Ai=xr.partial({key:!0}),Fr="/hardware/rack/retrieve",Oh="/hardware/rack/create",Th="/hardware/rack/delete",Jr=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()}),Gr=s.z.object({racks:ft(xr)}),zh=s.z.object({racks:Ai.array()}),Eh=s.z.object({racks:xr.array()}),Sh=s.z.object({keys:dt.array()}),Nh=s.z.object({});let Ii=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,Th,{keys:z(e)},Sh,Nh)}async create(e){const t=!Array.isArray(e),n=await w(this.client,Oh,{racks:z(e)},zh,Eh),a=this.sugar(n.racks);return t?a[0]:a}async search(e){const t=await w(this.client,Fr,{search:e},Jr,Gr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,Fr,{offset:e,limit:t},Jr,Gr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:a}=Ir(e,{string:"names",number:"keys"}),i=await w(this.client,Fr,{[t]:n},Jr,Gr),o=this.sugar(i.racks);return kr("Rack",e,o,a),a?o[0]:o}sugar(e){return e.map(({key:t,name:n})=>new ki(t,n,this.tasks))}};class ki{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 yt=async(r,e,t,n)=>{const a=await r.openStreamer([e,t]),i=o=>{const u=[];return t!=null&&u.push(...o.get(t).series.flatMap(l=>n("delete",l))),e!=null&&u.push(...o.get(e).series.flatMap(l=>n("set",l))),[u,u.length>0]};return new Mt(a,i)},Ah=Object.freeze(Object.defineProperty({__proto__:null,openObservable:yt},Symbol.toStringTag,{value:"Module"})),Ih="sy_device_set",kh="sy_device_delete",Hr="/hardware/device/retrieve",$h="/hardware/device/create",Ch="/hardware/device/delete",Pr=s.z.string(),Ut=s.z.object({key:Pr,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===""?{}:ht.JSON_ECD.decodeString(r)))}),$i=Ut.extend({properties:s.z.unknown().transform(r=>ht.JSON_ECD.encodeString(r))}),Rh=s.z.object({devices:$i.array()}),jh=s.z.object({devices:Ut.array()}),xh=s.z.object({keys:Pr.array()}),Ph=s.z.object({}),Xr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Pr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),Qr=s.z.object({devices:ft(Ut)});let Ci=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),a=await w(this.client,Hr,{keys:z(e),...t},Xr,Qr);return kr("Device",e,a.devices,n),n?a.devices[0]:a.devices}async search(e,t){return(await w(this.client,Hr,{search:e,...t},Xr,Qr)).devices}async page(e,t,n){return(await w(this.client,Hr,{offset:e,limit:t,...n},Xr,Qr)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,$h,{devices:z(e)},Rh,jh);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,Ch,{keys:z(e)},xh,Ph)}async openDeviceTracker(){return await yt(this.frameClient,Ih,kh,Dh)}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 Dh=(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})),Zh=Object.freeze(Object.defineProperty({__proto__:null,Client:Ci,deviceKeyZ:Pr,deviceZ:Ut,newDeviceZ:$i},Symbol.toStringTag,{value:"Module"})),Mh=Object.freeze(Object.defineProperty({__proto__:null,Client:Ii,Rack:ki,newRackZ:Ai,rackKeyZ:dt,rackZ:xr},Symbol.toStringTag,{value:"Module"}));let Uh="_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",Lh=(r=21)=>{let e="",t=r;for(;t--;)e+=Uh[Math.random()*64|0];return e};const At="sy_task_state",As="sy_task_cmd",pt=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:pt,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())}),Dr=s.z.object({key:pt,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===""?{}:ht.JSON_ECD.decodeString(r))),state:Pt.optional().nullable()}),Ri=Dr.omit({key:!0}).extend({key:pt.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>ht.JSON_ECD.encodeString(r))}),Bh=s.z.object({task:pt,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)))});class ji{constructor(e,t,n,a,i,o=!1,u){c(this,"key");c(this,"name");c(this,"internal");c(this,"type");c(this,"config");c(this,"state");c(this,"frameClient");this.key=e,this.name=t,this.type=n,this.config=a,this.internal=o,u!==null&&(this.state=u),this.frameClient=i}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}async executeCommand(e,t){const n=await this.frameClient.openWriter(As),a=Lh();return await n.write(As,[{task:this.key,type:e,key:a,args:t}]),await n.close(),a}async executeCommandSync(e,t,n){const a=await this.frameClient.openStreamer(At),i=await this.executeCommand(e,t);let o;const u=new Promise(l=>setTimeout(()=>l(!1),new N(n).milliseconds));for(;;){const l=await Promise.any([a.read(),u]);if(l===!1)throw new Error("Command timed out");const y=Pt.safeParse(l.at(-1).sy_task_state);if(y.success){if(o=y.data,o.key===i)break}else console.error(y.error)}return a.close(),o}async openStateObserver(){return new Mt(await this.frameClient.openStreamer(At),e=>{const t=e.get(At);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));if(!n.success)return[null,!1];const a=n.data;return a.task!==this.key?[null,!1]:[a,!0]})}}const _h=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()}),qh=s.z.object({tasks:ft(Dr)}),Yh="/hardware/task/retrieve",Kh="/hardware/task/create",Wh="/hardware/task/delete",Vh=s.z.object({tasks:Ri.array()}),Fh=s.z.object({tasks:Dr.array()}),Jh=s.z.object({keys:pt.array()}),Gh=s.z.object({});let xi=class{constructor(e,t){c(this,"type","task");c(this,"client");c(this,"frameClient");this.client=e,this.frameClient=t}async create(e){const t=!Array.isArray(e),n=await w(this.client,Kh,{tasks:z(e)},Vh,Fh),a=this.sugar(n.tasks);return t?a[0]:a}async delete(e){await w(this.client,Wh,{keys:z(e)},Jh,Gh)}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:a,variant:i}=Ir(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};i==="rack"?o.rack=e:o.keys=a;const u=await this.execRetrieve(o),l=this.sugar(u);return n&&i!=="rack"?l[0]:l}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return kr("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,Yh,e,_h,qh)).tasks}sugar(e){return e.map(({key:t,name:n,type:a,config:i,state:o,internal:u})=>new ji(t,n,a,i,this.frameClient,u,o))}async openTracker(){return await yt(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 Mt(await this.frameClient.openStreamer(At),e=>{const t=e.get(At);if(t.length===0)return[null,!1];const n=Pt.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const Hh=Object.freeze(Object.defineProperty({__proto__:null,Client:xi,Task:ji,commandZ:Bh,newTaskZ:Ri,stateZ:Pt,taskKeyZ:pt,taskZ:Dr},Symbol.toStringTag,{value:"Module"})),gt=s.z.string().uuid(),Lt=s.z.object({key:gt,name:s.z.string().min(1),color:s.z.string()}),Xh=r=>new J({type:"label",key:r}),Qh=s.z.object({keys:gt.array().optional(),for:ne.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),ef=s.z.object({labels:Lt.array().optional().default([])});var it;let Pi=(it=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=z(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(it.ENDPOINT,e,Qh,ef);if(n!=null)throw n;return t.labels}},c(it,"ENDPOINT","/label/retrieve"),it);const Di=Lt.extend({key:gt.optional()}),tf=s.z.object({labels:Di.array()}),rf=s.z.object({labels:Lt.array()}),nf=s.z.object({keys:gt.array()}),Zi=s.z.object({id:ne,labels:gt.array()}),sf=Zi,en=s.z.object({}),af="/label/create",of="/label/delete",cf="/label/set",uf="/label/remove";let Mi=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,af,{labels:z(e)},tf,rf)).labels}async delete(e){await w(this.client,of,{keys:z(e)},nf,en)}async set(e,t){await w(this.client,cf,{id:e,labels:t},Zi,en)}async remove(e,t){await w(this.client,uf,{id:e,labels:t},sf,en)}};const lf="sy_label_set",hf="sy_label_delete";let Ui=class{constructor(e,t){c(this,"type","label");c(this,"retriever");c(this,"writer");c(this,"frameClient");this.writer=new Mi(e),this.retriever=new Pi(e),this.frameClient=t}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(e)}async label(e,t){await this.writer.set(e,t)}async removeLabels(e,t){await this.writer.remove(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 yt(this.frameClient,lf,hf,ff)}};const ff=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Lt).map(t=>({variant:r,key:t.key,value:t})),df=Object.freeze(Object.defineProperty({__proto__:null,Client:Ui,Retriever:Pi,Writer:Mi,keyZ:gt,labelZ:Lt,newLabelPayloadZ:Di,ontologyID:Xh},Symbol.toStringTag,{value:"Module"})),G=s.z.string().uuid(),mt=s.z.object({key:G,name:s.z.string().min(1),timeRange:F.z,color:s.z.string().optional()}),Li=mt.extend({key:s.z.string().uuid().optional()}),Bi=r=>{const e=z(r);if(e.length===0)throw new Error("Range params must not be empty");const t=G.safeParse(e[0]).success;return{single:!Array.isArray(r),variant:t?"keys":"names",normalized:e,actual:r}},yf=s.z.object({}),pf=s.z.object({range:mt}),gf=s.z.object({range:G}),mf=s.z.object({range:G}),wf=s.z.object({}),vf="/range/set-active",bf="/range/retrieve-active",Of="/range/clear-active";class Tf{constructor(e){c(this,"client");this.client=e}async setActive(e){await w(this.client,vf,{range:e},gf,yf)}async retrieveActive(){const[e,t]=await this.client.send(bf,{},s.z.object({}),pf);if(Q.matches(t))return null;if(t!=null)throw t;return e.range}async clearActive(e){await w(this.client,Of,{range:e},mf,wf)}}const zf="sy_range_alias_set",Ef="sy_range_alias_delete",Sf=s.z.object({range:G,aliases:s.z.string().array()}),Nf=s.z.object({aliases:s.z.record(s.z.string(),Re)}),Af=s.z.object({range:G,aliases:s.z.record(Re.or(s.z.string()),s.z.string())}),If=s.z.unknown(),kf=s.z.object({range:G,channels:Re.array()}),$f=s.z.unknown(),Cf=s.z.object({range:G}),Rf=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),ue=class ue{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",a={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const u=this.cache.get(o);u!=null?a[o]=u:t.push(o)});if(t.length===0)return a;const i=await w(this.client,ue.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Sf,Nf);return Object.entries(i.aliases).forEach(([o,u])=>this.cache.set(o,u)),n?i.aliases[t[0]]:{...a,...i.aliases}}async set(e){await w(this.client,ue.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Af,If)}async list(){return(await w(this.client,ue.LIST_ENDPOINT,{range:this.rangeKey},Cf,Rf)).aliases}async delete(e){await w(this.client,ue.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},kf,$f)}async openChangeTracker(){return await yt(this.frameClient,zf,Ef,Pf(this.rangeKey))}};c(ue,"SET_ENDPOINT","/range/alias/set"),c(ue,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(ue,"LIST_ENDPOINT","/range/alias/list"),c(ue,"DELETE_ENDPOINT","/range/alias/delete");let yn=ue;const jf=s.z.object({range:G,channel:Re,alias:s.z.string()}),xf="---",Pf=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(xf)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(jf).map(n=>({variant:e,key:n.alias,value:n})),Df=s.z.object({range:G,keys:s.z.string().array()}),Zf=s.z.object({pairs:s.z.record(s.z.string(),s.z.string())}),Mf=s.z.object({range:G,pairs:s.z.record(s.z.string(),s.z.string())}),Uf=s.z.object({range:G,keys:s.z.string().array()}),ke=class ke{constructor(e,t){c(this,"rangeKey");c(this,"client");this.rangeKey=e,this.client=t}async get(e){const[t,n]=await this.client.send(ke.GET_ENDPOINT,{range:this.rangeKey,keys:z(e)},Df,Zf);if(n!=null)throw n;return Array.isArray(e)?t.pairs:t.pairs[e]}async list(){return this.get([])}async set(e,t=""){await w(this.client,ke.SET_ENDPOINT,{range:this.rangeKey,pairs:Bn(e)?e:{[e]:t}},Mf,s.z.unknown())}async delete(e){await w(this.client,ke.DELETE_ENDPOINT,{range:this.rangeKey,keys:z(e)},Uf,s.z.unknown())}};c(ke,"GET_ENDPOINT","/range/kv/get"),c(ke,"SET_ENDPOINT","/range/kv/set"),c(ke,"DELETE_ENDPOINT","/range/kv/delete");let pn=ke;const tn=r=>new J({type:"range",key:r});class _i{constructor(e,t=F.ZERO,n,a,i,o,u,l,y){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");this.key=n,this.name=e,this.timeRange=t,this.frameClient=i,this.color=a,this.kv=o,this.aliaser=u,this.channels=l,this.labelClient=y}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new Q(`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 openAliasTracker(){return await this.aliaser.openChangeTracker()}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)}}const Lf=s.z.object({keys:G.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:F.z.optional()}),Bf="/range/retrieve",_f=s.z.object({ranges:ft(mt)});let qi=class{constructor(e,t,n,a,i){c(this,"type","range");c(this,"frameClient");c(this,"writer");c(this,"unaryClient");c(this,"channels");c(this,"active");c(this,"labelClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=a,this.active=new Tf(n),this.labelClient=i}async create(e){const t=!Array.isArray(e),n=this.sugar(await this.writer.create(z(e)));return t?n[0]:n}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(z(e))}async search(e){return this.sugar(await this.execRetrieve({term:e}))}async page(){return[]}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new F(e)});const{single:t,actual:n,variant:a,normalized:i}=Bi(e),o=await this.execRetrieve({[a]:i});if(!t)return o;if(o.length===0)throw new Be(`range matching ${n} not found`);if(o.length>1)throw new _e(`multiple ranges matching ${n} found`);return o[0]}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,Bf,e,Lf,_f);return this.sugar(t)}async setActive(e){await this.active.setActive(e)}async retrieveActive(){const e=await this.active.retrieveActive();return e==null?null:this.sugar([e])[0]}async clearActive(e){await this.active.clearActive(e)}sugar(e){return e.map(t=>new _i(t.name,t.timeRange,t.key,t.color,this.frameClient,new pn(t.key,this.unaryClient),new yn(t.key,this.frameClient,this.unaryClient),this.channels,this.labelClient))}async openTracker(){return await yt(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(a=>({variant:e,key:a,value:void 0})):this.sugar(t.parseJSON(mt)).map(a=>({variant:e,key:a.key,value:a})))}};const qf=s.z.object({ranges:mt.array()}),Yf=s.z.object({ranges:Li.array()}),Kf=s.z.object({keys:G.array()}),Wf=s.z.object({}),Vf=s.z.object({key:G,name:s.z.string()}),Ff=s.z.object({}),Jf="/range/create",Gf="/range/delete",Hf="/range/rename";let Yi=class{constructor(e){c(this,"client");this.client=e}async rename(e,t){await w(this.client,Hf,{key:e,name:t},Vf,Ff)}async create(e){return(await w(this.client,Jf,{ranges:e},Yf,qf)).ranges}async delete(e){await w(this.client,Gf,{keys:e},Kf,Wf)}};const Xf=Object.freeze(Object.defineProperty({__proto__:null,Client:qi,Range:_i,Writer:Yi,analyzeParams:Bi,keyZ:G,newPayloadZ:Li,payloadZ:mt},Symbol.toStringTag,{value:"Module"})),Qf="/api/v1/";class ed{constructor(e,t=!1){c(this,"url");c(this,"unary");c(this,"stream");c(this,"secure");this.secure=t,this.url=e.child(Qf);const n=new ht.JSONEncoderDecoder;this.unary=new zc(this.url,n,this.secure),this.stream=new Rc(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Jn=s.z.string().uuid(),Gn=s.z.object({key:s.z.string(),name:s.z.string(),data:_n.or(s.z.string().transform(r=>JSON.parse(r)))}),td=s.z.object({keys:s.z.string().array()}),rd=s.z.object({linePlots:Gn.array()});let nd=class{constructor(e){c(this,"ENDPOINT","/workspace/lineplot/retrieve");c(this,"client");this.client=e}async retrieve(e){const t=z(e);return(await w(this.client,this.ENDPOINT,{keys:t},td,rd)).linePlots}};const xe=s.z.string().uuid(),Ki=r=>JSON.parse(r),Hn=s.z.object({name:s.z.string(),key:xe,layout:_n.or(s.z.string().transform(r=>Ki(r)))}),Xn=Hn.omit({layout:!0}).extend({layout:s.z.string().transform(r=>Ki(r))}),sd=Gn.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),ad=s.z.object({workspace:xe,linePlots:sd.array()}),id=s.z.object({linePlots:Gn.array()}),od=s.z.object({keys:Jn.array()}),cd=s.z.object({}),ud=s.z.object({key:Jn,name:s.z.string()}),ld=s.z.object({}),hd=s.z.object({key:Jn,data:s.z.string()}),fd=s.z.object({}),dd="/workspace/lineplot/create",yd="/workspace/lineplot/delete",pd="/workspace/lineplot/rename",gd="/workspace/lineplot/set-data";let md=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,dd,{workspace:e,linePlots:[n]},ad,id)).linePlots[0]}async delete(e){const t=z(e);await w(this.client,yd,{keys:t},od,cd)}async rename(e,t){await w(this.client,pd,{key:e,name:t},ud,ld)}async setData(e,t){await w(this.client,gd,{key:e,data:JSON.stringify(t)},hd,fd)}},wd=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new md(e),this.retriever=new nd(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 vd=s.z.object({keys:xe.array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),bd=s.z.object({workspaces:ft(Xn)});var ot;let Od=(ot=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=z(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,ot.ENDPOINT,e,vd,bd)).workspaces}},c(ot,"ENDPOINT","/workspace/retrieve"),ot);const Zr=s.z.string().uuid(),Td=s.z.object({key:s.z.string(),name:s.z.string(),data:_n.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),Qn=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),zd=s.z.object({keys:s.z.string().array()}),Ed=s.z.object({schematics:Qn.array()});class Sd{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:z(e)},zd,Ed)).schematics}}const Nd=Td.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Ad=s.z.object({workspace:xe,schematics:Nd.array()}),Id=s.z.object({schematics:Qn.array()}),kd=s.z.object({keys:Zr.array()}),$d=s.z.object({}),Cd=s.z.object({key:Zr,name:s.z.string()}),Is=s.z.object({}),Rd=s.z.object({key:Zr,data:s.z.string()});s.z.object({});const jd=s.z.object({key:Zr,name:s.z.string(),snapshot:s.z.boolean()}),xd=s.z.object({schematic:Qn}),Pd="/workspace/schematic/create",Dd="/workspace/schematic/delete",Zd="/workspace/schematic/rename",Md="/workspace/schematic/set-data",Ud="/workspace/schematic/copy";let Ld=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,Pd,{workspace:e,schematics:[n]},Ad,Id)).schematics[0]}async copy(e,t,n){return(await w(this.client,Ud,{key:e,name:t,snapshot:n},jd,xd)).schematic}async delete(e){const t=z(e);await w(this.client,Dd,{keys:t},kd,$d)}async rename(e,t){await w(this.client,Zd,{key:e,name:t},Cd,Is)}async setData(e,t){await w(this.client,Md,{key:e,data:JSON.stringify(t)},Rd,Is)}},Bd=class{constructor(e){c(this,"writer");c(this,"retriever");this.writer=new Ld(e),this.retriever=new Sd(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 _d=Hn.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),qd=s.z.object({workspaces:_d.array()}),Yd=s.z.object({workspaces:Xn.array()}),Kd=s.z.object({keys:xe.array()}),Wd=s.z.object({}),Vd=s.z.object({key:xe,name:s.z.string()}),Fd=s.z.object({}),Jd=s.z.object({key:xe,layout:s.z.string()}),Gd=s.z.object({}),Hd="/workspace/create",Xd="/workspace/delete",Qd="/workspace/rename",ey="/workspace/set-layout";class ty{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Hd,{workspaces:z(e)},qd,Yd)).workspaces}async delete(e){await w(this.client,Xd,{keys:z(e)},Kd,Wd)}async rename(e,t){await w(this.client,Qd,{key:e,name:t},Vd,Fd)}async setLayout(e,t){await w(this.client,ey,{key:e,layout:JSON.stringify(t)},Jd,Gd)}}class Wi{constructor(e){c(this,"type","workspace");c(this,"schematic");c(this,"linePlot");c(this,"retriever");c(this,"writer");this.schematic=new Bd(e),this.linePlot=new wd(e),this.retriever=new Od(e),this.writer=new ty(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 ry=Object.freeze(Object.defineProperty({__proto__:null,Client:Wi,keyZ:xe,workspaceRemoteZ:Xn,workspaceZ:Hn},Symbol.toStringTag,{value:"Module"})),Vi=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().optional(),password:s.z.string().optional(),connectivityPollFrequency:N.z.default(N.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class Fi extends zi{constructor(t){const n=Vi.parse(t),{host:a,port:i,username:o,password:u,connectivityPollFrequency:l,secure:y}=n,g=new ed(new hl({host:a,port:Number(i)}),y);g.use(Ju);let p;if(o!=null&&u!=null){const Gi=new Gl(g.unary,{username:o,password:u});g.use(Gi.middleware())}const D=new qn(new Rt(g.unary)),P=new pi(g.unary,D);super(g.stream,g.unary,D);c(this,"createdAt");c(this,"props");c(this,"ranges");c(this,"channels");c(this,"auth");c(this,"connectivity");c(this,"ontology");c(this,"workspaces");c(this,"labels");c(this,"hardware");c(this,"control");c(this,"transport");this.createdAt=E.now(),this.props=n,this.auth=p,this.transport=g,this.channels=new yi(this,D,g.unary,P),this.connectivity=new jt(g.unary,l,n.name),this.control=new Si(this),this.ontology=new di(g.unary,this);const ee=new Yi(this.transport.unary);this.labels=new Ui(this.transport.unary,this),this.ranges=new qi(this,ee,this.transport.unary,D,this.labels),this.workspaces=new Wi(this.transport.unary);const Z=new Ci(this.transport.unary,this),es=new xi(this.transport.unary,this),Ji=new Ii(this.transport.unary,this,es);this.hardware=new Ni(es,Ji,Z)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(Fi,"connectivity",jt);const ny=lt.Authority;exports.AuthError=Le;exports.Authority=ny;exports.Channel=Yn;exports.ContiguityError=on;exports.DataType=S;exports.Density=V;exports.Frame=L;exports.MultiSeries=Wa;exports.MultipleFoundError=_e;exports.NotFoundError=Be;exports.QueryError=Q;exports.Rate=Ar;exports.RouteError=Ct;exports.Series=Ze;exports.Synnax=Fi;exports.TimeRange=F;exports.TimeSpan=N;exports.TimeStamp=E;exports.UnexpectedError=$e;exports.ValidationError=x;exports.channel=Kl;exports.connection=Ql;exports.control=vh;exports.device=Zh;exports.framer=yh;exports.hardware=bh;exports.label=df;exports.ontology=Rl;exports.rack=Mh;exports.ranger=Xf;exports.signals=Ah;exports.synnaxPropsZ=Vi;exports.task=Hh;exports.workspace=ry;
34
+ `);const g=new Oe({data:t[u],dataType:f.dataType});c.push(f.key),l.push(g)}return new Z(c,l)}if(e instanceof Z||e instanceof Map){const c=new Z(e);if(this.adapter==null)return c;let l=[];return l=c.columns.map(u=>{var g;const f=typeof u=="string"?(g=this.adapter)==null?void 0:g.get(u):u;if(f==null)throw new x(`
35
+ Channel ${u} was not provided in the list of channels when opening the writer
36
+ `);return f}),new Z(l,c.series)}const n=[],i=[],a=Object.entries(e);for(let c=0;c<a.length;c++){const[l,u]=a[c],f=await this.fetchChannel(l),g=new Oe({data:u,dataType:f.dataType});n.push(f.key),i.push(g)}return new Z(n,i)}}class Fr{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.
37
+ Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(ge.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Pr=new E(-1);var _r=(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))(_r||{}),Js=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(Js||{});const tl=s.z.object({command:s.z.nativeEnum(_r),span:E.z.optional(),bounds:_.z.optional(),stamp:O.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),rl=s.z.object({variant:s.z.nativeEnum(Js),ack:s.z.boolean(),command:s.z.nativeEnum(_r),error:vt.optional().nullable(),frame:Ht.optional()}),yt=class yt{constructor(e,t){o(this,"stream");o(this,"adapter");o(this,"value");this.stream=new Fr("Iterator",e),this.value=new Z,this.adapter=t}static async _open(e,t,n,i,a={}){const c=await Xt.open(n,t),l=await i.stream(yt.ENDPOINT,tl,rl),u=new yt(l,c);return await u.execute({command:0,keys:c.keys,bounds:new _(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Pr){return await this.execute({command:1,span:new E(e)})}async prev(e=Pr){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 O(e)})}async seekGE(e){return await this.execute({command:6,stamp:new O(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new nl(this)}async execute(e){for(this.stream.send(e),this.value=new Z;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new Z(t.frame)))}}};o(yt,"ENDPOINT","/frame/iterate");let qt=yt;class nl{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 sl=s.z.object({start:O.z.optional(),keys:s.z.number().array()}),il=s.z.object({frame:Ht,error:vt.optional().nullable()}),al="/frame/stream";class Qt{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new Fr("Streamer",e),this.adapter=t}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,from:i}){const a=await Xt.open(e,n),c=await t.stream(al,sl,il),l=new Qt(c,a);return c.send({start:new O(i),keys:a.keys}),l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ge.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new Z((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Ot extends Rr.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 Gr=(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))(Gr||{}),wt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.PersistOnly=2]="PersistOnly",r[r.StreamOnly=3]="StreamOnly",r))(wt||{});const ol=new E(-1),cl=s.z.object({start:O.z.optional(),controlSubject:_e.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:_e.Authority.z.array().optional(),mode:s.z.nativeEnum(wt).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:E.z.optional()}),ll=s.z.object({command:s.z.nativeEnum(Gr),config:cl.optional(),frame:Ht.optional()}),ul=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Gr),error:vt.optional().nullable()});var fe;let Vs=(fe=class{constructor(e,t){o(this,"stream");o(this,"adapter");this.stream=new Fr("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=O.now(),authorities:a=_e.Authority.Absolute,controlSubject:c,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:f=!1,autoIndexPersistInterval:g=E.SECOND}){const p=await Wr.open(e,n),P=await t.stream(fe.ENDPOINT,ll,ul),C=new fe(P,p);return await C.execute({command:0,config:{start:new O(i),keys:p.keys,controlSubject:c,authorities:T(a),mode:l,errOnUnauthorized:u,enableAutoCommit:f,autoIndexPersistInterval:g}}),C}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){return(await this.execute({command:4,config:{keys:Object.keys(e).map(n=>Number(n)),authorities:Object.values(e)}})).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?Zr(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(fe,"ENDPOINT","/frame/write"),fe),Hs=class{constructor(e,t,n){o(this,"streamClient");o(this,"retriever");o(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new el(t)}async openIterator(e,t,n){return await qt._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await Vs._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await Qt._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:wt.PersistOnly});try{await c.write(a),await c.commit()}finally{await c.close()}return}const i=await this.openWriter({start:e,channels:t,mode:wt.PersistOnly,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:E.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=ye(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new Z;try{for await(const a of n)i.push(a)}finally{await n.close()}return i}async delete(e,t){const{normalized:n,variant:i}=ye(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const hl=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:ol,AUTO_SPAN:Pr,Client:Hs,Frame:Z,Iterator:qt,ObservableStreamer:Ot,Streamer:Qt,Writer:Vs,WriterMode:wt,frameZ:Ht,series:_s,seriesFromPayload:Gs,seriesToPayload:Ks},Symbol.toStringTag,{value:"Module"})),yl=_e.Authority,dl=_e.stateZ(s.z.number()),fl=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 Xs extends Ot{constructor(t){super(t,n=>{const i=this.ecd.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});o(this,"states");o(this,"ecd");this.states=new Map,this.ecd=new Ge.JSONEncoderDecoder}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 pl="sy_node_1_control";let Qs=class{constructor(e){o(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(pl);return new Xs(e)}};const gl=Object.freeze(Object.defineProperty({__proto__:null,Authority:yl,Client:Qs,StateTracker:Xs,stateZ:dl,transferString:fl},Symbol.toStringTag,{value:"Module"}));let ei=class{constructor(e,t,n){o(this,"tasks");o(this,"racks");o(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const ml=Object.freeze(Object.defineProperty({__proto__:null,Client:ei},Symbol.toStringTag,{value:"Module"})),Je=s.z.number(),er=s.z.object({key:Je,name:s.z.string()}),ti=er.partial({key:!0}),fr="/hardware/rack/retrieve",wl="/hardware/rack/create",bl="/hardware/rack/delete",pr=s.z.object({keys:Je.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),gr=s.z.object({racks:Ke(er)}),vl=s.z.object({racks:ti.array()}),Tl=s.z.object({racks:er.array()}),Ol=s.z.object({keys:Je.array()}),zl=s.z.object({});let ri=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,bl,{keys:T(e)},Ol,zl)}async create(e){const t=!Array.isArray(e),n=await w(this.client,wl,{racks:T(e)},vl,Tl),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,fr,{search:e},pr,gr);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,fr,{offset:e,limit:t},pr,gr);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=Kt(e,{string:"names",number:"keys"}),a=await w(this.client,fr,{[t]:n},pr,gr),c=this.sugar(a.racks);return Jt("Rack",e,c,i),i?c[0]:c}sugar(e){return e.map(({key:t,name:n})=>new ni(t,n,this.tasks))}};class ni{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 Ve=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 Ot(i,a)},El=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Ve},Symbol.toStringTag,{value:"Module"})),Sl="sy_device_set",Nl="sy_device_delete",mr="/hardware/device/retrieve",Il="/hardware/device/create",Al="/hardware/device/delete",tr=s.z.string(),zt=s.z.object({key:tr,rack:Je,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===""?{}:Ge.JSON_ECD.decodeString(r)))}),si=zt.extend({properties:s.z.unknown().transform(r=>Ge.JSON_ECD.encodeString(r))}),kl=s.z.object({devices:si.array()}),Rl=s.z.object({devices:zt.array()}),$l=s.z.object({keys:tr.array()}),xl=s.z.object({}),wr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:tr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),br=s.z.object({devices:Ke(zt)});let ii=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,mr,{keys:T(e),...t},wr,br);return Jt("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,mr,{search:e,...t},wr,br)).devices}async page(e,t,n){return(await w(this.client,mr,{offset:e,limit:t,...n},wr,br)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Il,{devices:T(e)},kl,Rl);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,Al,{keys:T(e)},$l,xl)}async openDeviceTracker(){return await Ve(this.frameClient,Sl,Nl,Cl)}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 Cl=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(zt).map(t=>({variant:r,key:t.key,value:t})),Pl=Object.freeze(Object.defineProperty({__proto__:null,Client:ii,deviceKeyZ:tr,deviceZ:zt,newDeviceZ:si},Symbol.toStringTag,{value:"Module"})),jl=Object.freeze(Object.defineProperty({__proto__:null,Client:ri,Rack:ni,newRackZ:ti,rackKeyZ:Je,rackZ:er},Symbol.toStringTag,{value:"Module"})),ht="sy_task_state",Mn="sy_task_cmd",He=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),bt=s.z.object({task:He,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())}),rr=s.z.object({key:He,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===""?{}:Ge.JSON_ECD.decodeString(r))),state:bt.optional().nullable()}),ai=rr.omit({key:!0}).extend({key:He.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>Ge.JSON_ECD.encodeString(r))}),Dl=s.z.object({task:He,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)))});class oi{constructor(e,t,n,i,a,c=!1,l){o(this,"key");o(this,"name");o(this,"internal");o(this,"type");o(this,"config");o(this,"state");o(this,"frameClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=c,l!==null&&(this.state=l),this.frameClient=a}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}async executeCommand(e,t){const n=await this.frameClient.openWriter(Mn),i=ko.id();return await n.write(Mn,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){const i=await this.frameClient.openStreamer(ht),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 f=bt.safeParse(u.at(-1).sy_task_state);if(f.success){if(c=f.data,c.key===a)break}else console.error(f.error)}return i.close(),c}async openStateObserver(){return new Ot(await this.frameClient.openStreamer(ht),e=>{const t=e.get(ht);if(t.length===0)return[null,!1];const n=bt.safeParse(t.at(-1));if(!n.success)return[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}}const Ml=s.z.object({rack:Je.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()}),Zl=s.z.object({tasks:Ke(rr)}),Ul="/hardware/task/retrieve",Bl="/hardware/task/create",Ll="/hardware/task/delete",ql=s.z.object({tasks:ai.array()}),Yl=s.z.object({tasks:rr.array()}),Wl=s.z.object({keys:He.array()}),Fl=s.z.object({});let ci=class{constructor(e,t){o(this,"type","task");o(this,"client");o(this,"frameClient");this.client=e,this.frameClient=t}async create(e){const t=!Array.isArray(e),n=await w(this.client,Bl,{tasks:T(e)},ql,Yl),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,Ll,{keys:T(e)},Wl,Fl)}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}=Kt(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 retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return Jt("Task",e,n,!0),this.sugar(n)[0]}async execRetrieve(e){return(await w(this.client,Ul,e,Ml,Zl)).tasks}sugar(e){return e.map(({key:t,name:n,type:i,config:a,state:c,internal:l})=>new oi(t,n,i,a,this.frameClient,l,c))}async openTracker(){return await Ve(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 Ot(await this.frameClient.openStreamer(ht),e=>{const t=e.get(ht);if(t.length===0)return[null,!1];const n=bt.safeParse(t.at(-1));return n.success?[n.data,!0]:[null,!1]})}};const _l=Object.freeze(Object.defineProperty({__proto__:null,Client:ci,Task:oi,commandZ:Dl,newTaskZ:ai,stateZ:bt,taskKeyZ:He,taskZ:rr},Symbol.toStringTag,{value:"Module"})),Xe=s.z.string().uuid(),Et=s.z.object({key:Xe,name:s.z.string().min(1),color:s.z.string()}),Gl=r=>new G({type:"label",key:r}),Kl=s.z.object({keys:Xe.array().optional(),for:ee.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Jl=s.z.object({labels:Et.array().optional().default([])});var ze;let li=(ze=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(ze.ENDPOINT,e,Kl,Jl);if(n!=null)throw n;return t.labels}},o(ze,"ENDPOINT","/label/retrieve"),ze);const ui=Et.extend({key:Xe.optional()}),Vl=s.z.object({labels:ui.array()}),Hl=s.z.object({labels:Et.array()}),Xl=s.z.object({keys:Xe.array()}),hi=s.z.object({id:ee,labels:Xe.array()}),Ql=hi,vr=s.z.object({}),eu="/label/create",tu="/label/delete",ru="/label/set",nu="/label/remove";let yi=class{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,eu,{labels:T(e)},Vl,Hl)).labels}async delete(e){await w(this.client,tu,{keys:T(e)},Xl,vr)}async set(e,t){await w(this.client,ru,{id:e,labels:t},hi,vr)}async remove(e,t){await w(this.client,nu,{id:e,labels:t},Ql,vr)}};const su="sy_label_set",iu="sy_label_delete";let di=class{constructor(e,t){o(this,"type","label");o(this,"retriever");o(this,"writer");o(this,"frameClient");this.writer=new yi(e),this.retriever=new li(e),this.frameClient=t}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(e)}async label(e,t){await this.writer.set(e,t)}async removeLabels(e,t){await this.writer.remove(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 Ve(this.frameClient,su,iu,au)}};const au=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(Et).map(t=>({variant:r,key:t.key,value:t})),ou=Object.freeze(Object.defineProperty({__proto__:null,Client:di,Retriever:li,Writer:yi,keyZ:Xe,labelZ:Et,newLabelPayloadZ:ui,ontologyID:Gl},Symbol.toStringTag,{value:"Module"})),K=s.z.string().uuid(),Qe=s.z.object({key:K,name:s.z.string().min(1),timeRange:_.z,color:s.z.string().optional()}),fi=Qe.extend({key:s.z.string().uuid().optional()}),pi=r=>{const e=T(r);if(e.length===0)throw new Error("Range params must not be empty");const t=K.safeParse(e[0]).success;return{single:!Array.isArray(r),variant:t?"keys":"names",normalized:e,actual:r}},cu=s.z.object({}),lu=s.z.object({range:Qe}),uu=s.z.object({range:K}),hu=s.z.object({range:K}),yu=s.z.object({}),du="/range/set-active",fu="/range/retrieve-active",pu="/range/clear-active";class gu{constructor(e){o(this,"client");this.client=e}async setActive(e){await w(this.client,du,{range:e},uu,cu)}async retrieveActive(){const[e,t]=await this.client.send(fu,{},s.z.object({}),lu);if(H.matches(t))return null;if(t!=null)throw t;return e.range}async clearActive(e){await w(this.client,pu,{range:e},hu,yu)}}const mu="sy_range_alias_set",wu="sy_range_alias_delete",bu=s.z.object({range:K,aliases:s.z.string().array()}),vu=s.z.object({aliases:s.z.record(s.z.string(),me)}),Tu=s.z.object({range:K,aliases:s.z.record(me.or(s.z.string()),s.z.string())}),Ou=s.z.unknown(),zu=s.z.object({range:K,channels:me.array()}),Eu=s.z.unknown(),Su=s.z.object({range:K}),Nu=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),ae=class ae{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,ae.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},bu,vu);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,ae.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Tu,Ou)}async list(){return(await w(this.client,ae.LIST_ENDPOINT,{range:this.rangeKey},Su,Nu)).aliases}async delete(e){await w(this.client,ae.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},zu,Eu)}async openChangeTracker(){return await Ve(this.frameClient,mu,wu,ku(this.rangeKey))}};o(ae,"SET_ENDPOINT","/range/alias/set"),o(ae,"RESOLVE_ENDPOINT","/range/alias/resolve"),o(ae,"LIST_ENDPOINT","/range/alias/list"),o(ae,"DELETE_ENDPOINT","/range/alias/delete");let jr=ae;const Iu=s.z.object({range:K,channel:me,alias:s.z.string()}),Au="---",ku=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(Au)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(Iu).map(n=>({variant:e,key:n.alias,value:n})),Ru=s.z.object({range:K,keys:s.z.string().array()}),$u=s.z.object({pairs:s.z.record(s.z.string(),s.z.string())}),xu=s.z.object({range:K,pairs:s.z.record(s.z.string(),s.z.string())}),Cu=s.z.object({range:K,keys:s.z.string().array()}),de=class de{constructor(e,t){o(this,"rangeKey");o(this,"client");this.rangeKey=e,this.client=t}async get(e){const[t,n]=await this.client.send(de.GET_ENDPOINT,{range:this.rangeKey,keys:T(e)},Ru,$u);if(n!=null)throw n;return Array.isArray(e)?t.pairs:t.pairs[e]}async list(){return this.get([])}async set(e,t=""){await w(this.client,de.SET_ENDPOINT,{range:this.rangeKey,pairs:Br(e)?e:{[e]:t}},xu,s.z.unknown())}async delete(e){await w(this.client,de.DELETE_ENDPOINT,{range:this.rangeKey,keys:T(e)},Cu,s.z.unknown())}};o(de,"GET_ENDPOINT","/range/kv/get"),o(de,"SET_ENDPOINT","/range/kv/set"),o(de,"DELETE_ENDPOINT","/range/kv/delete");let Dr=de;const Tr=r=>new G({type:"range",key:r});class gi{constructor(e,t=_.ZERO,n,i,a,c,l,u,f){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");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=f}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new H(`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 openAliasTracker(){return await this.aliaser.openChangeTracker()}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(Tr(this.key))}async addLabel(...e){await this.labelClient.label(Tr(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(Tr(this.key),e)}}const Pu=s.z.object({keys:K.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:_.z.optional()}),ju="/range/retrieve",Du=s.z.object({ranges:Ke(Qe)});let mi=class{constructor(e,t,n,i,a){o(this,"type","range");o(this,"frameClient");o(this,"writer");o(this,"unaryClient");o(this,"channels");o(this,"active");o(this,"labelClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.active=new gu(n),this.labelClient=a}async create(e){const t=!Array.isArray(e),n=this.sugar(await this.writer.create(T(e)));return t?n[0]:n}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(T(e))}async search(e){return this.sugar(await this.execRetrieve({term:e}))}async page(){return[]}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new _(e)});const{single:t,actual:n,variant:i,normalized:a}=pi(e),c=await this.execRetrieve({[i]:a});if(!t)return c;if(c.length===0)throw new Ie(`range matching ${n} not found`);if(c.length>1)throw new Ae(`multiple ranges matching ${n} found`);return c[0]}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,ju,e,Pu,Du);return this.sugar(t)}async setActive(e){await this.active.setActive(e)}async retrieveActive(){const e=await this.active.retrieveActive();return e==null?null:this.sugar([e])[0]}async clearActive(e){await this.active.clearActive(e)}sugar(e){return e.map(t=>new gi(t.name,t.timeRange,t.key,t.color,this.frameClient,new Dr(t.key,this.unaryClient),new jr(t.key,this.frameClient,this.unaryClient),this.channels,this.labelClient))}async openTracker(){return await Ve(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugar(t.parseJSON(Qe)).map(i=>({variant:e,key:i.key,value:i})))}};const Mu=s.z.object({ranges:Qe.array()}),Zu=s.z.object({ranges:fi.array()}),Uu=s.z.object({keys:K.array()}),Bu=s.z.object({}),Lu=s.z.object({key:K,name:s.z.string()}),qu=s.z.object({}),Yu="/range/create",Wu="/range/delete",Fu="/range/rename";let wi=class{constructor(e){o(this,"client");this.client=e}async rename(e,t){await w(this.client,Fu,{key:e,name:t},Lu,qu)}async create(e){return(await w(this.client,Yu,{ranges:e},Zu,Mu)).ranges}async delete(e){await w(this.client,Wu,{keys:e},Uu,Bu)}};const _u=Object.freeze(Object.defineProperty({__proto__:null,Client:mi,Range:gi,Writer:wi,analyzeParams:pi,keyZ:K,newPayloadZ:fi,payloadZ:Qe},Symbol.toStringTag,{value:"Module"})),Gu="/api/v1/";class Ku{constructor(e,t=!1){o(this,"url");o(this,"unary");o(this,"stream");o(this,"secure");this.secure=t,this.url=e.child(Gu);const n=new Ge.JSONEncoderDecoder;this.unary=new Pa(this.url,n,this.secure),this.stream=new Ya(this.url,n,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Kr=s.z.string().uuid(),Jr=s.z.object({key:s.z.string(),name:s.z.string(),data:Lr.or(s.z.string().transform(r=>JSON.parse(r)))}),Ju=s.z.object({keys:s.z.string().array()}),Vu=s.z.object({linePlots:Jr.array()});let Hu=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},Ju,Vu)).linePlots}};const be=s.z.string().uuid(),bi=r=>JSON.parse(r),Vr=s.z.object({name:s.z.string(),key:be,layout:Lr.or(s.z.string().transform(r=>bi(r)))}),Hr=Vr.omit({layout:!0}).extend({layout:s.z.string().transform(r=>bi(r))}),Xu=Jr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Qu=s.z.object({workspace:be,linePlots:Xu.array()}),eh=s.z.object({linePlots:Jr.array()}),th=s.z.object({keys:Kr.array()}),rh=s.z.object({}),nh=s.z.object({key:Kr,name:s.z.string()}),sh=s.z.object({}),ih=s.z.object({key:Kr,data:s.z.string()}),ah=s.z.object({}),oh="/workspace/lineplot/create",ch="/workspace/lineplot/delete",lh="/workspace/lineplot/rename",uh="/workspace/lineplot/set-data";let hh=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,oh,{workspace:e,linePlots:[n]},Qu,eh)).linePlots[0]}async delete(e){const t=T(e);await w(this.client,ch,{keys:t},th,rh)}async rename(e,t){await w(this.client,lh,{key:e,name:t},nh,sh)}async setData(e,t){await w(this.client,uh,{key:e,data:JSON.stringify(t)},ih,ah)}},yh=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new hh(e),this.retriever=new Hu(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 dh=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()}),fh=s.z.object({workspaces:Ke(Hr)});var Ee;let ph=(Ee=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,Ee.ENDPOINT,e,dh,fh)).workspaces}},o(Ee,"ENDPOINT","/workspace/retrieve"),Ee);const nr=s.z.string().uuid(),gh=s.z.object({key:s.z.string(),name:s.z.string(),data:Lr.or(s.z.string().transform(r=>JSON.parse(r))),snapshot:s.z.boolean()}),Xr=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(r=>JSON.parse(r))}),mh=s.z.object({keys:s.z.string().array()}),wh=s.z.object({schematics:Xr.array()});class bh{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)},mh,wh)).schematics}}const vh=gh.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Th=s.z.object({workspace:be,schematics:vh.array()}),Oh=s.z.object({schematics:Xr.array()}),zh=s.z.object({keys:nr.array()}),Eh=s.z.object({}),Sh=s.z.object({key:nr,name:s.z.string()}),Zn=s.z.object({}),Nh=s.z.object({key:nr,data:s.z.string()});s.z.object({});const Ih=s.z.object({key:nr,name:s.z.string(),snapshot:s.z.boolean()}),Ah=s.z.object({schematic:Xr}),kh="/workspace/schematic/create",Rh="/workspace/schematic/delete",$h="/workspace/schematic/rename",xh="/workspace/schematic/set-data",Ch="/workspace/schematic/copy";let Ph=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,kh,{workspace:e,schematics:[n]},Th,Oh)).schematics[0]}async copy(e,t,n){return(await w(this.client,Ch,{key:e,name:t,snapshot:n},Ih,Ah)).schematic}async delete(e){const t=T(e);await w(this.client,Rh,{keys:t},zh,Eh)}async rename(e,t){await w(this.client,$h,{key:e,name:t},Sh,Zn)}async setData(e,t){await w(this.client,xh,{key:e,data:JSON.stringify(t)},Nh,Zn)}},jh=class{constructor(e){o(this,"writer");o(this,"retriever");this.writer=new Ph(e),this.retriever=new bh(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 Dh=Vr.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Mh=s.z.object({workspaces:Dh.array()}),Zh=s.z.object({workspaces:Hr.array()}),Uh=s.z.object({keys:be.array()}),Bh=s.z.object({}),Lh=s.z.object({key:be,name:s.z.string()}),qh=s.z.object({}),Yh=s.z.object({key:be,layout:s.z.string()}),Wh=s.z.object({}),Fh="/workspace/create",_h="/workspace/delete",Gh="/workspace/rename",Kh="/workspace/set-layout";class Jh{constructor(e){o(this,"client");this.client=e}async create(e){return(await w(this.client,Fh,{workspaces:T(e)},Mh,Zh)).workspaces}async delete(e){await w(this.client,_h,{keys:T(e)},Uh,Bh)}async rename(e,t){await w(this.client,Gh,{key:e,name:t},Lh,qh)}async setLayout(e,t){await w(this.client,Kh,{key:e,layout:JSON.stringify(t)},Yh,Wh)}}class vi{constructor(e){o(this,"type","workspace");o(this,"schematic");o(this,"linePlot");o(this,"retriever");o(this,"writer");this.schematic=new jh(e),this.linePlot=new yh(e),this.retriever=new ph(e),this.writer=new Jh(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 Vh=Object.freeze(Object.defineProperty({__proto__:null,Client:vi,keyZ:be,workspaceRemoteZ:Hr,workspaceZ:Vr},Symbol.toStringTag,{value:"Module"})),Ti=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().optional(),password:s.z.string().optional(),connectivityPollFrequency:E.z.default(E.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional()});class Oi extends Hs{constructor(t){const n=Ti.parse(t),{host:i,port:a,username:c,password:l,connectivityPollFrequency:u,secure:f}=n,g=new Ku(new oc({host:i,port:Number(a)}),f);g.use(Fo);let p;if(c!=null&&l!=null){const Ei=new Gc(g.unary,{username:c,password:l});g.use(Ei.middleware())}const P=new qr(new gt(g.unary)),C=new Ys(g.unary,P);super(g.stream,g.unary,P);o(this,"createdAt");o(this,"props");o(this,"ranges");o(this,"channels");o(this,"auth");o(this,"connectivity");o(this,"ontology");o(this,"workspaces");o(this,"labels");o(this,"hardware");o(this,"control");o(this,"transport");this.createdAt=O.now(),this.props=n,this.auth=p,this.transport=g,this.channels=new qs(this,P,g.unary,C),this.connectivity=new mt(g.unary,u,n.name),this.control=new Qs(this),this.ontology=new Ls(g.unary,this);const X=new wi(this.transport.unary);this.labels=new di(this.transport.unary,this),this.ranges=new mi(this,X,this.transport.unary,P,this.labels),this.workspaces=new vi(this.transport.unary);const j=new ii(this.transport.unary,this),Qr=new ci(this.transport.unary,this),zi=new ri(this.transport.unary,this,Qr);this.hardware=new ei(Qr,zi,j)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}o(Oi,"connectivity",mt);const Hh=_e.Authority;exports.AuthError=Ne;exports.Authority=Hh;exports.Channel=Yr;exports.ContiguityError=Ar;exports.DataType=z;exports.Density=F;exports.Frame=Z;exports.MultiSeries=vs;exports.MultipleFoundError=Ae;exports.NotFoundError=Ie;exports.QueryError=H;exports.Rate=Gt;exports.RouteError=pt;exports.Series=Oe;exports.Synnax=Oi;exports.TimeRange=_;exports.TimeSpan=E;exports.TimeStamp=O;exports.UnexpectedError=pe;exports.ValidationError=x;exports.channel=qc;exports.connection=Vc;exports.control=gl;exports.device=Pl;exports.framer=hl;exports.hardware=ml;exports.label=ou;exports.ontology=kc;exports.rack=jl;exports.ranger=_u;exports.signals=El;exports.synnaxPropsZ=Ti;exports.task=_l;exports.workspace=Vh;