@synnaxlabs/client 0.38.1 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +7 -7
- package/dist/access/payload.d.ts +6 -6
- package/dist/access/payload.d.ts.map +1 -1
- package/dist/access/policy/client.d.ts +5 -3
- package/dist/access/policy/client.d.ts.map +1 -1
- package/dist/access/policy/external.d.ts +1 -0
- package/dist/access/policy/external.d.ts.map +1 -1
- package/dist/access/policy/ontology.d.ts +5 -0
- package/dist/access/policy/ontology.d.ts.map +1 -0
- package/dist/access/policy/payload.d.ts +86 -89
- package/dist/access/policy/payload.d.ts.map +1 -1
- package/dist/access/policy/retriever.d.ts +7 -6
- package/dist/access/policy/retriever.d.ts.map +1 -1
- package/dist/access/policy/writer.d.ts +2 -2
- package/dist/access/policy/writer.d.ts.map +1 -1
- package/dist/auth/auth.d.ts +2 -1
- package/dist/auth/auth.d.ts.map +1 -1
- package/dist/channel/client.d.ts +6 -5
- package/dist/channel/client.d.ts.map +1 -1
- package/dist/channel/payload.d.ts +13 -11
- package/dist/channel/payload.d.ts.map +1 -1
- package/dist/channel/retriever.d.ts +9 -6
- package/dist/channel/retriever.d.ts.map +1 -1
- package/dist/channel/writer.d.ts +6 -4
- package/dist/channel/writer.d.ts.map +1 -1
- package/dist/client.cjs +30 -30
- package/dist/client.d.ts +4 -2
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +3387 -3433
- package/dist/connection/checker.d.ts +5 -4
- package/dist/connection/checker.d.ts.map +1 -1
- package/dist/control/state.d.ts +10 -8
- package/dist/control/state.d.ts.map +1 -1
- package/dist/errors.d.ts +5 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/framer/adapter.d.ts +14 -15
- package/dist/framer/adapter.d.ts.map +1 -1
- package/dist/framer/client.d.ts +13 -15
- package/dist/framer/client.d.ts.map +1 -1
- package/dist/framer/deleter.d.ts +3 -2
- package/dist/framer/deleter.d.ts.map +1 -1
- package/dist/framer/frame.d.ts +31 -27
- package/dist/framer/frame.d.ts.map +1 -1
- package/dist/framer/iterator.d.ts +4 -5
- package/dist/framer/iterator.d.ts.map +1 -1
- package/dist/framer/streamer.d.ts +5 -6
- package/dist/framer/streamer.d.ts.map +1 -1
- package/dist/framer/writer.d.ts +42 -39
- package/dist/framer/writer.d.ts.map +1 -1
- package/dist/hardware/device/client.d.ts +20 -12
- package/dist/hardware/device/client.d.ts.map +1 -1
- package/dist/hardware/device/payload.d.ts +19 -16
- package/dist/hardware/device/payload.d.ts.map +1 -1
- package/dist/hardware/rack/client.d.ts +15 -15
- package/dist/hardware/rack/client.d.ts.map +1 -1
- package/dist/hardware/rack/payload.d.ts +9 -8
- package/dist/hardware/rack/payload.d.ts.map +1 -1
- package/dist/hardware/task/client.d.ts +38 -29
- package/dist/hardware/task/client.d.ts.map +1 -1
- package/dist/hardware/task/payload.d.ts +58 -53
- package/dist/hardware/task/payload.d.ts.map +1 -1
- package/dist/label/client.d.ts +4 -3
- package/dist/label/client.d.ts.map +1 -1
- package/dist/label/payload.d.ts +4 -4
- package/dist/label/payload.d.ts.map +1 -1
- package/dist/label/retriever.d.ts.map +1 -1
- package/dist/label/writer.d.ts +13 -10
- package/dist/label/writer.d.ts.map +1 -1
- package/dist/ontology/client.d.ts +12 -10
- package/dist/ontology/client.d.ts.map +1 -1
- package/dist/ontology/group/client.d.ts +5 -4
- package/dist/ontology/group/client.d.ts.map +1 -1
- package/dist/ontology/group/group.d.ts +7 -5
- package/dist/ontology/group/group.d.ts.map +1 -1
- package/dist/ontology/group/payload.d.ts +6 -5
- package/dist/ontology/group/payload.d.ts.map +1 -1
- package/dist/ontology/group/writer.d.ts +8 -8
- package/dist/ontology/group/writer.d.ts.map +1 -1
- package/dist/ontology/payload.d.ts +72 -62
- package/dist/ontology/payload.d.ts.map +1 -1
- package/dist/ontology/writer.d.ts.map +1 -1
- package/dist/ranger/alias.d.ts +9 -10
- package/dist/ranger/alias.d.ts.map +1 -1
- package/dist/ranger/client.d.ts +18 -18
- package/dist/ranger/client.d.ts.map +1 -1
- package/dist/ranger/external.d.ts +1 -1
- package/dist/ranger/external.d.ts.map +1 -1
- package/dist/ranger/kv.d.ts +18 -14
- package/dist/ranger/kv.d.ts.map +1 -1
- package/dist/ranger/payload.d.ts +13 -13
- package/dist/ranger/payload.d.ts.map +1 -1
- package/dist/ranger/writer.d.ts +14 -14
- package/dist/ranger/writer.d.ts.map +1 -1
- package/dist/setupspecs.d.ts.map +1 -1
- package/dist/signals/observable.d.ts +3 -1
- package/dist/signals/observable.d.ts.map +1 -1
- package/dist/user/client.d.ts +5 -3
- package/dist/user/client.d.ts.map +1 -1
- package/dist/user/payload.d.ts +7 -6
- package/dist/user/payload.d.ts.map +1 -1
- package/dist/user/retriever.d.ts +2 -1
- package/dist/user/retriever.d.ts.map +1 -1
- package/dist/user/writer.d.ts +2 -2
- package/dist/user/writer.d.ts.map +1 -1
- package/dist/util/decodeJSONString.d.ts +3 -0
- package/dist/util/decodeJSONString.d.ts.map +1 -0
- package/dist/util/parseWithoutKeyConversion.d.ts +3 -0
- package/dist/util/parseWithoutKeyConversion.d.ts.map +1 -0
- package/dist/util/retrieve.d.ts +1 -1
- package/dist/util/retrieve.d.ts.map +1 -1
- package/dist/util/telem.d.ts.map +1 -1
- package/dist/util/zod.d.ts.map +1 -1
- package/dist/workspace/client.d.ts +6 -60
- package/dist/workspace/client.d.ts.map +1 -1
- package/dist/workspace/external.d.ts +3 -0
- package/dist/workspace/external.d.ts.map +1 -0
- package/dist/workspace/index.d.ts +1 -1
- package/dist/workspace/index.d.ts.map +1 -1
- package/dist/workspace/lineplot/client.d.ts +5 -44
- package/dist/workspace/lineplot/client.d.ts.map +1 -1
- package/dist/workspace/lineplot/external.d.ts +3 -0
- package/dist/workspace/lineplot/external.d.ts.map +1 -0
- package/dist/workspace/lineplot/index.d.ts +1 -1
- package/dist/workspace/lineplot/index.d.ts.map +1 -1
- package/dist/workspace/lineplot/payload.d.ts +45 -0
- package/dist/workspace/lineplot/payload.d.ts.map +1 -0
- package/dist/workspace/log/client.d.ts +5 -44
- package/dist/workspace/log/client.d.ts.map +1 -1
- package/dist/workspace/log/external.d.ts +3 -0
- package/dist/workspace/log/external.d.ts.map +1 -0
- package/dist/workspace/log/index.d.ts +1 -1
- package/dist/workspace/log/index.d.ts.map +1 -1
- package/dist/workspace/log/payload.d.ts +45 -0
- package/dist/workspace/log/payload.d.ts.map +1 -0
- package/dist/workspace/payload.d.ts +60 -0
- package/dist/workspace/payload.d.ts.map +1 -0
- package/dist/workspace/schematic/client.d.ts +5 -68
- package/dist/workspace/schematic/client.d.ts.map +1 -1
- package/dist/workspace/schematic/external.d.ts +3 -0
- package/dist/workspace/schematic/external.d.ts.map +1 -0
- package/dist/workspace/schematic/index.d.ts +1 -1
- package/dist/workspace/schematic/index.d.ts.map +1 -1
- package/dist/workspace/schematic/payload.d.ts +71 -0
- package/dist/workspace/schematic/payload.d.ts.map +1 -0
- package/dist/workspace/table/client.d.ts +5 -57
- package/dist/workspace/table/client.d.ts.map +1 -1
- package/dist/workspace/table/external.d.ts +3 -0
- package/dist/workspace/table/external.d.ts.map +1 -0
- package/dist/workspace/table/index.d.ts +1 -1
- package/dist/workspace/table/index.d.ts.map +1 -1
- package/dist/workspace/table/payload.d.ts +60 -0
- package/dist/workspace/table/payload.d.ts.map +1 -0
- package/examples/node/basicReadWrite.js +26 -26
- package/examples/node/liveStream.js +15 -15
- package/examples/node/seriesAndFrames.js +38 -38
- package/examples/node/streamWrite.js +47 -45
- package/package.json +15 -13
- package/src/access/payload.ts +12 -12
- package/src/access/policy/client.ts +13 -12
- package/src/access/policy/external.ts +1 -0
- package/src/access/policy/ontology.ts +17 -0
- package/src/access/policy/payload.ts +7 -19
- package/src/access/policy/policy.spec.ts +16 -16
- package/src/access/policy/retriever.ts +2 -1
- package/src/access/policy/writer.ts +4 -4
- package/src/auth/auth.spec.ts +27 -23
- package/src/auth/auth.ts +7 -11
- package/src/channel/batchRetriever.spec.ts +25 -22
- package/src/channel/client.ts +19 -21
- package/src/channel/payload.ts +16 -20
- package/src/channel/retriever.ts +20 -21
- package/src/channel/writer.ts +11 -13
- package/src/client.ts +6 -16
- package/src/connection/checker.ts +9 -11
- package/src/connection/connection.spec.ts +17 -5
- package/src/control/state.ts +8 -9
- package/src/errors.spec.ts +1 -1
- package/src/errors.ts +8 -0
- package/src/framer/adapter.spec.ts +28 -23
- package/src/framer/adapter.ts +37 -41
- package/src/framer/client.spec.ts +5 -11
- package/src/framer/client.ts +34 -38
- package/src/framer/deleter.ts +5 -6
- package/src/framer/frame.ts +62 -50
- package/src/framer/iterator.ts +11 -16
- package/src/framer/streamer.spec.ts +2 -10
- package/src/framer/streamer.ts +15 -19
- package/src/framer/writer.spec.ts +48 -7
- package/src/framer/writer.ts +39 -31
- package/src/hardware/device/client.ts +67 -39
- package/src/hardware/device/device.spec.ts +91 -33
- package/src/hardware/device/payload.ts +29 -28
- package/src/hardware/rack/client.ts +52 -65
- package/src/hardware/rack/payload.ts +9 -18
- package/src/hardware/rack/rack.spec.ts +12 -0
- package/src/hardware/task/client.ts +160 -131
- package/src/hardware/task/payload.ts +49 -68
- package/src/hardware/task/task.spec.ts +98 -81
- package/src/label/client.ts +12 -15
- package/src/label/payload.ts +3 -9
- package/src/label/retriever.ts +3 -7
- package/src/label/writer.ts +8 -15
- package/src/ontology/client.ts +17 -22
- package/src/ontology/group/client.ts +5 -5
- package/src/ontology/group/group.spec.ts +4 -4
- package/src/ontology/group/group.ts +10 -7
- package/src/ontology/group/payload.ts +11 -35
- package/src/ontology/group/writer.ts +22 -26
- package/src/ontology/ontology.spec.ts +15 -15
- package/src/ontology/payload.ts +67 -43
- package/src/ontology/writer.ts +16 -23
- package/src/ranger/alias.ts +25 -42
- package/src/ranger/client.ts +29 -38
- package/src/ranger/external.ts +1 -1
- package/src/ranger/kv.ts +9 -32
- package/src/ranger/payload.ts +14 -36
- package/src/ranger/ranger.spec.ts +1 -2
- package/src/ranger/writer.ts +8 -26
- package/src/signals/observable.ts +3 -4
- package/src/user/client.ts +8 -4
- package/src/user/payload.ts +5 -9
- package/src/user/retriever.ts +1 -1
- package/src/user/user.spec.ts +17 -15
- package/src/user/writer.ts +3 -10
- package/src/util/decodeJSONString.ts +13 -0
- package/src/util/parseWithoutKeyConversion.ts +19 -0
- package/src/util/retrieve.spec.ts +3 -13
- package/src/util/retrieve.ts +2 -12
- package/src/util/telem.ts +1 -1
- package/src/vite-env.d.ts +1 -0
- package/src/workspace/client.ts +30 -57
- package/src/workspace/external.ts +11 -0
- package/src/workspace/index.ts +1 -1
- package/src/workspace/lineplot/client.ts +22 -36
- package/src/workspace/lineplot/external.ts +11 -0
- package/src/workspace/lineplot/index.ts +1 -1
- package/src/workspace/lineplot/linePlot.spec.ts +1 -2
- package/src/workspace/lineplot/payload.ts +32 -0
- package/src/workspace/log/client.ts +25 -39
- package/src/workspace/log/external.ts +11 -0
- package/src/workspace/log/index.ts +1 -1
- package/src/workspace/log/log.spec.ts +5 -18
- package/src/workspace/log/payload.ts +32 -0
- package/src/workspace/payload.ts +36 -0
- package/src/workspace/schematic/client.ts +30 -56
- package/src/workspace/schematic/external.ts +11 -0
- package/src/workspace/schematic/index.ts +1 -1
- package/src/workspace/schematic/payload.ts +37 -0
- package/src/workspace/schematic/schematic.spec.ts +15 -6
- package/src/workspace/table/client.ts +27 -50
- package/src/workspace/table/external.ts +11 -0
- package/src/workspace/table/index.ts +1 -1
- package/src/workspace/table/payload.ts +36 -0
- package/src/workspace/workspace.spec.ts +1 -2
- package/dist/channel/creator.d.ts +0 -9
- package/dist/channel/creator.d.ts.map +0 -1
- package/src/channel/creator.ts +0 -37
package/dist/client.cjs
CHANGED
|
@@ -1,51 +1,51 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`)}decodeString(
|
|
3
|
-
`).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const i=t.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),r.forEach(o=>{const l=o.split(",").map(u=>u.trim());i.forEach((u,h)=>{const f=this.parseValue(l[h]);f!=null&&a[u].push(f)})}),e!=null?e.parse(a):a}parseValue(n){if(n==null||n.length===0)return null;const e=Number(n);return isNaN(e)?n.startsWith('"')&&n.endsWith('"')?n.slice(1,-1):n:e}static registerCustomType(){}},Io=class{constructor(){It(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const r=new TextDecoder().decode(e);return t!=null?t.parse(r):r}};const rn=new No;new So;new Io;const ko=n=>n!=null&&typeof n=="object"&&"toString"in n,$o=(n,e=!1)=>{const t=ko(n)?"stringer":typeof n;let r;switch(t){case"string":r=(i,a)=>i.localeCompare(a);break;case"stringer":r=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":r=(i,a)=>Number(i)-Number(a);break;case"bigint":r=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":r=(i,a)=>Number(i)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Ao(r):r},Ao=n=>(e,t)=>n(t,e),Sn=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Vs=s.z.object({width:s.z.number(),height:s.z.number()}),Ro=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),xo=["width","height"];s.z.enum(xo);const Co=["start","center","end"],Po=["signedWidth","signedHeight"];s.z.enum(Po);const pn=s.z.object({x:s.z.number(),y:s.z.number()}),Do=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),jo=["x","y"],Js=s.z.enum(jo),Ks=["top","right","bottom","left"];s.z.enum(Ks);const Mo=["left","right"],Hs=s.z.enum(Mo),Bo=["top","bottom"],Xs=s.z.enum(Bo),Qs=["center"],Kr=s.z.enum(Qs),Uo=[...Ks,...Qs],ei=s.z.enum(Uo);s.z.enum(Co);const Zo=["first","last"];s.z.enum(Zo);const Lo=s.z.object({lower:s.z.number(),upper:s.z.number()}),qo=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Lo,Sn]);s.z.union([qo,Sn]);s.z.union([Js,ei]);s.z.union([Js,ei,s.z.instanceof(String)]);const Yo=n=>typeof n=="bigint"||n instanceof BigInt,Me=(n,e)=>Yo(n)?n.valueOf()*BigInt(e.valueOf()):n.valueOf()*Number(e.valueOf()),Re=(n,e)=>{const t={};if(typeof n=="number"||typeof n=="bigint")e!=null?(t.lower=n,t.upper=e):(t.lower=typeof n=="bigint"?0n:0,t.upper=n);else if(Array.isArray(n)){if(n.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=n}else return Hr(n);return Hr(t)},Hr=n=>n.lower>n.upper?{lower:n.upper,upper:n.lower}:n,Xr=(n,e)=>{const t=Re(n);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:Hs.or(Kr),y:Xs.or(Kr)});const _o=s.z.object({x:Hs,y:Xs}),Wo=Object.freeze({x:"left",y:"top"}),Go=(n,e)=>n.x===e.x&&n.y===e.y,Qr=s.z.union([s.z.number(),pn,Sn,Vs,Ro,Do]),Fo=(n,e)=>{if(typeof n=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return n==="x"?{x:e,y:0}:{x:0,y:e}}return typeof n=="number"?{x:n,y:e??n}:Array.isArray(n)?{x:n[0],y:n[1]}:"signedWidth"in n?{x:n.signedWidth,y:n.signedHeight}:"clientX"in n?{x:n.clientX,y:n.clientY}:"width"in n?{x:n.width,y:n.height}:{x:n.x,y:n.y}},es=Object.freeze({x:0,y:0}),Ht=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:Ht,left:Ht,width:Ht,height:Ht});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:pn,two:pn,root:_o});const $r=(n,e,t=0,r=0,i)=>{const a={one:{...es},two:{...es},root:i??Wo};if(typeof n=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:n,y:e},a.two={x:a.one.x+t,y:a.one.y+r},a}return"one"in n&&"two"in n&&"root"in n?{...n,root:i??n.root}:("getBoundingClientRect"in n&&(n=n.getBoundingClientRect()),"left"in n?(a.one={x:n.left,y:n.top},a.two={x:n.right,y:n.bottom},a):(a.one=n,e==null?a.two={x:a.one.x+t,y:a.one.y+r}: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))},Yn=n=>{const e=$r(n);return{lower:e.one.x,upper:e.two.x}},_n=n=>{const e=$r(n);return{lower:e.one.y,upper:e.two.y}},Vo=n=>typeof n!="object"||n==null?!1:"one"in n&&"two"in n&&"root"in n,Jo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Vs,Jo,pn,Sn]);var Ko=Object.defineProperty,Ho=(n,e,t)=>e in n?Ko(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ge=(n,e,t)=>Ho(n,typeof e!="symbol"?e+"":e,t);const Xo=(n,e,t)=>e!==void 0&&n<e?e:t!==void 0&&n>t?t:n;s.z.object({offset:Qr,scale:Qr});s.z.object({offset:s.z.number(),scale:s.z.number()});const Qo=n=>(e,t,r,i)=>t==="dimension"?[e,r]:[e,i?r-n:r+n],ec=n=>(e,t,r,i)=>[e,i?r/n:r*n],tc=n=>(e,t,r)=>{if(e===null)return[n,r];const{lower:i,upper:a}=e,{lower:o,upper:l}=n,u=a-i,h=l-o;if(t==="dimension")return[n,r*(h/u)];const f=(r-i)*(h/u)+o;return[n,f]},nc=n=>(e,t,r)=>[n,r],rc=()=>(n,e,t)=>{if(n===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[n,t];const{lower:r,upper:i}=n;return[n,i-(t-r)]},sc=n=>(e,t,r)=>{const{lower:i,upper:a}=n;return r=Xo(r,i,a),[e,r]},fr=class gt{constructor(){ge(this,"ops",[]),ge(this,"currBounds",null),ge(this,"currType",null),ge(this,"reversed",!1),this.ops=[]}static translate(e){return new gt().translate(e)}static magnify(e){return new gt().magnify(e)}static scale(e,t){return new gt().scale(e,t)}translate(e){const t=this.new(),r=Qo(e);return r.type="translate",t.ops.push(r),t}magnify(e){const t=this.new(),r=ec(e);return r.type="magnify",t.ops.push(r),t}scale(e,t){const r=Re(e,t),i=this.new(),a=tc(r);return a.type="scale",i.ops.push(a),i}clamp(e,t){const r=Re(e,t),i=this.new(),a=sc(r);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const r=Re(e,t),i=this.new(),a=nc(r);return a.type="re-bound",i.ops.push(a),i}invert(){const e=rc();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 gt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([r,i],a)=>a(r,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((r,i)=>{if(r.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([r,i])=>{const a=e.ops.slice(r,i);a.unshift(e.ops[i]),e.ops.splice(r,i-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};ge(fr,"IDENTITY",new fr);let ts=fr;const ns=class fe{constructor(e=new ts,t=new ts,r=null){ge(this,"x"),ge(this,"y"),ge(this,"currRoot"),this.x=e,this.y=t,this.currRoot=r}static translate(e,t){return new fe().translate(e,t)}static translateX(e){return new fe().translateX(e)}static translateY(e){return new fe().translateY(e)}static clamp(e){return new fe().clamp(e)}static magnify(e){return new fe().magnify(e)}static scale(e){return new fe().scale(e)}static reBound(e){return new fe().reBound(e)}translate(e,t){const r=Fo(e,t),i=this.copy();return i.x=this.x.translate(r.x),i.y=this.y.translate(r.y),i}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Vo(e)){const r=this.currRoot;return t.currRoot=e.root,r!=null&&!Go(r,e.root)&&(r.x!==e.root.x&&(t.x=t.x.invert()),r.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Yn(e)),t.y=t.y.scale(_n(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Yn(e)),t.y=this.y.reBound(_n(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Yn(e)),t.y=this.y.clamp(_n(e)),t}copy(){const e=new fe;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return $r(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};ge(ns,"IDENTITY",new ns);const ic=s.z.bigint().or(s.z.string().transform(BigInt));var ac=Object.defineProperty,oc=(n,e,t)=>e in n?ac(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,m=(n,e,t)=>oc(n,typeof e!="symbol"?e+"":e,t);let cc=(n,e=21)=>(t=e)=>{let r="",i=t|0;for(;i--;)r+=n[Math.random()*n.length|0];return r};const lc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",uc=cc(lc,11),hc=s.z.enum(["static","dynamic"]),ti=(n,e)=>{const t=new M(e);if(![D.DAY,D.HOUR,D.MINUTE,D.SECOND,D.MILLISECOND,D.MICROSECOND,D.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=n.valueOf()%t.valueOf();return n instanceof M?new M(r):new D(r)},R=class T{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let r=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(r=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+r}}static parseDate([e=1970,t=1,r=1]){const i=new Date(e,t-1,r,0,0,0,0);return new T(BigInt(i.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[r,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=T.hours(parseInt(r??"00")).add(T.minutes(parseInt(i??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(T.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new T(BigInt(r.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const r=this.toISOString(t);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${t} ${r}`}static get utcOffset(){return new D(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new Ar(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(D.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(D.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(D.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(D.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new T(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new T(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new T(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new T(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new T(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new T(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new T(t)}toString(){return this.date().toISOString()}remainder(e){return ti(this,e)}get isToday(){return this.truncate(D.DAY).equals(T.now().truncate(D.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const r of e){const i=new T(r);i.after(t)&&(t=i)}return t}static min(...e){let t=T.MAX;for(const r of e){const i=new T(r);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new T(e)}static microseconds(e){return T.nanoseconds(e*1e3)}static milliseconds(e){return T.microseconds(e*1e3)}static seconds(e){return T.milliseconds(e*1e3)}static minutes(e){return T.seconds(e*60)}static hours(e){return T.minutes(e*60)}static days(e){return T.hours(e*24)}};m(R,"NANOSECOND",R.nanoseconds(1)),m(R,"MICROSECOND",R.microseconds(1)),m(R,"MILLISECOND",R.milliseconds(1)),m(R,"SECOND",R.seconds(1)),m(R,"MINUTE",R.minutes(1)),m(R,"HOUR",R.hours(1)),m(R,"DAY",R.days(1)),m(R,"MAX",new R((1n<<63n)-1n)),m(R,"MIN",new R(0)),m(R,"ZERO",new R(0)),m(R,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(n=>new R(n.value)),s.z.string().transform(n=>new R(BigInt(n))),s.z.instanceof(Number).transform(n=>new R(n)),s.z.number().transform(n=>new R(n)),s.z.instanceof(R)]));let M=R;const x=class E{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof E?e:e instanceof rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.seconds(e):new E(e)}static fromMilliseconds(e){return e instanceof E?e:e instanceof rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.milliseconds(e):new E(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new E(e).valueOf()}greaterThan(e){return this.valueOf()>new E(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new E(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new E(e).valueOf()}remainder(e){return ti(this,e)}truncate(e){return new E(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(E.DAY),t=this.truncate(E.HOUR),r=this.truncate(E.MINUTE),i=this.truncate(E.SECOND),a=this.truncate(E.MILLISECOND),o=this.truncate(E.MICROSECOND),l=this.truncate(E.NANOSECOND),u=e,h=t.sub(e),f=r.sub(t),d=i.sub(r),j=a.sub(i),$=o.sub(a),re=l.sub(o);let L="";return u.isZero||(L+=`${u.days}d `),h.isZero||(L+=`${h.hours}h `),f.isZero||(L+=`${f.minutes}m `),d.isZero||(L+=`${d.seconds}s `),j.isZero||(L+=`${j.milliseconds}ms `),$.isZero||(L+=`${$.microseconds}µs `),re.isZero||(L+=`${re.nanoseconds}ns`),L.trim()}mult(e){return new E(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(E.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new E(e).valueOf()}add(e){return new E(this.valueOf()+new E(e).valueOf())}sub(e){return new E(this.valueOf()-new E(e).valueOf())}static nanoseconds(e=1){return new E(e)}static microseconds(e=1){return E.nanoseconds(Me(e,1e3))}static milliseconds(e=1){return E.microseconds(Me(e,1e3))}static seconds(e=1){return E.milliseconds(Me(e,1e3))}static minutes(e=1){return E.seconds(Me(e,60))}static hours(e){return E.minutes(Me(e,60))}static days(e){return E.hours(Me(e,24))}};m(x,"NANOSECOND",x.nanoseconds(1)),m(x,"MICROSECOND",x.microseconds(1)),m(x,"MILLISECOND",x.milliseconds(1)),m(x,"SECOND",x.seconds(1)),m(x,"MINUTE",x.minutes(1)),m(x,"HOUR",x.hours(1)),m(x,"DAY",x.days(1)),m(x,"MAX",new x((1n<<63n)-1n)),m(x,"MIN",new x(0)),m(x,"ZERO",new x(0)),m(x,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(n=>new x(n.value)),s.z.string().transform(n=>new x(BigInt(n))),s.z.instanceof(Number).transform(n=>new x(n)),s.z.number().transform(n=>new x(n)),s.z.instanceof(x)]));let D=x;const pt=class sn extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new sn(e).valueOf()}get period(){return D.seconds(1/this.valueOf())}sampleCount(e){return new D(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new X(t).valueOf()}span(e){return D.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new sn(e)}static khz(e){return sn.hz(e*1e3)}};m(pt,"z",s.z.union([s.z.number().transform(n=>new pt(n)),s.z.instanceof(Number).transform(n=>new pt(n)),s.z.instanceof(pt)]));let rs=pt;const W=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new yr(e*this.valueOf())}};m(W,"UNKNOWN",new W(0)),m(W,"BIT128",new W(16)),m(W,"BIT64",new W(8)),m(W,"BIT32",new W(4)),m(W,"BIT16",new W(2)),m(W,"BIT8",new W(1)),m(W,"z",s.z.union([s.z.number().transform(n=>new W(n)),s.z.instanceof(Number).transform(n=>new W(n)),s.z.instanceof(W)]));let X=W;const oe=class an{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new M(e.start),this.end=new M(e.end)):(this.start=new M(e),this.end=new M(t))}get span(){return new D(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new an(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=D.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const i=M.max(r.start,e.start),a=M.min(r.end,e.end);return a.before(i)?!1:new D(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let r=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return r<0&&(r=-r),i<0&&(i=-i),r<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof an?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new an(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(oe,"MAX",new oe(M.MIN,M.MAX)),m(oe,"MIN",new oe(M.MAX,M.MIN)),m(oe,"ZERO",new oe(M.ZERO,M.ZERO)),m(oe,"z",s.z.union([s.z.object({start:M.z,end:M.z}).transform(n=>new oe(n.start,n.end)),s.z.instanceof(oe)]));let Ar=oe;const g=class B extends String{constructor(e){if(e instanceof B||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=B.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(B.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=B.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(B.JSON)||this.equals(B.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(B.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=B.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(B.UINT8)||this.equals(B.UINT16)||this.equals(B.UINT32)||this.equals(B.UINT64)}get isSigned(){return this.equals(B.INT8)||this.equals(B.INT16)||this.equals(B.INT32)||this.equals(B.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(B.INT32)&&e.equals(B.FLOAT64)||this.equals(B.INT8)&&e.equals(B.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return B.BIG_INT_TYPES.some(e=>e.equals(this))}};m(g,"UNKNOWN",new g("unknown")),m(g,"FLOAT64",new g("float64")),m(g,"FLOAT32",new g("float32")),m(g,"INT64",new g("int64")),m(g,"INT32",new g("int32")),m(g,"INT16",new g("int16")),m(g,"INT8",new g("int8")),m(g,"UINT64",new g("uint64")),m(g,"UINT32",new g("uint32")),m(g,"UINT16",new g("uint16")),m(g,"UINT8",new g("uint8")),m(g,"BOOLEAN",g.UINT8),m(g,"TIMESTAMP",new g("timestamp")),m(g,"UUID",new g("uuid")),m(g,"STRING",new g("string")),m(g,"JSON",new g("json")),m(g,"ARRAY_CONSTRUCTORS",new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]])),m(g,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]])),m(g,"DENSITIES",new Map([[g.UINT8.toString(),X.BIT8],[g.UINT16.toString(),X.BIT16],[g.UINT32.toString(),X.BIT32],[g.UINT64.toString(),X.BIT64],[g.FLOAT32.toString(),X.BIT32],[g.FLOAT64.toString(),X.BIT64],[g.INT8.toString(),X.BIT8],[g.INT16.toString(),X.BIT16],[g.INT32.toString(),X.BIT32],[g.INT64.toString(),X.BIT64],[g.TIMESTAMP.toString(),X.BIT64],[g.STRING.toString(),X.UNKNOWN],[g.JSON.toString(),X.UNKNOWN],[g.UUID.toString(),X.BIT128]])),m(g,"ALL",[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON]),m(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),m(g,"z",s.z.union([s.z.string().transform(n=>new g(n)),s.z.instanceof(g)]));let A=g;const J=class q extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return q.bytes(this.valueOf()+e.valueOf())}sub(e){return q.bytes(this.valueOf()-e.valueOf())}truncate(e){return new q(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return q.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/q.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/q.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/q.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/q.TERABYTE.valueOf()}toString(){const e=this.truncate(q.TERABYTE),t=this.truncate(q.GIGABYTE),r=this.truncate(q.MEGABYTE),i=this.truncate(q.KILOBYTE),a=this.truncate(q.BYTE),o=e,l=t.sub(e),u=r.sub(t),h=i.sub(r),f=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!f.isZero||d==="")&&(d+=`${f.valueOf()}B`),d.trim()}static bytes(e=1){return new q(e)}static kilobytes(e=1){return q.bytes(e.valueOf()*1e3)}static megabytes(e=1){return q.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return q.megabytes(e.valueOf()*1e3)}static terabytes(e){return q.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};m(J,"BYTE",new J(1)),m(J,"KILOBYTE",J.kilobytes(1)),m(J,"MEGABYTE",J.megabytes(1)),m(J,"GIGABYTE",J.gigabytes(1)),m(J,"TERABYTE",J.terabytes(1)),m(J,"ZERO",new J(0)),m(J,"z",s.z.union([s.z.number().transform(n=>new J(n)),s.z.instanceof(J)]));let yr=J;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 ni=n=>{const e=typeof n;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||n instanceof M||n instanceof D||n instanceof Date},dc=(n,e,t,r=0)=>n.usesBigInt&&!e.usesBigInt?Number(t)-Number(r):!n.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(r.valueOf()):wt(t,-r).valueOf(),fc=n=>n==null?!1:Array.isArray(n)||n instanceof ArrayBuffer||ArrayBuffer.isView(n)&&!(n instanceof DataView)||n instanceof pc?!0:ni(n),Te=-1,yc=s.z.string().transform(n=>new Uint8Array(atob(n).split("").map(e=>e.charCodeAt(0))).buffer),gc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),gr=10,mt=class ce{constructor(e){m(this,"key",""),m(this,"isSynnaxSeries",!0),m(this,"dataType"),m(this,"sampleOffset"),m(this,"gl"),m(this,"_data"),m(this,"_timeRange"),m(this,"alignment",0n),m(this,"_cachedMin"),m(this,"_cachedMax"),m(this,"writePos",Te),m(this,"_refCount",0),m(this,"_cachedLength"),m(this,"_cachedIndexes"),fc(e)&&(e={data:e});const{dataType:t,timeRange:r,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=uc()}=e,u=e.data??[];if(u instanceof ce||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=ni(u),f=Array.isArray(u);if(t!=null)this.dataType=new A(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(f||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=A.STRING;else if(typeof d=="number")this.dataType=A.FLOAT64;else if(typeof d=="bigint")this.dataType=A.INT64;else if(typeof d=="boolean")this.dataType=A.BOOLEAN;else if(d instanceof M||d instanceof Date||d instanceof M)this.dataType=A.TIMESTAMP;else if(typeof d=="object")this.dataType=A.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new A(u)}if(!f&&!h)this._data=u;else{let d=h?[u]:u;const j=d[0];(j instanceof M||j instanceof Date||j instanceof D)&&(d=d.map($=>new M($).valueOf())),this.dataType.equals(A.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
1
|
+
"use strict";var Do=Object.defineProperty;var Mo=(r,e,t)=>e in r?Do(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var c=(r,e,t)=>Mo(r,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("zod"),b=r=>Array.isArray(r)?r:[r],Wn="policy",Fn="allow_all";var Bo=Object.defineProperty,Zo=(r,e,t)=>e in r?Bo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,A=(r,e,t)=>Zo(r,typeof e!="symbol"?e+"":e,t);const Uo=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},vi=r=>{const e=(t,n=$n)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!nn(t))return t;n=qo(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(nn(l)?Es(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&Ns(l)&&(l=[...l].map(h=>{let f=h;return nn(h)?Es(f,n.keepTypesOnRecursion)||(f=e(h,n)):Ns(h)&&(f=e({key:h},n).key),f}))),i[u]=l}),i};return e},Oi=vi(Uo),Lo=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),_o=vi(Lo),$n={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},qo=(r=$n)=>(r.recursive==null?r=$n:r.recursiveInArray??(r.recursiveInArray=!1),r),Ns=r=>r!=null&&Array.isArray(r),nn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Es=(r,e)=>(e||[]).some(t=>r instanceof t),Ni=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Yo=Object.defineProperty,Wo=(r,e,t)=>e in r?Yo(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Dt=(r,e,t)=>Wo(r,typeof e!="symbol"?e+"":e,t);let Fo=class{constructor(){Dt(this,"contentType","application/json"),Dt(this,"decoder"),Dt(this,"encoder"),this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r)).buffer}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Oi(t);return e!=null?e.parse(n):n}encodeString(r){const e=_o(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):Ni(n)&&"encode_value"in n?typeof n.value=="bigint"?n.value.toString():n.value:typeof n=="bigint"?n.toString():n)}static registerCustomType(){}},Go=class{constructor(){Dt(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||!Ni(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(n=>{const i=e.map(a=>JSON.stringify(n[a]??""));t.push(i.join(","))}),t.join(`
|
|
2
|
+
`)}decodeString(r,e){const[t,...n]=r.trim().split(`
|
|
3
|
+
`).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const i=t.split(",").map(o=>o.trim()),a={};return i.forEach(o=>{a[o]=[]}),n.forEach(o=>{const l=o.split(",").map(u=>u.trim());i.forEach((u,h)=>{const f=this.parseValue(l[h]);f!=null&&a[u].push(f)})}),e!=null?e.parse(a):a}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}static registerCustomType(){}},Vo=class{constructor(){Dt(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 yr=new Fo;new Go;new Vo;const Jo=r=>r!=null&&typeof r=="object"&&"toString"in r,Ko=(r,e=!1)=>{const t=Jo(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?Ho(n):n},Ho=r=>(e,t)=>r(t,e),Pr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Ei=s.z.object({width:s.z.number(),height:s.z.number()}),Xo=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Qo=["width","height"];s.z.enum(Qo);const ec=["start","center","end"],tc=["signedWidth","signedHeight"];s.z.enum(tc);const Er=s.z.object({x:s.z.number(),y:s.z.number()}),rc=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),nc=["x","y"],zi=s.z.enum(nc),Si=["top","right","bottom","left"];s.z.enum(Si);const sc=["left","right"],Ii=s.z.enum(sc),ic=["top","bottom"],$i=s.z.enum(ic),ki=["center"],zs=s.z.enum(ki),ac=[...Si,...ki],Ai=s.z.enum(ac);s.z.enum(ec);const oc=["first","last"];s.z.enum(oc);const cc=s.z.object({lower:s.z.number(),upper:s.z.number()}),lc=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([cc,Pr]);s.z.union([lc,Pr]);s.z.enum([...zi.options,...Ai.options]);s.z.union([zi,Ai,s.z.instanceof(String)]);const uc=r=>typeof r=="bigint"||r instanceof BigInt,_e=(r,e)=>uc(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),De=(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 Ss(r);return Ss(t)},Ss=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Is=(r,e)=>{const t=De(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:Ii.or(zs),y:$i.or(zs)});const hc=s.z.object({x:Ii,y:$i}),dc=Object.freeze({x:"left",y:"top"}),fc=(r,e)=>r.x===e.x&&r.y===e.y,$s=s.z.union([s.z.number(),Er,Pr,Ei,Xo,rc]),yc=(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}},ks=Object.freeze({x:0,y:0}),cr=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:cr,left:cr,width:cr,height:cr});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Er,two:Er,root:hc});const Gn=(r,e,t=0,n=0,i)=>{const a={one:{...ks},two:{...ks},root:i??dc};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))},sn=r=>{const e=Gn(r);return{lower:e.one.x,upper:e.two.x}},an=r=>{const e=Gn(r);return{lower:e.one.y,upper:e.two.y}},pc=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,gc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Ei,gc,Er,Pr]);var mc=Object.defineProperty,wc=(r,e,t)=>e in r?mc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,be=(r,e,t)=>wc(r,typeof e!="symbol"?e+"":e,t);const bc=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:$s,scale:$s});s.z.object({offset:s.z.number(),scale:s.z.number()});const Tc=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],vc=r=>(e,t,n,i)=>[e,i?n/r:n*r],Oc=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const f=(n-i)*(h/u)+o;return[r,f]},Nc=r=>(e,t,n)=>[r,n],Ec=()=>(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)]},zc=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=bc(n,i,a),[e,n]},kn=class Ot{constructor(){be(this,"ops",[]),be(this,"currBounds",null),be(this,"currType",null),be(this,"reversed",!1),this.ops=[]}static translate(e){return new Ot().translate(e)}static magnify(e){return new Ot().magnify(e)}static scale(e,t){return new Ot().scale(e,t)}translate(e){const t=this.new(),n=Tc(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=vc(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=De(e,t),i=this.new(),a=Oc(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=De(e,t),i=this.new(),a=zc(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=De(e,t),i=this.new(),a=Nc(n);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Ec();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Ot;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};be(kn,"IDENTITY",new kn);let As=kn;const xs=class me{constructor(e=new As,t=new As,n=null){be(this,"x"),be(this,"y"),be(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new me().translate(e,t)}static translateX(e){return new me().translateX(e)}static translateY(e){return new me().translateY(e)}static clamp(e){return new me().clamp(e)}static magnify(e){return new me().magnify(e)}static scale(e){return new me().scale(e)}static reBound(e){return new me().reBound(e)}translate(e,t){const n=yc(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(pc(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!fc(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(sn(e)),t.y=t.y.scale(an(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(sn(e)),t.y=this.y.reBound(an(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(sn(e)),t.y=this.y.clamp(an(e)),t}copy(){const e=new me;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Gn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};be(xs,"IDENTITY",new xs);var Sc=Object.defineProperty,Ic=(r,e,t)=>e in r?Sc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,m=(r,e,t)=>Ic(r,typeof e!="symbol"?e+"":e,t);let $c=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const kc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Ac=$c(kc,11),xc=()=>Ac(),Rc=s.z.enum(["static","dynamic"]),xi=(r,e)=>{const t=new M(e);if(![D.DAY,D.HOUR,D.MINUTE,D.SECOND,D.MILLISECOND,D.MICROSECOND,D.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 M?new M(n):new D(n)},R=class T{constructor(e,t="UTC"){if(m(this,"value"),m(this,"encodeValue",!0),e==null)this.value=T.now().valueOf();else if(e instanceof Date)this.value=BigInt(e.getTime())*T.MILLISECOND.valueOf();else if(typeof e=="string")this.value=T.parseDateTimeString(e,t).valueOf();else if(Array.isArray(e))this.value=T.parseDate(e);else{let n=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=T.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=T.MAX:e=T.MIN)),this.value=BigInt(e.valueOf())+n}}static parseDate([e=1970,t=1,n=1]){const i=new Date(e,t-1,n,0,0,0,0);return new T(BigInt(i.getTime())*T.MILLISECOND.valueOf()).truncate(T.DAY).valueOf()}encode(){return this.value.toString()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=T.hours(parseInt(n??"00")).add(T.minutes(parseInt(i??"00"))).add(T.seconds(parseInt(o??"00"))).add(T.milliseconds(parseInt(l??"00")));return t==="local"&&(u=u.add(T.utcOffset)),u.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return T.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new T(BigInt(n.getTime())*T.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(T.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new D(BigInt(new Date().getTimezoneOffset())*T.MINUTE.valueOf())}static since(e){return new T().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new T(e).valueOf()}span(e){return this.range(e).span}range(e){return new Vn(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new T(e).valueOf()}afterEq(e){return this.valueOf()>=new T(e).valueOf()}before(e){return this.valueOf()<new T(e).valueOf()}beforeEq(e){return this.valueOf()<=new T(e).valueOf()}add(e){return new T(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new T(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(D.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(D.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(D.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(D.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new T(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new T(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new T(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new T(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new T(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new T(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new T(t)}toString(){return this.date().toISOString()}remainder(e){return xi(this,e)}get isToday(){return this.truncate(D.DAY).equals(T.now().truncate(D.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new T(new Date)}static max(...e){let t=T.MIN;for(const n of e){const i=new T(n);i.after(t)&&(t=i)}return t}static min(...e){let t=T.MAX;for(const n of e){const i=new T(n);i.before(t)&&(t=i)}return t}static nanoseconds(e){return new T(e)}static microseconds(e){return T.nanoseconds(e*1e3)}static milliseconds(e){return T.microseconds(e*1e3)}static seconds(e){return T.milliseconds(e*1e3)}static minutes(e){return T.seconds(e*60)}static hours(e){return T.minutes(e*60)}static days(e){return T.hours(e*24)}};m(R,"NANOSECOND",R.nanoseconds(1)),m(R,"MICROSECOND",R.microseconds(1)),m(R,"MILLISECOND",R.milliseconds(1)),m(R,"SECOND",R.seconds(1)),m(R,"MINUTE",R.minutes(1)),m(R,"HOUR",R.hours(1)),m(R,"DAY",R.days(1)),m(R,"MAX",new R((1n<<63n)-1n)),m(R,"MIN",new R(0)),m(R,"ZERO",new R(0)),m(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 M=R;const C=class E{constructor(e){m(this,"value"),m(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof E?e:e instanceof Rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.seconds(e):new E(e)}static fromMilliseconds(e){return e instanceof E?e:e instanceof Rs?e.period:e instanceof M?new E(e):["number","bigint"].includes(typeof e)?E.milliseconds(e):new E(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new E(e).valueOf()}greaterThan(e){return this.valueOf()>new E(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new E(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new E(e).valueOf()}remainder(e){return xi(this,e)}truncate(e){return new E(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(E.DAY),t=this.truncate(E.HOUR),n=this.truncate(E.MINUTE),i=this.truncate(E.SECOND),a=this.truncate(E.MILLISECOND),o=this.truncate(E.MICROSECOND),l=this.truncate(E.NANOSECOND),u=e,h=t.sub(e),f=n.sub(t),d=i.sub(n),k=a.sub(i),S=o.sub(a),se=l.sub(o);let L="";return u.isZero||(L+=`${u.days}d `),h.isZero||(L+=`${h.hours}h `),f.isZero||(L+=`${f.minutes}m `),d.isZero||(L+=`${d.seconds}s `),k.isZero||(L+=`${k.milliseconds}ms `),S.isZero||(L+=`${S.microseconds}µs `),se.isZero||(L+=`${se.nanoseconds}ns`),L.trim()}mult(e){return new E(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(E.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(E.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(E.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(E.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(E.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(E.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new E(e).valueOf()}add(e){return new E(this.valueOf()+new E(e).valueOf())}sub(e){return new E(this.valueOf()-new E(e).valueOf())}static nanoseconds(e=1){return new E(e)}static microseconds(e=1){return E.nanoseconds(_e(e,1e3))}static milliseconds(e=1){return E.microseconds(_e(e,1e3))}static seconds(e=1){return E.milliseconds(_e(e,1e3))}static minutes(e=1){return E.seconds(_e(e,60))}static hours(e){return E.minutes(_e(e,60))}static days(e){return E.hours(_e(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 D=C;const Nt=class pr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new pr(e).valueOf()}get period(){return D.seconds(1/this.valueOf())}sampleCount(e){return new D(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new ee(t).valueOf()}span(e){return D.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new pr(e)}static khz(e){return pr.hz(e*1e3)}};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)]));let Rs=Nt;const W=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new An(e*this.valueOf())}};m(W,"UNKNOWN",new W(0)),m(W,"BIT128",new W(16)),m(W,"BIT64",new W(8)),m(W,"BIT32",new W(4)),m(W,"BIT16",new W(2)),m(W,"BIT8",new W(1)),m(W,"z",s.z.union([s.z.number().transform(r=>new W(r)),s.z.instanceof(Number).transform(r=>new W(r)),s.z.instanceof(W)]));let ee=W;const ce=class gr{constructor(e,t){m(this,"start"),m(this,"end"),typeof e=="object"&&"start"in e?(this.start=new M(e.start),this.end=new M(e.end)):(this.start=new M(e),this.end=new M(t))}get span(){return new D(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new gr(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=D.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=M.max(n.start,e.start),a=M.min(n.end,e.end);return a.before(i)?!1:new D(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 gr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new gr(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(ce,"MAX",new ce(M.MIN,M.MAX)),m(ce,"MIN",new ce(M.MAX,M.MIN)),m(ce,"ZERO",new ce(M.ZERO,M.ZERO)),m(ce,"z",s.z.union([s.z.object({start:M.z,end:M.z}).transform(r=>new ce(r.start,r.end)),s.z.instanceof(ce)]));let Vn=ce;const p=class B extends String{constructor(e){if(e instanceof B||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=B.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(B.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=B.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(B.JSON)||this.equals(B.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(B.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=B.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(B.UINT8)||this.equals(B.UINT16)||this.equals(B.UINT32)||this.equals(B.UINT64)}get isSigned(){return this.equals(B.INT8)||this.equals(B.INT16)||this.equals(B.INT32)||this.equals(B.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(B.INT32)&&e.equals(B.FLOAT64)||this.equals(B.INT8)&&e.equals(B.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return B.BIG_INT_TYPES.some(e=>e.equals(this))}};m(p,"UNKNOWN",new p("unknown")),m(p,"FLOAT64",new p("float64")),m(p,"FLOAT32",new p("float32")),m(p,"INT64",new p("int64")),m(p,"INT32",new p("int32")),m(p,"INT16",new p("int16")),m(p,"INT8",new p("int8")),m(p,"UINT64",new p("uint64")),m(p,"UINT32",new p("uint32")),m(p,"UINT16",new p("uint16")),m(p,"UINT8",new p("uint8")),m(p,"BOOLEAN",p.UINT8),m(p,"TIMESTAMP",new p("timestamp")),m(p,"UUID",new p("uuid")),m(p,"STRING",new p("string")),m(p,"JSON",new p("json")),m(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),m(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),m(p,"DENSITIES",new Map([[p.UINT8.toString(),ee.BIT8],[p.UINT16.toString(),ee.BIT16],[p.UINT32.toString(),ee.BIT32],[p.UINT64.toString(),ee.BIT64],[p.FLOAT32.toString(),ee.BIT32],[p.FLOAT64.toString(),ee.BIT64],[p.INT8.toString(),ee.BIT8],[p.INT16.toString(),ee.BIT16],[p.INT32.toString(),ee.BIT32],[p.INT64.toString(),ee.BIT64],[p.TIMESTAMP.toString(),ee.BIT64],[p.STRING.toString(),ee.UNKNOWN],[p.JSON.toString(),ee.UNKNOWN],[p.UUID.toString(),ee.BIT128]])),m(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),m(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),m(p,"z",s.z.union([s.z.string().transform(r=>new p(r)),s.z.instanceof(p)]));let x=p;const K=class _ extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return _.bytes(this.valueOf()+e.valueOf())}sub(e){return _.bytes(this.valueOf()-e.valueOf())}truncate(e){return new _(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return _.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/_.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/_.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/_.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/_.TERABYTE.valueOf()}toString(){const e=this.truncate(_.TERABYTE),t=this.truncate(_.GIGABYTE),n=this.truncate(_.MEGABYTE),i=this.truncate(_.KILOBYTE),a=this.truncate(_.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),f=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!f.isZero||d==="")&&(d+=`${f.valueOf()}B`),d.trim()}static bytes(e=1){return new _(e)}static kilobytes(e=1){return _.bytes(e.valueOf()*1e3)}static megabytes(e=1){return _.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return _.megabytes(e.valueOf()*1e3)}static terabytes(e){return _.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 An=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)]);const Ri=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof M||r instanceof D||r instanceof Date},Cc=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):Et(t,-n).valueOf(),Et=(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),Pc=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Mc?!0:Ri(r),ze=-1,jc=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Dc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),xn=10,zt=class le{constructor(e){m(this,"key",""),m(this,"isSynnaxSeries",!0),m(this,"dataType"),m(this,"sampleOffset"),m(this,"gl"),m(this,"_data"),m(this,"_timeRange"),m(this,"alignment",0n),m(this,"_cachedMin"),m(this,"_cachedMax"),m(this,"writePos",ze),m(this,"_refCount",0),m(this,"_cachedLength"),m(this,"_cachedIndexes"),Pc(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=xc()}=e,u=e.data??[];if(u instanceof le||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=Ri(u),f=Array.isArray(u);if(t!=null)this.dataType=new x(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(f||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=x.STRING;else if(typeof d=="number")this.dataType=x.FLOAT64;else if(typeof d=="bigint")this.dataType=x.INT64;else if(typeof d=="boolean")this.dataType=x.BOOLEAN;else if(d instanceof M||d instanceof Date||d instanceof M)this.dataType=x.TIMESTAMP;else if(typeof d=="object")this.dataType=x.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new x(u)}if(!f&&!h)this._data=u;else{let d=h?[u]:u;const k=d[0];(k instanceof M||k instanceof Date||k instanceof D)&&(d=d.map(S=>new M(S).valueOf())),this.dataType.equals(x.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
4
4
|
`)}
|
|
5
|
-
`).buffer):this.dataType.equals(
|
|
5
|
+
`).buffer):this.dataType.equals(x.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(S=>yr.encodeString(S)).join(`
|
|
6
6
|
`)}
|
|
7
|
-
`).buffer):this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=
|
|
7
|
+
`).buffer):this.dataType.usesBigInt&&typeof k=="number"?this._data=new this.dataType.Array(d.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof k=="bigint"?this._data=new this.dataType.Array(d.map(S=>Number(S))).buffer:this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new x(t).Array(e),a=new le({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static createTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(t.span(o)).valueOf());return new le({data:a,dataType:x.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(`${e.join(`
|
|
8
8
|
`)}
|
|
9
|
-
`);return new
|
|
9
|
+
`);return new le({data:n,dataType:x.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(`${e.map(i=>yr.encodeString(i)).join(`
|
|
10
10
|
`)}
|
|
11
|
-
`);return new
|
|
12
|
-
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(
|
|
13
|
-
`).slice(0,-1).map(t=>e.parse(rn.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new yr(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Te?this.byteCapacity:this.dataType.isVariable?new yr(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Te?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((r,i)=>{r===gr&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let i=0;i<this.length;i++)r[i]=dc(this.dataType,e,this.data[i],t);return new ce({data:r.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(A.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,r)=>t>r?t:r)}else{const e=this.data;this._cachedMax=e.reduce((t,r)=>t>r?t:r)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),wt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(A.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,r)=>t<r?t:r)}else{const e=this.data;this._cachedMin=e.reduce((t,r)=>t<r?t:r)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),wt(this._cachedMin,this.sampleOffset))}get bounds(){return Re(Number(this.min),Number(this.max))}maybeRecomputeMinMax(e){if(this._cachedMin!=null){const t=e._cachedMin??e.calcRawMin();t<this._cachedMin&&(this._cachedMin=t)}if(this._cachedMax!=null){const t=e._cachedMax??e.calcRawMax();t>this._cachedMax&&(this._cachedMax=t)}}enrich(){this.max,this.min}get range(){return wt(this.max,-this.min)}atAlignment(e,t){const r=Number(e-this.alignment);if(r<0||r>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return wt(r,this.sampleOffset)}atVariable(e,t){let r=0,i=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===gr){if(e===0){i=o;break}r=o+1,e--}if(i===0&&(i=this.data.length),r>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,i);return this.dataType.equals(A.STRING)?new TextDecoder().decode(a):Gs(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,r=this.length-1;const i=$o(e);for(;t<=r;){const a=Math.floor((t+r)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:r=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(A.FLOAT32)&&!this.dataType.equals(A.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:r,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Te){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Te}as(e){if(e==="string"){if(!this.dataType.equals(A.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(A.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:{lower:ls(this.alignmentBounds.lower),upper:ls(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return Re(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 mc(this);return this.dataType.equals(A.JSON)?new wc(e):e}return new bc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ss(this,e,t??this.length)}subAlignmentIterator(e,t){return new ss(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,t);return new ce({data:r,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,r){if(t<=0&&(r==null||r>=this.length))return this;let i;return e?i=this.data.subarray(t,r):i=this.data.slice(t,r),new ce({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ce({data:this.buffer,dataType:this.dataType,timeRange:Ar.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(mt,"crudeZ",s.z.object({timeRange:Ar.z.optional(),dataType:A.z,alignment:ic.optional(),data:s.z.union([yc,gc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:hc.optional().default("static").optional()})),m(mt,"z",mt.crudeZ.transform(n=>new mt(n)));let pc=mt;class ss{constructor(e,t,r){m(this,"series"),m(this,"end"),m(this,"index"),this.series=e;const i=Re(0,e.length);this.end=Xr(i,r),this.index=Xr(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}class mc{constructor(e){if(m(this,"series"),m(this,"index"),m(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==gr;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}[Symbol.iterator](){return this}}var is,as;class wc{constructor(e){m(this,"wrapped"),m(this,is,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:rn.decodeString(e.value)}}[(as=Symbol.iterator,is=Symbol.toStringTag,as)](){return this}}var os,cs;class bc{constructor(e){m(this,"series"),m(this,"index"),m(this,os,"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)}}[(cs=Symbol.iterator,os=Symbol.toStringTag,cs)](){return this}}const wt=(n,e)=>typeof n=="bigint"&&typeof e=="bigint"||typeof n=="number"&&typeof e=="number"?n+e:e===0?n:n===0?e:Number(n)+Number(e),ls=n=>{const e=n>>32n,t=n&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const ri=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Tc=ri(),si=["macOS","Windows","Linux"],vc=["macos","windows","linux"],Oc={macos:"macOS",windows:"Windows",linux:"Linux"},zc=s.z.enum(si).or(s.z.enum(vc).transform(n=>Oc[n])),Ec=()=>{if(typeof window>"u")return;const n=window.navigator.userAgent.toLowerCase();if(n.includes("mac"))return"macOS";if(n.includes("win"))return"Windows";if(n.includes("linux"))return"Linux"};let Wn;const Nc=(n={})=>{const{force:e,default:t}=n;return e??Wn??(Wn=Ec(),Wn??t)},ii=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:si,RUNTIME:Tc,detect:ri,getOS:Nc,osZ:zc},Symbol.toStringTag,{value:"Module"}));var Sc=Object.defineProperty,Ic=(n,e,t)=>e in n?Sc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,bt=(n,e,t)=>Ic(n,typeof e!="symbol"?e+"":e,t);const kc=(...n)=>n.map(ai).join(""),ai=n=>(n.endsWith("/")||(n+="/"),n.startsWith("/")&&(n=n.slice(1)),n),$c=n=>n.endsWith("/")?n.slice(0,-1):n,Ac=(n,e="")=>n===null?"":`?${Object.entries(n).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,r])=>`${e}${t}=${r}`).join("&")}`,pr=class mr{constructor({host:e,port:t,protocol:r="",pathPrefix:i=""}){bt(this,"protocol"),bt(this,"host"),bt(this,"port"),bt(this,"path"),this.protocol=r,this.host=e,this.port=t,this.path=ai(i)}replace(e){return new mr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new mr({...this,pathPrefix:kc(this.path,e)})}toString(){return $c(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};bt(pr,"UNKNOWN",new pr({host:"unknown",port:0}));let Rc=pr;var xc=Object.defineProperty,Cc=(n,e,t)=>e in n?xc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,on=(n,e,t)=>Cc(n,typeof e!="symbol"?e+"":e,t);const Pc=async n=>await new Promise(e=>setTimeout(e,D.fromMilliseconds(n).milliseconds)),Dc=s.z.object({interval:D.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),jc=(n={})=>{const e=n.sleepFn||Pc,t=n.maxRetries??5,r=n.scale??1;let i=0,a=new D(n.interval??D.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(r),i++,!0)},Mc=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:Dc,create:jc},Symbol.toStringTag,{value:"Module"})),Be=class extends Number{};on(Be,"Absolute",255),on(Be,"Default",1),on(Be,"z",s.z.union([s.z.instanceof(Be),s.z.number().int().min(0).max(255).transform(n=>new Be(n)),s.z.instanceof(Number).transform(n=>new Be(n))]));s.z.object({name:s.z.string(),key:s.z.string()});const oi=class Tt extends Error{constructor(){super(Tt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(Tt.MESSAGE):e instanceof Tt||e.message.includes(Tt.MESSAGE)}};on(oi,"MESSAGE","canceled");let Bc=oi;new Bc;s.z.string().regex(/^\d+\.\d+\.\d+$/);const te=n=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.includes(n):e instanceof Error?e.message.includes(n):typeof e!="string"?!1:e.includes(n);class ae extends Error{constructor(){super(...arguments),k(this,"discriminator","FreighterError"),k(this,"type","")}}const Uc=n=>{if(n==null||typeof n!="object")return!1;const e=n;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},us="unknown",hs="nil",Zc="freighter",Bt=s.z.object({type:s.z.string(),data:s.z.string()});class Lc{constructor(){k(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:hs,data:""};if(Uc(e))for(const t of this.providers){const r=t.encode(e);if(r!=null)return r}return{type:us,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===hs)return null;if(e.type===us)return new ds(e.data);for(const t of this.providers){const r=t.decode(e);if(r!=null)return r}return new ds(e.data)}}const ci=new Lc,li=({encode:n,decode:e})=>ci.register({encode:n,decode:e}),mn=n=>ci.decode(n);class ds extends ae{constructor(){super(...arguments),k(this,"type","unknown")}}const In="freighter.",cn=class ui extends ae{constructor(){super("EOF"),k(this,"type",ui.TYPE)}};k(cn,"TYPE",`${In}eof`),k(cn,"matches",te(cn.TYPE));let Ie=cn;const ln=class hi extends ae{constructor(){super("StreamClosed"),k(this,"type",hi.TYPE)}};k(ln,"TYPE",`${In}stream_closed`),k(ln,"matches",te(ln.TYPE));let rt=ln;const un=class di extends ae{constructor(e={}){const{message:t="Unreachable",url:r=Rc.UNKNOWN}=e;super(t),k(this,"type",di.TYPE),k(this,"url"),this.url=r}};k(un,"TYPE",`${In}unreachable`),k(un,"matches",te(un.TYPE));let ke=un;const qc=n=>{if(!n.type.startsWith(Zc))return null;if(Ie.matches(n))return{type:Ie.TYPE,data:"EOF"};if(rt.matches(n))return{type:rt.TYPE,data:"StreamClosed"};if(ke.matches(n))return{type:ke.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${n.type}: ${n.message}`)},Yc=n=>{if(!n.type.startsWith(In))return null;switch(n.type){case Ie.TYPE:return new Ie;case rt.TYPE:return new rt;case ke.TYPE:return new ke;default:throw new Error(`Unknown error type: ${n.data}`)}};li({encode:qc,decode:Yc});let fi=class{constructor(){k(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let r=0;const i=async a=>{if(r===this.middleware.length)return await t(a);const o=this.middleware[r];return r++,await o(a,i)};return await i(e)}};const yi="Content-Type",fs=n=>{if(ii.RUNTIME!=="node")return fetch;const e=require("node-fetch");if(n==="http")return e;const t=require("https"),r=new t.Agent({rejectUnauthorized:!1});return async(i,a)=>await e(i,{...a,agent:r})};class _c extends fi{constructor(e,t,r=!1){return super(),k(this,"endpoint"),k(this,"encoder"),k(this,"fetch"),this.endpoint=e.replace({protocol:r?"https":"http"}),this.encoder=t,this.fetch=fs(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[yi]:this.encoder.contentType}}async send(e,t,r,i){t=r==null?void 0:r.parse(t);let a=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const f={...h,params:{}};l.headers={...this.headers,...h.params};let d;try{d=await fs(h.protocol)(h.target,l)}catch($){let re=$;return re.message==="Load failed"&&(re=new ke({url:o})),[f,re]}const j=await d.arrayBuffer();if(d!=null&&d.ok)return i!=null&&(a=this.encoder.decode(j,i)),[f,null];try{if(d.status!==400)return[f,new Error(d.statusText)];const $=this.encoder.decode(j,Bt),re=mn($);return[f,re]}catch($){return[f,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${$.message}`)]}});return[a,u]}}const Wc=(n,e)=>{class t{constructor(i){k(this,"wrapped"),this.wrapped=i}use(...i){this.wrapped.use(...i)}async send(i,a,o,l){const u=Mc.create(e);do{const[h,f]=await this.wrapped.send(i,a,o,l);if(f==null||!ke.matches(f))return[h,f];if(!await u())return[h,f]}while(!0)}}return new t(n)},w=async(n,e,t,r,i)=>{const[a,o]=await n.send(e,t,r,i);if(o!=null)throw o;return a},Gc=()=>ii.RUNTIME!=="node"?n=>new WebSocket(n):n=>new(require("ws")).WebSocket(n,{rejectUnauthorized:!1}),Fc=s.z.object({type:s.z.union([s.z.literal("data"),s.z.literal("close"),s.z.literal("open")]),payload:s.z.unknown().optional(),error:s.z.optional(Bt)});class Vc{constructor(e,t,r,i){k(this,"encoder"),k(this,"reqSchema"),k(this,"resSchema"),k(this,"ws"),k(this,"serverClosed"),k(this,"sendClosed"),k(this,"receiveDataQueue",[]),k(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=r,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return mn(e.error)}return null}send(e){if(this.serverClosed!=null)return new Ie;if(this.sendClosed)throw new rt;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=mn(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,r)=>this.receiveCallbacksQueue.push({resolve:t,reject:r}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=e=>this.addMessage(this.encoder.decode(e.data,Fc)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:Qc(e)?Ie.TYPE:rt.TYPE,data:""}})}}const Jc="freighterctx",Kc=1e3,Hc=1001,Xc=[Kc,Hc],Qc=n=>Xc.includes(n.code),gi=class pi extends fi{constructor(e,t,r=!1){super(),k(this,"baseUrl"),k(this,"encoder"),this.baseUrl=e.replace({protocol:r?"wss":"ws"}),this.encoder=t}async stream(e,t,r){const i=Gc();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=pi.MESSAGE_TYPE;const f=await this.wrapSocket(u,t,r);return f instanceof Error?[h,f]:(a=f,[h,null])});if(o!=null)throw o;return a}buildURL(e,t){const r=Ac({[yi]:this.encoder.contentType,...t.params},Jc);return this.baseUrl.child(e).toString()+r}async wrapSocket(e,t,r){return await new Promise(i=>{e.onopen=()=>{const a=new Vc(e,this.encoder,t,r);a.receiveOpenAck().then(o=>{o!=null?i(o):i(a)}).catch(o=>i(o))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};k(gi,"MESSAGE_TYPE","arraybuffer");let el=gi;const wn=s.z.union([s.z.literal("all"),s.z.literal("create"),s.z.literal("delete"),s.z.literal("retrieve"),s.z.literal("update")]),tl="all",nl="create",rl="delete",sl="retrieve",il="update",al=n=>{const e=n.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},mi=n=>{const e=(t,r=wr)=>{if(typeof t=="string")return n(t);if(Array.isArray(t))return t.map(o=>e(o,r));if(!Gn(t))return t;r=ll(r);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=n(o);r.recursive&&(Gn(l)?gs(l,r.keepTypesOnRecursion)||(l=e(l,r)):r.recursiveInArray&&ys(l)&&(l=[...l].map(h=>{let f=h;return Gn(h)?gs(f,r.keepTypesOnRecursion)||(f=e(h,r)):ys(h)&&(f=e({key:h},r).key),f}))),i[u]=l}),i};return e},wi=mi(al),ol=n=>n.replace(/([a-z0-9])([A-Z])/g,(e,t,r)=>`${t}_${r.toLowerCase()}`),cl=mi(ol),wr={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},ll=(n=wr)=>(n.recursive==null?n=wr:n.recursiveInArray??(n.recursiveInArray=!1),n),ys=n=>n!=null&&Array.isArray(n),Gn=n=>n!=null&&typeof n=="object"&&!Array.isArray(n),gs=(n,e)=>(e||[]).some(t=>n instanceof t),Rr=n=>n!=null&&typeof n=="object"&&!Array.isArray(n);var ul=Object.defineProperty,hl=(n,e,t)=>e in n?ul(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,kt=(n,e,t)=>hl(n,typeof e!="symbol"?e+"":e,t);let bi=class{constructor(){kt(this,"contentType","application/json"),kt(this,"decoder"),kt(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 r=JSON.parse(e),i=wi(r);return t!=null?t.parse(i):i}encodeString(e){const t=cl(e);return JSON.stringify(t,(r,i)=>ArrayBuffer.isView(i)?Array.from(i):Rr(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},Ti=class{constructor(){kt(this,"contentType","text/csv")}encode(e){const t=this.encodeString(e);return new TextEncoder().encode(t).buffer}decode(e,t){const r=new TextDecoder().decode(e);return this.decodeString(r,t)}encodeString(e){if(!Array.isArray(e)||e.length===0||!Rr(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),r=[t.join(",")];return e.forEach(i=>{const a=t.map(o=>JSON.stringify(i[o]??""));r.push(a.join(","))}),r.join(`
|
|
14
|
-
`)}decodeString(e,t){const[
|
|
15
|
-
`).map(l=>l.trim());if(r.length===0)return t!=null?t.parse({}):{};const a=r.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,f)=>{const d=this.parseValue(u[f]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},vi=class{constructor(){kt(this,"contentType","text/plain")}encode(e){return new TextEncoder().encode(e).buffer}decode(e,t){const r=new TextDecoder().decode(e);return t!=null?t.parse(r):r}};const nt=new bi,dl=new Ti,fl=new vi,yl=[nt],lt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Ti,CSV_CODEC:dl,ENCODERS:yl,JSONCodec:bi,JSON_CODEC:nt,TEXT_CODEC:fl,TextCodec:vi},Symbol.toStringTag,{value:"Module"})),gl=n=>[...new Set(n)],pl=(n,e,t=!0)=>{const r=new Map;return n.forEach(i=>{const a=e(i);if(r.has(a)){if(t)return;r.delete(a)}r.set(a,i)}),Array.from(r.values())},ps=Object.freeze(Object.defineProperty({__proto__:null,by:pl,unique:gl},Symbol.toStringTag,{value:"Module"})),ml=n=>n!=null&&typeof n=="object"&&"toString"in n,wl=(n,e=!1)=>{const t=ml(n)?"stringer":typeof n;let r;switch(t){case"string":r=(i,a)=>i.localeCompare(a);break;case"stringer":r=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":r=(i,a)=>Number(i)-Number(a);break;case"bigint":r=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":r=(i,a)=>Number(i)-Number(a);break;case"undefined":r=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?bl(r):r},bl=n=>(e,t)=>n(t,e),kn=0,Fn=-1,Vn=1,Tl=n=>n<kn,vl=n=>n>kn,Ol=n=>n===kn,$n=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Oi=s.z.object({width:s.z.number(),height:s.z.number()}),zl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),El=["width","height"];s.z.enum(El);const Nl=["start","center","end"],Sl=["signedWidth","signedHeight"];s.z.enum(Sl);const bn=s.z.object({x:s.z.number(),y:s.z.number()}),Il=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),kl=["x","y"],zi=s.z.enum(kl),Ei=["top","right","bottom","left"];s.z.enum(Ei);const $l=["left","right"],Ni=s.z.enum($l),Al=["top","bottom"],Si=s.z.enum(Al),Ii=["center"],ms=s.z.enum(Ii),Rl=[...Ei,...Ii],ki=s.z.enum(Rl);s.z.enum(Nl);const xl=["first","last"];s.z.enum(xl);const Cl=s.z.object({lower:s.z.number(),upper:s.z.number()}),Pl=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Cl,$n]);s.z.union([Pl,$n]);s.z.union([zi,ki]);s.z.union([zi,ki,s.z.instanceof(String)]);const ut=n=>typeof n=="bigint"||n instanceof BigInt,Jn=(n,e)=>ut(n)?n.valueOf()-BigInt(e.valueOf().valueOf()):n.valueOf()-Number(e.valueOf()),Dl=(n,e)=>ut(n)?n.valueOf()+BigInt(e.valueOf().valueOf()):n+Number(e.valueOf()),ws=(n,e)=>ut(n)?n===BigInt(e.valueOf().valueOf()):n===Number(e.valueOf()),jl=(n,e)=>ut(n)?n.valueOf()<BigInt(e.valueOf())?n:BigInt(e.valueOf()):n.valueOf()<Number(e.valueOf())?n:Number(e.valueOf()),Ml=n=>ut(n)||n instanceof BigInt?n.valueOf()<0n?-n:n:n.valueOf()<0?-n:n,Ue=(n,e)=>ut(n)?n.valueOf()*BigInt(e.valueOf()):n.valueOf()*Number(e.valueOf()),Q=(n,e)=>{const t={};if(typeof n=="number"||typeof n=="bigint")e!=null?(t.lower=n,t.upper=e):(t.lower=typeof n=="bigint"?0n:0,t.upper=n);else if(Array.isArray(n)){if(n.length!==2)throw new Error("bounds: expected array of length 2");[t.lower,t.upper]=n}else return bs(n);return bs(t)},bs=n=>n.lower>n.upper?{lower:n.upper,upper:n.lower}:n,Ts=(n,e)=>{const t=Q(n);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},Xt=(n,e)=>{const t=Q(n);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const r=Q(e);return r.lower>=t.lower&&r.upper<=t.upper},Bl=(n,e,t)=>{const r=n.map(l=>Q(l)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;ws(a,0)===!1;){const l=r.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(l!==-1){const u=r[l];let h;if(i>0?h=Jn(u.upper,o):h=Jn(o,u.lower),h>0){const f=jl(Ml(a),h);if(o=Dl(o,i>0?f:-f),a=Jn(a,i>0?f:-f),ws(a,0))return o;continue}}if(i>0){const u=r.filter(h=>h.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=r.filter(h=>h.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},Ul=(n,e,t)=>{const r=n.map(o=>Q(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?Q([e,t]):Q([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of r){const l=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(l<u){const h=u-l;a=a+h}}return a};s.z.object({x:Ni.or(ms),y:Si.or(ms)});const Zl=s.z.object({x:Ni,y:Si}),Ll=Object.freeze({x:"left",y:"top"}),ql=(n,e)=>n.x===e.x&&n.y===e.y,vs=s.z.union([s.z.number(),bn,$n,Oi,zl,Il]),Yl=(n,e)=>{if(typeof n=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return n==="x"?{x:e,y:0}:{x:0,y:e}}return typeof n=="number"?{x:n,y:e??n}:Array.isArray(n)?{x:n[0],y:n[1]}:"signedWidth"in n?{x:n.signedWidth,y:n.signedHeight}:"clientX"in n?{x:n.clientX,y:n.clientY}:"width"in n?{x:n.width,y:n.height}:{x:n.x,y:n.y}},Os=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:bn,two:bn,root:Zl});const xr=(n,e,t=0,r=0,i)=>{const a={one:{...Os},two:{...Os},root:i??Ll};if(typeof n=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return a.one={x:n,y:e},a.two={x:a.one.x+t,y:a.one.y+r},a}return"one"in n&&"two"in n&&"root"in n?{...n,root:i??n.root}:("getBoundingClientRect"in n&&(n=n.getBoundingClientRect()),"left"in n?(a.one={x:n.left,y:n.top},a.two={x:n.right,y:n.bottom},a):(a.one=n,e==null?a.two={x:a.one.x+t,y:a.one.y+r}: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))},Kn=n=>{const e=xr(n);return{lower:e.one.x,upper:e.two.x}},Hn=n=>{const e=xr(n);return{lower:e.one.y,upper:e.two.y}},_l=n=>typeof n!="object"||n==null?!1:"one"in n&&"two"in n&&"root"in n,Wl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Oi,Wl,bn,$n]);var Gl=Object.defineProperty,Fl=(n,e,t)=>e in n?Gl(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,pe=(n,e,t)=>Fl(n,typeof e!="symbol"?e+"":e,t);const Vl=(n,e,t)=>e!==void 0&&n<e?e:t!==void 0&&n>t?t:n;s.z.object({offset:vs,scale:vs});s.z.object({offset:s.z.number(),scale:s.z.number()});const Jl=n=>(e,t,r,i)=>t==="dimension"?[e,r]:[e,i?r-n:r+n],Kl=n=>(e,t,r,i)=>[e,i?r/n:r*n],Hl=n=>(e,t,r)=>{if(e===null)return[n,r];const{lower:i,upper:a}=e,{lower:o,upper:l}=n,u=a-i,h=l-o;if(t==="dimension")return[n,r*(h/u)];const f=(r-i)*(h/u)+o;return[n,f]},Xl=n=>(e,t,r)=>[n,r],Ql=()=>(n,e,t)=>{if(n===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[n,t];const{lower:r,upper:i}=n;return[n,i-(t-r)]},eu=n=>(e,t,r)=>{const{lower:i,upper:a}=n;return r=Vl(r,i,a),[e,r]},br=class vt{constructor(){pe(this,"ops",[]),pe(this,"currBounds",null),pe(this,"currType",null),pe(this,"reversed",!1),this.ops=[]}static translate(e){return new vt().translate(e)}static magnify(e){return new vt().magnify(e)}static scale(e,t){return new vt().scale(e,t)}translate(e){const t=this.new(),r=Jl(e);return r.type="translate",t.ops.push(r),t}magnify(e){const t=this.new(),r=Kl(e);return r.type="magnify",t.ops.push(r),t}scale(e,t){const r=Q(e,t),i=this.new(),a=Hl(r);return a.type="scale",i.ops.push(a),i}clamp(e,t){const r=Q(e,t),i=this.new(),a=eu(r);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const r=Q(e,t),i=this.new(),a=Xl(r);return a.type="re-bound",i.ops.push(a),i}invert(){const e=Ql();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new vt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([r,i],a)=>a(r,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((r,i)=>{if(r.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([r,i])=>{const a=e.ops.slice(r,i);a.unshift(e.ops[i]),e.ops.splice(r,i-r+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};pe(br,"IDENTITY",new br);let zs=br;const Es=class ye{constructor(e=new zs,t=new zs,r=null){pe(this,"x"),pe(this,"y"),pe(this,"currRoot"),this.x=e,this.y=t,this.currRoot=r}static translate(e,t){return new ye().translate(e,t)}static translateX(e){return new ye().translateX(e)}static translateY(e){return new ye().translateY(e)}static clamp(e){return new ye().clamp(e)}static magnify(e){return new ye().magnify(e)}static scale(e){return new ye().scale(e)}static reBound(e){return new ye().reBound(e)}translate(e,t){const r=Yl(e,t),i=this.copy();return i.x=this.x.translate(r.x),i.y=this.y.translate(r.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(_l(e)){const r=this.currRoot;return t.currRoot=e.root,r!=null&&!ql(r,e.root)&&(r.x!==e.root.x&&(t.x=t.x.invert()),r.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Kn(e)),t.y=t.y.scale(Hn(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(Kn(e)),t.y=this.y.reBound(Hn(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Kn(e)),t.y=this.y.clamp(Hn(e)),t}copy(){const e=new ye;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return xr(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};pe(Es,"IDENTITY",new Es);const tu=s.z.bigint().or(s.z.string().transform(BigInt));var nu=Object.defineProperty,ru=(n,e,t)=>e in n?nu(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,y=(n,e,t)=>ru(n,typeof e!="symbol"?e+"":e,t);let su=(n,e=21)=>(t=e)=>{let r="",i=t|0;for(;i--;)r+=n[Math.random()*n.length|0];return r};const iu="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",$i=su(iu,11),au=Object.freeze(Object.defineProperty({__proto__:null,id:$i},Symbol.toStringTag,{value:"Module"})),ou=s.z.enum(["static","dynamic"]),Ai=(n,e)=>{const t=new I(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(i=>i.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const r=n.valueOf()%t.valueOf();return n instanceof I?new I(r):new z(r)},C=class v{constructor(e,t="UTC"){if(y(this,"value"),y(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 r=BigInt(0);e instanceof Number&&(e=e.valueOf()),t==="local"&&(r=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())+r}}static parseDate([e=1970,t=1,r=1]){const i=new Date(e,t-1,r,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[r,i,a]=e.split(":");let o="00",l="00";a!=null&&([o,l]=a.split("."));let u=v.hours(parseInt(r??"00")).add(v.minutes(parseInt(i??"00"))).add(v.seconds(parseInt(o??"00"))).add(v.milliseconds(parseInt(l??"00")));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 r=new Date(e);return e.includes(":")||r.setUTCHours(0,0,0,0),new v(BigInt(r.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 r=this.toISOString(t);return e?r.slice(11,23):r.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),r=e.toLocaleString("default",{day:"numeric"});return`${t} ${r}`}static get utcOffset(){return new z(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 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 v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new v(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new v(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new v(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new v(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new v(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new v(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new v(t)}toString(){return this.date().toISOString()}remainder(e){return Ai(this,e)}get isToday(){return this.truncate(z.DAY).equals(v.now().truncate(z.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 r of e){const i=new v(r);i.after(t)&&(t=i)}return t}static min(...e){let t=v.MAX;for(const r of e){const i=new v(r);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)}};y(C,"NANOSECOND",C.nanoseconds(1)),y(C,"MICROSECOND",C.microseconds(1)),y(C,"MILLISECOND",C.milliseconds(1)),y(C,"SECOND",C.seconds(1)),y(C,"MINUTE",C.minutes(1)),y(C,"HOUR",C.hours(1)),y(C,"DAY",C.days(1)),y(C,"MAX",new C((1n<<63n)-1n)),y(C,"MIN",new C(0)),y(C,"ZERO",new C(0)),y(C,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(n=>new C(n.value)),s.z.string().transform(n=>new C(BigInt(n))),s.z.instanceof(Number).transform(n=>new C(n)),s.z.number().transform(n=>new C(n)),s.z.instanceof(C)]));let I=C;const P=class N{constructor(e){y(this,"value"),y(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof N?e:e instanceof st?e.period:e instanceof I?new N(e):["number","bigint"].includes(typeof e)?N.seconds(e):new N(e)}static fromMilliseconds(e){return e instanceof N?e:e instanceof st?e.period:e instanceof I?new N(e):["number","bigint"].includes(typeof e)?N.milliseconds(e):new N(e)}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 Ai(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),r=this.truncate(N.MINUTE),i=this.truncate(N.SECOND),a=this.truncate(N.MILLISECOND),o=this.truncate(N.MICROSECOND),l=this.truncate(N.NANOSECOND),u=e,h=t.sub(e),f=r.sub(t),d=i.sub(r),j=a.sub(i),$=o.sub(a),re=l.sub(o);let L="";return u.isZero||(L+=`${u.days}d `),h.isZero||(L+=`${h.hours}h `),f.isZero||(L+=`${f.minutes}m `),d.isZero||(L+=`${d.seconds}s `),j.isZero||(L+=`${j.milliseconds}ms `),$.isZero||(L+=`${$.microseconds}µs `),re.isZero||(L+=`${re.nanoseconds}ns`),L.trim()}mult(e){return new N(this.valueOf()*BigInt(e))}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(Ue(e,1e3))}static milliseconds(e=1){return N.microseconds(Ue(e,1e3))}static seconds(e=1){return N.milliseconds(Ue(e,1e3))}static minutes(e=1){return N.seconds(Ue(e,60))}static hours(e){return N.minutes(Ue(e,60))}static days(e){return N.hours(Ue(e,24))}};y(P,"NANOSECOND",P.nanoseconds(1)),y(P,"MICROSECOND",P.microseconds(1)),y(P,"MILLISECOND",P.milliseconds(1)),y(P,"SECOND",P.seconds(1)),y(P,"MINUTE",P.minutes(1)),y(P,"HOUR",P.hours(1)),y(P,"DAY",P.days(1)),y(P,"MAX",new P((1n<<63n)-1n)),y(P,"MIN",new P(0)),y(P,"ZERO",new P(0)),y(P,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(n=>new P(n.value)),s.z.string().transform(n=>new P(BigInt(n))),s.z.instanceof(Number).transform(n=>new P(n)),s.z.number().transform(n=>new P(n)),s.z.instanceof(P)]));let z=P;const Ot=class hn extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new hn(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new H(t).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new hn(e)}static khz(e){return hn.hz(e*1e3)}};y(Ot,"z",s.z.union([s.z.number().transform(n=>new Ot(n)),s.z.instanceof(Number).transform(n=>new Ot(n)),s.z.instanceof(Ot)]));let st=Ot;const G=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new it(e*this.valueOf())}};y(G,"UNKNOWN",new G(0)),y(G,"BIT128",new G(16)),y(G,"BIT64",new G(8)),y(G,"BIT32",new G(4)),y(G,"BIT16",new G(2)),y(G,"BIT8",new G(1)),y(G,"z",s.z.union([s.z.number().transform(n=>new G(n)),s.z.instanceof(Number).transform(n=>new G(n)),s.z.instanceof(G)]));let H=G;const le=class dn{constructor(e,t){y(this,"start"),y(this,"end"),typeof e=="object"&&"start"in e?(this.start=new I(e.start),this.end=new I(e.end)):(this.start=new I(e),this.end=new I(t))}get span(){return new z(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new dn(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=z.ZERO){e=e.makeValid();const r=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(r.start)||r.end.equals(e.start))return!1;const i=I.max(r.start,e.start),a=I.min(r.end,e.end);return a.before(i)?!1:new z(a.sub(i)).greaterThanOrEqual(t)}roughlyEquals(e,t){let r=this.start.sub(e.start).valueOf(),i=this.end.sub(e.end).valueOf();return r<0&&(r=-r),i<0&&(i=-i),r<=t.valueOf()&&i<=t.valueOf()}contains(e){return e instanceof dn?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new dn(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}};y(le,"MAX",new le(I.MIN,I.MAX)),y(le,"MIN",new le(I.MAX,I.MIN)),y(le,"ZERO",new le(I.ZERO,I.ZERO)),y(le,"z",s.z.union([s.z.object({start:I.z,end:I.z}).transform(n=>new le(n.start,n.end)),s.z.instanceof(le)]));let F=le;const cu=(n,e)=>n.start.before(e.start)?-1:n.start.after(e.start)?1:n.end.before(e.end)?-1:n.end.after(e.end)?1:0,p=class U extends String{constructor(e){if(e instanceof U||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=U.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(U.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=U.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(U.JSON)||this.equals(U.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(U.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=U.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(U.UINT8)||this.equals(U.UINT16)||this.equals(U.UINT32)||this.equals(U.UINT64)}get isSigned(){return this.equals(U.INT8)||this.equals(U.INT16)||this.equals(U.INT32)||this.equals(U.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(U.INT32)&&e.equals(U.FLOAT64)||this.equals(U.INT8)&&e.equals(U.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return U.BIG_INT_TYPES.some(e=>e.equals(this))}};y(p,"UNKNOWN",new p("unknown")),y(p,"FLOAT64",new p("float64")),y(p,"FLOAT32",new p("float32")),y(p,"INT64",new p("int64")),y(p,"INT32",new p("int32")),y(p,"INT16",new p("int16")),y(p,"INT8",new p("int8")),y(p,"UINT64",new p("uint64")),y(p,"UINT32",new p("uint32")),y(p,"UINT16",new p("uint16")),y(p,"UINT8",new p("uint8")),y(p,"BOOLEAN",p.UINT8),y(p,"TIMESTAMP",new p("timestamp")),y(p,"UUID",new p("uuid")),y(p,"STRING",new p("string")),y(p,"JSON",new p("json")),y(p,"ARRAY_CONSTRUCTORS",new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]])),y(p,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]])),y(p,"DENSITIES",new Map([[p.UINT8.toString(),H.BIT8],[p.UINT16.toString(),H.BIT16],[p.UINT32.toString(),H.BIT32],[p.UINT64.toString(),H.BIT64],[p.FLOAT32.toString(),H.BIT32],[p.FLOAT64.toString(),H.BIT64],[p.INT8.toString(),H.BIT8],[p.INT16.toString(),H.BIT16],[p.INT32.toString(),H.BIT32],[p.INT64.toString(),H.BIT64],[p.TIMESTAMP.toString(),H.BIT64],[p.STRING.toString(),H.UNKNOWN],[p.JSON.toString(),H.UNKNOWN],[p.UUID.toString(),H.BIT128]])),y(p,"ALL",[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON]),y(p,"BIG_INT_TYPES",[p.INT64,p.UINT64,p.TIMESTAMP]),y(p,"z",s.z.union([s.z.string().transform(n=>new p(n)),s.z.instanceof(p)]));let S=p;const K=class Y extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return Y.bytes(this.valueOf()+e.valueOf())}sub(e){return Y.bytes(this.valueOf()-e.valueOf())}truncate(e){return new Y(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return Y.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/Y.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/Y.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/Y.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/Y.TERABYTE.valueOf()}toString(){const e=this.truncate(Y.TERABYTE),t=this.truncate(Y.GIGABYTE),r=this.truncate(Y.MEGABYTE),i=this.truncate(Y.KILOBYTE),a=this.truncate(Y.BYTE),o=e,l=t.sub(e),u=r.sub(t),h=i.sub(r),f=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!f.isZero||d==="")&&(d+=`${f.valueOf()}B`),d.trim()}static bytes(e=1){return new Y(e)}static kilobytes(e=1){return Y.bytes(e.valueOf()*1e3)}static megabytes(e=1){return Y.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return Y.megabytes(e.valueOf()*1e3)}static terabytes(e){return Y.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};y(K,"BYTE",new K(1)),y(K,"KILOBYTE",K.kilobytes(1)),y(K,"MEGABYTE",K.megabytes(1)),y(K,"GIGABYTE",K.gigabytes(1)),y(K,"TERABYTE",K.terabytes(1)),y(K,"ZERO",new K(0)),y(K,"z",s.z.union([s.z.number().transform(n=>new K(n)),s.z.instanceof(K)]));let it=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)]);const Ri=n=>{const e=typeof n;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||n instanceof I||n instanceof z||n instanceof Date},lu=(n,e,t,r=0)=>n.usesBigInt&&!e.usesBigInt?Number(t)-Number(r):!n.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(r.valueOf()):Et(t,-r).valueOf(),uu=n=>n==null?!1:Array.isArray(n)||n instanceof ArrayBuffer||ArrayBuffer.isView(n)&&!(n instanceof DataView)||n instanceof Ee?!0:Ri(n),ve=-1,Tr={[Symbol.iterator]:()=>Tr,next:()=>({done:!0,value:void 0})},hu=s.z.string().transform(n=>new Uint8Array(atob(n).split("").map(e=>e.charCodeAt(0))).buffer),du=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),vr=10,zt=class ue{constructor(e){y(this,"key",""),y(this,"isSynnaxSeries",!0),y(this,"dataType"),y(this,"sampleOffset"),y(this,"gl"),y(this,"_data"),y(this,"_timeRange"),y(this,"alignment",0n),y(this,"_cachedMin"),y(this,"_cachedMax"),y(this,"writePos",ve),y(this,"_refCount",0),y(this,"_cachedLength"),y(this,"_cachedIndexes"),uu(e)&&(e={data:e});const{dataType:t,timeRange:r,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=$i()}=e,u=e.data??[];if(u instanceof ue||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=Ri(u),f=Array.isArray(u);if(t!=null)this.dataType=new S(t);else{if(u instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(f||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=S.STRING;else if(typeof d=="number")this.dataType=S.FLOAT64;else if(typeof d=="bigint")this.dataType=S.INT64;else if(typeof d=="boolean")this.dataType=S.BOOLEAN;else if(d instanceof I||d instanceof Date||d instanceof I)this.dataType=S.TIMESTAMP;else if(typeof d=="object")this.dataType=S.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new S(u)}if(!f&&!h)this._data=u;else{let d=h?[u]:u;const j=d[0];(j instanceof I||j instanceof Date||j instanceof z)&&(d=d.map($=>new I($).valueOf())),this.dataType.equals(S.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
11
|
+
`);return new le({data:n,dataType:x.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===ze)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===ze)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this._cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===ze?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(x.STRING,x.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
|
|
12
|
+
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(x.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=x.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(x.JSON))throw new Error("cannot parse non-JSON series as JSON");return new TextDecoder().decode(this.underlyingData).split(`
|
|
13
|
+
`).slice(0,-1).map(t=>e.parse(yr.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new An(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ze?this.byteCapacity:this.dataType.isVariable?new An(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ze?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===xn&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=Cc(this.dataType,e,this.data[i],t);return new 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(x.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),Et(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(x.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),Et(this._cachedMin,this.sampleOffset))}get bounds(){return De(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 Et(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return Et(n,this.sampleOffset)}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===xn){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(x.STRING)?new TextDecoder().decode(a):Oi(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Ko(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(x.FLOAT32)&&!this.dataType.equals(x.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer: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!==ze){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ze}as(e){if(e==="string"){if(!this.dataType.equals(x.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(x.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:{lower:Bs(this.alignmentBounds.lower),upper:Bs(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return De(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 Bc(this);return this.dataType.equals(x.JSON)?new Zc(e):e}return new Uc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Cs(this,e,t??this.length)}subAlignmentIterator(e,t){return new Cs(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new le({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new le({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new le({data:this.buffer,dataType:this.dataType,timeRange:Vn.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};m(zt,"crudeZ",s.z.object({timeRange:Vn.z.optional(),dataType:x.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([jc,Dc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Rc.optional().default("static").optional()})),m(zt,"z",zt.crudeZ.transform(r=>new zt(r)));let Mc=zt;class Cs{constructor(e,t,n){m(this,"series"),m(this,"end"),m(this,"index"),this.series=e;const i=De(0,e.length);this.end=Is(i,n),this.index=Is(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}class Bc{constructor(e){if(m(this,"series"),m(this,"index"),m(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==xn;)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 Ps,js;class Zc{constructor(e){m(this,"wrapped"),m(this,Ps,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:yr.decodeString(e.value)}}[(js=Symbol.iterator,Ps=Symbol.toStringTag,js)](){return this}}var Ds,Ms;class Uc{constructor(e){m(this,"series"),m(this,"index"),m(this,Ds,"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)}}[(Ms=Symbol.iterator,Ds=Symbol.toStringTag,Ms)](){return this}}const Bs=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const Ci=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser",Lc=Ci(),Pi=["macOS","Windows","Linux"],_c=["macos","windows","linux"],qc={macos:"macOS",windows:"Windows",linux:"Linux"},Yc=s.z.enum(Pi).or(s.z.enum(_c).transform(r=>qc[r])),Wc=()=>{if(typeof window>"u")return;const r=window.navigator.userAgent.toLowerCase();if(r.includes("mac"))return"macOS";if(r.includes("win"))return"Windows";if(r.includes("linux"))return"Linux"};let on;const Fc=(r={})=>{const{force:e,default:t}=r;return e??on??(on=Wc(),on??t)},ji=Object.freeze(Object.defineProperty({__proto__:null,OPERATING_SYSTEMS:Pi,RUNTIME:Lc,detect:Ci,getOS:Fc,osZ:Yc},Symbol.toStringTag,{value:"Module"}));var Gc=Object.defineProperty,Vc=(r,e,t)=>e in r?Gc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,St=(r,e,t)=>Vc(r,typeof e!="symbol"?e+"":e,t);const Jc=(...r)=>r.map(Di).join(""),Di=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),Kc=r=>r.endsWith("/")?r.slice(0,-1):r,Hc=(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("&")}`,Rn=class Cn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){St(this,"protocol"),St(this,"host"),St(this,"port"),St(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=Di(i)}replace(e){return new Cn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Cn({...this,pathPrefix:Jc(this.path,e)})}toString(){return Kc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};St(Rn,"UNKNOWN",new Rn({host:"unknown",port:0}));let Xc=Rn;const Qc=-128,el=127;s.z.number().int().min(Qc).max(el);const tl=-32768,rl=32767;s.z.number().int().min(tl).max(rl);const nl=-2147483648,sl=2147483647;s.z.number().int().min(nl).max(sl);const il=-9223372036854775808n,al=9223372036854775807n;s.z.bigint().min(il).max(al);const ol=255;s.z.number().int().min(0).max(ol);const cl=65535;s.z.number().int().min(0).max(cl);const ll=4294967295;s.z.number().int().min(0).max(ll);const ul=18446744073709551615n;s.z.bigint().min(0n).max(ul);var hl=Object.defineProperty,dl=(r,e,t)=>e in r?hl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,It=(r,e,t)=>dl(r,typeof e!="symbol"?e+"":e,t);const fl=async r=>await new Promise(e=>setTimeout(e,D.fromMilliseconds(r).milliseconds)),yl=s.z.object({interval:D.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),pl=(r={})=>{const e=r.sleepFn||fl,t=r.maxRetries??5,n=r.scale??1;let i=0,a=new D(r.interval??D.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(n),i++,!0)},gl=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:yl,create:pl},Symbol.toStringTag,{value:"Module"})),ge=class extends Number{};It(ge,"ABSOLUTE",255),It(ge,"MINIMUM",0),It(ge,"BOUNDS",{lower:ge.MINIMUM,upper:ge.ABSOLUTE+1}),It(ge,"z",s.z.union([s.z.instanceof(ge),s.z.number().int().min(0).max(255).transform(r=>new ge(r)),s.z.instanceof(Number).transform(r=>new ge(r))]));s.z.object({name:s.z.string(),key:s.z.string()});const Mi=class $t extends Error{constructor(){super($t.MESSAGE)}matches(e){return typeof e=="string"?e.includes($t.MESSAGE):e instanceof $t||e.message.includes($t.MESSAGE)}};It(Mi,"MESSAGE","canceled");let ml=Mi;new ml;s.z.string().regex(/^\d+\.\d+\.\d+$/);const Q=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 oe=class extends Error{constructor(){super(...arguments),A(this,"discriminator","FreighterError"),A(this,"type","")}};const wl=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},Zs="unknown",Us="nil",bl="freighter",Vt=s.z.object({type:s.z.string(),data:s.z.string()});class Tl{constructor(){A(this,"providers",[])}register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Us,data:""};if(wl(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}return{type:Zs,data:JSON.stringify(e)}}decode(e){if(e==null||e.type===Us)return null;if(e.type===Zs)return new Ls(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Ls(e.data)}}const Bi=new Tl,Zi=({encode:r,decode:e})=>Bi.register({encode:r,decode:e}),zr=r=>Bi.decode(r);class Ls extends oe{constructor(){super(...arguments),A(this,"type","unknown")}}const jr="freighter.",mr=class Ui extends oe{constructor(){super("EOF"),A(this,"type",Ui.TYPE)}};A(mr,"TYPE",`${jr}eof`),A(mr,"matches",Q(mr.TYPE));let Re=mr;const wr=class Li extends oe{constructor(){super("StreamClosed"),A(this,"type",Li.TYPE)}};A(wr,"TYPE",`${jr}stream_closed`),A(wr,"matches",Q(wr.TYPE));let lt=wr;const br=class _i extends oe{constructor(e={}){const{message:t="Unreachable",url:n=Xc.UNKNOWN}=e;super(t),A(this,"type",_i.TYPE),A(this,"url"),this.url=n}};A(br,"TYPE",`${jr}unreachable`),A(br,"matches",Q(br.TYPE));let Ce=br;const vl=r=>{if(!r.type.startsWith(bl))return null;if(Re.matches(r))return{type:Re.TYPE,data:"EOF"};if(lt.matches(r))return{type:lt.TYPE,data:"StreamClosed"};if(Ce.matches(r))return{type:Ce.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},Ol=r=>{if(!r.type.startsWith(jr))return null;switch(r.type){case Re.TYPE:return new Re;case lt.TYPE:return new lt;case Ce.TYPE:return new Ce;default:throw new Error(`Unknown error type: ${r.data}`)}};Zi({encode:vl,decode:Ol});let qi=class{constructor(){A(this,"middleware",[])}use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const i=async a=>{if(n===this.middleware.length)return await t(a);const o=this.middleware[n];return n++,await o(a,i)};return await i(e)}};const Yi="Content-Type",_s=r=>{if(ji.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 Nl extends qi{constructor(e,t,n=!1){return super(),A(this,"endpoint"),A(this,"encoder"),A(this,"fetch"),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,this.fetch=_s(this.endpoint.protocol),new Proxy(this,{get:(i,a,o)=>a==="endpoint"?this.endpoint:Reflect.get(i,a,o)})}get headers(){return{[Yi]:this.encoder.contentType}}async send(e,t,n,i){t=n==null?void 0:n.parse(t);let a=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,u]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async h=>{const f={...h,params:{}};l.headers={...this.headers,...h.params};let d;try{d=await _s(h.protocol)(h.target,l)}catch(S){let se=S;return se.message==="Load failed"&&(se=new Ce({url:o})),[f,se]}const k=await d.arrayBuffer();if(d!=null&&d.ok)return i!=null&&(a=this.encoder.decode(k,i)),[f,null];try{if(d.status!==400)return[f,new Error(d.statusText)];const S=this.encoder.decode(k,Vt),se=zr(S);return[f,se]}catch(S){return[f,new Error(`[freighter] - failed to decode error: ${d.statusText}: ${S.message}`)]}});return[a,u]}}const El=(r,e)=>{class t{constructor(i){A(this,"wrapped"),this.wrapped=i}use(...i){this.wrapped.use(...i)}async send(i,a,o,l){const u=gl.create(e);do{const[h,f]=await this.wrapped.send(i,a,o,l);if(f==null||!Ce.matches(f))return[h,f];if(!await u())return[h,f]}while(!0)}}return new t(r)},w=async(r,e,t,n,i)=>{const[a,o]=await r.send(e,t,n,i);if(o!=null)throw o;return a},zl=()=>ji.RUNTIME!=="node"?r=>new WebSocket(r):r=>new(require("ws")).WebSocket(r,{rejectUnauthorized:!1}),Sl=s.z.object({type:s.z.enum(["data","close","open"]),payload:s.z.unknown().optional(),error:s.z.optional(Vt)});class Il{constructor(e,t,n,i){A(this,"encoder"),A(this,"reqSchema"),A(this,"resSchema"),A(this,"ws"),A(this,"serverClosed"),A(this,"sendClosed"),A(this,"receiveDataQueue",[]),A(this,"receiveCallbacksQueue",[]),this.encoder=t,this.reqSchema=n,this.resSchema=i,this.ws=e,this.sendClosed=!1,this.serverClosed=null,this.listenForMessages()}async receiveOpenAck(){const e=await this.receiveMsg();if(e.type!=="open"){if(e.error==null)throw new Error("Message error must be defined");return zr(e.error)}return null}send(e){if(this.serverClosed!=null)return new Re;if(this.sendClosed)throw new lt;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,Sl)),this.ws.onclose=e=>this.addMessage({type:"close",error:{type:Rl(e)?Re.TYPE:lt.TYPE,data:""}})}}const $l="freighterctx",kl=1e3,Al=1001,xl=[kl,Al],Rl=r=>xl.includes(r.code),Wi=class Fi extends qi{constructor(e,t,n=!1){super(),A(this,"baseUrl"),A(this,"encoder"),this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}async stream(e,t,n){const i=zl();let a;const[,o]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async l=>{const u=i(this.buildURL(e,l)),h={...l,params:{}};u.binaryType=Fi.MESSAGE_TYPE;const f=await this.wrapSocket(u,t,n);return f instanceof Error?[h,f]:(a=f,[h,null])});if(o!=null)throw o;return a}buildURL(e,t){const n=Hc({[Yi]:this.encoder.contentType,...t.params},$l);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(i=>{e.onopen=()=>{const a=new Il(e,this.encoder,t,n);a.receiveOpenAck().then(o=>{o!=null?i(o):i(a)}).catch(o=>i(o))},e.onerror=a=>{const o=a;i(new Error(o.message))}})}};A(Wi,"MESSAGE_TYPE","arraybuffer");let Cl=Wi;const Gi="all",Vi="create",Ji="delete",Ki="retrieve",Hi="update",Sr=s.z.enum([Gi,Vi,Ji,Ki,Hi]),Pl=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Xi=r=>{const e=(t,n=Pn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!cn(t))return t;n=Ml(n);const i={},a=t;return Object.keys(a).forEach(o=>{let l=a[o];const u=r(o);n.recursive&&(cn(l)?Ys(l,n.keepTypesOnRecursion)||(l=e(l,n)):n.recursiveInArray&&qs(l)&&(l=[...l].map(h=>{let f=h;return cn(h)?Ys(f,n.keepTypesOnRecursion)||(f=e(h,n)):qs(h)&&(f=e({key:h},n).key),f}))),i[u]=l}),i};return e},Qi=Xi(Pl),jl=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Dl=Xi(jl),Pn={recursive:!0,recursiveInArray:!0,keepTypesOnRecursion:[Number,String,Uint8Array]},Ml=(r=Pn)=>(r.recursive==null?r=Pn:r.recursiveInArray??(r.recursiveInArray=!1),r),qs=r=>r!=null&&Array.isArray(r),cn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Ys=(r,e)=>(e||[]).some(t=>r instanceof t),Jn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);var Bl=Object.defineProperty,Zl=(r,e,t)=>e in r?Bl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Mt=(r,e,t)=>Zl(r,typeof e!="symbol"?e+"":e,t);let ea=class{constructor(){Mt(this,"contentType","application/json"),Mt(this,"decoder"),Mt(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=Qi(n);return t!=null?t.parse(i):i}encodeString(e){const t=Dl(e);return JSON.stringify(t,(n,i)=>ArrayBuffer.isView(i)?Array.from(i):Jn(i)&&"encode_value"in i?typeof i.value=="bigint"?i.value.toString():i.value:typeof i=="bigint"?i.toString():i)}static registerCustomType(){}},ta=class{constructor(){Mt(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||!Jn(e[0]))throw new Error("Payload must be an array of objects");const t=Object.keys(e[0]),n=[t.join(",")];return e.forEach(i=>{const a=t.map(o=>JSON.stringify(i[o]??""));n.push(a.join(","))}),n.join(`
|
|
14
|
+
`)}decodeString(e,t){const[n,...i]=e.trim().split(`
|
|
15
|
+
`).map(l=>l.trim());if(n.length===0)return t!=null?t.parse({}):{};const a=n.split(",").map(l=>l.trim()),o={};return a.forEach(l=>{o[l]=[]}),i.forEach(l=>{const u=l.split(",").map(h=>h.trim());a.forEach((h,f)=>{const d=this.parseValue(u[f]);d!=null&&o[h].push(d)})}),t!=null?t.parse(o):o}parseValue(e){if(e==null||e.length===0)return null;const t=Number(e);return isNaN(t)?e.startsWith('"')&&e.endsWith('"')?e.slice(1,-1):e:t}static registerCustomType(){}},ra=class{constructor(){Mt(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 ct=new ea,Ul=new ta,Ll=new ra,_l=[ct],Jt=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:ta,CSV_CODEC:Ul,ENCODERS:_l,JSONCodec:ea,JSON_CODEC:ct,TEXT_CODEC:Ll,TextCodec:ra},Symbol.toStringTag,{value:"Module"})),ql=r=>[...new Set(r)],Yl=(r,e,t=!0)=>{const n=new Map;return r.forEach(i=>{const a=e(i);if(n.has(a)){if(t)return;n.delete(a)}n.set(a,i)}),Array.from(n.values())},Ws=Object.freeze(Object.defineProperty({__proto__:null,by:Yl,unique:ql},Symbol.toStringTag,{value:"Module"})),Wl=r=>r!=null&&typeof r=="object"&&"toString"in r,Fl=(r,e=!1)=>{const t=Wl(r)?"stringer":typeof r;let n;switch(t){case"string":n=(i,a)=>i.localeCompare(a);break;case"stringer":n=(i,a)=>i.toString().localeCompare(a.toString());break;case"number":n=(i,a)=>Number(i)-Number(a);break;case"bigint":n=(i,a)=>BigInt(i)-BigInt(a)>0n?1:-1;break;case"boolean":n=(i,a)=>Number(i)-Number(a);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?Gl(n):n},Gl=r=>(e,t)=>r(t,e),Dr=0,ln=-1,un=1,Vl=r=>r<Dr,Jl=r=>r>Dr,Kl=r=>r===Dr,Mr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const na=s.z.object({width:s.z.number(),height:s.z.number()}),Hl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Xl=["width","height"];s.z.enum(Xl);const Ql=["start","center","end"],eu=["signedWidth","signedHeight"];s.z.enum(eu);const Ir=s.z.object({x:s.z.number(),y:s.z.number()}),tu=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),ru=["x","y"],sa=s.z.enum(ru),ia=["top","right","bottom","left"];s.z.enum(ia);const nu=["left","right"],aa=s.z.enum(nu),su=["top","bottom"],oa=s.z.enum(su),ca=["center"],Fs=s.z.enum(ca),iu=[...ia,...ca],la=s.z.enum(iu);s.z.enum(Ql);const au=["first","last"];s.z.enum(au);const ou=s.z.object({lower:s.z.number(),upper:s.z.number()}),cu=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([ou,Mr]);s.z.union([cu,Mr]);s.z.enum([...sa.options,...la.options]);s.z.union([sa,la,s.z.instanceof(String)]);const pt=r=>typeof r=="bigint"||r instanceof BigInt,hn=(r,e)=>pt(r)?r.valueOf()-BigInt(e.valueOf().valueOf()):r.valueOf()-Number(e.valueOf()),lu=(r,e)=>pt(r)?r.valueOf()+BigInt(e.valueOf().valueOf()):r+Number(e.valueOf()),Gs=(r,e)=>pt(r)?r===BigInt(e.valueOf().valueOf()):r===Number(e.valueOf()),uu=(r,e)=>pt(r)?r.valueOf()<BigInt(e.valueOf())?r:BigInt(e.valueOf()):r.valueOf()<Number(e.valueOf())?r:Number(e.valueOf()),hu=r=>pt(r)||r instanceof BigInt?r.valueOf()<0n?-r:r:r.valueOf()<0?-r:r,qe=(r,e)=>pt(r)?r.valueOf()*BigInt(e.valueOf()):r.valueOf()*Number(e.valueOf()),te=(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 Vs(r);return Vs(t)},Vs=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Js=(r,e)=>{const t=te(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},lr=(r,e)=>{const t=te(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=te(e);return n.lower>=t.lower&&n.upper<=t.upper},du=(r,e,t)=>{const n=r.map(l=>te(l)),i=t>0?1:t<0?-1:0;if(i===0)return e;let a=t,o=e;for(;Gs(a,0)===!1;){const l=n.findIndex(u=>i>0?o>=u.lower&&o<u.upper:o>u.lower&&o<=u.upper);if(l!==-1){const u=n[l];let h;if(i>0?h=hn(u.upper,o):h=hn(o,u.lower),h>0){const f=uu(hu(a),h);if(o=lu(o,i>0?f:-f),a=hn(a,i>0?f:-f),Gs(a,0))return o;continue}}if(i>0){const u=n.filter(h=>h.lower>o);if(u.length>0)o=u[0].lower;else return o}else{const u=n.filter(h=>h.upper<o);if(u.length>0)o=u[u.length-1].upper;else return o}}return o},fu=(r,e,t)=>{const n=r.map(o=>te(o));if(e===t)return typeof e=="bigint"?0n:0;const i=e<t?te([e,t]):te([t,e]);let a=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>i.lower?o.lower:i.lower,u=o.upper<i.upper?o.upper:i.upper;if(l<u){const h=u-l;a=a+h}}return a};s.z.object({x:aa.or(Fs),y:oa.or(Fs)});const yu=s.z.object({x:aa,y:oa}),pu=Object.freeze({x:"left",y:"top"}),gu=(r,e)=>r.x===e.x&&r.y===e.y,Ks=s.z.union([s.z.number(),Ir,Mr,na,Hl,tu]),mu=(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}},Hs=Object.freeze({x:0,y:0}),ur=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:ur,left:ur,width:ur,height:ur});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Ir,two:Ir,root:yu});const Kn=(r,e,t=0,n=0,i)=>{const a={one:{...Hs},two:{...Hs},root:i??pu};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))},dn=r=>{const e=Kn(r);return{lower:e.one.x,upper:e.two.x}},fn=r=>{const e=Kn(r);return{lower:e.one.y,upper:e.two.y}},wu=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([na,bu,Ir,Mr]);var Tu=Object.defineProperty,vu=(r,e,t)=>e in r?Tu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Te=(r,e,t)=>vu(r,typeof e!="symbol"?e+"":e,t);const Ou=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:Ks,scale:Ks});s.z.object({offset:s.z.number(),scale:s.z.number()});const Nu=r=>(e,t,n,i)=>t==="dimension"?[e,n]:[e,i?n-r:n+r],Eu=r=>(e,t,n,i)=>[e,i?n/r:n*r],zu=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:i,upper:a}=e,{lower:o,upper:l}=r,u=a-i,h=l-o;if(t==="dimension")return[r,n*(h/u)];const f=(n-i)*(h/u)+o;return[r,f]},Su=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:i}=r;return[r,i-(t-n)]},$u=r=>(e,t,n)=>{const{lower:i,upper:a}=r;return n=Ou(n,i,a),[e,n]},jn=class kt{constructor(){Te(this,"ops",[]),Te(this,"currBounds",null),Te(this,"currType",null),Te(this,"reversed",!1),this.ops=[]}static translate(e){return new kt().translate(e)}static magnify(e){return new kt().magnify(e)}static scale(e,t){return new kt().scale(e,t)}translate(e){const t=this.new(),n=Nu(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=Eu(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=te(e,t),i=this.new(),a=zu(n);return a.type="scale",i.ops.push(a),i}clamp(e,t){const n=te(e,t),i=this.new(),a=$u(n);return a.type="clamp",i.ops.push(a),i}reBound(e,t){const n=te(e,t),i=this.new(),a=Su(n);return a.type="re-bound",i.ops.push(a),i}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 kt;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,i],a)=>a(n,e,i,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,i)=>{if(n.type==="scale"||t.some(([o,l])=>i>=o&&i<=l))return;const a=e.ops.findIndex((o,l)=>o.type==="scale"&&l>i);a!==-1&&t.push([i,a])}),t.forEach(([n,i])=>{const a=e.ops.slice(n,i);a.unshift(e.ops[i]),e.ops.splice(n,i-n+1,...a)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}};Te(jn,"IDENTITY",new jn);let Xs=jn;const Qs=class we{constructor(e=new Xs,t=new Xs,n=null){Te(this,"x"),Te(this,"y"),Te(this,"currRoot"),this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new we().translate(e,t)}static translateX(e){return new we().translateX(e)}static translateY(e){return new we().translateY(e)}static clamp(e){return new we().clamp(e)}static magnify(e){return new we().magnify(e)}static scale(e){return new we().scale(e)}static reBound(e){return new we().reBound(e)}translate(e,t){const n=mu(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(wu(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!gu(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(dn(e)),t.y=t.y.scale(fn(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(dn(e)),t.y=this.y.reBound(fn(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(dn(e)),t.y=this.y.clamp(fn(e)),t}copy(){const e=new we;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return Kn(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}};Te(Qs,"IDENTITY",new Qs);var ku=Object.defineProperty,Au=(r,e,t)=>e in r?ku(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,y=(r,e,t)=>Au(r,typeof e!="symbol"?e+"":e,t);let xu=(r,e=21)=>(t=e)=>{let n="",i=t|0;for(;i--;)n+=r[Math.random()*r.length|0];return n};const Ru="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Cu=xu(Ru,11),ua=()=>Cu(),Pu=Object.freeze(Object.defineProperty({__proto__:null,create:ua},Symbol.toStringTag,{value:"Module"})),ju=s.z.enum(["static","dynamic"]),ha=(r,e)=>{const t=new $(e);if(![N.DAY,N.HOUR,N.MINUTE,N.SECOND,N.MILLISECOND,N.MICROSECOND,N.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 $?new $(n):new N(n)},P=class v{constructor(e,t="UTC"){if(y(this,"value"),y(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 o="00",l="00";a!=null&&([o,l]=a.split("."));let u=v.hours(parseInt(n??"00")).add(v.minutes(parseInt(i??"00"))).add(v.seconds(parseInt(o??"00"))).add(v.milliseconds(parseInt(l??"00")));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 N(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 G(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===BigInt(0)}after(e){return this.valueOf()>new v(e).valueOf()}afterEq(e){return this.valueOf()>=new v(e).valueOf()}before(e){return this.valueOf()<new v(e).valueOf()}beforeEq(e){return this.valueOf()<=new v(e).valueOf()}add(e){return new v(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new v(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(N.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(N.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(N.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(N.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get year(){return this.date().getFullYear()}setYear(e){const t=this.date();return t.setFullYear(e),new v(t)}get month(){return this.date().getMonth()}setMonth(e){const t=this.date();return t.setMonth(e),new v(t)}get day(){return this.date().getDate()}setDay(e){const t=this.date();return t.setDate(e),new v(t)}get hour(){return this.date().getHours()}setHour(e){const t=this.date();return t.setHours(e),new v(t)}get minute(){return this.date().getMinutes()}setMinute(e){const t=this.date();return t.setMinutes(e),new v(t)}get second(){return this.date().getSeconds()}setSecond(e){const t=this.date();return t.setSeconds(e),new v(t)}get millisecond(){return this.date().getMilliseconds()}setMillisecond(e){const t=this.date();return t.setMilliseconds(e),new v(t)}toString(){return this.date().toISOString()}remainder(e){return ha(this,e)}get isToday(){return this.truncate(N.DAY).equals(v.now().truncate(N.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)}};y(P,"NANOSECOND",P.nanoseconds(1)),y(P,"MICROSECOND",P.microseconds(1)),y(P,"MILLISECOND",P.milliseconds(1)),y(P,"SECOND",P.seconds(1)),y(P,"MINUTE",P.minutes(1)),y(P,"HOUR",P.hours(1)),y(P,"DAY",P.days(1)),y(P,"MAX",new P((1n<<63n)-1n)),y(P,"MIN",new P(0)),y(P,"ZERO",new P(0)),y(P,"z",s.z.union([s.z.object({value:s.z.bigint()}).transform(r=>new P(r.value)),s.z.string().transform(r=>new P(BigInt(r))),s.z.instanceof(Number).transform(r=>new P(r)),s.z.number().transform(r=>new P(r)),s.z.instanceof(P)]));let $=P;const j=class z{constructor(e){y(this,"value"),y(this,"encodeValue",!0),typeof e=="number"&&(e=Math.trunc(e.valueOf())),this.value=BigInt(e.valueOf())}static fromSeconds(e){return e instanceof z?e:e instanceof ut?e.period:e instanceof $?new z(e):["number","bigint"].includes(typeof e)?z.seconds(e):new z(e)}static fromMilliseconds(e){return e instanceof z?e:e instanceof ut?e.period:e instanceof $?new z(e):["number","bigint"].includes(typeof e)?z.milliseconds(e):new z(e)}encode(){return this.value.toString()}valueOf(){return this.value}lessThan(e){return this.valueOf()<new z(e).valueOf()}greaterThan(e){return this.valueOf()>new z(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new z(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new z(e).valueOf()}remainder(e){return ha(this,e)}truncate(e){return new z(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(z.DAY),t=this.truncate(z.HOUR),n=this.truncate(z.MINUTE),i=this.truncate(z.SECOND),a=this.truncate(z.MILLISECOND),o=this.truncate(z.MICROSECOND),l=this.truncate(z.NANOSECOND),u=e,h=t.sub(e),f=n.sub(t),d=i.sub(n),k=a.sub(i),S=o.sub(a),se=l.sub(o);let L="";return u.isZero||(L+=`${u.days}d `),h.isZero||(L+=`${h.hours}h `),f.isZero||(L+=`${f.minutes}m `),d.isZero||(L+=`${d.seconds}s `),k.isZero||(L+=`${k.milliseconds}ms `),S.isZero||(L+=`${S.microseconds}µs `),se.isZero||(L+=`${se.nanoseconds}ns`),L.trim()}mult(e){return new z(this.valueOf()*BigInt(e))}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(z.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(z.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===BigInt(0)}equals(e){return this.valueOf()===new z(e).valueOf()}add(e){return new z(this.valueOf()+new z(e).valueOf())}sub(e){return new z(this.valueOf()-new z(e).valueOf())}static nanoseconds(e=1){return new z(e)}static microseconds(e=1){return z.nanoseconds(qe(e,1e3))}static milliseconds(e=1){return z.microseconds(qe(e,1e3))}static seconds(e=1){return z.milliseconds(qe(e,1e3))}static minutes(e=1){return z.seconds(qe(e,60))}static hours(e){return z.minutes(qe(e,60))}static days(e){return z.hours(qe(e,24))}};y(j,"NANOSECOND",j.nanoseconds(1)),y(j,"MICROSECOND",j.microseconds(1)),y(j,"MILLISECOND",j.milliseconds(1)),y(j,"SECOND",j.seconds(1)),y(j,"MINUTE",j.minutes(1)),y(j,"HOUR",j.hours(1)),y(j,"DAY",j.days(1)),y(j,"MAX",new j((1n<<63n)-1n)),y(j,"MIN",new j(0)),y(j,"ZERO",new j(0)),y(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 At=class Tr extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Tr(e).valueOf()}get period(){return N.seconds(1/this.valueOf())}sampleCount(e){return new N(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new X(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 Tr(e)}static khz(e){return Tr.hz(e*1e3)}};y(At,"z",s.z.union([s.z.number().transform(r=>new At(r)),s.z.instanceof(Number).transform(r=>new At(r)),s.z.instanceof(At)]));let ut=At;const F=class extends Number{constructor(e){e instanceof Number?super(e.valueOf()):super(e)}length(e){return e.valueOf()/this.valueOf()}size(e){return new ht(e*this.valueOf())}};y(F,"UNKNOWN",new F(0)),y(F,"BIT128",new F(16)),y(F,"BIT64",new F(8)),y(F,"BIT32",new F(4)),y(F,"BIT16",new F(2)),y(F,"BIT8",new F(1)),y(F,"z",s.z.union([s.z.number().transform(r=>new F(r)),s.z.instanceof(Number).transform(r=>new F(r)),s.z.instanceof(F)]));let X=F;const ue=class vr{constructor(e,t){y(this,"start"),y(this,"end"),typeof e=="object"&&"start"in e?(this.start=new $(e.start),this.end=new $(e.end)):(this.start=new $(e),this.end=new $(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}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new vr(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 i=$.max(n.start,e.start),a=$.min(n.end,e.end);return a.before(i)?!1:new N(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 vr?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new vr(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}};y(ue,"MAX",new ue($.MIN,$.MAX)),y(ue,"MIN",new ue($.MAX,$.MIN)),y(ue,"ZERO",new ue($.ZERO,$.ZERO)),y(ue,"z",s.z.union([s.z.object({start:$.z,end:$.z}).transform(r=>new ue(r.start,r.end)),s.z.instanceof(ue)]));let G=ue;const Du=(r,e)=>r.start.before(e.start)?-1:r.start.after(e.start)?1:r.end.before(e.end)?-1:r.end.after(e.end)?1:0,g=class Z extends String{constructor(e){if(e instanceof Z||typeof e=="string"||typeof e.valueOf()=="string"){super(e.valueOf());return}const t=Z.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t!=null){super(t.valueOf());return}throw super(Z.UNKNOWN.valueOf()),new Error(`unable to find data type for ${e.toString()}`)}get Array(){const e=Z.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(Z.JSON)||this.equals(Z.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(Z.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=Z.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsigned(){return this.equals(Z.UINT8)||this.equals(Z.UINT16)||this.equals(Z.UINT32)||this.equals(Z.UINT64)}get isSigned(){return this.equals(Z.INT8)||this.equals(Z.INT16)||this.equals(Z.INT32)||this.equals(Z.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsigned&&e.isSigned?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(Z.INT32)&&e.equals(Z.FLOAT64)||this.equals(Z.INT8)&&e.equals(Z.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsigned===e.isUnsigned:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}toJSON(){return this.toString()}get usesBigInt(){return Z.BIG_INT_TYPES.some(e=>e.equals(this))}};y(g,"UNKNOWN",new g("unknown")),y(g,"FLOAT64",new g("float64")),y(g,"FLOAT32",new g("float32")),y(g,"INT64",new g("int64")),y(g,"INT32",new g("int32")),y(g,"INT16",new g("int16")),y(g,"INT8",new g("int8")),y(g,"UINT64",new g("uint64")),y(g,"UINT32",new g("uint32")),y(g,"UINT16",new g("uint16")),y(g,"UINT8",new g("uint8")),y(g,"BOOLEAN",g.UINT8),y(g,"TIMESTAMP",new g("timestamp")),y(g,"UUID",new g("uuid")),y(g,"STRING",new g("string")),y(g,"JSON",new g("json")),y(g,"ARRAY_CONSTRUCTORS",new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]])),y(g,"ARRAY_CONSTRUCTOR_DATA_TYPES",new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]])),y(g,"DENSITIES",new Map([[g.UINT8.toString(),X.BIT8],[g.UINT16.toString(),X.BIT16],[g.UINT32.toString(),X.BIT32],[g.UINT64.toString(),X.BIT64],[g.FLOAT32.toString(),X.BIT32],[g.FLOAT64.toString(),X.BIT64],[g.INT8.toString(),X.BIT8],[g.INT16.toString(),X.BIT16],[g.INT32.toString(),X.BIT32],[g.INT64.toString(),X.BIT64],[g.TIMESTAMP.toString(),X.BIT64],[g.STRING.toString(),X.UNKNOWN],[g.JSON.toString(),X.UNKNOWN],[g.UUID.toString(),X.BIT128]])),y(g,"ALL",[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON]),y(g,"BIG_INT_TYPES",[g.INT64,g.UINT64,g.TIMESTAMP]),y(g,"z",s.z.union([s.z.string().transform(r=>new g(r)),s.z.instanceof(g)]));let I=g;const H=class q extends Number{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return q.bytes(this.valueOf()+e.valueOf())}sub(e){return q.bytes(this.valueOf()-e.valueOf())}truncate(e){return new q(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return q.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/q.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/q.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/q.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/q.TERABYTE.valueOf()}toString(){const e=this.truncate(q.TERABYTE),t=this.truncate(q.GIGABYTE),n=this.truncate(q.MEGABYTE),i=this.truncate(q.KILOBYTE),a=this.truncate(q.BYTE),o=e,l=t.sub(e),u=n.sub(t),h=i.sub(n),f=a.sub(i);let d="";return o.isZero||(d+=`${o.terabytes}TB `),l.isZero||(d+=`${l.gigabytes}GB `),u.isZero||(d+=`${u.megabytes}MB `),h.isZero||(d+=`${h.kilobytes}KB `),(!f.isZero||d==="")&&(d+=`${f.valueOf()}B`),d.trim()}static bytes(e=1){return new q(e)}static kilobytes(e=1){return q.bytes(e.valueOf()*1e3)}static megabytes(e=1){return q.kilobytes(e.valueOf()*1e3)}static gigabytes(e=1){return q.megabytes(e.valueOf()*1e3)}static terabytes(e){return q.gigabytes(e.valueOf()*1e3)}get isZero(){return this.valueOf()===0}};y(H,"BYTE",new H(1)),y(H,"KILOBYTE",H.kilobytes(1)),y(H,"MEGABYTE",H.megabytes(1)),y(H,"GIGABYTE",H.gigabytes(1)),y(H,"TERABYTE",H.terabytes(1)),y(H,"ZERO",new H(0)),y(H,"z",s.z.union([s.z.number().transform(r=>new H(r)),s.z.instanceof(H)]));let ht=H;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 da=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof $||r instanceof N||r instanceof Date},Mu=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):xt(t,-n).valueOf(),xt=(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),Bu=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof ke?!0:da(r),Se=-1,Dn={[Symbol.iterator]:()=>Dn,next:()=>({done:!0,value:void 0})},Zu=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Uu=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),Mn=10,Rt=class he{constructor(e){y(this,"key",""),y(this,"isSynnaxSeries",!0),y(this,"dataType"),y(this,"sampleOffset"),y(this,"gl"),y(this,"_data"),y(this,"_timeRange"),y(this,"alignment",0n),y(this,"_cachedMin"),y(this,"_cachedMax"),y(this,"writePos",Se),y(this,"_refCount",0),y(this,"_cachedLength"),y(this,"_cachedIndexes"),Bu(e)&&(e={data:e});const{dataType:t,timeRange:n,sampleOffset:i=0,glBufferUsage:a="static",alignment:o=0n,key:l=ua()}=e,u=e.data??[];if(u instanceof he||typeof u=="object"&&"isSynnaxSeries"in u&&u.isSynnaxSeries===!0){const d=u;this.key=d.key,this.dataType=d.dataType,this.sampleOffset=d.sampleOffset,this.gl=d.gl,this._data=d._data,this._timeRange=d._timeRange,this.alignment=d.alignment,this._cachedMin=d._cachedMin,this._cachedMax=d._cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this._cachedLength=d._cachedLength;return}const h=da(u),f=Array.isArray(u);if(t!=null)this.dataType=new I(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(f||h){let d=u;if(!h){if(u.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");d=u[0]}if(typeof d=="string")this.dataType=I.STRING;else if(typeof d=="number")this.dataType=I.FLOAT64;else if(typeof d=="bigint")this.dataType=I.INT64;else if(typeof d=="boolean")this.dataType=I.BOOLEAN;else if(d instanceof $||d instanceof Date||d instanceof $)this.dataType=I.TIMESTAMP;else if(typeof d=="object")this.dataType=I.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new I(u)}if(!f&&!h)this._data=u;else{let d=h?[u]:u;const k=d[0];(k instanceof $||k instanceof Date||k instanceof N)&&(d=d.map(S=>new $(S).valueOf())),this.dataType.equals(I.STRING)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
16
16
|
`)}
|
|
17
|
-
`).buffer):this.dataType.equals(
|
|
17
|
+
`).buffer):this.dataType.equals(I.JSON)?(this._cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(S=>ct.encodeString(S)).join(`
|
|
18
18
|
`)}
|
|
19
|
-
`).buffer):this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=
|
|
19
|
+
`).buffer):this.dataType.usesBigInt&&typeof k=="number"?this._data=new this.dataType.Array(d.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof k=="bigint"?this._data=new this.dataType.Array(d.map(S=>Number(S))).buffer:this._data=new this.dataType.Array(d).buffer}this.key=l,this.alignment=o,this.sampleOffset=i??0,this._timeRange=n,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:a}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const i=new new I(t).Array(e),a=new he({data:i.buffer,dataType:t,...n});return a.writePos=0,a}static createTimestamps(e,t,n){const i=n.spanRange(t.span(e)),a=new BigInt64Array(e);for(let o=0;o<e;o++)a[o]=BigInt(n.add(t.span(o)).valueOf());return new he({data:a,dataType:I.TIMESTAMP,timeRange:i})}get refCount(){return this._refCount}static fromStrings(e,t){const n=new TextEncoder().encode(`${e.join(`
|
|
20
20
|
`)}
|
|
21
|
-
`);return new
|
|
21
|
+
`);return new he({data:n,dataType:I.STRING,timeRange:t})}static fromJSON(e,t){const n=new TextEncoder().encode(`${e.map(i=>ct.encodeString(i)).join(`
|
|
22
22
|
`)}
|
|
23
|
-
`);return new
|
|
24
|
-
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(
|
|
25
|
-
`).slice(0,-1).map(t=>e.parse(nt.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new it(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity:this.dataType.isVariable?new it(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ve?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((r,i)=>{r===vr&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const r=new e.Array(this.length);for(let i=0;i<this.length;i++)r[i]=lu(this.dataType,e,this.data[i],t);return new ue({data:r.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,r)=>t>r?t:r)}else{const e=this.data;this._cachedMax=e.reduce((t,r)=>t>r?t:r)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),Et(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,r)=>t<r?t:r)}else{const e=this.data;this._cachedMin=e.reduce((t,r)=>t<r?t:r)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),Et(this._cachedMin,this.sampleOffset))}get bounds(){return Q(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 Et(this.max,-this.min)}atAlignment(e,t){const r=Number(e-this.alignment);if(r<0||r>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${r}`);return}return this.at(r,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const r=this.data[e];if(r==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return Et(r,this.sampleOffset)}atVariable(e,t){let r=0,i=0;if(this._cachedIndexes!=null)r=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===vr){if(e===0){i=o;break}r=o+1,e--}if(i===0&&(i=this.data.length),r>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(r,i);return this.dataType.equals(S.STRING)?new TextDecoder().decode(a):wi(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,r=this.length-1;const i=wl(e);for(;t<=r;){const a=Math.floor((t+r)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:r=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(S.FLOAT32)&&!this.dataType.equals(S.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:r,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==ve){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,r==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ve}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:{lower:xs(this.alignmentBounds.lower),upper:xs(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return Q(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 fu(this);return this.dataType.equals(S.JSON)?new yu(e):e}return new gu(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Ns(this,e,t??this.length)}subAlignmentIterator(e,t){return new Ns(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const r=this.data.subarray(e,t);return new ue({data:r,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,r){if(t<=0&&(r==null||r>=this.length))return this;let i;return e?i=this.data.subarray(t,r):i=this.data.slice(t,r),new ue({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ue({data:this.buffer,dataType:this.dataType,timeRange:F.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};y(zt,"crudeZ",s.z.object({timeRange:F.z.optional(),dataType:S.z,alignment:tu.optional(),data:s.z.union([hu,du,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:ou.optional().default("static").optional()})),y(zt,"z",zt.crudeZ.transform(n=>new zt(n)));let Ee=zt,Ns=class{constructor(e,t,r){y(this,"series"),y(this,"end"),y(this,"index"),this.series=e;const i=Q(0,e.length);this.end=Ts(i,r),this.index=Ts(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class fu{constructor(e){if(y(this,"series"),y(this,"index"),y(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==vr;)this.index++;const r=this.index;return e===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,r))})}[Symbol.iterator](){return this}}var Ss,Is;class yu{constructor(e){y(this,"wrapped"),y(this,Ss,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:nt.decodeString(e.value)}}[(Is=Symbol.iterator,Ss=Symbol.toStringTag,Is)](){return this}}var ks,$s;class gu{constructor(e){y(this,"series"),y(this,"index"),y(this,ks,"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)}}[($s=Symbol.iterator,ks=Symbol.toStringTag,$s)](){return this}}const Et=(n,e)=>typeof n=="bigint"&&typeof e=="bigint"||typeof n=="number"&&typeof e=="number"?n+e:e===0?n:n===0?e:Number(n)+Number(e);class xi{constructor(e){if(y(this,"series"),e.length!==0){const t=e[0].dataType;for(let r=1;r<e.length;r++)if(!e[r].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)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?Q(0n,0n):Q(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const r of this.series)if(Xt(r.alignmentBounds,e))return r.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const r of this.series){if(e<r.length)return r.at(e,t);e-=r.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new Xn(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return Tr;let r=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)r+=o.length;else if(Xt(o.alignmentBounds,e)){r+=Number(e-o.alignment);break}}let i=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)i+=o.length;else if(Xt(o.alignmentBounds,t)){i+=Number(t-o.alignment);break}}return new Xn(this,r,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return Tr;let r=0;for(let i=0;i<this.series.length;i++){const a=this.series[i];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)r+=a.length;else if(Xt(a.alignmentBounds,e)){r+=Number(e-a.alignment);break}}return new Xn(this,r,r+t)}get byteLength(){return new it(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const r of this.series)e.set(r.data,t),t+=r.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const r=this.series.map(i=>i.alignmentBounds);return Bl(r,e,t)}distance(e,t){const r=this.series.map(i=>i.alignmentBounds);return Ul(r,e,t)}parseJSON(e){if(!this.dataType.equals(S.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new pu(this.series)}}var As,Rs;class pu{constructor(e){y(this,"series"),y(this,"seriesIndex"),y(this,"internal"),y(this,As,"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())}[(Rs=Symbol.iterator,As=Symbol.toStringTag,Rs)](){return this}}class Xn{constructor(e,t,r){y(this,"series"),y(this,"index"),y(this,"end"),this.series=e,this.end=r,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const xs=n=>{const e=n>>32n,t=n&0xffffffffn;return{domain:e,sample:t}},mu=(n,e)=>{let t=null;return e===0?n:(...r)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>n(...r),e)}};s.z.object({key:s.z.string(),value:s.z.string()});var wu=Object.defineProperty,bu=(n,e,t)=>e in n?wu(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,fn=(n,e,t)=>bu(n,typeof e!="symbol"?e+"":e,t);let Tu=class{constructor(e,t){fn(this,"handlers"),fn(this,"transform"),fn(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[r,i]=this.transform(e);if(!i)return;t=r}this.handlers.forEach((r,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},vu=class{constructor(e){fn(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,r)=>r(e))}};const xe=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:vu,Observer:Tu},Symbol.toStringTag,{value:"Module"})),Ut=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),Ou=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Ou();const zu=["macOS","Windows","Linux"],Eu=["macos","windows","linux"],Nu={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(zu).or(s.z.enum(Eu).transform(n=>Nu[n]));var Su=Object.defineProperty,Iu=(n,e,t)=>e in n?Su(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Nt=(n,e,t)=>Iu(n,typeof e!="symbol"?e+"":e,t);const ku=(...n)=>n.map(Ci).join(""),Ci=n=>(n.endsWith("/")||(n+="/"),n.startsWith("/")&&(n=n.slice(1)),n),$u=n=>n.endsWith("/")?n.slice(0,-1):n,Or=class zr{constructor({host:e,port:t,protocol:r="",pathPrefix:i=""}){Nt(this,"protocol"),Nt(this,"host"),Nt(this,"port"),Nt(this,"path"),this.protocol=r,this.host=e,this.port=t,this.path=Ci(i)}replace(e){return new zr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new zr({...this,pathPrefix:ku(this.path,e)})}toString(){return $u(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Nt(Or,"UNKNOWN",new Or({host:"unknown",port:0}));let Au=Or;var Ru=Object.defineProperty,xu=(n,e,t)=>e in n?Ru(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,yn=(n,e,t)=>xu(n,typeof e!="symbol"?e+"":e,t);const Cu=async n=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(n).milliseconds)),Pu=s.z.object({interval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Du=(n={})=>{const e=n.sleepFn||Cu,t=n.maxRetries??5,r=n.scale??1;let i=0,a=new z(n.interval??z.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(r),i++,!0)},ju=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:Pu,create:Du},Symbol.toStringTag,{value:"Module"})),Ae=class extends Number{};yn(Ae,"Absolute",255),yn(Ae,"Default",1),yn(Ae,"z",s.z.union([s.z.instanceof(Ae),s.z.number().int().min(0).max(255).transform(n=>new Ae(n)),s.z.instanceof(Number).transform(n=>new Ae(n))]));let Pi=Ae;const Di=s.z.object({name:s.z.string(),key:s.z.string()}),Mu=n=>s.z.object({subject:Di,resource:n,authority:Pi.z}),Bu=(...n)=>e=>e.filter(t=>{let r=!1;return t.to!=null&&(r=n.includes(t.to.resource)),t.from!=null&&!r&&(r=n.includes(t.from.resource)),r}),at=Object.freeze(Object.defineProperty({__proto__:null,Authority:Pi,filterTransfersByChannelKey:Bu,stateZ:Mu,subjectZ:Di},Symbol.toStringTag,{value:"Module"})),ji=class St extends Error{constructor(){super(St.MESSAGE)}matches(e){return typeof e=="string"?e.includes(St.MESSAGE):e instanceof St||e.message.includes(St.MESSAGE)}};yn(ji,"MESSAGE","canceled");let Uu=ji;new Uu;const Er=s.z.string().regex(/^\d+\.\d+\.\d+$/),Zt=(n,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const r=Er.parse(n),i=Er.parse(e),[a,o,l]=r.split(".").map(Number),[u,h,f]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return Fn;if(a>u)return Vn}if(t.checkMinor){if(o<h)return Fn;if(o>h)return Vn}if(t.checkPatch){if(l<f)return Fn;if(l>f)return Vn}return kn},Zu=(n,e,t={})=>Ol(Zt(n,e,t)),Mi=(n,e,t={})=>vl(Zt(n,e,t)),Lu=(n,e,t={})=>Tl(Zt(n,e,t)),qu=({name:n,migrate:e})=>t=>{try{const r=e(t);return console.log(`${n} migrated: ${t.version} -> ${r.version}`),r}catch(r){throw console.log(`${n} failed to migrate from ${t.version}`),console.error(r),r}},Yu=({name:n,migrations:e,targetSchema:t,defaultVersion:r,def:i})=>{const a=Object.keys(e).sort(Zt).pop();if(a==null)return h=>{if(h.version??(h.version=r),h.version!==i.version)return console.log(`${n} version ${h.version} is newer than latest version of ${i.version}.
|
|
23
|
+
`);return new he({data:n,dataType:I.JSON,timeRange:t})}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){if(this._refCount--,this._refCount===0&&this.gl.control!=null)this.maybeGarbageCollectGLBuffer(this.gl.control);else if(this._refCount<0)throw new Error("cannot release an array with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Se)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this._cachedLength!=null&&(this._cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===Se)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this._cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===Se?this.underlyingData:new this.dataType.Array(this._data,0,this.writePos)}toStrings(){if(!this.dataType.matches(I.STRING,I.UUID))throw new Error("cannot convert non-string series to strings");return new TextDecoder().decode(this.underlyingData).split(`
|
|
24
|
+
`).slice(0,-1)}toUUIDs(){if(!this.dataType.equals(I.UUID))throw new Error("cannot convert non-uuid series to uuids");const e=I.UUID.density.valueOf(),t=Array(this.length);for(let n=0;n<this.length;n++){const i=this.underlyingData.slice(n*e,(n+1)*e),a=Array.from(new Uint8Array(i.buffer),o=>o.toString(16).padStart(2,"0")).join("").replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/,"$1-$2-$3-$4-$5");t[n]=a}return t}parseJSON(e){if(!this.dataType.equals(I.JSON))throw new Error("cannot parse non-JSON series as JSON");return new TextDecoder().decode(this.underlyingData).split(`
|
|
25
|
+
`).slice(0,-1).map(t=>e.parse(ct.decodeString(t)))}get timeRange(){if(this._timeRange==null)throw new Error("time range not set on series");return this._timeRange}get byteCapacity(){return new ht(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===Se?this.byteCapacity:this.dataType.isVariable?new ht(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this._cachedLength!=null?this._cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===Se?this.data.length:this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const t=[0];return this.data.forEach((n,i)=>{n===Mn&&(e++,t.push(i+1))}),this._cachedIndexes=t,this._cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let i=0;i<this.length;i++)n[i]=Mu(this.dataType,e,this.data[i],t);return new he({data:n.buffer,dataType:e,timeRange:this._timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(I.TIMESTAMP))this._cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this._cachedMax=e.reduce((t,n)=>t>n?t:n)}return this._cachedMax}get max(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this._cachedMax??(this._cachedMax=this.calcRawMax()),xt(this._cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(I.TIMESTAMP))this._cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this._cachedMin=e.reduce((t,n)=>t<n?t:n)}return this._cachedMin}get min(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this._cachedMin??(this._cachedMin=this.calcRawMin()),xt(this._cachedMin,this.sampleOffset))}get bounds(){return te(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 xt(this.max,-this.min)}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t){if(this.dataType.isVariable)return this.atVariable(e,t??!1);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return xt(n,this.sampleOffset)}atVariable(e,t){let n=0,i=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],i=this._cachedIndexes[e+1]-1;else{e<0&&(e=this.length+e);for(let o=0;o<this.data.length;o++)if(this.data[o]===Mn){if(e===0){i=o;break}n=o+1,e--}if(i===0&&(i=this.data.length),n>=i||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const a=this.data.slice(n,i);return this.dataType.equals(I.STRING)?new TextDecoder().decode(a):Qi(JSON.parse(new TextDecoder().decode(a)))}binarySearch(e){let t=0,n=this.length-1;const i=Fl(e);for(;t<=n;){const a=Math.floor((t+n)/2),o=i(this.at(a,!0),e);if(o===0)return a;o<0?t=a+1:n=a-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(I.FLOAT32)&&!this.dataType.equals(I.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:i}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==i)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Se){i===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const a=this.dataType.density.size(i).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,a,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Se}as(e){if(e==="string"){if(!this.dataType.equals(I.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(I.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:{lower:oi(this.alignmentBounds.lower),upper:oi(this.alignmentBounds.upper)},timeRange:(e=this._timeRange)==null?void 0:e.toString(),length:this.length,capacity:this.capacity}}get memInfo(){return{key:this.key,length:this.length,byteLength:this.byteLength,glBuffer:this.gl.buffer!=null}}get alignmentBounds(){return te(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 Lu(this);return this.dataType.equals(I.JSON)?new _u(e):e}return new qu(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new ei(this,e,t??this.length)}subAlignmentIterator(e,t){return new ei(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new he({data:n,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let i;return e?i=this.data.subarray(t,n):i=this.data.slice(t,n),new he({data:i,dataType:this.dataType,timeRange:this._timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new he({data:this.buffer,dataType:this.dataType,timeRange:G.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}};y(Rt,"crudeZ",s.z.object({timeRange:G.z.optional(),dataType:I.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Zu,Uu,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:ju.optional().default("static").optional()})),y(Rt,"z",Rt.crudeZ.transform(r=>new Rt(r)));let ke=Rt,ei=class{constructor(e,t,n){y(this,"series"),y(this,"end"),y(this,"index"),this.series=e;const i=te(0,e.length);this.end=Js(i,n),this.index=Js(i,t)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};class Lu{constructor(e){if(y(this,"series"),y(this,"index"),y(this,"decoder"),!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,t=this.series.data;for(;this.index<t.length&&t[this.index]!==Mn;)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 ti,ri;class _u{constructor(e){y(this,"wrapped"),y(this,ti,"JSONSeriesIterator"),this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:ct.decodeString(e.value)}}[(ri=Symbol.iterator,ti=Symbol.toStringTag,ri)](){return this}}var ni,si;class qu{constructor(e){y(this,"series"),y(this,"index"),y(this,ni,"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)}}[(si=Symbol.iterator,ni=Symbol.toStringTag,si)](){return this}}class fa{constructor(e){if(y(this,"series"),e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){if(!new I(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?I.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?G.ZERO:new G(this.series[0].timeRange.start,this.series[this.series.length-1].timeRange.end)}get alignment(){return this.series.length===0?0n:this.series[0].alignment}get alignmentBounds(){return this.series.length===0?te(0n,0n):te(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){this.series.push(e)}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){if(this.series.length===0){if(t)throw new Error(`[series] - no value at alignment ${e}`);return}for(const n of this.series)if(lr(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new yn(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return Dn;let n=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)n+=o.length;else if(lr(o.alignmentBounds,e)){n+=Number(e-o.alignment);break}}let i=0;for(let a=0;a<this.series.length;a++){const o=this.series[a];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)i+=o.length;else if(lr(o.alignmentBounds,t)){i+=Number(t-o.alignment);break}}return new yn(this,n,i)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return Dn;let n=0;for(let i=0;i<this.series.length;i++){const a=this.series[i];if(e<a.alignment)break;if(e>=a.alignmentBounds.upper)n+=a.length;else if(lr(a.alignmentBounds,e)){n+=Number(e-a.alignment);break}}return new yn(this,n,n+t)}get byteLength(){return new ht(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const n=this.series.map(i=>i.alignmentBounds);return du(n,e,t)}distance(e,t){const n=this.series.map(i=>i.alignmentBounds);return fu(n,e,t)}parseJSON(e){if(!this.dataType.equals(I.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new Yu(this.series)}}var ii,ai;class Yu{constructor(e){y(this,"series"),y(this,"seriesIndex"),y(this,"internal"),y(this,ii,"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())}[(ai=Symbol.iterator,ii=Symbol.toStringTag,ai)](){return this}}let yn=class{constructor(e,t,n){y(this,"series"),y(this,"index"),y(this,"end"),this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}};const oi=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},Wu=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},Fu=(r,e,t=".")=>{const n=r.split(t);return n.map((i,a)=>{const o=e(i,a,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(i=>i!=null).join(t)},Gu=(r,e,t={optional:!1,separator:"."})=>{t.separator??(t.separator=".");const{optional:n,getter:i=(l,u)=>l[u]}=t,a=e.split(t.separator);if(a.length===1&&a[0]==="")return r;let o=r;for(const l of a){const u=i(o,l);if(u==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=u}return o};s.z.object({key:s.z.string(),value:s.z.string()});var Vu=Object.defineProperty,Ju=(r,e,t)=>e in r?Vu(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Or=(r,e,t)=>Ju(r,typeof e!="symbol"?e+"":e,t);let Ku=class{constructor(e,t){Or(this,"handlers"),Or(this,"transform"),Or(this,"closer"),this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,i]=this.transform(e);if(!i)return;t=n}this.handlers.forEach((n,i)=>i(t))}setCloser(e){this.closer=e}async close(){var e;return await((e=this.closer)==null?void 0:e.call(this))}},Hu=class{constructor(e){Or(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 Me=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Hu,Observer:Ku},Symbol.toStringTag,{value:"Module"})),Kt=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),Xu=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Xu();const Qu=["macOS","Windows","Linux"],eh=["macos","windows","linux"],th={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(Qu).or(s.z.enum(eh).transform(r=>th[r]));var rh=Object.defineProperty,nh=(r,e,t)=>e in r?rh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Ct=(r,e,t)=>nh(r,typeof e!="symbol"?e+"":e,t);const sh=(...r)=>r.map(ya).join(""),ya=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),ih=r=>r.endsWith("/")?r.slice(0,-1):r,Bn=class Zn{constructor({host:e,port:t,protocol:n="",pathPrefix:i=""}){Ct(this,"protocol"),Ct(this,"host"),Ct(this,"port"),Ct(this,"path"),this.protocol=n,this.host=e,this.port=t,this.path=ya(i)}replace(e){return new Zn({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new Zn({...this,pathPrefix:sh(this.path,e)})}toString(){return ih(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}};Ct(Bn,"UNKNOWN",new Bn({host:"unknown",port:0}));let ah=Bn;const oh=-128,ch=127,lh=s.z.number().int().min(oh).max(ch),uh=-32768,hh=32767,dh=s.z.number().int().min(uh).max(hh),fh=-2147483648,yh=2147483647,ph=s.z.number().int().min(fh).max(yh),gh=-9223372036854775808n,mh=9223372036854775807n,wh=s.z.bigint().min(gh).max(mh),bh=255,Th=s.z.number().int().min(0).max(bh),vh=65535,Oh=s.z.number().int().min(0).max(vh),Nh=4294967295,Eh=s.z.number().int().min(0).max(Nh),zh=18446744073709551615n,Sh=s.z.bigint().min(0n).max(zh),pa=r=>Fu(r,(e,t,n)=>{const i=t===n.length-1,a=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[t+1]));return a&&(e="element"),i||o?e:[e,"shape"]}),ci=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},Ih=(r,e,t)=>Gu(ci(r,"shape"),pa(e),{...t,getter:ci}),$h=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:Ih,getFieldSchemaPath:pa,int16:dh,int32:ph,int64:wh,int8:lh,uint16:Oh,uint32:Eh,uint64:Sh,uint8:Th},Symbol.toStringTag,{value:"Module"}));var kh=Object.defineProperty,Ah=(r,e,t)=>e in r?kh(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t,Pt=(r,e,t)=>Ah(r,typeof e!="symbol"?e+"":e,t);const xh=async r=>await new Promise(e=>setTimeout(e,N.fromMilliseconds(r).milliseconds)),Rh=s.z.object({interval:N.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Ch=(r={})=>{const e=r.sleepFn||xh,t=r.maxRetries??5,n=r.scale??1;let i=0,a=new N(r.interval??N.milliseconds(1));return async()=>i>=t?!1:(await e(a),a=a.mult(n),i++,!0)},Ph=Object.freeze(Object.defineProperty({__proto__:null,breakerConfig:Rh,create:Ch},Symbol.toStringTag,{value:"Module"})),de=class extends Number{};Pt(de,"ABSOLUTE",255),Pt(de,"MINIMUM",0),Pt(de,"BOUNDS",{lower:de.MINIMUM,upper:de.ABSOLUTE+1}),Pt(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 ga=de;const ma=s.z.object({name:s.z.string(),key:s.z.string()}),jh=r=>s.z.object({subject:ma,resource:r,authority:ga.z}),Dh=(...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}),dt=Object.freeze(Object.defineProperty({__proto__:null,Authority:ga,filterTransfersByChannelKey:Dh,stateZ:jh,subjectZ:ma},Symbol.toStringTag,{value:"Module"})),wa=class jt extends Error{constructor(){super(jt.MESSAGE)}matches(e){return typeof e=="string"?e.includes(jt.MESSAGE):e instanceof jt||e.message.includes(jt.MESSAGE)}};Pt(wa,"MESSAGE","canceled");let Mh=wa;new Mh;const Un=s.z.string().regex(/^\d+\.\d+\.\d+$/),Ht=(r,e,t={})=>{t.checkMajor??(t.checkMajor=!0),t.checkMinor??(t.checkMinor=!0),t.checkPatch??(t.checkPatch=!0);const n=Un.parse(r),i=Un.parse(e),[a,o,l]=n.split(".").map(Number),[u,h,f]=i.split(".").map(Number);if(t.checkMajor){if(a<u)return ln;if(a>u)return un}if(t.checkMinor){if(o<h)return ln;if(o>h)return un}if(t.checkPatch){if(l<f)return ln;if(l>f)return un}return Dr},Bh=(r,e,t={})=>Kl(Ht(r,e,t)),ba=(r,e,t={})=>Jl(Ht(r,e,t)),Zh=(r,e,t={})=>Vl(Ht(r,e,t)),Uh=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},Lh=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:i})=>{const a=Object.keys(e).sort(Ht).pop();if(a==null)return h=>{if(h.version??(h.version=n),h.version!==i.version)return console.log(`${r} version ${h.version} is newer than latest version of ${i.version}.
|
|
26
26
|
Returning default instead.
|
|
27
|
-
`),i;try{return t!=null?t.parse(h):h}catch(f){return console.log(`${
|
|
27
|
+
`),i;try{return t!=null?t.parse(h):h}catch(f){return console.log(`${r} failed to parse default. Exiting with default`),console.error(f),i}};const o=Object.keys(e).length;let l=!1;const u=h=>{try{if(o===0||ba(h.version,a))return console.log(l?`${r} ${h.version} now up to date`:`${r} version ${h.version} is up to date with target version ${i.version}`),h;const f=h.version,d=e[f],k=d(h);return l=!0,u(k)}catch(f){return console.log(`${r} failed to migrate from ${h.version} to ${a}`),console.error(f),i}};return h=>{try{if(h.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),h.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),i;return u(h)}catch(f){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(f),i}}},li=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Ht,createMigration:Uh,migrator:Lh,semVerNewer:ba,semVerOlder:Zh,semVerZ:Un,versionsEqual:Bh},Symbol.toStringTag,{value:"Module"})),_h=(r,e="")=>{const t=r.length;return t===0?e:t===1?r[0]:t===2?`${r[0]} and ${r[1]}`:`${r.slice(0,-1).join(", ")}, and ${r[t-1]}`},qh=r=>{const e=r.split(" "),t=new Set,n=e.map(o=>o.charAt(0).toLowerCase()).join("");t.add(n.replace(/-/g,"_")),t.add(n.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const i=/\d+/g;r.match(i)&&e.forEach((o,l)=>{if(i.test(o)){const u=e.map((h,f)=>f!==l?h.charAt(0).toLowerCase():h).join("");t.add(u.replace(/-/g,"_")),t.add(u.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const a=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return t.add(a.join("").replace(/-/g,"_")),t.add(a.join("_").replace(/-/g,"_")),Array.from(t).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},Yh=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:qh,naturalLanguageJoin:_h},Symbol.toStringTag,{value:"Module"})),Pe="sy.",Ge=class Ge extends oe{constructor(){super(...arguments);c(this,"type",Ge.TYPE)}};c(Ge,"TYPE",`${Pe}validation`),c(Ge,"matches",Q(Ge.TYPE));let U=Ge;const Ve=class Ve extends U{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",`${U.TYPE}.field`),c(Ve,"matches",Q(Ve.TYPE));let $r=Ve;const Je=class Je extends oe{constructor(){super(...arguments);c(this,"type",Je.TYPE)}};c(Je,"TYPE",`${Pe}auth`),c(Je,"matches",Q(Je.TYPE));let ve=Je;const Ke=class Ke extends ve{constructor(){super(...arguments);c(this,"type",Ke.TYPE)}};c(Ke,"TYPE",`${ve.TYPE}.invalid-token`),c(Ke,"matches",Q(Ke.TYPE));let Ut=Ke;const He=class He extends ve{constructor(){super(...arguments);c(this,"type",He.TYPE)}};c(He,"TYPE",`${ve.TYPE}.expired-token`),c(He,"matches",Q(He.TYPE));let Lt=He;const Xe=class Xe extends oe{constructor(t){super(`
|
|
28
28
|
Unexpected error encountered:
|
|
29
29
|
|
|
30
30
|
${t}
|
|
31
31
|
|
|
32
32
|
Please report this to the Synnax team.
|
|
33
|
-
`);c(this,"type",Ge.TYPE)}};c(Ge,"TYPE",`${$e}unexpected`),c(Ge,"matches",te(Ge.TYPE));let Se=Ge;const Fe=class Fe extends ae{constructor(){super(...arguments);c(this,"type",Fe.TYPE)}};c(Fe,"TYPE",`${$e}query`),c(Fe,"matches",te(Fe.TYPE));let se=Fe;const Ve=class Ve extends se{constructor(){super(...arguments);c(this,"type",Ve.TYPE)}};c(Ve,"TYPE",`${se.TYPE}.not_found`),c(Ve,"matches",te(Ve.TYPE));let me=Ve;const Je=class Je extends se{constructor(){super(...arguments);c(this,"type",Je.TYPE)}};c(Je,"TYPE",`${se.TYPE}.multiple_results`),c(Je,"matches",te(Je.TYPE));let we=Je;const Ke=class Ke extends ae{constructor(t,r){super(t);c(this,"type",Ke.TYPE);c(this,"path");this.path=r}};c(Ke,"TYPE",`${$e}route`),c(Ke,"matches",te(Ke.TYPE));let xt=Ke;const He=class He extends ae{constructor(){super(...arguments);c(this,"type",He.TYPE)}};c(He,"TYPE",`${$e}control`),c(He,"matches",te(He.TYPE));let ot=He;const Xe=class Xe extends ot{constructor(){super(...arguments);c(this,"type",Xe.TYPE)}};c(Xe,"TYPE",`${ot.TYPE}.unauthorized`),c(Xe,"matches",te(Xe.TYPE));let vn=Xe;const Qe=class Qe extends ae{constructor(){super(...arguments);c(this,"type",Qe.TYPE)}};c(Qe,"TYPE",`${$e}contiguity`),c(Qe,"matches",te(Qe.TYPE));let Nr=Qe;const Fu=n=>{if(!n.type.startsWith($e))return null;if(n.type.startsWith(Z.TYPE)){if(n.type===Tn.TYPE){const e=n.data.split(": ");return e.length<2?new Z(n.data):new Tn(e[0],e[1])}return new Z(n.data)}return n.type.startsWith(Ce.TYPE)?n.type.startsWith(Rt.TYPE)?new Rt(n.data):new Ce(n.data):n.type.startsWith(Se.TYPE)?new Se(n.data):n.type.startsWith(se.TYPE)?n.type.startsWith(me.TYPE)?new me(n.data):n.type.startsWith(we.TYPE)?new we(n.data):new se(n.data):n.type.startsWith(ot.TYPE)?n.type.startsWith(vn.TYPE)?new vn(n.data):new ot(n.data):n.type.startsWith(xt.TYPE)?new xt(n.data,n.data):new Se(n.data)},Vu=()=>{throw new Error("Not implemented")};li({encode:Vu,decode:Fu});const Ju=async(n,e)=>{const[t,r]=await e(n);return r==null?[t,r]:r instanceof ke?[t,new ke({message:`Cannot reach cluster at ${r.url.host}:${r.url.port}`,url:r.url})]:[t,r]},Cr=s.z.string().uuid(),Pr=s.z.object({key:Cr,name:s.z.string()}),Ku=n=>{const e=b(n);if(e.length===0)throw new Error("No groups specified");const t=Cr.safeParse(e[0]).success;return{single:!Array.isArray(n),variant:t?"keys":"names",normalized:e,actual:n}},Bi="group",Ui=n=>new O({type:Bi,key:n});class Dr{constructor(e,t){c(this,"key");c(this,"name");this.key=t,this.name=e}get ontologyID(){return Ui(this.key)}}const Lt=s.z.union([s.z.literal("label"),s.z.literal("log"),s.z.literal("allow_all"),s.z.literal("builtin"),s.z.literal("cluster"),s.z.literal("channel"),s.z.literal("node"),s.z.literal("group"),s.z.literal("range"),s.z.literal("framer"),s.z.literal("range-alias"),s.z.literal("user"),s.z.literal("workspace"),s.z.literal("schematic"),s.z.literal("lineplot"),s.z.literal("rack"),s.z.literal("device"),s.z.literal("task"),s.z.literal("policy"),s.z.literal("table")]),Zi="builtin",Hu="cluster",Xu="node",ee=s.z.object({type:Lt,key:s.z.string()}),Li=s.z.string().transform(n=>{const[e,t]=n.split(":");return{type:Lt.parse(e),key:t??""}}),Ze=s.z.union([Li,ee]),et=class et{constructor(e){c(this,"type");c(this,"key");if(e instanceof et){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,r]=e.split(":");this.type=t,this.key=r??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};c(et,"z",s.z.union([s.z.instanceof(et),Ze.transform(e=>new et(e))]));let O=et;const Qu=new O({type:Zi,key:"root"}),qi=s.z.object({type:s.z.number()}),Yi=s.z.object({type:Lt,fields:s.z.record(qi)}),_i=s.z.object({id:O.z,name:s.z.string(),schema:Yi.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(n=>({key:n.id.toString(),...n})),eh=s.z.object({from:O.z,type:s.z.string(),to:O.z}),Sr=n=>{const[e,t,r]=n.split("->");return{from:new O(e),type:t,to:new O(r)}},th=s.z.object({group:Pr}),nh=s.z.object({parent:ee,key:s.z.string().uuid().optional(),name:s.z.string()}),rh=s.z.object({key:s.z.string(),name:s.z.string()}),sh=s.z.object({keys:s.z.array(s.z.string())});var ie;let ih=(ie=class{constructor(e){c(this,"client");this.client=e}async create(e,t,r){return(await w(this.client,ie.ENDPOINT,{parent:e,name:t,key:r},nh,th)).group}async rename(e,t){await w(this.client,ie.ENDPOINT_RENAME,{key:e,name:t},rh,s.z.object({}))}async delete(e){await w(this.client,ie.ENDPOINT_DELETE,{keys:e},sh,s.z.object({}))}},c(ie,"ENDPOINT","/ontology/create-group"),c(ie,"ENDPOINT_RENAME","/ontology/rename-group"),c(ie,"ENDPOINT_DELETE","/ontology/delete-group"),ie),Wi=class{constructor(e){c(this,"creator");this.creator=new ih(e)}async create(e,t,r){return this.sugar(await this.creator.create(e,t,r))}async rename(e,t){return await this.creator.rename(e,t)}async delete(...e){return await this.creator.delete(e)}sugar(e){return new Dr(e.name,e.key)}};const ah=Object.freeze(Object.defineProperty({__proto__:null,Client:Wi,Group:Dr,ONTOLOGY_TYPE:Bi,analyzeParams:Ku,groupZ:Pr,keyZ:Cr,ontologyID:Ui},Symbol.toStringTag,{value:"Module"})),Qn={ADD_CHILDREN:"/ontology/add-children",REMOVE_CHILDREN:"/ontology/remove-children",MOVE_CHILDREN:"/ontology/move-children"},Ps=s.z.object({id:ee,children:ee.array()}),oh=s.z.object({from:ee,to:ee,children:ee.array()});let ch=class{constructor(e){c(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,Qn.ADD_CHILDREN,{id:new O(e).payload,children:t.map(r=>new O(r).payload)},Ps,s.z.object({}))}async removeChildren(e,...t){await w(this.client,Qn.REMOVE_CHILDREN,{id:new O(e).payload,children:t.map(r=>new O(r).payload)},Ps,s.z.object({}))}async moveChildren(e,t,...r){const i={from:new O(e).payload,to:new O(t).payload,children:r.map(a=>new O(a).payload)};await w(this.client,Qn.MOVE_CHILDREN,i,oh,s.z.object({}))}};const lh="/ontology/retrieve",uh=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(),types:Lt.array().optional()}),hh=s.z.object({resources:_i.array()}),gn=n=>b(n).map(e=>new O(e).payload);let Gi=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 ch(e),this.groups=new Wi(e),this.framer=t}async search(e,t){return await this.execRetrieve({term:e,...t})}async retrieve(e,t){const r=await this.execRetrieve({ids:gn(e),...t});if(Array.isArray(e))return r;if(r.length===0)throw new se(`No resource found with ID ${Gu.naturalLanguageJoin(b(e).map(i=>new O(i).toString()))}`);return r[0]}async page(e,t,r){return await this.execRetrieve({offset:e,limit:t,...r})}async retrieveChildren(e,t){return await this.execRetrieve({ids:gn(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:gn(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,...r){return await this.writer.moveChildren(e,t,...r)}async openChangeTracker(){return await qt.open(this.framer,this)}async openDependentTracker(e){return await An.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,r)=>this.page(t,r,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,lh,e,uh,hh);return t}};const Ds="sy_ontology_resource_set",js="sy_ontology_resource_delete",Ms="sy_ontology_relationship_set",Bs="sy_ontology_relationship_delete";class qt{constructor(e,t){c(this,"relationships");c(this,"resources");c(this,"resourceObs");c(this,"relationshipObs");c(this,"streamer");c(this,"client");c(this,"closePromise");this.relationshipObs=new xe.Observer,this.relationships=this.relationshipObs,this.resourceObs=new xe.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),r=this.parseResourceDeletes(e);t.concat(r).length>0&&this.resourceObs.notify(t.concat(r));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(Ms);return t.length===0?[]:Array.from(t.as("string")).map(r=>({variant:"set",key:Sr(r),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(Bs);return t.length===0?[]:Array.from(t.as("string")).map(r=>({variant:"delete",key:Sr(r)}))}async parseResourceSets(e){const t=e.get(Ds);if(t.length===0)return[];const r=Array.from(t.as("string")).map(i=>new O(i));try{return(await this.client.retrieve(r)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof se)return[];throw i}}parseResourceDeletes(e){const t=e.get(js);return t.length===0?[]:Array.from(t.as("string")).map(r=>({variant:"delete",key:new O(r)}))}static async open(e,t){const r=await e.openStreamer([Ds,js,Ms,Bs]);return new qt(r,t)}}const Us=n=>n==="from"?"to":"from";class An extends xe.Observer{constructor({target:t,dependents:r,relationshipType:i="parent",relationshipDirection:a="from",resourceType:o},l,u){super();c(this,"internal");c(this,"target");c(this,"relDir");c(this,"resourceType");c(this,"dependents");c(this,"client");c(this,"relType");c(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(r=>{const i=t.find(a=>a.key.toString()==r.id.toString());return i==null||i.variant==="delete"?r:i.value}),this.notify(this.dependents)});c(this,"handleRelationshipChange",t=>{const r=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Us(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!r.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[Us(this.relDir)].type===this.resourceType));if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)}).catch(console.error)});this.resourceType=o,this.internal=l,this.target=t,this.dependents=r,this.resourceType!=null&&(this.dependents=this.dependents.filter(h=>h.id.type===this.resourceType)),this.client=u,this.relType=i,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,r,i){const a=await qt.open(r,i);return new An(t,a,i)}async close(){await this.internal.close()}}const dh=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:Zi,CLUSTER_TYPE:Hu,ChangeTracker:qt,Client:Gi,DependentTracker:An,ID:O,NODE_TYPE:Xu,Root:Qu,crudeIDZ:Ze,idZ:ee,parseIDs:gn,parseRelationship:Sr,relationshipSchemaZ:eh,resourceSchemaZ:_i,resourceTypeZ:Lt,schemaFieldZ:qi,schemaZ:Yi,stringIDZ:Li},Symbol.toStringTag,{value:"Module"})),V=n=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),n.array()]),Yt=s.z.string().uuid(),Fi=s.z.object({key:Yt.optional(),subjects:Ze.array().or(Ze),objects:Ze.array().or(Ze),actions:wn.array().or(wn)}),Rn=s.z.object({key:Yt,subjects:V(ee),objects:V(ee),actions:V(wn)}),Vi="policy",fh=n=>new O({type:Vi,key:n}),Ji="allow_all",yh=new O({type:Ji,key:""}),gh=s.z.object({keys:Yt.array().optional(),subjects:ee.array().optional()}),ph=s.z.object({policies:V(Rn)}),mh="/access/policy/retrieve";let wh=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,mh,e,gh,ph)).policies}};const bh=s.z.object({policies:Rn.partial({key:!0}).array()}),Th=s.z.object({policies:Rn.array()}),vh=s.z.object({keys:Yt.array()}),Oh=s.z.object({}),zh="/access/policy/create",Eh="/access/policy/delete";let Nh=class{constructor(e){c(this,"client");this.client=e}async create(e){const r=Fi.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await w(this.client,zh,{policies:r},bh,Th)).policies}async delete(e){await w(this.client,Eh,{keys:b(e)},vh,Oh)}},Ki=class{constructor(e){c(this,"retriever");c(this,"writer");this.retriever=new wh(e),this.writer=new Nh(e)}async create(e){const t=Array.isArray(e),r=await this.writer.create(e);return t?r:r[0]}async retrieve(e){const t=Array.isArray(e),r=await this.retriever.retrieve({keys:b(e)});return t?r:r[0]}async retrieveFor(e){const t=b(e).map(r=>new O(r).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const Sh=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:yh,ALLOW_ALL_ONTOLOGY_TYPE:Ji,Client:Ki,ONTOLOGY_TYPE:Vi,keyZ:Yt,newPolicyZ:Fi,ontologyID:fh,policyZ:Rn},Symbol.toStringTag,{value:"Module"}));let Hi=class{constructor(e){c(this,"policy");this.policy=new Ki(e)}};const Ih=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:tl,CREATE_ACTION:nl,Client:Hi,DELETE_ACTION:rl,RETRIEVE_ACTION:sl,UPDATE_ACTION:il,actionZ:wn},Symbol.toStringTag,{value:"Module"})),de=s.z.number(),_t=s.z.object({name:s.z.string(),key:s.z.number(),rate:st.z,dataType:S.z,leaseholder:s.z.number(),index:s.z.number(),isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:V(de)}),Xi=_t.extend({key:s.z.number().optional(),leaseholder:s.z.number().optional(),index:s.z.number().optional(),rate:st.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1),expression:s.z.string().optional().default(""),requires:V(de).optional().default([])}),Qi="channel",ea=n=>new O({type:Qi,key:n.toString()}),kh=new Error("request for lock canceled");var $h=function(n,e,t,r){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(f){try{h(r.next(f))}catch(d){o(d)}}function u(f){try{h(r.throw(f))}catch(d){o(d)}}function h(f){f.done?a(f.value):i(f.value).then(l,u)}h((r=r.apply(n,e||[])).next())})};class Ah{constructor(e,t=kh){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((r,i)=>{const a={resolve:r,reject:i,weight:e,priority:t},o=ta(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return $h(this,arguments,void 0,function*(t,r=1,i=0){const[a,o]=yield this.acquire(r,i);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(r=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Rh(this._weightedWaiters[e-1],{resolve:r,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(r=>r.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const r=this._weightedWaiters[t-1];if(!r)continue;const i=r.findIndex(a=>a.priority<=e);(i===-1?r:r.splice(0,i)).forEach(a=>a.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Rh(n,e){const t=ta(n,r=>e.priority<=r.priority);n.splice(t+1,0,e)}function ta(n,e){for(let t=n.length-1;t>=0;t--)if(e(n[t]))return t;return-1}var xh=function(n,e,t,r){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(f){try{h(r.next(f))}catch(d){o(d)}}function u(f){try{h(r.throw(f))}catch(d){o(d)}}function h(f){f.done?a(f.value):i(f.value).then(l,u)}h((r=r.apply(n,e||[])).next())})};class Ch{constructor(e){this._semaphore=new Ah(1,e)}acquire(){return xh(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 xn=(n,e,{convertNumericStrings:t=!0}={})=>{const r=!Array.isArray(n);let i=b(n);const a=i[0],o=typeof a;let l;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[o],{single:r,variant:l,normalized:i,actual:n}},Cn=(n,e,t,r)=>{if(r){if(t.length===0)throw new me(`${n} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new we(`Expected one ${n} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Ph=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()}),Dh=s.z.object({channels:V(_t)}),be=n=>xn(n,{number:"keys",string:"names"}),En=class En{constructor(e){c(this,"client");this.client=e}async search(e,t){return await this.execute({search:e,...t})}async retrieve(e,t){const r=be(e),{variant:i}=r;let{normalized:a}=r;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async page(e,t,r){return await this.execute({offset:e,limit:t,...r})}async execute(e){const[t,r]=await this.client.send(En.ENDPOINT,e,Ph,Dh);if(r!=null)throw r;return t.channels}};c(En,"ENDPOINT","/channel/retrieve");let Ct=En;class jr{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,r){return await this.wrapped.page(e,t,r)}async retrieve(e,t){const{normalized:r}=xn(e,{string:"names",number:"keys"}),i=[],a=[];if(r.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,t);return this.set(o),i.concat(o)}delete(e){const{variant:t,normalized:r}=be(e);t==="names"?r.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):r.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((r,i)=>{const a=t[i],o=this.cache.get(r);if(o==null)return;this.cache.delete(r);const l=this.namesToKeys.get(o.name);l!=null&&(l.delete(r),l.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(r,o);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([r])):u.add(r)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const r=this.namesToKeys.get(t.name);r==null?this.namesToKeys.set(t.name,new Set([t.key])):r.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 r=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&r.push(a)}),r.length!==0)return r}}class na{constructor(e,t){c(this,"mu",new Ch);c(this,"requests",new Map);c(this,"wrapped");c(this,"debouncedRun");this.wrapped=e,this.debouncedRun=mu(()=>{this.run()},t)}async search(e,t){return await this.wrapped.search(e,t)}async page(e,t,r){return await this.wrapped.page(e,t,r)}async retrieve(e){const{normalized:t,variant:r}=be(e);return r==="names"?await this.wrapped.retrieve(t):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,r)=>r.forEach(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((r,i)=>r.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(r=>r.reject(t))}finally{this.requests.clear()}})}}const ra=async(n,e)=>{const{normalized:t}=be(e),r=await n.retrieve(t),i=[];if(t.forEach(a=>{r.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new se(`Could not find channels: ${JSON.stringify(i)}`);return r};class Mr{constructor({dataType:e,rate:t,name:r,leaseholder:i=0,key:a=0,isIndex:o=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:f,alias:d,expression:j="",requires:$=[]}){c(this,"_frameClient");c(this,"key");c(this,"name");c(this,"rate");c(this,"dataType");c(this,"leaseholder");c(this,"index");c(this,"isIndex");c(this,"internal");c(this,"alias");c(this,"virtual");c(this,"expression");c(this,"requires");this.key=a,this.name=r,this.rate=new st(t??0),this.dataType=new S(e),this.leaseholder=i,this.index=l,this.isIndex=o,this.internal=u,this.alias=d,this.virtual=h,this.expression=j,this.requires=$??[],this._frameClient=f??null}get framer(){if(this._frameClient==null)throw new Z("cannot read from a channel that has not been created");return this._frameClient}get payload(){return _t.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,virtual:this.virtual,expression:this.expression,requires:this.requires})}get isCalculated(){return Pt(this.payload)}get ontologyID(){return ea(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const jh="/channel/retrieve-group",Mh=s.z.object({}),Bh=s.z.object({group:Pr});let sa=class{constructor(e,t,r,i){c(this,"type","channel");c(this,"frameClient");c(this,"client");c(this,"retriever");c(this,"writer");this.frameClient=e,this.retriever=t,this.client=r,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:r=!1}=t,i=!Array.isArray(e);let a=b(e),o=[];if(r){const l=await this.retriever.retrieve(a.map(h=>h.name)),u=new Set(l.map(h=>h.name));a=a.filter(h=>!u.has(h.name)),o=this.sugar(l)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){const r=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return Cn("channel",e,i,r),r?i[0]:i}async search(e,t){return this.sugar(await this.retriever.search(e,t))}async delete(e){const{normalized:t,variant:r}=be(e);return r==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,r)=>await this.page(t,r,e)}}async page(e,t,r){return this.sugar(await this.retriever.page(e,t,r))}createDebouncedBatchRetriever(e=10){return new jr(new na(new Ct(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(r=>new Mr({...r,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,jh,{},Mh,Bh);return new Dr(e.group.name,e.group.key)}};const Pt=({virtual:n,expression:e})=>n&&e!=="",ia=async(n,e)=>{if(!Pt(e))return e.index;for(const t of e.requires){const r=await n(t);if(r==null)return null;if(!r.virtual)return r.index}for(const t of e.requires){const r=await n(t);if(r==null)return null;if(Pt(r)){const i=await ia(n,r);if(i!=null)return i}}return null},Uh=s.z.object({channels:Xi.array()}),Zh=s.z.object({channels:_t.array()}),Lh=s.z.object({keys:de.array().optional(),names:s.z.string().array().optional()}),qh=s.z.object({}),Yh=s.z.object({keys:de.array(),names:s.z.string().array()}),_h=s.z.object({}),Wh="/channel/create",Gh="/channel/delete",Fh="/channel/rename";let aa=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,Wh,{channels:e},Uh,Zh);return this.cache.set(t),t}async delete(e){await w(this.client,Gh,e,Lh,qh),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Fh,{keys:e,names:t},Yh,_h),this.cache.rename(e,t)}};const Vh=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:jr,Channel:Mr,Client:sa,ClusterRetriever:Ct,DebouncedBatchRetriever:na,ONTOLOGY_TYPE:Qi,Writer:aa,analyzeChannelParams:be,isCalculated:Pt,keyZ:de,newPayload:Xi,ontologyID:ea,payload:_t,resolveCalculatedIndex:ia,retrieveRequired:ra},Symbol.toStringTag,{value:"Module"})),ht=s.z.string().uuid(),Wt=s.z.object({key:ht,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),oa=Wt.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),ca="user",Jh=n=>new O({type:ca,key:n}),Kh=s.z.object({keys:ht.array().optional(),usernames:s.z.string().array().optional()}),Hh=s.z.object({users:V(Wt)}),Xh="/user/retrieve";let Qh=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Xh,e,Kh,Hh)).users}};const ed=s.z.object({users:oa.array()}),td=s.z.object({users:Wt.array()}),nd=s.z.object({key:ht,username:s.z.string().min(1)}),rd=s.z.object({}),sd=s.z.object({key:ht,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),id=s.z.object({}),ad=s.z.object({keys:ht.array()}),od=s.z.object({}),cd="/user/create",ld="/user/change-username",ud="/user/rename",hd="/user/delete";let dd=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,cd,{users:b(e)},ed,td)).users}async changeUsername(e,t){await w(this.client,ld,{key:e,username:t},nd,rd)}async rename(e,t,r){await w(this.client,ud,{key:e,firstName:t,lastName:r},sd,id)}async delete(e){await w(this.client,hd,{keys:b(e)},ad,od)}},la=class{constructor(e){c(this,"reader");c(this,"writer");this.writer=new dd(e),this.reader=new Qh(e)}async create(e){const t=Array.isArray(e),r=await this.writer.create(e);return t?r:r[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),r=await this.reader.retrieve({keys:b(e)});if(t)return r;if(r.length===0)throw new me(`No user with key ${e} found`);if(r.length>1)throw new we(`Multiple users found with key ${e}`);return r[0]}async retrieveByName(e){const t=Array.isArray(e),r=await this.reader.retrieve({usernames:b(e)});if(t)return r;if(r.length===0)throw new me(`No user with username ${e} found`);if(r.length>1)throw new we(`Multiple users found with username ${e}`);return r[0]}async rename(e,t,r){await this.writer.rename(e,t,r)}async delete(e){await this.writer.delete(e)}};const fd=Object.freeze(Object.defineProperty({__proto__:null,Client:la,ONTOLOGY_TYPE:ca,keyZ:ht,newUserZ:oa,ontologyID:Jh,userZ:Wt},Symbol.toStringTag,{value:"Module"})),yd=s.z.object({username:s.z.string(),password:s.z.string()}),gd=s.z.object({token:s.z.string(),user:Wt}),Zs="/auth/login",pd=3,md="/auth/change-password",wd=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),bd=s.z.object({});let Td=class{constructor(e,t){c(this,"token");c(this,"client");c(this,"credentials");c(this,"authenticating");c(this,"authenticated");c(this,"user");c(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await w(this.client,md,{username:this.credentials.username,password:this.credentials.password,newPassword:e},wd,bd),this.credentials.password=e}middleware(){const e=async(t,r)=>{if(!this.authenticated&&!t.target.endsWith(Zs)){this.authenticating??(this.authenticating=new Promise((l,u)=>{this.client.send(Zs,this.credentials,yd,gd).then(([h,f])=>{if(f!=null)return l(f);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(null)}).catch(u)}));const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await r(t);return Rt.matches(a)&&this.retryCount<pd?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,r)):(this.retryCount=0,[i,a])};return e}};const vd=["disconnected","connecting","connected","failed"],ua=s.z.enum(vd),ha=s.z.object({status:ua,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),Od=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),Ls={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.38.1"},qs=(n,e,t)=>{const r=t?"cluster":"client";return`Synnax cluster node version ${n!=null?`${n} `:""}is too ${t?"old":"new"} for client version ${e}.
|
|
34
|
-
|
|
35
|
-
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${r}-version`},tt=class tt{constructor(e,t=z.seconds(30),r,i){c(this,"_state");c(this,"pollFrequency",z.seconds(30));c(this,"client");c(this,"name");c(this,"interval");c(this,"clientVersion");c(this,"onChangeHandlers",[]);c(this,"versionWarned",!1);this._state={...Ls},this.client=e,this.pollFrequency=t,this.clientVersion=r,this.name=i,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[r,i]=await this.client.send(tt.ENDPOINT,{},s.z.object({}),Od);if(i!=null)throw i;const a=r.nodeVersion,o=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(qs(null,o,!0)),this.versionWarned=!0)):Cs.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(qs(a,o,Cs.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=r.clusterKey,this._state.nodeVersion=r.nodeVersion,this._state.clientVersion=this.clientVersion}catch(r){this._state.status="failed",this._state.error=r,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(r=>r(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};c(tt,"ENDPOINT","/connectivity/check"),c(tt,"DEFAULT",Ls),c(tt,"connectionStateZ",ha);let Dt=tt;const zd=Object.freeze(Object.defineProperty({__proto__:null,Checker:Dt,state:ha,status:ua},Symbol.toStringTag,{value:"Module"})),Ed=s.z.object({keys:de.array().optional(),bounds:F.z,names:s.z.string().array().optional()}),Nd=s.z.object({}),Sd="/frame/delete";class Id{constructor(e){c(this,"client");this.client=e}async delete(e){await w(this.client,Sd,e,Ed,Nd)}}const Ys=n=>{const e=b(n);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},_s=(n,e)=>{const t=b(n);if(t.length===e.length)return;const r=Ys(n);throw Ys===null?new Z("[Frame] - channel keys or names must be provided when constructing a frame."):new Z(`[Frame] - ${r}s and series must be the same length.
|
|
36
|
-
Got ${t.length} ${r}s and ${e.length} series.`)};class _{constructor(e=[],t=[]){c(this,"columns",[]);c(this,"series",[]);if(e instanceof _){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...b(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e;i.series??(i.series=[]),i.keys??(i.keys=[]);const a=i.series.map(o=>da(o));_s(i.keys,a),i.keys.forEach((o,l)=>this.push(o,a[l]))}else Object.entries(e).forEach(([i,a])=>{const o=parseInt(i);if(!isNaN(o))return this.push(o,...b(a));this.push(i,...b(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=b(t),a=b(e);_s(a,i),i.forEach((o,l)=>this.push(a[l],o));return}throw new Z(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
33
|
+
`);c(this,"type",Xe.TYPE)}};c(Xe,"TYPE",`${Pe}unexpected`),c(Xe,"matches",Q(Xe.TYPE));let xe=Xe;const Qe=class Qe extends oe{constructor(){super(...arguments);c(this,"type",Qe.TYPE)}};c(Qe,"TYPE",`${Pe}query`),c(Qe,"matches",Q(Qe.TYPE));let ie=Qe;const et=class et extends ie{constructor(){super(...arguments);c(this,"type",et.TYPE)}};c(et,"TYPE",`${ie.TYPE}.not_found`),c(et,"matches",Q(et.TYPE));let Oe=et;const tt=class tt extends ie{constructor(){super(...arguments);c(this,"type",tt.TYPE)}};c(tt,"TYPE",`${ie.TYPE}.multiple_results`),c(tt,"matches",Q(tt.TYPE));let Ne=tt;const rt=class rt extends oe{constructor(t,n){super(t);c(this,"type",rt.TYPE);c(this,"path");this.path=n}};c(rt,"TYPE",`${Pe}route`),c(rt,"matches",Q(rt.TYPE));let _t=rt;const nt=class nt extends oe{constructor(){super(...arguments);c(this,"type",nt.TYPE)}};c(nt,"TYPE",`${Pe}control`),c(nt,"matches",Q(nt.TYPE));let ft=nt;const st=class st extends ft{constructor(){super(...arguments);c(this,"type",st.TYPE)}};c(st,"TYPE",`${ft.TYPE}.unauthorized`),c(st,"matches",Q(st.TYPE));let kr=st;const it=class it extends oe{constructor(){super(...arguments);c(this,"type",it.TYPE)}};c(it,"TYPE",`${Pe}contiguity`),c(it,"matches",Q(it.TYPE));let Ln=it;const Wh=r=>{if(!r.type.startsWith(Pe))return null;if(r.type.startsWith(U.TYPE)){if(r.type===$r.TYPE){const e=r.data.split(": ");return e.length<2?new U(r.data):new $r(e[0],e[1])}return new U(r.data)}return r.type.startsWith(ve.TYPE)?r.type.startsWith(Ut.TYPE)?new Ut(r.data):r.type.startsWith(Lt.TYPE)?new Lt(r.data):new ve(r.data):r.type.startsWith(xe.TYPE)?new xe(r.data):r.type.startsWith(ie.TYPE)?r.type.startsWith(Oe.TYPE)?new Oe(r.data):r.type.startsWith(Ne.TYPE)?new Ne(r.data):new ie(r.data):r.type.startsWith(ft.TYPE)?r.type.startsWith(kr.TYPE)?new kr(r.data):new ft(r.data):r.type.startsWith(_t.TYPE)?new _t(r.data,r.data):new xe(r.data)},Fh=()=>{throw new Error("Not implemented")};Zi({encode:Fh,decode:Wh});const Gh=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ce?[t,new Ce({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]},gt=s.z.string().uuid(),Br=s.z.string(),Hn=s.z.object({key:gt,name:Br}),Vh=r=>{const e=b(r);if(e.length===0)throw new Error("No groups specified");const t=gt.safeParse(e[0]).success;return{single:!Array.isArray(r),variant:t?"keys":"names",normalized:e,actual:r}},Xn="group",V=r=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),r.array()]),J=s.z.number(),Xt=s.z.string(),Qt=s.z.object({name:Xt,key:J,rate:ut.z,dataType:I.z,leaseholder:s.z.number(),index:J,isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:V(J)}),Ta=Qt.extend({key:J.optional(),leaseholder:s.z.number().optional(),index:J.optional(),rate:ut.z.optional().default(0),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1),expression:s.z.string().optional().default(""),requires:V(J).optional().default([])}),Zr="channel",Qn="framer",ui=r=>{const e=b(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},hi=(r,e)=>{const t=b(r);if(t.length===e.length)return;const n=ui(r);throw ui===null?new U("[Frame] - channel keys or names must be provided when constructing a frame."):new U(`[Frame] - ${n}s and series must be the same length.
|
|
34
|
+
Got ${t.length} ${n}s and ${e.length} series.`)};class Y{constructor(e=[],t=[]){c(this,"columns",[]);c(this,"series",[]);if(e instanceof Y){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((i,a)=>this.push(a,...b(i)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const i=e;i.series??(i.series=[]),i.keys??(i.keys=[]);const a=i.series.map(o=>va(o));hi(i.keys,a),i.keys.forEach((o,l)=>this.push(o,a[l]))}else Object.entries(e).forEach(([i,a])=>{const o=parseInt(i);if(!isNaN(o))return this.push(o,...b(a));this.push(i,...b(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const i=b(t),a=b(e);hi(a,i),i.forEach((o,l)=>this.push(a[l],o));return}throw new U(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
37
35
|
payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
|
|
38
|
-
name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new Se("colType is not key");return this.columns??[]}get uniqueKeys(){return ps.unique(this.keys)}get names(){if(this.colType==="key")throw new Se("colType is not name");return this.columns??[]}get uniqueNames(){return ps.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>fa(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 r=I.min(...this.series.map(a=>a.timeRange.start)),i=I.max(...this.series.map(a=>a.timeRange.end));return new F(r,i)}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 xi(this.series.filter((t,r)=>this.columns[r]===e))}push(e,...t){if(e instanceof _){if(this.colType!==null&&e.colType!==this.colType)throw new Z("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 Z("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new Z("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new _([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new _;return this.forEach((r,i,a)=>t.push(...e(r,i,a))),t}forEach(e){this.columns.forEach((t,r)=>{const i=this.series[r];e(t,i,r)})}at(e,t=!1){const r={};return this.uniqueColumns.forEach(i=>{r[i]=this.get(i).at(e,t)}),r}filter(e){const t=new _;return this.columns.forEach((r,i)=>{const a=this.series[i];e(r,a,i)&&t.push(r,a)}),t}get byteLength(){return new it(this.series.reduce((e,t)=>e.add(t.byteLength),it.ZERO))}get digest(){const e={};return this.keys.forEach((t,r)=>{const i=this.series[r].digest;t in e?e[t].push(i):e[t]=[i]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const Pn=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(()=>[]),Ee.crudeZ.array().optional().default([])])}),da=n=>{const{dataType:e,data:t,timeRange:r,alignment:i}=n;return new Ee({data:t,dataType:e,timeRange:r,glBufferUsage:"static",alignment:i})},fa=n=>({timeRange:n._timeRange,dataType:n.dataType,data:new Uint8Array(n.data.buffer),alignment:n.alignment});class Dn{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 r=new Dn(e);return await r.update(t),r}async update(e){const{variant:t,normalized:r}=be(e);if(t==="keys"){this.adapter=null,this.keys=r;return}const i=await this.retriever.retrieve(r),a=new Map;this.adapter=a,r.forEach(o=>{const l=i.find(u=>u.name===o);if(l==null)throw new Error(`Channel ${o} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((r,i)=>{if(typeof r=="number"){const a=t.get(r);if(a==null)throw new Error(`Channel ${r} not found`);return[a,i]}return[r,i]})}}class Br{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 r=new Br(e);return await r.update(t),r}async adaptObjectKeys(e){const t={};for(const[r,i]of Object.entries(e))t[await this.adaptToKey(r)]=i;return t}async update(e){const t=await ra(this.retriever,e);this.adapter=new Map(t.map(r=>[r.name,r.key])),this.keys=t.map(r=>r.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new Z(`
|
|
36
|
+
name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new xe("colType is not key");return this.columns??[]}get uniqueKeys(){return Ws.unique(this.keys)}get names(){if(this.colType==="key")throw new xe("colType is not name");return this.columns??[]}get uniqueNames(){return Ws.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>Oa(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 G.ZERO;const n=$.min(...this.series.map(a=>a.timeRange.start)),i=$.max(...this.series.map(a=>a.timeRange.end));return new G(n,i)}const t=this.get(e);return t==null?G.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 fa(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof Y){if(this.colType!==null&&e.colType!==this.colType)throw new U("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 U("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new U("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new Y([...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 Y;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 Y;return this.columns.forEach((n,i)=>{const a=this.series[i];e(n,a,i)&&t.push(n,a)}),t}get byteLength(){return new ht(this.series.reduce((e,t)=>e.add(t.byteLength),ht.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const i=this.series[n].digest;t in e?e[t].push(i):e[t]=[i]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}}const Ur=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(()=>[]),ke.crudeZ.array().optional().default([])])}),va=r=>{const{dataType:e,data:t,timeRange:n,alignment:i}=r;return new ke({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:i})},Oa=r=>({timeRange:r._timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment}),mt=$h.uint32,Lr=s.z.object({key:mt,name:s.z.string()}),Na=Lr.partial({key:!0}),_r="rack",Ea=r=>r?Jt.JSON_CODEC.decodeString(r):{},qr=s.z.string(),er=s.z.object({key:qr,rack:mt,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(Ea))}),za=er.extend({properties:s.z.unknown().transform(r=>Jt.JSON_CODEC.encodeString(r))}),Yr="device",ye=r=>r?JSON.parse(r):{},je=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),Sa=s.z.enum(["info","success","error","warning"]),qt=s.z.object({task:je,variant:Sa,key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(ye)).or(s.z.array(s.z.unknown())).or(s.z.null())}),tr=s.z.object({key:je,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(Ea)),state:qt.optional().nullable(),snapshot:s.z.boolean().optional()}),Ia=tr.omit({key:!0}).extend({key:je.transform(r=>r.toString()).optional(),config:s.z.unknown().transform(r=>Jt.JSON_CODEC.encodeString(r))}),es=s.z.object({task:je,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(ye)).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),Wr="task",Jh=r=>Number(BigInt(r)>>32n),wt=s.z.string().uuid(),rr=s.z.object({key:wt,name:s.z.string().min(1),color:s.z.string()}),ts="label",ne=s.z.string().uuid(),rs=s.z.string().min(1),nr=s.z.object({key:ne,name:rs,timeRange:G.z,color:s.z.string().optional()}),$a=nr.partial({key:!0}),ka=r=>{const e=b(r),t=e.length===0;let n=!1;return t||(n=ne.safeParse(e[0]).success),{single:!Array.isArray(r),variant:n?"keys":"names",normalized:e,actual:r,empty:t}},ns="range",ss="range-alias",Ze=s.z.string().uuid(),sr=s.z.object({key:Ze,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),Aa=sr.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),is="user",bt=s.z.string().uuid(),Fr=s.z.object({key:bt,name:s.z.string(),data:Kt.or(s.z.string().transform(ye))}),xa=Fr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),as="lineplot",Tt=s.z.string().uuid(),Gr=s.z.object({key:Tt,name:s.z.string(),data:Kt.or(s.z.string().transform(ye))}),Ra=Gr.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),os="log",pe=s.z.string().uuid(),Vr=s.z.object({key:pe,name:s.z.string(),layout:Kt.or(s.z.string().transform(ye))}),Jr="workspace",Ca=Vr.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),Pa=Vr.omit({layout:!0}).extend({layout:s.z.string().transform(ye)}),Ue=s.z.string().uuid(),Kr=s.z.object({key:Ue,name:s.z.string(),data:Kt.or(s.z.string().transform(ye)),snapshot:s.z.boolean()}),ja=Kr.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),cs=Kr.extend({data:s.z.string().transform(ye)}),ls="schematic",vt=s.z.string().uuid(),us=s.z.object({key:vt,name:s.z.string(),data:Kt.or(s.z.string().transform(ye))}),Da=us.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),hs=us.extend({data:s.z.string().transform(ye)}),ds="table",fs="builtin",Ma="cluster",Ba="node",ir=s.z.enum([ts,os,Fn,fs,Ma,Zr,Ba,Xn,ns,Qn,ss,is,Jr,ls,as,_r,Yr,Wr,Wn,ds]),re=s.z.object({type:ir,key:s.z.string()}),Za=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:ir.parse(e),key:t??""}}),We=s.z.union([Za,re]),at=class at{constructor(e){c(this,"type");c(this,"key");if(e instanceof at){this.type=e.type,this.key=e.key;return}if(typeof e=="string"){const[t,n]=e.split(":");this.type=t,this.key=n??"";return}this.type=e.type,this.key=e.key}toString(){return`${this.type}:${this.key}`}isType(){return this.key===""}matchesType(e){return this.type===e&&this.isType()}get payload(){return{type:this.type,key:this.key}}};c(at,"z",s.z.union([s.z.instanceof(at),We.transform(e=>new at(e))]));let O=at;const Kh=new O({type:fs,key:"root"}),Ua=s.z.object({type:s.z.number()}),La=s.z.object({type:ir,fields:s.z.record(Ua)}),_a=s.z.object({id:O.z,name:s.z.string(),schema:La.optional().nullable(),data:s.z.record(s.z.unknown()).optional().nullable()}).transform(r=>({key:r.id.toString(),...r})),Hh="to",Xh="from",Qh=s.z.object({from:O.z,type:s.z.string(),to:O.z}),_n=r=>{const[e,t,n]=r.split("->");return{from:new O(e),type:t,to:new O(n)}};class ys{constructor(e,t){c(this,"key");c(this,"name");this.key=t,this.name=e}get ontologyID(){return qa(this.key)}}const qa=r=>new O({type:Xn,key:r}),ed=s.z.object({group:Hn}),td=s.z.object({parent:re,key:gt.optional(),name:Br}),rd=s.z.object({key:gt,name:Br}),nd=s.z.object({keys:s.z.array(gt)});var ae;let sd=(ae=class{constructor(e){c(this,"client");this.client=e}async create(e,t,n){return(await w(this.client,ae.CREATE_ENDPOINT,{parent:e,name:t,key:n},td,ed)).group}async rename(e,t){await w(this.client,ae.RENAME_ENDPOINT,{key:e,name:t},rd,s.z.object({}))}async delete(e){await w(this.client,ae.DELETE_ENDPOINT,{keys:e},nd,s.z.object({}))}},c(ae,"CREATE_ENDPOINT","/ontology/create-group"),c(ae,"RENAME_ENDPOINT","/ontology/rename-group"),c(ae,"DELETE_ENDPOINT","/ontology/delete-group"),ae),Ya=class{constructor(e){c(this,"creator");this.creator=new sd(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 ys(e.name,e.key)}};const id=Object.freeze(Object.defineProperty({__proto__:null,Client:Ya,Group:ys,ONTOLOGY_TYPE:Xn,analyzeParams:Vh,groupZ:Hn,keyZ:gt,nameZ:Br,ontologyID:qa},Symbol.toStringTag,{value:"Module"})),ad="/ontology/add-children",od="/ontology/remove-children",cd="/ontology/move-children",di=s.z.object({id:re,children:re.array()}),ld=s.z.object({from:re,to:re,children:re.array()}),pn=s.z.object({});let ud=class{constructor(e){c(this,"client");this.client=e}async addChildren(e,...t){await w(this.client,ad,{id:new O(e).payload,children:t.map(n=>new O(n).payload)},di,pn)}async removeChildren(e,...t){await w(this.client,od,{id:new O(e).payload,children:t.map(n=>new O(n).payload)},di,pn)}async moveChildren(e,t,...n){const i={from:new O(e).payload,to:new O(t).payload,children:n.map(a=>new O(a).payload)};await w(this.client,cd,i,ld,pn)}};const hd="/ontology/retrieve",dd=s.z.object({ids:re.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),includeSchema:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),term:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:ir.array().optional()}),fd=s.z.object({resources:_a.array()}),Nr=r=>b(r).map(e=>new O(e).payload);let Wa=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 ud(e),this.groups=new Ya(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:Nr(e),...t});if(Array.isArray(e))return n;if(n.length===0)throw new ie(`No resource found with ID ${Yh.naturalLanguageJoin(b(e).map(i=>new O(i).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:Nr(e),children:!0,...t})}async retrieveParents(e,t){return await this.execRetrieve({ids:Nr(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 ar.open(this.framer,this)}async openDependentTracker(e){return await Hr.open(e,this.framer,this)}newSearcherWithOptions(e){return{type:this.type,search:t=>this.search(t,e),retrieve:t=>this.retrieve(t,e),page:(t,n)=>this.page(t,n,e)}}async execRetrieve(e){const{resources:t}=await w(this.client,hd,e,dd,fd);return t}};const fi="sy_ontology_resource_set",yi="sy_ontology_resource_delete",pi="sy_ontology_relationship_set",gi="sy_ontology_relationship_delete";class ar{constructor(e,t){c(this,"relationships");c(this,"resources");c(this,"resourceObs");c(this,"relationshipObs");c(this,"streamer");c(this,"client");c(this,"closePromise");this.relationshipObs=new Me.Observer,this.relationships=this.relationshipObs,this.resourceObs=new Me.Observer,this.resources=this.resourceObs,this.client=t,this.streamer=e,this.closePromise=this.start()}async close(){this.streamer.close(),await this.closePromise}async start(){for await(const e of this.streamer)await this.update(e)}async update(e){const t=await this.parseResourceSets(e),n=this.parseResourceDeletes(e);t.concat(n).length>0&&this.resourceObs.notify(t.concat(n));const a=this.parseRelationshipSets(e),o=this.parseRelationshipDeletes(e);a.concat(o).length>0&&this.relationshipObs.notify(a.concat(o))}parseRelationshipSets(e){const t=e.get(pi);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"set",key:_n(n),value:void 0}))}parseRelationshipDeletes(e){const t=e.get(gi);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:_n(n)}))}async parseResourceSets(e){const t=e.get(fi);if(t.length===0)return[];const n=Array.from(t.as("string")).map(i=>new O(i));try{return(await this.client.retrieve(n)).map(a=>({variant:"set",key:a.id,value:a}))}catch(i){if(i instanceof ie)return[];throw i}}parseResourceDeletes(e){const t=e.get(yi);return t.length===0?[]:Array.from(t.as("string")).map(n=>({variant:"delete",key:new O(n)}))}static async open(e,t){const n=await e.openStreamer([fi,yi,pi,gi]);return new ar(n,t)}}const mi=r=>r==="from"?"to":"from";class Hr extends Me.Observer{constructor({target:t,dependents:n,relationshipType:i="parent",relationshipDirection:a="from",resourceType:o},l,u){super();c(this,"internal");c(this,"target");c(this,"relDir");c(this,"resourceType");c(this,"dependents");c(this,"client");c(this,"relType");c(this,"handleResourceChange",t=>{this.dependents=this.dependents.map(n=>{const i=t.find(a=>a.key.toString()==n.id.toString());return i==null||i.variant==="delete"?n:i.value}),this.notify(this.dependents)});c(this,"handleRelationshipChange",t=>{const n=t.filter(a=>a.variant==="delete"&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[mi(this.relDir)].type===this.resourceType));this.dependents=this.dependents.filter(a=>!n.some(o=>o.key.to.toString()===a.id.toString()&&o.key.type===this.relType));const i=t.filter(a=>a.variant==="set"&&a.key.type===this.relType&&a.key[this.relDir].toString()===this.target.toString()&&(this.resourceType==null||a.key[mi(this.relDir)].type===this.resourceType));if(i.length===0)return this.notify(this.dependents);this.client.retrieve(i.map(a=>a.key.to)).then(a=>{this.dependents=this.dependents.concat(a),this.notify(this.dependents)}).catch(console.error)});this.resourceType=o,this.internal=l,this.target=t,this.dependents=n,this.resourceType!=null&&(this.dependents=this.dependents.filter(h=>h.id.type===this.resourceType)),this.client=u,this.relType=i,this.relDir=a,this.internal.resources.onChange(this.handleResourceChange),this.internal.relationships.onChange(this.handleRelationshipChange)}static async open(t,n,i){const a=await ar.open(n,i);return new Hr(t,a,i)}async close(){await this.internal.close()}}const yd=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:fs,CLUSTER_TYPE:Ma,ChangeTracker:ar,Client:Wa,DependentTracker:Hr,FROM_RELATIONSHIP_DIRECTION:Xh,ID:O,NODE_TYPE:Ba,ROOT_ID:Kh,TO_RELATIONSHIP_DIRECTION:Hh,crudeIDZ:We,idZ:re,parseIDs:Nr,parseRelationship:_n,relationshipSchemaZ:Qh,resourceTypeZ:ir,resourceZ:_a,schemaFieldZ:Ua,schemaZ:La,stringIDZ:Za},Symbol.toStringTag,{value:"Module"})),or=s.z.string().uuid(),Xr=s.z.object({key:or,subjects:V(re),objects:V(re),actions:V(Sr)}),Fa=s.z.object({key:or.optional(),subjects:We.array().or(We),objects:We.array().or(We),actions:Sr.array().or(Sr)}),pd=s.z.object({keys:or.array().optional(),subjects:re.array().optional()}),gd=s.z.object({policies:V(Xr)}),md="/access/policy/retrieve";let wd=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,md,e,pd,gd)).policies}};const bd=s.z.object({policies:Xr.partial({key:!0}).array()}),Td=s.z.object({policies:Xr.array()}),vd=s.z.object({keys:or.array()}),Od=s.z.object({}),Nd="/access/policy/create",Ed="/access/policy/delete";let zd=class{constructor(e){c(this,"client");this.client=e}async create(e){const n=Fa.array().parse(b(e)).map(a=>({objects:b(a.objects),actions:b(a.actions),subjects:b(a.subjects)}));return(await w(this.client,Nd,{policies:n},bd,Td)).policies}async delete(e){await w(this.client,Ed,{keys:b(e)},vd,Od)}},Ga=class{constructor(e){c(this,"retriever");c(this,"writer");this.retriever=new wd(e),this.writer=new zd(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve({keys:b(e)});return t?n:n[0]}async retrieveFor(e){const t=b(e).map(n=>new O(n).payload);return await this.retriever.retrieve({subjects:t})}async delete(e){await this.writer.delete(e)}};const Sd=r=>new O({type:Wn,key:r}),Id=new O({type:Fn,key:""}),$d=Object.freeze(Object.defineProperty({__proto__:null,ALLOW_ALL_ONTOLOGY_ID:Id,ALLOW_ALL_ONTOLOGY_TYPE:Fn,Client:Ga,ONTOLOGY_TYPE:Wn,keyZ:or,newZ:Fa,ontologyID:Sd,policyZ:Xr},Symbol.toStringTag,{value:"Module"}));let Va=class{constructor(e){c(this,"policy");this.policy=new Ga(e)}};const kd=Object.freeze(Object.defineProperty({__proto__:null,ALL_ACTION:Gi,CREATE_ACTION:Vi,Client:Va,DELETE_ACTION:Ji,RETRIEVE_ACTION:Ki,UPDATE_ACTION:Hi,actionZ:Sr},Symbol.toStringTag,{value:"Module"})),Ad=new Error("request for lock canceled");var xd=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(f){try{h(n.next(f))}catch(d){o(d)}}function u(f){try{h(n.throw(f))}catch(d){o(d)}}function h(f){f.done?a(f.value):i(f.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class Rd{constructor(e,t=Ad){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,i)=>{const a={resolve:n,reject:i,weight:e,priority:t},o=Ja(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(a):this._queue.splice(o+1,0,a)})}runExclusive(e){return xd(this,arguments,void 0,function*(t,n=1,i=0){const[a,o]=yield this.acquire(n,i);try{return yield t(a)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Cd(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 Cd(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 Pd=function(r,e,t,n){function i(a){return a instanceof t?a:new t(function(o){o(a)})}return new(t||(t=Promise))(function(a,o){function l(f){try{h(n.next(f))}catch(d){o(d)}}function u(f){try{h(n.throw(f))}catch(d){o(d)}}function h(f){f.done?a(f.value):i(f.value).then(l,u)}h((n=n.apply(r,e||[])).next())})};class jd{constructor(e){this._semaphore=new Rd(1,e)}acquire(){return Pd(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 Qr=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let i=b(r);const a=i[0],o=typeof a;let l;return o==="string"&&t&&!isNaN(parseInt(a))&&"number"in e?(l=e.number,i=i.map(u=>parseInt(u))):l=e[o],{single:n,variant:l,normalized:i,actual:r}},en=(r,e,t,n)=>{if(n){if(t.length===0)throw new Oe(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new Ne(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},Dd=s.z.object({leaseholder:s.z.number().optional(),keys:J.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:I.z.array().optional(),notDataTypes:I.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional()}),Md=s.z.object({channels:V(Qt)}),Ee=r=>Qr(r,{number:"keys",string:"names"}),Rr=class Rr{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=Ee(e),{variant:i}=n;let{normalized:a}=n;return i==="keys"&&a.indexOf(0)!==-1&&(a=a.filter(o=>o!==0)),a.length===0?[]:await this.execute({[i]:a,...t})}async page(e,t,n){return await this.execute({offset:e,limit:t,...n})}async execute(e){const[t,n]=await this.client.send(Rr.ENDPOINT,e,Dd,Md);if(n!=null)throw n;return t.channels}};c(Rr,"ENDPOINT","/channel/retrieve");let Yt=Rr;class ps{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}=Qr(e,{string:"names",number:"keys"}),i=[],a=[];if(n.forEach(l=>{const u=this.get(l);u!=null?i.push(...u):a.push(l)}),a.length===0)return i;const o=await this.wrapped.retrieve(a,t);return this.set(o),i.concat(o)}delete(e){const{variant:t,normalized:n}=Ee(e);t==="names"?n.forEach(i=>{const a=this.namesToKeys.get(i);a!=null&&(a.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(i))}):n.forEach(i=>{const a=this.cache.get(i);a!=null&&(this.cache.delete(i),this.namesToKeys.delete(a.name))})}rename(e,t){e.forEach((n,i)=>{const a=t[i],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const l=this.namesToKeys.get(o.name);l!=null&&(l.delete(n),l.size===0&&this.namesToKeys.delete(o.name)),o.name=a,this.cache.set(n,o);const u=this.namesToKeys.get(a);u==null?this.namesToKeys.set(a,new Set([n])):u.add(n)})}set(e){e.forEach(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const i=this.cache.get(e);return i==null?void 0:[i]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(i=>{const a=this.cache.get(i);a!=null&&n.push(a)}),n.length!==0)return n}}class Ka{constructor(e,t){c(this,"mu",new jd);c(this,"requests",new Map);c(this,"wrapped");c(this,"debouncedRun");this.wrapped=e,this.debouncedRun=Wu(()=>{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}=Ee(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,o)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:o}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(i=>e.add(i)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,i)=>n.resolve(t.filter(a=>i.includes(a.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Ha=async(r,e)=>{const{normalized:t}=Ee(e),n=await r.retrieve(t),i=[];if(t.forEach(a=>{n.find(o=>o.name===a||o.key===a)==null&&i.push(a)}),i.length>0)throw new ie(`Could not find channels: ${JSON.stringify(i)}`);return n};class gs{constructor({dataType:e,rate:t,name:n,leaseholder:i=0,key:a=0,isIndex:o=!1,index:l=0,internal:u=!1,virtual:h=!1,frameClient:f,alias:d,expression:k="",requires:S=[]}){c(this,"_frameClient");c(this,"key");c(this,"name");c(this,"rate");c(this,"dataType");c(this,"leaseholder");c(this,"index");c(this,"isIndex");c(this,"internal");c(this,"alias");c(this,"virtual");c(this,"expression");c(this,"requires");this.key=a,this.name=n,this.rate=new ut(t??0),this.dataType=new I(e),this.leaseholder=i,this.index=l,this.isIndex=o,this.internal=u,this.alias=d,this.virtual=h,this.expression=k,this.requires=S??[],this._frameClient=f??null}get framer(){if(this._frameClient==null)throw new U("cannot read from a channel that has not been created");return this._frameClient}get payload(){return Qt.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,virtual:this.virtual,expression:this.expression,requires:this.requires})}get isCalculated(){return Wt(this.payload)}get ontologyID(){return eo(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const Bd="/channel/retrieve-group",Zd=s.z.object({}),Ud=s.z.object({group:Hn});let Xa=class{constructor(e,t,n,i){c(this,"type",Zr);c(this,"frameClient");c(this,"client");c(this,"retriever");c(this,"writer");this.frameClient=e,this.retriever=t,this.client=n,this.writer=i}async create(e,t={}){const{retrieveIfNameExists:n=!1}=t,i=!Array.isArray(e);let a=b(e),o=[];if(n){const l=await this.retriever.retrieve(a.map(h=>h.name)),u=new Set(l.map(h=>h.name));a=a.filter(h=>!u.has(h.name)),o=this.sugar(l)}return o=o.concat(this.sugar(await this.writer.create(a))),i?o[0]:o}async retrieve(e,t){const n=!Array.isArray(e),i=this.sugar(await this.retriever.retrieve(e,t));return en("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}=Ee(e);return n==="keys"?await this.writer.delete({keys:t}):await this.writer.delete({names:t})}async rename(e,t){return await this.writer.rename(b(e),b(t))}newSearcherWithOptions(e){return{type:this.type,search:async t=>await this.search(t,e),retrieve:async t=>await this.retrieve(t,e),page:async(t,n)=>await this.page(t,n,e)}}async page(e,t,n){return this.sugar(await this.retriever.page(e,t,n))}createDebouncedBatchRetriever(e=10){return new ps(new Ka(new Yt(this.client),e))}sugar(e){const{frameClient:t}=this;return e.map(n=>new gs({...n,frameClient:t}))}async retrieveGroup(){const e=await w(this.client,Bd,{},Zd,Ud);return new ys(e.group.name,e.group.key)}};const Wt=({virtual:r,expression:e})=>r&&e!=="",Qa=async(r,e)=>{if(!Wt(e))return e.index;for(const t of e.requires){const n=await r(t);if(n==null)return null;if(!n.virtual)return n.index}for(const t of e.requires){const n=await r(t);if(n==null)return null;if(Wt(n)){const i=await Qa(r,n);if(i!=null)return i}}return null},eo=r=>new O({type:Zr,key:r.toString()}),Ld=s.z.object({channels:Ta.array()}),_d=s.z.object({channels:Qt.array()}),qd=s.z.object({keys:J.array().optional(),names:Xt.array().optional()}),Yd=s.z.object({}),Wd=s.z.object({keys:J.array(),names:Xt.array()}),Fd=s.z.object({}),Gd="/channel/create",Vd="/channel/delete",Jd="/channel/rename";let to=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,Gd,{channels:e},Ld,_d);return this.cache.set(t),t}async delete(e){await w(this.client,Vd,e,qd,Yd),e.keys!=null&&this.cache.delete(e.keys),e.names!=null&&this.cache.delete(e.names)}async rename(e,t){await w(this.client,Jd,{keys:e,names:t},Wd,Fd),this.cache.rename(e,t)}};const Kd=Object.freeze(Object.defineProperty({__proto__:null,CacheRetriever:ps,Channel:gs,Client:Xa,ClusterRetriever:Yt,DebouncedBatchRetriever:Ka,ONTOLOGY_TYPE:Zr,Writer:to,analyzeParams:Ee,channelZ:Qt,isCalculated:Wt,keyZ:J,nameZ:Xt,newZ:Ta,ontologyID:eo,resolveCalculatedIndex:Qa,retrieveRequired:Ha},Symbol.toStringTag,{value:"Module"})),Hd=s.z.object({keys:Ze.array().optional(),usernames:s.z.string().array().optional()}),Xd=s.z.object({users:V(sr)}),Qd="/user/retrieve";let ef=class{constructor(e){c(this,"client");this.client=e}async retrieve(e){return(await w(this.client,Qd,e,Hd,Xd)).users}};const tf=s.z.object({users:Aa.array()}),rf=s.z.object({users:sr.array()}),nf=s.z.object({key:Ze,username:s.z.string().min(1)}),sf=s.z.object({}),af=s.z.object({key:Ze,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),of=s.z.object({}),cf=s.z.object({keys:Ze.array()}),lf=s.z.object({}),uf="/user/create",hf="/user/change-username",df="/user/rename",ff="/user/delete";let yf=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,uf,{users:b(e)},tf,rf)).users}async changeUsername(e,t){await w(this.client,hf,{key:e,username:t},nf,sf)}async rename(e,t,n){await w(this.client,df,{key:e,firstName:t,lastName:n},af,of)}async delete(e){await w(this.client,ff,{keys:b(e)},cf,lf)}},ro=class{constructor(e){c(this,"reader");c(this,"writer");this.writer=new yf(e),this.reader=new ef(e)}async create(e){const t=Array.isArray(e),n=await this.writer.create(e);return t?n:n[0]}async changeUsername(e,t){await this.writer.changeUsername(e,t)}async retrieve(e){const t=Array.isArray(e),n=await this.reader.retrieve({keys:b(e)});if(t)return n;if(n.length===0)throw new Oe(`No user with key ${e} found`);if(n.length>1)throw new Ne(`Multiple users found with key ${e}`);return n[0]}async retrieveByName(e){const t=Array.isArray(e),n=await this.reader.retrieve({usernames:b(e)});if(t)return n;if(n.length===0)throw new Oe(`No user with username ${e} found`);if(n.length>1)throw new Ne(`Multiple users found with username ${e}`);return n[0]}async rename(e,t,n){await this.writer.rename(e,t,n)}async delete(e){await this.writer.delete(e)}};const pf=r=>new O({type:is,key:r}),gf=Object.freeze(Object.defineProperty({__proto__:null,Client:ro,ONTOLOGY_TYPE:is,keyZ:Ze,newZ:Aa,ontologyID:pf,userZ:sr},Symbol.toStringTag,{value:"Module"})),mf=s.z.object({username:s.z.string(),password:s.z.string()}),wf=s.z.object({token:s.z.string(),user:sr}),wi="/auth/login",bf=3,Tf="/auth/change-password",vf=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),Of=s.z.object({}),Nf=[Ut,Lt];let Ef=class{constructor(e,t){c(this,"token");c(this,"client");c(this,"credentials");c(this,"authenticating");c(this,"authenticated");c(this,"user");c(this,"retryCount");this.client=e,this.authenticated=!1,this.credentials=t,this.retryCount=0}async changePassword(e){if(!this.authenticated)throw new Error("Not authenticated");await w(this.client,Tf,{username:this.credentials.username,password:this.credentials.password,newPassword:e},vf,Of),this.credentials.password=e}middleware(){const e=async(t,n)=>{if(!this.authenticated&&!t.target.endsWith(wi)){this.authenticating??(this.authenticating=new Promise((l,u)=>{this.client.send(wi,this.credentials,mf,wf).then(([h,f])=>{if(f!=null)return l(f);this.token=h==null?void 0:h.token,this.user=h==null?void 0:h.user,this.authenticated=!0,l(null)}).catch(u)}));const o=await this.authenticating;if(o!=null)return[t,o]}t.params.Authorization=`Bearer ${this.token}`;const[i,a]=await n(t);return Nf.some(o=>o.matches(a))&&this.retryCount<bf?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,e(t,n)):(this.retryCount=0,[i,a])};return e}};const no=s.z.enum(["disconnected","connecting","connected","failed"]),so=s.z.object({status:no,error:s.z.instanceof(Error).optional(),message:s.z.string().optional(),clusterKey:s.z.string(),clientVersion:s.z.string(),clientServerCompatible:s.z.boolean(),nodeVersion:s.z.string().optional()}),zf=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),bi={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.40.0"},Ti=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
|
|
37
|
+
This may cause compatibility issues. We recommend updating the ${n}. For more information, see
|
|
38
|
+
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`},ot=class ot{constructor(e,t=N.seconds(30),n,i){c(this,"_state");c(this,"pollFrequency",N.seconds(30));c(this,"client");c(this,"name");c(this,"interval");c(this,"clientVersion");c(this,"onChangeHandlers",[]);c(this,"versionWarned",!1);this._state={...bi},this.client=e,this.pollFrequency=t,this.clientVersion=n,this.name=i,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){var t;const e=this._state.status;try{const[n,i]=await this.client.send(ot.ENDPOINT,{},s.z.object({}),zf);if(i!=null)throw i;const a=n.nodeVersion,o=this.clientVersion,l=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,l||(console.warn(Ti(null,o,!0)),this.versionWarned=!0)):li.versionsEqual(o,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,l||(console.warn(Ti(a,o,li.semVerNewer(o,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=n.clusterKey,this._state.nodeVersion=n.nodeVersion,this._state.clientVersion=this.clientVersion}catch(n){this._state.status="failed",this._state.error=n,this._state.message=(t=this.state.error)==null?void 0:t.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(n=>n(this.state)),this.state}get state(){return{...this._state}}onChange(e){this.onChangeHandlers.push(e)}startChecking(){this.interval=setInterval(()=>{this.check()},this.pollFrequency.milliseconds)}};c(ot,"ENDPOINT","/connectivity/check"),c(ot,"DEFAULT",bi),c(ot,"connectionStateZ",so);let Ft=ot;const Sf=Object.freeze(Object.defineProperty({__proto__:null,Checker:Ft,stateZ:so,statusZ:no},Symbol.toStringTag,{value:"Module"})),If=s.z.object({keys:J.array().optional(),bounds:G.z,names:Xt.array().optional()}),$f=s.z.object({}),kf="/frame/delete";class Af{constructor(e){c(this,"client");this.client=e}async delete(e){await w(this.client,kf,e,If,$f)}}class tn{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 tn(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=Ee(e);if(t==="keys"){this.adapter=null,this.keys=n;return}const i=await this.retriever.retrieve(n),a=new Map;this.adapter=a,n.forEach(o=>{const l=i.find(u=>u.name===o);if(l==null)throw new Error(`Channel ${o} not found`);a.set(l.key,l.name)}),this.keys=Array.from(this.adapter.keys())}adapt(e){if(this.adapter==null)return e;const t=this.adapter;return e.map((n,i)=>{if(typeof n=="number"){const a=t.get(n);if(a==null)throw new Error(`Channel ${n} not found`);return[a,i]}return[n,i]})}}class ms{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 ms(e);return await n.update(t),n}async adaptObjectKeys(e){const t={};for(const[n,i]of Object.entries(e))t[await this.adaptToKey(n)]=i;return t}async update(e){const t=await Ha(this.retriever,e);this.adapter=new Map(t.map(n=>[n.name,n.key])),this.keys=t.map(n=>n.key)}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${e} not found`);return t[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}async adapt(e,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new U(`
|
|
39
39
|
Received a single channel name or key but no series.
|
|
40
|
-
`);if(Array.isArray(t)){if(t.some(u=>u instanceof
|
|
40
|
+
`);if(Array.isArray(t)){if(t.some(u=>u instanceof ke||Array.isArray(u)))throw new U(`
|
|
41
41
|
Received a single channel name or key but multiple series.
|
|
42
|
-
`);t=t}const o=await this.fetchChannel(e),l=new
|
|
42
|
+
`);t=t}const o=await this.fetchChannel(e),l=new ke({data:t,dataType:o.dataType});return new Y(o.key,l)}if(Array.isArray(e)){if(t==null)throw new U(`
|
|
43
43
|
Received an array of channel names or keys but no series.
|
|
44
|
-
`);if(!Array.isArray(t))throw new
|
|
44
|
+
`);if(!Array.isArray(t))throw new U(`
|
|
45
45
|
Received an array of channel names or keys but no array of series.
|
|
46
|
-
`);const o=[],l=[];for(let u=0;u<e.length;u++){const h=await this.fetchChannel(e[u]);if(u>=t.length)throw new
|
|
46
|
+
`);const o=[],l=[];for(let u=0;u<e.length;u++){const h=await this.fetchChannel(e[u]);if(u>=t.length)throw new U(`
|
|
47
47
|
Received an array of channel names or keys but not enough series.
|
|
48
|
-
`);const f=new
|
|
48
|
+
`);const f=new ke({data:t[u],dataType:h.dataType});o.push(h.key),l.push(f)}return new Y(o,l)}if(e instanceof Y||e instanceof Map){const o=new Y(e);if(this.adapter==null)return o;const l=o.columns.map(u=>{var f;const h=typeof u=="string"?(f=this.adapter)==null?void 0:f.get(u):u;if(h==null)throw new U(`
|
|
49
49
|
Channel ${u} was not provided in the list of channels when opening the writer
|
|
50
|
-
`);return h});return new
|
|
51
|
-
Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Ie.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Ir=new z(-1);var Zr=(n=>(n[n.Open=0]="Open",n[n.Next=1]="Next",n[n.Prev=2]="Prev",n[n.SeekFirst=3]="SeekFirst",n[n.SeekLast=4]="SeekLast",n[n.SeekLE=5]="SeekLE",n[n.SeekGE=6]="SeekGE",n[n.Valid=7]="Valid",n[n.Error=8]="Error",n))(Zr||{}),ya=(n=>(n[n.None=0]="None",n[n.Ack=1]="Ack",n[n.Data=2]="Data",n))(ya||{});const kd=s.z.object({command:s.z.nativeEnum(Zr),span:z.z.optional(),bounds:F.z.optional(),stamp:I.z.optional(),keys:s.z.number().array().optional(),chunkSize:s.z.number().optional()}),$d=s.z.object({variant:s.z.nativeEnum(ya),ack:s.z.boolean(),command:s.z.nativeEnum(Zr),error:Bt.optional().nullable(),frame:Pn.optional()}),At=class At{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"value");this.stream=new Ur("Iterator",e),this.value=new _,this.adapter=t}static async _open(e,t,r,i,a={}){const o=await Dn.open(r,t),l=await i.stream(At.ENDPOINT,kd,$d),u=new At(l,o);return await u.execute({command:0,keys:o.keys,bounds:new F(e),chunkSize:a.chunkSize??1e5}),u}async next(e=Ir){return await this.execute({command:1,span:new z(e)})}async prev(e=Ir){return await this.execute({command:2,span:new z(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 I(e)})}async seekGE(e){return await this.execute({command:6,stamp:new I(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new Ad(this)}async execute(e){for(this.stream.send(e),this.value=new _;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new _(t.frame)))}}};c(At,"ENDPOINT","/frame/iterate");let On=At;class Ad{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 Rd=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),xd=s.z.object({frame:Pn,error:Bt.optional().nullable()}),Cd="/frame/stream";class jn{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"downsampleFactor");this.stream=new Ur("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,t,{channels:r,downsampleFactor:i}){const a=await Dn.open(e,r),o=await t.stream(Cd,Rd,xd),l=new jn(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await o.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Ie.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new _((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys,downsampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Pe extends xe.Observer{constructor(t,r){super(r);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 Lr=(n=>(n[n.Open=0]="Open",n[n.Write=1]="Write",n[n.Commit=2]="Commit",n[n.Error=3]="Error",n[n.SetAuthority=4]="SetAuthority",n))(Lr||{}),ct=(n=>(n[n.PersistStream=1]="PersistStream",n[n.Persist=2]="Persist",n[n.Stream=3]="Stream",n))(ct||{});const Pd=n=>{switch(n){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof n=="number"&&n in ct)return n;throw new Error(`invalid writer mode: ${n}`)}},Dd=new z(-1),jd=s.z.object({start:I.z.optional(),controlSubject:at.subjectZ.optional(),keys:s.z.number().array().optional(),authorities:at.Authority.z.array().optional(),mode:s.z.nativeEnum(ct).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:z.z.optional()}),Md=s.z.object({command:s.z.nativeEnum(Lr),config:jd.optional(),frame:Pn.optional()}),Bd=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Lr),error:Bt.optional().nullable()});var Ne;let ga=(Ne=class{constructor(e,t){c(this,"stream");c(this,"adapter");this.stream=new Ur("Writer",e),this.adapter=t}static async _open(e,t,{channels:r,start:i=I.now(),authorities:a=at.Authority.Absolute,controlSubject:o,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:f=z.SECOND}){const d=await Br.open(e,r),j=await t.stream(Ne.ENDPOINT,Md,Bd),$=new Ne(j,d);return await $.execute({command:0,config:{start:new I(i),keys:d.keys,controlSubject:o,authorities:b(a),mode:Pd(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:f}}),$}async write(e,t){const r=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:r.toPayload()}),!0}async setAuthority(e,t){let r;if(typeof e=="number"&&t==null)r={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),r={keys:Object.keys(a).map(o=>Number(o)),authorities:Object.values(a)}}return(await this.execute({command:4,config:r})).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?mn(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(Ne,"ENDPOINT","/frame/write"),Ne);const pa="framer",Ud=n=>new O({type:pa,key:n.toString()});let ma=class{constructor(e,t,r){c(this,"streamClient");c(this,"retriever");c(this,"deleter");this.streamClient=e,this.retriever=r,this.deleter=new Id(t)}async openIterator(e,t,r){return await On._open(e,t,this.retriever,this.streamClient,r)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ga._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await jn._open(this.retriever,this.streamClient,e)}async write(e,t,r){if(r==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:ct.Persist});try{await o.write(a),await o.commit()}finally{await o.close()}return}const i=await this.openWriter({start:e,channels:t,mode:ct.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});try{await i.write(t,r)}finally{await i.close()}}async read(e,t){const{single:r}=be(t),i=await this.readFrame(e,t);return r?i.get(t):i}async readFrame(e,t){const r=await this.openIterator(e,t),i=new _;try{for await(const a of r)i.push(a)}finally{await r.close()}return i}async delete(e,t){const{normalized:r,variant:i}=be(e);return i==="keys"?await this.deleter.delete({keys:r,bounds:t}):await this.deleter.delete({names:r,bounds:t})}};const Zd=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Dd,AUTO_SPAN:Ir,Client:ma,Frame:_,Iterator:On,ONTOLOGY_TYPE:pa,ObservableStreamer:Pe,Streamer:jn,Writer:ga,WriterMode:ct,frameZ:Pn,ontologyID:Ud,seriesFromPayload:da,seriesToPayload:fa},Symbol.toStringTag,{value:"Module"})),Ld=at.Authority,qd=at.stateZ(s.z.number()),Yd=n=>{var e,t;return n.to==null?`${(e=n.from)==null?void 0:e.resource} - ${(t=n.from)==null?void 0:t.subject.name} -> released`:n.from==null?`${n.to.resource} - released -> ${n.to.subject.name} (${n.to.authority.toString()})`:`${n.to.resource} - ${n.from.subject.name} -> ${n.to.subject.name} (${n.to.authority.toString()})`};class wa extends Pe{constructor(t){super(t,r=>{const i=this.codec.decode(r.series[0].buffer);return this.merge(i),[i.transfers,!0]});c(this,"states");c(this,"codec");this.states=new Map,this.codec=new lt.JSONCodec}subjects(){const t=new Map;return this.states.forEach(r=>t.set(r.subject.key,r.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(r=>{r.from==null&&r.to==null&&console.warn("Invalid transfer: ",r),r.to==null?this.states.delete(r.from.resource):this.states.set(r.to.resource,r.to)})}}const _d="sy_node_1_control";let ba=class{constructor(e){c(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(_d);return new wa(e)}};const Wd=Object.freeze(Object.defineProperty({__proto__:null,Authority:Ld,Client:ba,StateTracker:wa,stateZ:qd,transferString:Yd},Symbol.toStringTag,{value:"Module"}));let Ta=class{constructor(e,t,r){c(this,"tasks");c(this,"racks");c(this,"devices");this.tasks=e,this.racks=t,this.devices=r}};const Gd=Object.freeze(Object.defineProperty({__proto__:null,Client:Ta},Symbol.toStringTag,{value:"Module"})),dt=s.z.number(),Mn=s.z.object({key:dt,name:s.z.string()}),va=Mn.partial({key:!0}),Oa="rack",Fd=n=>new O({type:Oa,key:n.toString()}),Bn=s.z.string(),Gt=s.z.object({key:Bn,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(n=>n===""?{}:lt.JSON_CODEC.decodeString(n)))}),za=Gt.extend({properties:s.z.unknown().transform(n=>lt.JSON_CODEC.encodeString(n))}),Ea="device",Vd=n=>new O({type:Ea,key:n.toString()}),De=async(n,e,t,r)=>{const i=await n.openStreamer([e,t]),a=o=>{const l=[];return t!=null&&l.push(...o.get(t).series.flatMap(u=>r("delete",u))),e!=null&&l.push(...o.get(e).series.flatMap(u=>r("set",u))),[l,l.length>0]};return new Pe(i,a)},Jd=Object.freeze(Object.defineProperty({__proto__:null,openObservable:De},Symbol.toStringTag,{value:"Module"})),Kd="sy_device_set",Hd="sy_device_delete",er="/hardware/device/retrieve",Xd="/hardware/device/create",Qd="/hardware/device/delete",ef=s.z.object({devices:za.array()}),tf=s.z.object({devices:Gt.array()}),nf=s.z.object({keys:Bn.array()}),rf=s.z.object({}),tr=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:Bn.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional()}),nr=s.z.object({devices:V(Gt)});let Na=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 r=!Array.isArray(e),i=await w(this.client,er,{keys:b(e),...t},tr,nr);return Cn("Device",e,i.devices,r),r?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,er,{search:e,...t},tr,nr)).devices}async page(e,t,r){return(await w(this.client,er,{offset:e,limit:t,...r},tr,nr)).devices}async create(e){const t=!Array.isArray(e),r=await w(this.client,Xd,{devices:b(e)},ef,tf);return t?r.devices[0]:r.devices}async delete(e){await w(this.client,Qd,{keys:b(e)},nf,rf)}async openDeviceTracker(){return await De(this.frameClient,Kd,Hd,sf)}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,r)=>await this.page(t,r,e)}}};const sf=(n,e)=>n==="delete"?e.toStrings().map(t=>({variant:n,key:t,value:void 0})):e.parseJSON(Gt).map(t=>({variant:n,key:t.key,value:t})),af=Object.freeze(Object.defineProperty({__proto__:null,Client:Na,ONTOLOGY_TYPE:Ea,deviceKeyZ:Bn,deviceZ:Gt,newDeviceZ:za,ontologyID:Vd},Symbol.toStringTag,{value:"Module"})),rr="/hardware/rack/retrieve",of="/hardware/rack/create",cf="/hardware/rack/delete",sr=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()}),ir=s.z.object({racks:V(Mn)}),lf=s.z.object({racks:va.array()}),uf=s.z.object({racks:Mn.array()}),hf=s.z.object({keys:dt.array()}),df=s.z.object({});let Sa=class{constructor(e,t,r){c(this,"type","rack");c(this,"client");c(this,"frameClient");c(this,"tasks");this.client=e,this.frameClient=t,this.tasks=r}async delete(e){await w(this.client,cf,{keys:b(e)},hf,df)}async create(e){const t=!Array.isArray(e),r=await w(this.client,of,{racks:b(e)},lf,uf),i=this.sugar(r.racks);return t?i[0]:i}async search(e){const t=await w(this.client,rr,{search:e},sr,ir);return this.sugar(t.racks)}async page(e,t){const r=await w(this.client,rr,{offset:e,limit:t},sr,ir);return this.sugar(r.racks)}async retrieve(e){const{variant:t,normalized:r,single:i}=xn(e,{string:"names",number:"keys"}),a=await w(this.client,rr,{[t]:r},sr,ir),o=this.sugar(a.racks);return Cn("Rack",e,o,i),i?o[0]:o}sugar(e){return e.map(({key:t,name:r})=>new Ia(t,r,this.tasks))}};class Ia{constructor(e,t,r){c(this,"key");c(this,"name");c(this,"tasks");this.key=e,this.name=t,this.tasks=r}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 ff=Object.freeze(Object.defineProperty({__proto__:null,Client:Sa,ONTOLOGY_TYPE:Oa,Rack:Ia,newRackZ:va,ontologyID:Fd,rackKeyZ:dt,rackZ:Mn},Symbol.toStringTag,{value:"Module"})),je=s.z.union([s.z.string(),s.z.bigint().transform(n=>n.toString()),s.z.number().transform(n=>n.toString())]),jt=s.z.object({task:je,variant:s.z.string(),key:s.z.string().optional(),details:s.z.record(s.z.unknown()).or(s.z.string().transform(n=>n===""?{}:JSON.parse(n))).or(s.z.array(s.z.unknown())).or(s.z.null())}),Ft=s.z.object({key:je,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(n=>n===""?{}:lt.JSON_CODEC.decodeString(n))),state:jt.optional().nullable(),snapshot:s.z.boolean().optional()}),ka=Ft.omit({key:!0}).extend({key:je.transform(n=>n.toString()).optional(),config:s.z.unknown().transform(n=>lt.JSON_CODEC.encodeString(n))}),qr=s.z.object({task:je,type:s.z.string(),key:s.z.string(),args:s.z.record(s.z.unknown()).or(s.z.string().transform(n=>n===""?{}:JSON.parse(n))).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),$a="task",Aa=n=>new O({type:$a,key:n.toString()}),$t="sy_task_state",Le="sy_task_cmd",yt=new Error("Task not created");class Ra{constructor(e,t,r,i,a=!1,o=!1,l,u=null,h=null,f=null){c(this,"key");c(this,"name");c(this,"internal");c(this,"type");c(this,"config");c(this,"snapshot");c(this,"state");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=e,this.name=t,this.type=r,this.config=i,this.internal=a,this.snapshot=o,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=f}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return Aa(this.key)}async executeCommand(e,t){if(this.frameClient==null)throw yt;const r=await this.frameClient.openWriter(Le),i=au.id();return await r.write(Le,[{task:this.key,type:e,key:i,args:t}]),await r.close(),i}async executeCommandSync(e,t,r){if(this.frameClient==null)throw yt;const i=await this.frameClient.openStreamer($t),a=await this.executeCommand(e,t);let o;const l=new Promise(u=>setTimeout(()=>u(!1),new z(r).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=jt.safeParse(u.at(-1).sy_task_state);if(h.success){if(o=h.data,o.key===a)break}else console.error(h.error)}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw yt;return new Pe(await this.frameClient.openStreamer($t),e=>{const t=e.get($t);if(t.length===0)return[null,!1];const r=jt.safeParse(t.at(-1));if(!r.success)return console.error(r.error),[null,!1];const i=r.data;return i.task!==this.key?[null,!1]:[i,!0]})}async openCommandObserver(){if(this.frameClient==null)throw yt;return new Pe(await this.frameClient.openStreamer(Le),e=>{const t=e.get(Le);if(t.length===0)return[null,!1];const r=qr.safeParse(t.at(-1));if(!r.success)return console.error(r.error),[null,!1];const i=r.data;return i.task!==this.key?[null,!1]:[i,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw yt;if(!this.snapshot)return null;const e=await this.ontologyClient.retrieveParents(this.ontologyID);return e.length==0?null:e[0]}}const yf=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()}),gf=s.z.object({tasks:V(Ft)}),pf="/hardware/task/retrieve",mf="/hardware/task/create",wf="/hardware/task/delete",bf="/hardware/task/copy",Tf=s.z.object({tasks:ka.array()}),vf=s.z.object({tasks:Ft.array()}),Of=s.z.object({keys:je.array()}),zf=s.z.object({}),Ef=s.z.object({key:je,name:s.z.string(),snapshot:s.z.boolean()}),Nf=s.z.object({task:Ft});let xa=class{constructor(e,t,r,i){c(this,"type","task");c(this,"client");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=r,this.rangeClient=i}async create(e){const t=!Array.isArray(e),r=await w(this.client,mf,{tasks:b(e)},Tf,vf),i=this.sugar(r.tasks);return t?i[0]:i}async delete(e){await w(this.client,wf,{keys:b(e)},Of,zf)}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:r,normalized:i,variant:a}=xn(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=i;const l=await this.execRetrieve(o),u=this.sugar(l);return r&&a!=="rack"?u[0]:u}async copy(e,t,r){const i=await w(this.client,bf,{key:e,name:t,snapshot:r},Ef,Nf);return this.sugar([i.task])[0]}async retrieveByName(e,t){const r=await this.execRetrieve({names:[e],rack:t});return Cn("Task",e,r,!0),this.sugar(r)[0]}async execRetrieve(e){return(await w(this.client,pf,e,yf,gf)).tasks}sugar(e){return e.map(({key:t,name:r,type:i,config:a,state:o,internal:l,snapshot:u})=>new Ra(t,r,i,a,l,u,o,this.frameClient,this.ontologyClient,this.rangeClient))}async openTracker(){return await De(this.frameClient,"sy_task_set","sy_task_delete",(e,t)=>Array.from(t).map(r=>({variant:e,key:r.toString(),value:r.toString()})))}async openStateObserver(){return new Pe(await this.frameClient.openStreamer($t),e=>{const t=e.get($t);if(t.length===0)return[null,!1];const r=jt.safeParse(t.at(-1));return r.success?[r.data,!0]:(console.error(r.error),[null,!1])})}async openCommandObserver(){return new Pe(await this.frameClient.openStreamer(Le),e=>{const t=e.get(Le);if(t.length===0)return[null,!1];const r=qr.safeParse(t.at(-1));return r.success?[r.data,!0]:(console.error(r.error),[null,!1])})}};const Sf=Object.freeze(Object.defineProperty({__proto__:null,Client:xa,ONTOLOGY_TYPE:$a,Task:Ra,commandZ:qr,newTaskZ:ka,ontologyID:Aa,stateZ:jt,taskKeyZ:je,taskZ:Ft},Symbol.toStringTag,{value:"Module"})),ft=s.z.string().uuid(),Vt=s.z.object({key:ft,name:s.z.string().min(1),color:s.z.string()}),Ca="label",Pa=n=>new O({type:Ca,key:n}),If=s.z.object({keys:ft.array().optional(),for:ee.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),kf=s.z.object({labels:V(Vt)}),Nn=class Nn{constructor(e){c(this,"client");this.client=e}async retrieve(e){const t=b(e);return await this.execute({keys:t})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,r]=await this.client.send(Nn.ENDPOINT,e,If,kf);if(r!=null)throw r;return t.labels}};c(Nn,"ENDPOINT","/label/retrieve");let zn=Nn;const Da=Vt.extend({key:ft.optional()}),$f=s.z.object({labels:Da.array()}),Af=s.z.object({labels:Vt.array()}),Rf=s.z.object({keys:ft.array()}),ja=s.z.object({id:ee,labels:ft.array(),replace:s.z.boolean().optional()}),xf=ja.omit({replace:!0}),ar=s.z.object({}),Cf="/label/create",Pf="/label/delete",Df="/label/set",jf="/label/remove";let Ma=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,Cf,{labels:b(e)},$f,Af)).labels}async delete(e){await w(this.client,Pf,{keys:b(e)},Rf,ar)}async set(e,t,{replace:r}={}){await w(this.client,Df,{id:e,labels:t,replace:r},ja,ar)}async remove(e,t){await w(this.client,jf,{id:e,labels:t},xf,ar)}};const Mf="sy_label_set",Bf="sy_label_delete";let Ba=class{constructor(e,t,r){c(this,"type","label");c(this,"retriever");c(this,"writer");c(this,"frameClient");c(this,"ontology");this.writer=new Ma(e),this.retriever=new zn(e),this.frameClient=t,this.ontology=r}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),r=await this.retriever.retrieve(e);return t?r:r[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new O(e))}async label(e,t,r={}){await this.writer.set(new O(e),t,r)}async removeLabels(e,t){await this.writer.remove(new O(e),t)}async page(e,t){return await this.retriever.page(e,t)}async create(e){const t=Array.isArray(e),r=await this.writer.create(e);return t?r:r[0]}async delete(e){await this.writer.delete(e)}async openChangeTracker(){return await De(this.frameClient,Mf,Bf,Uf)}async trackLabelsOf(e){const t=new xe.Observer,r=(await this.retrieveFor(e)).map(a=>({id:Pa(a.key),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new O(e),dependents:r,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var l,u;return{key:o.id.key,color:(l=o.data)==null?void 0:l.color,name:(u=o.data)==null?void 0:u.name}}))),t}};const Uf=(n,e)=>n==="delete"?e.toUUIDs().map(t=>({variant:n,key:t})):e.parseJSON(Vt).map(t=>({variant:n,key:t.key,value:t})),Zf=Object.freeze(Object.defineProperty({__proto__:null,Client:Ba,ONTOLOGY_TYPE:Ca,Retriever:zn,Writer:Ma,keyZ:ft,labelZ:Vt,newLabelPayloadZ:Da,ontologyID:Pa},Symbol.toStringTag,{value:"Module"})),ne=s.z.string().uuid(),Jt=s.z.object({key:ne,name:s.z.string().min(1),timeRange:F.z,color:s.z.string().optional()}),Ua=Jt.extend({key:s.z.string().uuid().optional()}),Za=n=>{const e=b(n),t=e.length===0;let r=!1;return t||(r=ne.safeParse(e[0]).success),{single:!Array.isArray(n),variant:r?"keys":"names",normalized:e,actual:n,empty:t}},La="range",qa="range-alias",Oe=n=>new O({type:La,key:n}),Lf=n=>new O({type:qa,key:n}),qf="sy_range_alias_set",Yf="sy_range_alias_delete",_f=s.z.object({range:ne,aliases:s.z.string().array()}),Wf=s.z.object({aliases:s.z.record(s.z.string(),de)}),Gf=s.z.object({range:ne,aliases:s.z.record(de.or(s.z.string()),s.z.string())}),Ff=s.z.unknown(),Vf=s.z.object({range:ne,channels:de.array()}),Jf=s.z.unknown(),Kf=s.z.object({range:ne}),Hf=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),he=class he{constructor(e,t,r){c(this,"frameClient");c(this,"cache",new Map);c(this,"client");c(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=r,this.frameClient=t}async resolve(e){const t=[],r=typeof e=="string",i={};if(r){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?i[o]=l:t.push(o)});if(t.length===0)return i;const a=await w(this.client,he.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},_f,Wf);return Object.entries(a.aliases).forEach(([o,l])=>this.cache.set(o,l)),r?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,he.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Gf,Ff)}async list(){return(await w(this.client,he.LIST_ENDPOINT,{range:this.rangeKey},Kf,Hf)).aliases}async delete(e){await w(this.client,he.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Vf,Jf)}async openChangeTracker(){return await De(this.frameClient,qf,Yf,ey(this.rangeKey))}};c(he,"SET_ENDPOINT","/range/alias/set"),c(he,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(he,"LIST_ENDPOINT","/range/alias/list"),c(he,"DELETE_ENDPOINT","/range/alias/delete");let kr=he;const Xf=s.z.object({range:ne,channel:de,alias:s.z.string()}),Qf="---",ey=n=>(e,t)=>e==="delete"?t.toStrings().filter(r=>r.split(Qf)[0]===n).map(r=>({variant:e,key:r,value:void 0})):t.parseJSON(Xf).map(r=>({variant:e,key:r.alias,value:r})),ty=s.z.object({range:ne,keys:s.z.string().array()}),Yr=s.z.object({range:ne,key:s.z.string(),value:s.z.string()}),ny=s.z.object({pairs:V(Yr)}),ry=s.z.object({range:ne,pairs:Yr.array()}),sy=s.z.object({range:ne,keys:s.z.string().array()}),ze=class ze{constructor(e,t,r){c(this,"rangeKey");c(this,"client");c(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=r}async get(e){const t=await w(this.client,ze.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},ty,ny);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(r=>[r.key,r.value]))}async list(){return this.get([])}async set(e,t=""){let r;Rr(e)?r=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):r=[{range:this.rangeKey,key:e,value:t}],await w(this.client,ze.SET_ENDPOINT,{range:this.rangeKey,pairs:r},ry,s.z.unknown())}async delete(e){await w(this.client,ze.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},sy,s.z.unknown())}async openTracker(){return await De(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(r=>{const[i,a]=r.split("<--->",2);return{variant:e,key:r,value:{range:i,key:a,value:""}}}):t.parseJSON(Yr).map(r=>({variant:e,key:`${r.range}${r.key}`,value:r})))}};c(ze,"GET_ENDPOINT","/range/kv/get"),c(ze,"SET_ENDPOINT","/range/kv/set"),c(ze,"DELETE_ENDPOINT","/range/kv/delete");let Mt=ze;class Ya{constructor(e,t=F.ZERO,r,i,a,o,l,u,h,f,d){c(this,"key");c(this,"name");c(this,"kv");c(this,"timeRange");c(this,"color");c(this,"channels");c(this,"aliaser");c(this,"frameClient");c(this,"labelClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=r,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=f,this.rangeClient=d}get ontologyID(){return Oe(this.key)}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const r=await this.channels.retrieve(e);if(r.length===0)throw new se(`Channel ${e} does not exist`);await this.aliaser.set({[r[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(Oe(this.key))}async addLabel(...e){await this.labelClient.label(Oe(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(Oe(this.key),e)}async openChildRangeTracker(){const e=new xe.Observer,t=(await this.retrieveChildren()).map(i=>{const a=Oe(i.key);return{id:a,key:a.toString(),name:i.name,data:i.payload}}),r=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return r.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await r.close()),e}async openParentRangeTracker(){const e=new xe.Observer,t=await this.retrieveParent();if(t==null)return null;const r=Oe(t.key),i={id:r,key:r.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const l=this.rangeClient.resourcesToRanges(o);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const iy=(n,e)=>cu(n.timeRange,e.timeRange),ay=s.z.object({keys:ne.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:F.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),oy="/range/retrieve",cy=s.z.object({ranges:V(Jt)});let _a=class{constructor(e,t,r,i,a,o){c(this,"type","range");c(this,"frameClient");c(this,"writer");c(this,"unaryClient");c(this,"channels");c(this,"labelClient");c(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=r,this.channels=i,this.labelClient=a,this.ontologyClient=o}async create(e,t){const r=!Array.isArray(e),i=this.sugarMany(await this.writer.create(b(e),t));return r?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new F(e)});const{single:t,actual:r,variant:i,normalized:a,empty:o}=Za(e);if(o)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new me(`range matching ${r} not found`);if(l.length>1)throw new we(`multiple ranges matching ${r} found`);return l[0]}getKV(e){return new Mt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,oy,e,ay,cy);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents(Oe(e));if(t.length===0)return null;const r=t[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOne(e){return new Ya(e.name,e.timeRange,e.key,e.color,this.frameClient,new Mt(e.key,this.unaryClient,this.frameClient),new kr(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await De(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugarMany(t.parseJSON(Jt)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,r,i;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new F((r=e.data)==null?void 0:r.timeRange),color:(i=e.data)==null?void 0:i.color})}};const ly=s.z.object({ranges:Jt.array()}),uy=s.z.object({parent:ee.optional(),ranges:Ua.array()}),hy=s.z.object({keys:ne.array()}),dy=s.z.object({}),fy=s.z.object({key:ne,name:s.z.string()}),yy=s.z.object({}),gy="/range/create",py="/range/delete",my="/range/rename";class Wa{constructor(e){c(this,"client");this.client=e}async rename(e,t){await w(this.client,my,{key:e,name:t},fy,yy)}async create(e,t){return(await w(this.client,gy,{ranges:e,...t},uy,ly)).ranges}async delete(e){await w(this.client,py,{keys:e},hy,dy)}}const wy=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:qa,Client:_a,KV:Mt,ONTOLOGY_TYPE:La,Range:Ya,Writer:Wa,aliasOntologyID:Lf,analyzeParams:Za,keyZ:ne,newPayloadZ:Ua,ontologyID:Oe,payloadZ:Jt,sort:iy},Symbol.toStringTag,{value:"Module"})),by="/api/v1/";class Ty{constructor(e,t={},r=!1){c(this,"url");c(this,"unary");c(this,"stream");c(this,"secure");this.secure=r,this.url=e.child(by);const i=new lt.JSONCodec;this.unary=Wc(new _c(this.url,i,this.secure),t),this.stream=new el(this.url,i,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Kt=s.z.string().uuid(),Un=s.z.object({key:s.z.string(),name:s.z.string(),data:Ut.or(s.z.string().transform(n=>JSON.parse(n)))}),Ga="lineplot",vy=n=>new O({type:Ga,key:n}),Oy="/workspace/lineplot/retrieve",zy="/workspace/lineplot/create",Ey="/workspace/lineplot/rename",Ny="/workspace/lineplot/set-data",Sy="/workspace/lineplot/delete",Fa=Un.partial({key:!0}).transform(n=>({...n,data:JSON.stringify(n.data)})),Iy=s.z.object({keys:Kt.array()}),ky=s.z.object({workspace:s.z.string(),linePlots:Fa.array()}),$y=s.z.object({key:Kt,name:s.z.string()}),Ay=s.z.object({key:Kt,data:s.z.string()}),Ry=s.z.object({keys:Kt.array()}),xy=s.z.object({linePlots:V(Un)}),Cy=s.z.object({linePlots:Un.array()}),or=s.z.object({});let Va=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const r=Array.isArray(t),i=b(t),a=await w(this.client,zy,{workspace:e,linePlots:i},ky,Cy);return r?a.linePlots:a.linePlots[0]}async rename(e,t){await w(this.client,Ey,{key:e,name:t},$y,or)}async setData(e,t){await w(this.client,Ny,{key:e,data:JSON.stringify(t)},Ay,or)}async retrieve(e){const t=Array.isArray(e),r=b(e),i=await w(this.client,Oy,{keys:r},Iy,xy);return t?i.linePlots:i.linePlots[0]}async delete(e){const t=b(e);await w(this.client,Sy,{keys:t},Ry,or)}};const Py=Object.freeze(Object.defineProperty({__proto__:null,Client:Va,ONTOLOGY_TYPE:Ga,keyZ:Kt,linePlotZ:Un,newLinePlotZ:Fa,ontologyID:vy},Symbol.toStringTag,{value:"Module"})),Dy=s.z.string().uuid(),Zn=s.z.object({key:s.z.string(),name:s.z.string(),data:Ut.or(s.z.string().transform(n=>JSON.parse(n)))}),Ja="log",jy=n=>new O({type:Ja,key:n}),My="/workspace/log/retrieve",By="/workspace/log/create",Uy="/workspace/log/rename",Zy="/workspace/log/set-data",Ly="/workspace/log/delete",Ka=Zn.partial({key:!0}).transform(n=>({...n,data:JSON.stringify(n.data)})),qy=s.z.object({keys:s.z.string().array()}),Yy=s.z.object({workspace:s.z.string(),logs:Ka.array()}),_y=s.z.object({key:s.z.string(),name:s.z.string()}),Wy=s.z.object({key:s.z.string(),data:s.z.string()}),Gy=s.z.object({keys:s.z.string().array()}),Fy=s.z.object({logs:Zn.array()}),Vy=s.z.object({logs:Zn.array()}),cr=s.z.object({});let Ha=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const r=Array.isArray(t),i=b(t),a=await w(this.client,By,{workspace:e,logs:i},Yy,Vy);return r?a.logs:a.logs[0]}async rename(e,t){await w(this.client,Uy,{key:e,name:t},_y,cr)}async setData(e,t){await w(this.client,Zy,{key:e,data:JSON.stringify(t)},Wy,cr)}async retrieve(e){const t=Array.isArray(e),r=b(e),i=await w(this.client,My,{keys:r},qy,Fy);return t?i.logs:i.logs[0]}async delete(e){const t=b(e);await w(this.client,Ly,{keys:t},Gy,cr)}};const Jy=Object.freeze(Object.defineProperty({__proto__:null,Client:Ha,ONTOLOGY_TYPE:Ja,keyZ:Dy,logZ:Zn,newLogZ:Ka,ontologyID:jy},Symbol.toStringTag,{value:"Module"})),Ky=s.z.string().uuid(),_r=s.z.object({key:s.z.string(),name:s.z.string(),data:Ut.or(s.z.string().transform(n=>JSON.parse(n))),snapshot:s.z.boolean()}),Wr=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean(),data:s.z.string().transform(n=>JSON.parse(n))}),Xa="schematic",Hy=n=>new O({type:Xa,key:n}),Xy="/workspace/schematic/retrieve",Qy="/workspace/schematic/create",eg="/workspace/schematic/rename",tg="/workspace/schematic/set-data",ng="/workspace/schematic/delete",rg="/workspace/schematic/copy",Qa=_r.partial({key:!0,snapshot:!0}).transform(n=>({...n,data:JSON.stringify(n.data)})),sg=s.z.object({keys:s.z.string().array()}),ig=s.z.object({workspace:s.z.string(),schematics:Qa.array()}),ag=s.z.object({key:s.z.string(),name:s.z.string()}),og=s.z.object({key:s.z.string(),data:s.z.string()}),cg=s.z.object({keys:s.z.string().array()}),lg=s.z.object({key:s.z.string(),name:s.z.string(),snapshot:s.z.boolean()}),ug=s.z.object({schematics:V(Wr)}),hg=s.z.object({schematics:Wr.array()}),dg=s.z.object({schematic:_r}),lr=s.z.object({});let eo=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const r=Array.isArray(t),i=b(t),a=await w(this.client,Qy,{workspace:e,schematics:i},ig,hg);return r?a.schematics:a.schematics[0]}async rename(e,t){await w(this.client,eg,{key:e,name:t},ag,lr)}async setData(e,t){await w(this.client,tg,{key:e,data:JSON.stringify(t)},og,lr)}async retrieve(e){const t=Array.isArray(e),r=b(e),i=await w(this.client,Xy,{keys:r},sg,ug);return t?i.schematics:i.schematics[0]}async delete(e){const t=b(e);await w(this.client,ng,{keys:t},cg,lr)}async copy(e,t,r){return(await w(this.client,rg,{key:e,name:t,snapshot:r},lg,dg)).schematic}};const fg=Object.freeze(Object.defineProperty({__proto__:null,Client:eo,ONTOLOGY_TYPE:Xa,keyZ:Ky,newSchematicZ:Qa,ontologyID:Hy,schematicRemoteZ:Wr,schematicZ:_r},Symbol.toStringTag,{value:"Module"})),yg=s.z.string().uuid(),to=s.z.object({key:s.z.string(),name:s.z.string(),data:Ut.or(s.z.string().transform(n=>JSON.parse(n)))}),no="table",gg=n=>new O({type:no,key:n}),pg="/workspace/table/retrieve",mg="/workspace/table/create",wg="/workspace/table/rename",bg="/workspace/table/set-data",Tg="/workspace/table/delete",ro=to.partial({key:!0}).transform(n=>({...n,data:JSON.stringify(n.data)})),Gr=s.z.object({key:s.z.string(),name:s.z.string(),data:s.z.string().transform(n=>JSON.parse(n))}),vg=s.z.object({keys:s.z.string().array()}),Og=s.z.object({workspace:s.z.string(),tables:ro.array()}),zg=s.z.object({key:s.z.string(),name:s.z.string()}),Eg=s.z.object({key:s.z.string(),data:s.z.string()}),Ng=s.z.object({keys:s.z.string().array()}),Sg=s.z.object({tables:Gr.array()}),Ig=s.z.object({tables:Gr.array()}),ur=s.z.object({});let so=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const r=Array.isArray(t),i=b(t),a=await w(this.client,mg,{workspace:e,tables:i},Og,Ig);return r?a.tables:a.tables[0]}async rename(e,t){await w(this.client,wg,{key:e,name:t},zg,ur)}async setData(e,t){await w(this.client,bg,{key:e,data:JSON.stringify(t)},Eg,ur)}async retrieve(e){const t=Array.isArray(e),r=b(e),i=await w(this.client,pg,{keys:r},vg,Sg);return t?i.tables:i.tables[0]}async delete(e){const t=b(e);await w(this.client,Tg,{keys:t},Ng,ur)}};const kg=Object.freeze(Object.defineProperty({__proto__:null,Client:so,ONTOLOGY_TYPE:no,keyZ:yg,newTableZ:ro,ontologyID:gg,tableRemoteZ:Gr,tableZ:to},Symbol.toStringTag,{value:"Module"})),$g=s.z.string().uuid(),io=n=>JSON.parse(n),Ln=s.z.object({key:s.z.string(),name:s.z.string(),layout:Ut.or(s.z.string().transform(n=>io(n)))}),ao="workspace",Ag=n=>new O({type:ao,key:n}),en="/workspace/retrieve",Rg="/workspace/create",xg="/workspace/rename",Cg="/workspace/set-layout",Pg="/workspace/delete",oo=Ln.partial({key:!0}).transform(n=>({...n,layout:JSON.stringify(n.layout)})),co=Ln.omit({layout:!0}).extend({layout:s.z.string().transform(n=>io(n))}),tn=s.z.object({keys:s.z.string().array().optional(),search:s.z.string().optional(),author:s.z.string().uuid().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Dg=s.z.object({workspaces:oo.array()}),jg=s.z.object({key:s.z.string(),name:s.z.string()}),Mg=s.z.object({key:s.z.string(),layout:s.z.string()}),Bg=s.z.object({keys:s.z.string().array()}),nn=s.z.object({workspaces:V(Ln)}),Ug=s.z.object({workspaces:co.array()}),hr=s.z.object({});class lo{constructor(e){c(this,"type","workspace");c(this,"schematic");c(this,"linePlot");c(this,"log");c(this,"table");c(this,"client");this.client=e,this.schematic=new eo(e),this.linePlot=new Va(e),this.log=new Ha(e),this.table=new so(e)}async create(e){const t=Array.isArray(e),r=b(e),i=await w(this.client,Rg,{workspaces:r},Dg,Ug);return t?i.workspaces:i.workspaces[0]}async rename(e,t){await w(this.client,xg,{key:e,name:t},jg,hr)}async setLayout(e,t){await w(this.client,Cg,{key:e,layout:JSON.stringify(t)},Mg,hr)}async retrieve(e){const t=Array.isArray(e),r=b(e),i=await w(this.client,en,{keys:r},tn,nn);return t?i.workspaces:i.workspaces[0]}async retrieveByAuthor(e){return(await w(this.client,en,{author:e},tn,nn)).workspaces}async search(e){return(await w(this.client,en,{search:e},tn,nn)).workspaces}async page(e,t){return(await w(this.client,en,{offset:e,limit:t},tn,nn)).workspaces}async delete(e){const t=b(e);await w(this.client,Pg,{keys:t},Bg,hr)}}const Zg=Object.freeze(Object.defineProperty({__proto__:null,Client:lo,ONTOLOGY_TYPE:ao,keyZ:$g,newWorkspaceZ:oo,ontologyID:Ag,workspaceRemoteZ:co,workspaceZ:Ln},Symbol.toStringTag,{value:"Module"})),uo=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:z.z.default(z.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:ju.breakerConfig.optional()});class ho extends ma{constructor(t){const r=uo.parse(t),{host:i,port:a,username:o,password:l,connectivityPollFrequency:u,secure:h,retry:f}=r,d=new Ty(new Au({host:i,port:Number(a)}),f,h);d.use(Ju);let j;o!=null&&l!=null&&(j=new Td(d.unary,{username:o,password:l}),d.use(j.middleware()));const $=new jr(new Ct(d.unary)),re=new aa(d.unary,$);super(d.stream,d.unary,$);c(this,"createdAt");c(this,"props");c(this,"ranges");c(this,"channels");c(this,"auth");c(this,"user");c(this,"access");c(this,"connectivity");c(this,"ontology");c(this,"workspaces");c(this,"labels");c(this,"hardware");c(this,"control");c(this,"transport");c(this,"clientVersion","0.38.1");this.createdAt=I.now(),this.props=r,this.auth=j,this.transport=d,this.channels=new sa(this,$,d.unary,re),this.connectivity=new Dt(d.unary,u,this.clientVersion,r.name),this.control=new ba(this),this.ontology=new Gi(d.unary,this);const L=new Wa(this.transport.unary);this.labels=new Ba(this.transport.unary,this,this.ontology),this.ranges=new _a(this,L,this.transport.unary,$,this.labels,this.ontology),this.access=new Hi(this.transport.unary),this.user=new la(this.transport.unary),this.workspaces=new lo(this.transport.unary);const fo=new Na(this.transport.unary,this),Fr=new xa(this.transport.unary,this,this.ontology,this.ranges),yo=new Sa(this.transport.unary,this,Fr);this.hardware=new Ta(Fr,yo,fo)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(ho,"connectivity",Dt);const Lg=at.Authority;exports.AuthError=Ce;exports.Authority=Lg;exports.Channel=Mr;exports.ContiguityError=Nr;exports.DataType=S;exports.Density=H;exports.Frame=_;exports.MultiSeries=xi;exports.MultipleFoundError=we;exports.NotFoundError=me;exports.QueryError=se;exports.Rate=st;exports.RouteError=xt;exports.Series=Ee;exports.Synnax=ho;exports.TimeRange=F;exports.TimeSpan=z;exports.TimeStamp=I;exports.UnexpectedError=Se;exports.ValidationError=Z;exports.access=Ih;exports.channel=Vh;exports.connection=zd;exports.control=Wd;exports.device=af;exports.framer=Zd;exports.group=ah;exports.hardware=Gd;exports.isCalculated=Pt;exports.label=Zf;exports.linePlot=Py;exports.log=Jy;exports.ontology=dh;exports.policy=Sh;exports.rack=ff;exports.ranger=wy;exports.schematic=fg;exports.signals=Jd;exports.synnaxPropsZ=uo;exports.table=kg;exports.task=Sf;exports.user=fd;exports.workspace=Zg;
|
|
50
|
+
`);return h});return new Y(l,o.series)}const n=[],i=[],a=Object.entries(e);for(let o=0;o<a.length;o++){const[l,u]=a[o],h=await this.fetchChannel(l),f=new ke({data:u,dataType:h.dataType});n.push(h.key),i.push(f)}return new Y(n,i)}}class ws{constructor(e,t){c(this,"name");c(this,"stream");this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on closure.
|
|
51
|
+
Please report this error to the Synnax team. ${JSON.stringify(e)}`),t!=null){if(Re.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const qn=new N(-1);var bs=(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))(bs||{}),io=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(io||{});const xf=s.z.object({command:s.z.nativeEnum(bs),span:N.z.optional(),bounds:G.z.optional(),stamp:$.z.optional(),keys:J.array().optional(),chunkSize:s.z.number().optional()}),Rf=s.z.object({variant:s.z.nativeEnum(io),ack:s.z.boolean(),command:s.z.nativeEnum(bs),error:Vt.optional().nullable(),frame:Ur.optional()}),Zt=class Zt{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"value");this.stream=new ws("Iterator",e),this.value=new Y,this.adapter=t}static async _open(e,t,n,i,a={}){const o=await tn.open(n,t),l=await i.stream(Zt.ENDPOINT,xf,Rf),u=new Zt(l,o);return await u.execute({command:0,keys:o.keys,bounds:new G(e),chunkSize:a.chunkSize??1e5}),u}async next(e=qn){return await this.execute({command:1,span:new N(e)})}async prev(e=qn){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)})}async seekGE(e){return await this.execute({command:6,stamp:new $(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new Cf(this)}async execute(e){for(this.stream.send(e),this.value=new Y;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new Y(t.frame)))}}};c(Zt,"ENDPOINT","/frame/iterate");let Ar=Zt;class Cf{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 Pf=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),jf=s.z.object({frame:Ur,error:Vt.optional().nullable()}),Df="/frame/stream";class rn{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"downsampleFactor");this.stream=new ws("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}static async _open(e,t,{channels:n,downsampleFactor:i}){const a=await tn.open(e,n),o=await t.stream(Df,Pf,jf),l=new rn(o,a);o.send({keys:a.keys,downsampleFactor:i??1});const[,u]=await o.receive();if(u!=null)throw u;return l}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(Re.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new Y((await this.stream.receive()).frame))}async update(e){await this.adapter.update(e),this.stream.send({keys:this.adapter.keys,downsampleFactor:this.downsampleFactor})}close(){this.stream.closeSend()}[Symbol.asyncIterator](){return this}}class Be extends Me.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 Ts=(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))(Ts||{}),yt=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(yt||{});const Mf=r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1;default:if(typeof r=="number"&&r in yt)return r;throw new Error(`invalid writer mode: ${r}`)}},Bf=new N(-1),Zf=s.z.object({start:$.z.optional(),controlSubject:dt.subjectZ.optional(),keys:J.array().optional(),authorities:dt.Authority.z.array().optional(),mode:s.z.nativeEnum(yt).optional(),errOnUnauthorized:s.z.boolean().optional(),enableAutoCommit:s.z.boolean().optional(),autoIndexPersistInterval:N.z.optional()}),Uf=s.z.object({command:s.z.nativeEnum(Ts),config:Zf.optional(),frame:Ur.optional()}),Lf=s.z.object({ack:s.z.boolean(),command:s.z.nativeEnum(Ts),error:Vt.optional().nullable()});var Ae;let ao=(Ae=class{constructor(e,t){c(this,"stream");c(this,"adapter");c(this,"errAccumulated",!1);this.stream=new ws("Writer",e),this.adapter=t}static async _open(e,t,{channels:n,start:i=$.now(),authorities:a=dt.Authority.ABSOLUTE,controlSubject:o,mode:l=1,errOnUnauthorized:u=!1,enableAutoCommit:h=!1,autoIndexPersistInterval:f=N.SECOND}){const d=await ms.open(e,n),k=await t.stream(Ae.ENDPOINT,Uf,Lf),S=new Ae(k,d);return await S.execute({command:0,config:{start:new $(i),keys:d.keys,controlSubject:o,authorities:b(a),mode:Mf(l),errOnUnauthorized:u,enableAutoCommit:h,autoIndexPersistInterval:f}}),S}async checkForAccumulatedError(){if(!this.errAccumulated&&this.stream.received())for(this.errAccumulated=!0;this.stream.received();)await this.stream.receive();return this.errAccumulated}async write(e,t){if(await this.checkForAccumulatedError())return!1;const n=await this.adapter.adapt(e,t);return this.stream.send({command:1,frame:n.toPayload()}),!0}async setAuthority(e,t){if(await this.checkForAccumulatedError())return!1;let n;if(typeof e=="number"&&t==null)n={keys:[],authorities:[e]};else{let a;typeof e=="string"||typeof e=="number"?a={[e]:t}:a=e,a=await this.adapter.adaptObjectKeys(a),n={keys:Object.keys(a).map(o=>Number(o)),authorities:Object.values(a)}}return(await this.execute({command:4,config:n})).ack}async commit(){return await this.checkForAccumulatedError()?!1:(await this.execute({command:2})).ack}async error(){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()}},c(Ae,"ENDPOINT","/frame/write"),Ae);const _f=r=>new O({type:Qn,key:r.toString()});let oo=class{constructor(e,t,n){c(this,"streamClient");c(this,"retriever");c(this,"deleter");this.streamClient=e,this.retriever=n,this.deleter=new Af(t)}async openIterator(e,t,n){return await Ar._open(e,t,this.retriever,this.streamClient,n)}async openWriter(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e}),await ao._open(this.retriever,this.streamClient,e)}async openStreamer(e){return(Array.isArray(e)||typeof e!="object")&&(e={channels:e,downsampleFactor:1}),await rn._open(this.retriever,this.streamClient,e)}async write(e,t,n){if(n==null){const a=t,o=await this.openWriter({start:e,channels:Object.keys(a),mode:yt.Persist});try{await o.write(a),await o.commit()}finally{await o.close()}return}const i=await this.openWriter({start:e,channels:t,mode:yt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:N.MAX});try{await i.write(t,n)}finally{await i.close()}}async read(e,t){const{single:n}=Ee(t),i=await this.readFrame(e,t);return n?i.get(t):i}async readFrame(e,t){const n=await this.openIterator(e,t),i=new Y;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}=Ee(e);return i==="keys"?await this.deleter.delete({keys:n,bounds:t}):await this.deleter.delete({names:n,bounds:t})}};const qf=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Bf,AUTO_SPAN:qn,Client:oo,Frame:Y,Iterator:Ar,ONTOLOGY_TYPE:Qn,ObservableStreamer:Be,Streamer:rn,Writer:ao,WriterMode:yt,frameZ:Ur,ontologyID:_f,seriesFromPayload:va,seriesToPayload:Oa},Symbol.toStringTag,{value:"Module"})),Yf=dt.Authority,Wf=dt.stateZ(s.z.number()),Ff=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 co extends Be{constructor(t){super(t,n=>{const i=this.codec.decode(n.series[0].buffer);return this.merge(i),[i.transfers,!0]});c(this,"states");c(this,"codec");this.states=new Map,this.codec=new Jt.JSONCodec}subjects(){const t=new Map;return this.states.forEach(n=>t.set(n.subject.key,n.subject)),Array.from(t.values())}merge(t){t.transfers.forEach(n=>{n.from==null&&n.to==null&&console.warn("Invalid transfer: ",n),n.to==null?this.states.delete(n.from.resource):this.states.set(n.to.resource,n.to)})}}const Gf="sy_node_1_control";let lo=class{constructor(e){c(this,"framer");this.framer=e}async openStateTracker(){const e=await this.framer.openStreamer(Gf);return new co(e)}};const Vf=Object.freeze(Object.defineProperty({__proto__:null,Authority:Yf,Client:lo,StateTracker:co,stateZ:Wf,transferString:Ff},Symbol.toStringTag,{value:"Module"}));let uo=class{constructor(e,t,n){c(this,"tasks");c(this,"racks");c(this,"devices");this.tasks=e,this.racks=t,this.devices=n}};const Jf=Object.freeze(Object.defineProperty({__proto__:null,Client:uo},Symbol.toStringTag,{value:"Module"})),Le=async(r,e,t,n)=>{const i=await r.openStreamer([e,t]),a=o=>{const l=[];return t!=null&&l.push(...o.get(t).series.flatMap(u=>n("delete",u))),e!=null&&l.push(...o.get(e).series.flatMap(u=>n("set",u))),[l,l.length>0]};return new Be(i,a)},Kf=Object.freeze(Object.defineProperty({__proto__:null,openObservable:Le},Symbol.toStringTag,{value:"Module"})),Hf="sy_device_set",Xf="sy_device_delete",gn="/hardware/device/retrieve",Qf="/hardware/device/create",ey="/hardware/device/delete",ty=s.z.object({devices:za.array()}),ry=s.z.object({devices:er.array()}),ny=s.z.object({keys:qr.array()}),sy=s.z.object({}),mn=s.z.object({search:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),keys:qr.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional(),ignoreNotFound:s.z.boolean().optional()}),wn=s.z.object({devices:V(er)});let ho=class{constructor(e,t){c(this,"type",Yr);c(this,"client");c(this,"frameClient");this.client=e,this.frameClient=t}async retrieve(e,t){const n=!Array.isArray(e),i=await w(this.client,gn,{keys:b(e),...t},mn,wn);return en("Device",e,i.devices,n),n?i.devices[0]:i.devices}async search(e,t){return(await w(this.client,gn,{search:e,...t},mn,wn)).devices}async page(e,t,n){return(await w(this.client,gn,{offset:e,limit:t,...n},mn,wn)).devices}async create(e){const t=!Array.isArray(e),n=await w(this.client,Qf,{devices:b(e)},ty,ry);return t?n.devices[0]:n.devices}async delete(e){await w(this.client,ey,{keys:b(e)},ny,sy)}async openDeviceTracker(){return await Le(this.frameClient,Hf,Xf,iy)}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 iy=(r,e)=>r==="delete"?e.toStrings().map(t=>({variant:r,key:t,value:void 0})):e.parseJSON(er).map(t=>({variant:r,key:t.key,value:t})),ay=r=>new O({type:Yr,key:r}),oy=Object.freeze(Object.defineProperty({__proto__:null,Client:ho,ONTOLOGY_TYPE:Yr,deviceZ:er,keyZ:qr,newZ:za,ontologyID:ay},Symbol.toStringTag,{value:"Module"})),bn="/hardware/rack/retrieve",cy="/hardware/rack/create",ly="/hardware/rack/delete",Tn=s.z.object({keys:mt.array().optional(),names:s.z.string().array().optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),vn=s.z.object({racks:V(Lr)}),uy=s.z.object({racks:Na.array()}),hy=s.z.object({racks:Lr.array()}),dy=s.z.object({keys:mt.array()}),fy=s.z.object({});let fo=class{constructor(e,t){c(this,"type",_r);c(this,"client");c(this,"tasks");this.client=e,this.tasks=t}async delete(e){await w(this.client,ly,{keys:b(e)},dy,fy)}async create(e){const t=!Array.isArray(e),n=await w(this.client,cy,{racks:b(e)},uy,hy),i=this.sugar(n.racks);return t?i[0]:i}async search(e){const t=await w(this.client,bn,{search:e},Tn,vn);return this.sugar(t.racks)}async page(e,t){const n=await w(this.client,bn,{offset:e,limit:t},Tn,vn);return this.sugar(n.racks)}async retrieve(e){const{variant:t,normalized:n,single:i}=Qr(e,{string:"names",number:"keys"}),a=await w(this.client,bn,{[t]:n},Tn,vn),o=this.sugar(a.racks);return en("Rack",e,o,i),i?o[0]:o}sugar(e){return e.map(({key:t,name:n})=>new yo(t,n,this.tasks))}};class yo{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 retrieveTaskByType(e){return await this.tasks.retrieveByType(e,this.key)}async createTask(e){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e)}async deleteTask(e){await this.tasks.delete([e])}}const yy=r=>new O({type:_r,key:r.toString()}),py=Object.freeze(Object.defineProperty({__proto__:null,Client:fo,ONTOLOGY_TYPE:_r,Rack:yo,keyZ:mt,newZ:Na,ontologyID:yy,rackZ:Lr},Symbol.toStringTag,{value:"Module"})),Bt="sy_task_state",Fe="sy_task_cmd",gy="sy_task_set",my="sy_task_delete",Ye=new Error("Task not created"),po=async(r,e)=>{const t=await e.retrieveParents(r);return t.length===0?null:t[0]};class go{constructor(e,t,n,i,a=!1,o=!1,l,u=null,h=null,f=null){c(this,"key");c(this,"name");c(this,"internal");c(this,"type");c(this,"config");c(this,"snapshot");c(this,"state");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=e,this.name=t,this.type=n,this.config=i,this.internal=a,this.snapshot=o,l!==null&&(this.state=l),this.frameClient=u,this.ontologyClient=h,this.rangeClient=f}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,state:this.state,internal:this.internal}}get ontologyID(){return wo(this.key)}async executeCommand(e,t){if(this.frameClient==null)throw Ye;const n=await this.frameClient.openWriter(Fe),i=Pu.create();return await n.write(Fe,[{task:this.key,type:e,key:i,args:t}]),await n.close(),i}async executeCommandSync(e,t,n){if(this.frameClient==null)throw Ye;const i=await this.frameClient.openStreamer(Bt),a=await this.executeCommand(e,t);let o;const l=new Promise(u=>setTimeout(()=>u(!1),new N(n).milliseconds));for(;;){const u=await Promise.any([i.read(),l]);if(u===!1)throw new Error("Command timed out");const h=qt.safeParse(u.at(-1).sy_task_state);if(h.success){if(o=h.data,o.key===a)break}else throw h.error}return i.close(),o}async openStateObserver(){if(this.frameClient==null)throw Ye;return new Be(await this.frameClient.openStreamer(Bt),e=>{const t=e.get(Bt);if(t.length===0)return[null,!1];const n=qt.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async openCommandObserver(){if(this.frameClient==null)throw Ye;return new Be(await this.frameClient.openStreamer(Fe),e=>{const t=e.get(Fe);if(t.length===0)return[null,!1];const n=es.safeParse(t.at(-1));if(!n.success)return console.error(n.error),[null,!1];const i=n.data;return i.task!==this.key?[null,!1]:[i,!0]})}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Ye;return this.snapshot?await po(this.key,this.ontologyClient):null}}const wy=s.z.object({rack:mt.optional(),keys:je.array().optional(),names:s.z.string().array().optional(),types:s.z.string().array().optional(),includeState:s.z.boolean().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),by=s.z.object({tasks:V(tr)}),Ty="/hardware/task/retrieve",vy="/hardware/task/create",Oy="/hardware/task/delete",Ny="/hardware/task/copy",Ey=s.z.object({tasks:Ia.array()}),zy=s.z.object({tasks:tr.array()}),Sy=s.z.object({keys:je.array()}),Iy=s.z.object({}),$y=s.z.object({key:je,name:s.z.string(),snapshot:s.z.boolean()}),ky=s.z.object({task:tr});let mo=class{constructor(e,t,n,i){c(this,"type",Wr);c(this,"client");c(this,"frameClient");c(this,"ontologyClient");c(this,"rangeClient");this.client=e,this.frameClient=t,this.ontologyClient=n,this.rangeClient=i}async create(e){const t=!Array.isArray(e),n=await w(this.client,vy,{tasks:b(e)},Ey,zy),i=this.sugar(n.tasks);return t?i[0]:i}async delete(e){await w(this.client,Oy,{keys:b(e)},Sy,Iy)}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}=Qr(e,{number:"rack",string:"keys"},{convertNumericStrings:!1}),o={...t};a==="rack"?o.rack=e:o.keys=i;const l=await this.execRetrieve(o),u=this.sugar(l);return n&&a!=="rack"?u[0]:u}async copy(e,t,n){const i=await w(this.client,Ny,{key:e,name:t,snapshot:n},$y,ky);return this.sugar([i.task])[0]}async retrieveByName(e,t){const n=await this.execRetrieve({names:[e],rack:t});return en("Task",e,n,!0),this.sugar(n)[0]}async retrieveByType(e,t){const n=await this.execRetrieve({types:[e],rack:t});return this.sugar(n)}async retrieveSnapshottedTo(e){if(this.ontologyClient==null)throw Ye;return await po(e,this.ontologyClient)}async execRetrieve(e){return(await w(this.client,Ty,e,wy,by)).tasks}sugar(e){const t=!Array.isArray(e),n=b(e).map(({key:i,name:a,type:o,config:l,state:u,internal:h,snapshot:f})=>new go(i,a,o,l,h,f,u,this.frameClient,this.ontologyClient,this.rangeClient));return t?n[0]:n}async openTracker(){return await Le(this.frameClient,gy,my,(e,t)=>Array.from(t).map(n=>({variant:e,key:n.toString(),value:n.toString()})))}async openStateObserver(){return new Be(await this.frameClient.openStreamer(Bt),e=>{const t=e.get(Bt);if(t.length===0)return[null,!1];const n=qt.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}async openCommandObserver(){return new Be(await this.frameClient.openStreamer(Fe),e=>{const t=e.get(Fe);if(t.length===0)return[null,!1];const n=es.safeParse(t.at(-1));return n.success?[n.data,!0]:(console.error(n.error),[null,!1])})}};const wo=r=>new O({type:Wr,key:r}),Ay=Object.freeze(Object.defineProperty({__proto__:null,Client:mo,ONTOLOGY_TYPE:Wr,Task:go,commandZ:es,getRackKey:Jh,keyZ:je,newZ:Ia,ontologyID:wo,stateZ:qt,statusZ:Sa,taskZ:tr},Symbol.toStringTag,{value:"Module"})),xy=s.z.object({keys:wt.array().optional(),for:re.optional(),search:s.z.string().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Ry=s.z.object({labels:V(rr)}),Cr=class Cr{constructor(e){c(this,"client");this.client=e}async retrieve(e){return await this.execute({keys:b(e)})}async retrieveFor(e){return await this.execute({for:e})}async search(e){return await this.execute({search:e})}async page(e,t){return await this.execute({offset:e,limit:t})}async execute(e){const[t,n]=await this.client.send(Cr.ENDPOINT,e,xy,Ry);if(n!=null)throw n;return t.labels}};c(Cr,"ENDPOINT","/label/retrieve");let xr=Cr;const bo=rr.extend({key:wt.optional()}),Cy=s.z.object({labels:bo.array()}),Py=s.z.object({labels:rr.array()}),jy=s.z.object({keys:wt.array()}),To=s.z.object({id:re,labels:wt.array(),replace:s.z.boolean().optional()}),Dy=To.omit({replace:!0}),On=s.z.object({}),My="/label/create",By="/label/delete",Zy="/label/set",Uy="/label/remove";let vo=class{constructor(e){c(this,"client");this.client=e}async create(e){return(await w(this.client,My,{labels:b(e)},Cy,Py)).labels}async delete(e){await w(this.client,By,{keys:b(e)},jy,On)}async set(e,t,{replace:n}={}){await w(this.client,Zy,{id:e,labels:t,replace:n},To,On)}async remove(e,t){await w(this.client,Uy,{id:e,labels:t},Dy,On)}};const Ly="sy_label_set",_y="sy_label_delete";let Oo=class{constructor(e,t,n){c(this,"type","label");c(this,"retriever");c(this,"writer");c(this,"frameClient");c(this,"ontology");this.writer=new vo(e),this.retriever=new xr(e),this.frameClient=t,this.ontology=n}async search(e){return await this.retriever.search(e)}async retrieve(e){const t=Array.isArray(e),n=await this.retriever.retrieve(e);return t?n:n[0]}async retrieveFor(e){return await this.retriever.retrieveFor(new O(e))}async label(e,t,n={}){await this.writer.set(new O(e),t,n)}async removeLabels(e,t){await this.writer.remove(new O(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 Le(this.frameClient,Ly,_y,qy)}async trackLabelsOf(e){const t=new Me.Observer,n=(await this.retrieveFor(e)).map(a=>({id:No(a.key),key:a.key,name:a.name,data:a}));return(await this.ontology.openDependentTracker({target:new O(e),dependents:n,relationshipType:"labeled_by"})).onChange(a=>t.notify(a.map(o=>{var l,u;return{key:o.id.key,color:(l=o.data)==null?void 0:l.color,name:(u=o.data)==null?void 0:u.name}}))),t}};const qy=(r,e)=>r==="delete"?e.toUUIDs().map(t=>({variant:r,key:t})):e.parseJSON(rr).map(t=>({variant:r,key:t.key,value:t})),No=r=>new O({type:ts,key:r}),Yy=Object.freeze(Object.defineProperty({__proto__:null,Client:Oo,ONTOLOGY_TYPE:ts,Retriever:xr,Writer:vo,keyZ:wt,labelZ:rr,newZ:bo,ontologyID:No},Symbol.toStringTag,{value:"Module"})),Wy="sy_range_alias_set",Fy="sy_range_alias_delete",Gy=s.z.object({range:ne,aliases:s.z.string().array()}),Vy=s.z.object({aliases:s.z.record(s.z.string(),J)}),Jy=s.z.object({range:ne,aliases:s.z.record(J.or(s.z.string()),s.z.string())}),Ky=s.z.unknown(),Hy=s.z.object({range:ne,channels:J.array()}),Xy=s.z.unknown(),Qy=s.z.object({range:ne}),ep=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),fe=class fe{constructor(e,t,n){c(this,"frameClient");c(this,"cache",new Map);c(this,"client");c(this,"rangeKey");this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",i={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?i[o]=l:t.push(o)});if(t.length===0)return i;const a=await w(this.client,fe.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Gy,Vy);return Object.entries(a.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?a.aliases[t[0]]:{...i,...a.aliases}}async set(e){await w(this.client,fe.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Jy,Ky)}async list(){return(await w(this.client,fe.LIST_ENDPOINT,{range:this.rangeKey},Qy,ep)).aliases}async delete(e){await w(this.client,fe.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},Hy,Xy)}async openChangeTracker(){return await Le(this.frameClient,Wy,Fy,np(this.rangeKey))}};c(fe,"SET_ENDPOINT","/range/alias/set"),c(fe,"RESOLVE_ENDPOINT","/range/alias/resolve"),c(fe,"LIST_ENDPOINT","/range/alias/list"),c(fe,"DELETE_ENDPOINT","/range/alias/delete");let Yn=fe;const tp=s.z.object({range:ne,channel:J,alias:s.z.string()}),rp="---",np=r=>(e,t)=>e==="delete"?t.toStrings().filter(n=>n.split(rp)[0]===r).map(n=>({variant:e,key:n,value:void 0})):t.parseJSON(tp).map(n=>({variant:e,key:n.alias,value:n})),vs=s.z.object({range:ne,key:s.z.string(),value:s.z.string()}),sp=s.z.object({range:ne,keys:s.z.string().array()}),ip=s.z.object({pairs:V(vs)}),ap=s.z.object({range:ne,pairs:vs.array()}),op=s.z.object({range:ne,keys:s.z.string().array()}),$e=class $e{constructor(e,t,n){c(this,"rangeKey");c(this,"client");c(this,"frameClient");this.rangeKey=e,this.client=t,this.frameClient=n}async get(e){const t=await w(this.client,$e.GET_ENDPOINT,{range:this.rangeKey,keys:b(e)},sp,ip);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;Jn(e)?n=Object.entries(e).map(([i,a])=>({range:this.rangeKey,key:i,value:a})):n=[{range:this.rangeKey,key:e,value:t}],await w(this.client,$e.SET_ENDPOINT,{range:this.rangeKey,pairs:n},ap,s.z.unknown())}async delete(e){await w(this.client,$e.DELETE_ENDPOINT,{range:this.rangeKey,keys:b(e)},op,s.z.unknown())}async openTracker(){return await Le(this.frameClient,"sy_range_kv_set","sy_range_kv_delete",(e,t)=>e==="delete"?t.toStrings().map(n=>{const[i,a]=n.split("<--->",2);return{variant:e,key:n,value:{range:i,key:a,value:""}}}):t.parseJSON(vs).map(n=>({variant:e,key:`${n.range}${n.key}`,value:n})))}};c($e,"GET_ENDPOINT","/range/kv/get"),c($e,"SET_ENDPOINT","/range/kv/set"),c($e,"DELETE_ENDPOINT","/range/kv/delete");let Gt=$e;class Eo{constructor(e,t=G.ZERO,n,i,a,o,l,u,h,f,d){c(this,"key");c(this,"name");c(this,"kv");c(this,"timeRange");c(this,"color");c(this,"channels");c(this,"aliaser");c(this,"frameClient");c(this,"labelClient");c(this,"ontologyClient");c(this,"rangeClient");this.key=n,this.name=e,this.timeRange=t,this.frameClient=a,this.color=i,this.kv=o,this.aliaser=l,this.channels=u,this.labelClient=h,this.ontologyClient=f,this.rangeClient=d}get ontologyID(){return Ie(this.key)}get payload(){return{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color}}async setAlias(e,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new ie(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async openAliasTracker(){return await this.aliaser.openChangeTracker()}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async labels(){return await this.labelClient.retrieveFor(Ie(this.key))}async addLabel(...e){await this.labelClient.label(Ie(this.key),e)}async removeLabel(...e){await this.labelClient.removeLabels(Ie(this.key),e)}async openChildRangeTracker(){const e=new Me.Observer,t=(await this.retrieveChildren()).map(i=>{const a=Ie(i.key);return{id:a,key:a.toString(),name:i.name,data:i.payload}}),n=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:t,resourceType:"range"});return n.onChange(i=>e.notify(this.rangeClient.resourcesToRanges(i))),e.setCloser(async()=>await n.close()),e}async openParentRangeTracker(){const e=new Me.Observer,t=await this.retrieveParent();if(t==null)return null;const n=Ie(t.key),i={id:n,key:n.toString(),name:t.name,data:t.payload},a=await this.ontologyClient.openDependentTracker({target:this.ontologyID,dependents:[i],relationshipDirection:"to"});return a.onChange(o=>{const l=this.rangeClient.resourcesToRanges(o);if(l.length===0)return;const u=l[0];e.notify(u)}),e.setCloser(async()=>await a.close()),e}}const cp=(r,e)=>Du(r.timeRange,e.timeRange),lp=s.z.object({keys:ne.array().optional(),names:s.z.array(s.z.string()).optional(),term:s.z.string().optional(),overlapsWith:G.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional()}),up="/range/retrieve",hp=s.z.object({ranges:V(nr)});let zo=class{constructor(e,t,n,i,a,o){c(this,"type","range");c(this,"frameClient");c(this,"writer");c(this,"unaryClient");c(this,"channels");c(this,"labelClient");c(this,"ontologyClient");this.frameClient=e,this.writer=t,this.unaryClient=n,this.channels=i,this.labelClient=a,this.ontologyClient=o}async create(e,t){const n=!Array.isArray(e),i=this.sugarMany(await this.writer.create(b(e),t));return n?i[0]:i}async rename(e,t){await this.writer.rename(e,t)}async delete(e){await this.writer.delete(b(e))}async search(e){return this.sugarMany(await this.execRetrieve({term:e}))}async page(e,t){return this.sugarMany(await this.execRetrieve({offset:e,limit:t}))}async retrieve(e){if(typeof e=="object"&&"start"in e)return await this.execRetrieve({overlapsWith:new G(e)});const{single:t,actual:n,variant:i,normalized:a,empty:o}=ka(e);if(o)return[];const l=await this.execRetrieve({[i]:a});if(!t)return l;if(l.length===0)throw new Oe(`range matching ${n} not found`);if(l.length>1)throw new Ne(`multiple ranges matching ${n} found`);return l[0]}getKV(e){return new Gt(e,this.unaryClient,this.frameClient)}async execRetrieve(e){const{ranges:t}=await w(this.unaryClient,up,e,lp,hp);return this.sugarMany(t)}async retrieveParent(e){const t=await this.ontologyClient.retrieveParents(Ie(e));if(t.length===0)return null;const n=t[0];return n.id.type!=="range"?null:await this.retrieve(n.id.key)}sugarOne(e){return new Eo(e.name,e.timeRange,e.key,e.color,this.frameClient,new Gt(e.key,this.unaryClient,this.frameClient),new Yn(e.key,this.frameClient,this.unaryClient),this.channels,this.labelClient,this.ontologyClient,this)}sugarMany(e){return e.map(t=>this.sugarOne(t))}async openTracker(){return await Le(this.frameClient,"sy_range_set","sy_range_delete",(e,t)=>e==="delete"?t.toStrings().map(i=>({variant:e,key:i,value:void 0})):this.sugarMany(t.parseJSON(nr)).map(i=>({variant:e,key:i.key,value:i})))}resourcesToRanges(e){return e.map(t=>this.resourceToRange(t))}resourceToRange(e){var t,n,i;return this.sugarOne({key:e.id.key,name:(t=e.data)==null?void 0:t.name,timeRange:new G((n=e.data)==null?void 0:n.timeRange),color:(i=e.data)==null?void 0:i.color})}};const Ie=r=>new O({type:ns,key:r}),dp=r=>new O({type:ss,key:r}),fp=s.z.object({ranges:nr.array()}),yp=s.z.object({parent:re.optional(),ranges:$a.array()}),pp=s.z.object({keys:ne.array()}),gp=s.z.object({}),mp=s.z.object({key:ne,name:rs}),wp=s.z.object({}),bp="/range/create",Tp="/range/delete",vp="/range/rename";class So{constructor(e){c(this,"client");this.client=e}async rename(e,t){await w(this.client,vp,{key:e,name:t},mp,wp)}async create(e,t){return(await w(this.client,bp,{ranges:e,...t},yp,fp)).ranges}async delete(e){await w(this.client,Tp,{keys:e},pp,gp)}}const Op=Object.freeze(Object.defineProperty({__proto__:null,ALIAS_ONTOLOGY_TYPE:ss,Client:zo,KV:Gt,ONTOLOGY_TYPE:ns,Range:Eo,Writer:So,aliasOntologyID:dp,analyzeParams:ka,keyZ:ne,nameZ:rs,newZ:$a,ontologyID:Ie,payloadZ:nr,sort:cp},Symbol.toStringTag,{value:"Module"})),Np="/api/v1/";class Ep{constructor(e,t={},n=!1){c(this,"url");c(this,"unary");c(this,"stream");c(this,"secure");this.secure=n,this.url=e.child(Np);const i=new Jt.JSONCodec;this.unary=El(new Nl(this.url,i,this.secure),t),this.stream=new Cl(this.url,i,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const zp="/workspace/lineplot/retrieve",Sp="/workspace/lineplot/create",Ip="/workspace/lineplot/rename",$p="/workspace/lineplot/set-data",kp="/workspace/lineplot/delete",Ap=s.z.object({keys:bt.array()}),xp=s.z.object({workspace:pe,linePlots:xa.array()}),Rp=s.z.object({key:bt,name:s.z.string()}),Cp=s.z.object({key:bt,data:s.z.string()}),Pp=s.z.object({keys:bt.array()}),jp=s.z.object({linePlots:V(Fr)}),Dp=s.z.object({linePlots:Fr.array()}),Nn=s.z.object({});let Io=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=await w(this.client,Sp,{workspace:e,linePlots:b(t)},xp,Dp);return n?i.linePlots:i.linePlots[0]}async rename(e,t){await w(this.client,Ip,{key:e,name:t},Rp,Nn)}async setData(e,t){await w(this.client,$p,{key:e,data:JSON.stringify(t)},Cp,Nn)}async retrieve(e){const t=Array.isArray(e),n=await w(this.client,zp,{keys:b(e)},Ap,jp);return t?n.linePlots:n.linePlots[0]}async delete(e){await w(this.client,kp,{keys:b(e)},Pp,Nn)}};const Mp=r=>new O({type:as,key:r}),Bp=Object.freeze(Object.defineProperty({__proto__:null,Client:Io,ONTOLOGY_TYPE:as,keyZ:bt,linePlotZ:Fr,newZ:xa,ontologyID:Mp},Symbol.toStringTag,{value:"Module"})),Zp="/workspace/log/retrieve",Up="/workspace/log/create",Lp="/workspace/log/rename",_p="/workspace/log/set-data",qp="/workspace/log/delete",Yp=s.z.object({keys:Tt.array()}),Wp=s.z.object({workspace:pe,logs:Ra.array()}),Fp=s.z.object({key:Tt,name:s.z.string()}),Gp=s.z.object({key:Tt,data:s.z.string()}),Vp=s.z.object({keys:Tt.array()}),Jp=s.z.object({logs:Gr.array()}),Kp=s.z.object({logs:Gr.array()}),En=s.z.object({});let $o=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=await w(this.client,Up,{workspace:e,logs:b(t)},Wp,Kp);return n?i.logs:i.logs[0]}async rename(e,t){await w(this.client,Lp,{key:e,name:t},Fp,En)}async setData(e,t){await w(this.client,_p,{key:e,data:JSON.stringify(t)},Gp,En)}async retrieve(e){const t=Array.isArray(e),n=await w(this.client,Zp,{keys:b(e)},Yp,Jp);return t?n.logs:n.logs[0]}async delete(e){await w(this.client,qp,{keys:b(e)},Vp,En)}};const Hp=r=>new O({type:os,key:r}),Xp=Object.freeze(Object.defineProperty({__proto__:null,Client:$o,ONTOLOGY_TYPE:os,keyZ:Tt,logZ:Gr,newZ:Ra,ontologyID:Hp},Symbol.toStringTag,{value:"Module"})),Qp="/workspace/schematic/retrieve",eg="/workspace/schematic/create",tg="/workspace/schematic/rename",rg="/workspace/schematic/set-data",ng="/workspace/schematic/delete",sg="/workspace/schematic/copy",ig=s.z.object({keys:Ue.array()}),ag=s.z.object({workspace:pe,schematics:ja.array()}),og=s.z.object({key:Ue,name:s.z.string()}),cg=s.z.object({key:Ue,data:s.z.string()}),lg=s.z.object({keys:Ue.array()}),ug=s.z.object({key:Ue,name:s.z.string(),snapshot:s.z.boolean()}),hg=s.z.object({schematics:V(cs)}),dg=s.z.object({schematics:cs.array()}),fg=s.z.object({schematic:Kr}),zn=s.z.object({});let ko=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=await w(this.client,eg,{workspace:e,schematics:b(t)},ag,dg);return n?i.schematics:i.schematics[0]}async rename(e,t){await w(this.client,tg,{key:e,name:t},og,zn)}async setData(e,t){await w(this.client,rg,{key:e,data:JSON.stringify(t)},cg,zn)}async retrieve(e){const t=Array.isArray(e),n=await w(this.client,Qp,{keys:b(e)},ig,hg);return t?n.schematics:n.schematics[0]}async delete(e){await w(this.client,ng,{keys:b(e)},lg,zn)}async copy(e,t,n){return(await w(this.client,sg,{key:e,name:t,snapshot:n},ug,fg)).schematic}};const yg=r=>new O({type:ls,key:r}),pg=Object.freeze(Object.defineProperty({__proto__:null,Client:ko,ONTOLOGY_TYPE:ls,keyZ:Ue,newZ:ja,ontologyID:yg,remoteZ:cs,schematicZ:Kr},Symbol.toStringTag,{value:"Module"})),gg="/workspace/table/retrieve",mg="/workspace/table/create",wg="/workspace/table/rename",bg="/workspace/table/set-data",Tg="/workspace/table/delete",vg=s.z.object({keys:vt.array()}),Og=s.z.object({workspace:pe,tables:Da.array()}),Ng=s.z.object({key:vt,name:s.z.string()}),Eg=s.z.object({key:vt,data:s.z.string()}),zg=s.z.object({keys:vt.array()}),Sg=s.z.object({tables:hs.array()}),Ig=s.z.object({tables:hs.array()}),Sn=s.z.object({});let Ao=class{constructor(e){c(this,"client");this.client=e}async create(e,t){const n=Array.isArray(t),i=await w(this.client,mg,{workspace:e,tables:b(t)},Og,Ig);return n?i.tables:i.tables[0]}async rename(e,t){await w(this.client,wg,{key:e,name:t},Ng,Sn)}async setData(e,t){await w(this.client,bg,{key:e,data:JSON.stringify(t)},Eg,Sn)}async retrieve(e){const t=Array.isArray(e),n=await w(this.client,gg,{keys:b(e)},vg,Sg);return t?n.tables:n.tables[0]}async delete(e){await w(this.client,Tg,{keys:b(e)},zg,Sn)}};const $g=r=>new O({type:ds,key:r}),kg=Object.freeze(Object.defineProperty({__proto__:null,Client:Ao,ONTOLOGY_TYPE:ds,keyZ:vt,newZ:Da,ontologyID:$g,remoteZ:hs,tableZ:us},Symbol.toStringTag,{value:"Module"})),hr="/workspace/retrieve",Ag="/workspace/create",xg="/workspace/rename",Rg="/workspace/set-layout",Cg="/workspace/delete",dr=s.z.object({keys:pe.array().optional(),search:s.z.string().optional(),author:Ze.optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Pg=s.z.object({workspaces:Ca.array()}),jg=s.z.object({key:pe,name:s.z.string()}),Dg=s.z.object({key:pe,layout:s.z.string()}),Mg=s.z.object({keys:pe.array()}),fr=s.z.object({workspaces:V(Vr)}),Bg=s.z.object({workspaces:Pa.array()}),In=s.z.object({});class xo{constructor(e){c(this,"type",Jr);c(this,"schematic");c(this,"linePlot");c(this,"log");c(this,"table");c(this,"client");this.client=e,this.schematic=new ko(e),this.linePlot=new Io(e),this.log=new $o(e),this.table=new Ao(e)}async create(e){const t=Array.isArray(e),n=await w(this.client,Ag,{workspaces:b(e)},Pg,Bg);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await w(this.client,xg,{key:e,name:t},jg,In)}async setLayout(e,t){await w(this.client,Rg,{key:e,layout:JSON.stringify(t)},Dg,In)}async retrieve(e){const t=Array.isArray(e),n=await w(this.client,hr,{keys:b(e)},dr,fr);return t?n.workspaces:n.workspaces[0]}async retrieveByAuthor(e){return(await w(this.client,hr,{author:e},dr,fr)).workspaces}async search(e){return(await w(this.client,hr,{search:e},dr,fr)).workspaces}async page(e,t){return(await w(this.client,hr,{offset:e,limit:t},dr,fr)).workspaces}async delete(e){await w(this.client,Cg,{keys:b(e)},Mg,In)}}const Zg=r=>new O({type:Jr,key:r}),Ug=Object.freeze(Object.defineProperty({__proto__:null,Client:xo,ONTOLOGY_TYPE:Jr,keyZ:pe,newZ:Ca,ontologyID:Zg,remoteZ:Pa,workspaceZ:Vr},Symbol.toStringTag,{value:"Module"})),Ro=s.z.object({host:s.z.string({required_error:"Host is required"}).min(1,"Host is required"),port:s.z.number({required_error:"Port is required"}).or(s.z.string({required_error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:N.z.default(N.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:Ph.breakerConfig.optional()});class Co extends oo{constructor(t){const n=Ro.parse(t),{host:i,port:a,username:o,password:l,connectivityPollFrequency:u,secure:h,retry:f}=n,d=new Ep(new ah({host:i,port:Number(a)}),f,h);d.use(Gh);let k;o!=null&&l!=null&&(k=new Ef(d.unary,{username:o,password:l}),d.use(k.middleware()));const S=new ps(new Yt(d.unary)),se=new to(d.unary,S);super(d.stream,d.unary,S);c(this,"createdAt");c(this,"props");c(this,"ranges");c(this,"channels");c(this,"auth");c(this,"user");c(this,"access");c(this,"connectivity");c(this,"ontology");c(this,"workspaces");c(this,"labels");c(this,"hardware");c(this,"control");c(this,"transport");c(this,"clientVersion","0.40.0");this.createdAt=$.now(),this.props=n,this.auth=k,this.transport=d,this.channels=new Xa(this,S,d.unary,se),this.connectivity=new Ft(d.unary,u,this.clientVersion,n.name),this.control=new lo(this),this.ontology=new Wa(d.unary,this);const L=new So(this.transport.unary);this.labels=new Oo(this.transport.unary,this,this.ontology),this.ranges=new zo(this,L,this.transport.unary,S,this.labels,this.ontology),this.access=new Va(this.transport.unary),this.user=new ro(this.transport.unary),this.workspaces=new xo(this.transport.unary);const Po=new ho(this.transport.unary,this),Os=new mo(this.transport.unary,this,this.ontology,this.ranges),jo=new fo(this.transport.unary,Os);this.hardware=new uo(Os,jo,Po)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}c(Co,"connectivity",Ft);const Lg=dt.Authority;exports.AuthError=ve;exports.Authority=Lg;exports.Channel=gs;exports.ContiguityError=Ln;exports.DataType=I;exports.Density=X;exports.Frame=Y;exports.MultiSeries=fa;exports.MultipleFoundError=Ne;exports.NotFoundError=Oe;exports.QueryError=ie;exports.Rate=ut;exports.RouteError=_t;exports.Series=ke;exports.Synnax=Co;exports.TimeRange=G;exports.TimeSpan=N;exports.TimeStamp=$;exports.UnexpectedError=xe;exports.ValidationError=U;exports.access=kd;exports.channel=Kd;exports.connection=Sf;exports.control=Vf;exports.device=oy;exports.framer=qf;exports.group=id;exports.hardware=Jf;exports.isCalculated=Wt;exports.label=Yy;exports.linePlot=Bp;exports.log=Xp;exports.ontology=yd;exports.policy=$d;exports.rack=py;exports.ranger=Op;exports.schematic=pg;exports.signals=Kf;exports.synnaxPropsZ=Ro;exports.table=kg;exports.task=Ay;exports.user=gf;exports.workspace=Ug;
|