@synnaxlabs/pluto 0.44.5 → 0.44.7
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/dist/{Animated-BDoJWl9g.cjs → Animated-D5LYKEkW.cjs} +1 -1
- package/dist/{Animated-fI-NFaha.js → Animated-DdcRuSba.js} +2 -2
- package/dist/Editable-7Abx7gK5.cjs +92 -0
- package/dist/{Editable-C1g_CFYk.js → Editable-BrtvNf66.js} +11315 -11270
- package/dist/{LinePlot-Ck0rhtFk.js → LinePlot-BIZ1E3Rb.js} +423 -420
- package/dist/LinePlot-DslwDvAo.cjs +53 -0
- package/dist/{Toggle-DUKDeqpe.cjs → Toggle-BVFmU1mL.cjs} +1 -1
- package/dist/{Toggle-DEJ8Uvun.js → Toggle-DfINNQZ3.js} +1 -1
- package/dist/{Video-B6tujjr8.js → Video-CMuBiBcp.js} +1 -1
- package/dist/{Video-BjRd9sFv.cjs → Video-CbaEeyGH.cjs} +1 -1
- package/dist/button.cjs +1 -1
- package/dist/button.js +1 -1
- package/dist/color.cjs +1 -1
- package/dist/color.js +1 -1
- package/dist/{css-DvIPI3Qm.js → css-BlHGoCgb.js} +578 -559
- package/dist/css-CZ_XGkIB.cjs +8 -0
- package/dist/css.cjs +1 -1
- package/dist/css.js +2 -2
- package/dist/dialog.cjs +1 -1
- package/dist/dialog.js +1 -1
- package/dist/{eraser-CnRJY__h.js → eraser-BstNvEkO.js} +1940 -1889
- package/dist/eraser-DiJNbabo.cjs +63 -0
- package/dist/ether.cjs +1 -1
- package/dist/ether.js +13 -13
- package/dist/{external-DKh0JhWO.cjs → external-B33LW5pz.cjs} +1 -1
- package/dist/{external-Dfr7xymv.js → external-BNwo0Mju.js} +3 -3
- package/dist/{external-CAAPXpVr.cjs → external-C3hm9xgd.cjs} +1 -1
- package/dist/external-CE5Gf1U4.cjs +1 -0
- package/dist/{external-D6hAP7eJ.js → external-CSkXMvdW.js} +7 -7
- package/dist/{external-R9a28aP6.js → external-C_25EtbW.js} +31 -31
- package/dist/{external-dew29Q0v.js → external-ClD0dLdB.js} +2 -2
- package/dist/{external-CKhbbig_.js → external-CoEPLcYb.js} +12 -12
- package/dist/{external-DwRvB5ZT.cjs → external-CoVeaXHg.cjs} +1 -1
- package/dist/{external-CNF5TNBY.cjs → external-Cs-XdMNw.cjs} +1 -1
- package/dist/{external-BzV_PGNe.js → external-CsZA1s33.js} +2 -2
- package/dist/{external-Db9iKa8k.js → external-CtRU4mkG.js} +3 -3
- package/dist/{external-D98a3YQJ.cjs → external-D-FHwqls.cjs} +1 -1
- package/dist/{external-BS9S-b49.cjs → external-D91gCQ3U.cjs} +1 -1
- package/dist/external-DE-uFhwW.cjs +1 -0
- package/dist/{external-DOEaBrpz.cjs → external-DSkHe-2Y.cjs} +1 -1
- package/dist/{external-DNO3FJLl.cjs → external-DXm6LsSg.cjs} +1 -1
- package/dist/{external-C2iqWGd2.js → external-DkZwoQZk.js} +29 -29
- package/dist/external-Ds3Wz9sk.js +44 -0
- package/dist/{external-B3dPSZUg.js → external-FrSPoRvt.js} +2 -2
- package/dist/{external-DRuZ24L7.js → external-GS2AbOOd.js} +6 -6
- package/dist/{external-Blrrgnzw.cjs → external-IBErJ3kF.cjs} +1 -1
- package/dist/{external-GR-20z_c.js → external-J5kFGShS.js} +20 -20
- package/dist/{external-Daage1AI.js → external-V3Tbt95R.js} +10 -10
- package/dist/{external-BenP6Hcm.cjs → external-mX8u0eSb.cjs} +1 -1
- package/dist/{external-BVDQNHbo.cjs → external-vdf1a_j1.cjs} +1 -1
- package/dist/flex.cjs +1 -1
- package/dist/flex.js +1 -1
- package/dist/{fontString-CW0wLG5g.js → fontString-Ca1-oixk.js} +2 -2
- package/dist/{fontString-aK--tYMM.cjs → fontString-Cp4X6CqQ.cjs} +1 -1
- package/dist/header.cjs +1 -1
- package/dist/header.js +1 -1
- package/dist/index.cjs +7 -7
- package/dist/index.js +6521 -6434
- package/dist/input.cjs +1 -1
- package/dist/input.js +1 -1
- package/dist/list.cjs +1 -1
- package/dist/list.js +1 -1
- package/dist/menu.cjs +1 -1
- package/dist/menu.js +1 -1
- package/dist/pluto.css +1 -1
- package/dist/src/channel/LinePlot.d.ts +0 -4
- package/dist/src/channel/LinePlot.d.ts.map +1 -1
- package/dist/src/channel/queries.d.ts +13 -13
- package/dist/src/channel/queries.d.ts.map +1 -1
- package/dist/src/dialog/Dialog.d.ts.map +1 -1
- package/dist/src/dialog/Frame.d.ts +13 -7
- package/dist/src/dialog/Frame.d.ts.map +1 -1
- package/dist/src/dialog/position.d.ts +22 -8
- package/dist/src/dialog/position.d.ts.map +1 -1
- package/dist/src/dialog/position.spec.d.ts +2 -0
- package/dist/src/dialog/position.spec.d.ts.map +1 -0
- package/dist/src/flux/core/store.d.ts +2 -0
- package/dist/src/flux/core/store.d.ts.map +1 -1
- package/dist/src/flux/list.d.ts +9 -2
- package/dist/src/flux/list.d.ts.map +1 -1
- package/dist/src/group/index.d.ts +2 -0
- package/dist/src/group/index.d.ts.map +1 -0
- package/dist/src/group/queries.d.ts +35 -0
- package/dist/src/group/queries.d.ts.map +1 -0
- package/dist/src/group/queries.spec.d.ts +2 -0
- package/dist/src/group/queries.spec.d.ts.map +1 -0
- package/dist/src/hardware/device/queries.d.ts +1 -1
- package/dist/src/hardware/device/queries.d.ts.map +1 -1
- package/dist/src/hardware/rack/queries.d.ts +1 -1
- package/dist/src/hardware/rack/queries.d.ts.map +1 -1
- package/dist/src/hardware/task/queries.d.ts +1 -1
- package/dist/src/hardware/task/queries.d.ts.map +1 -1
- package/dist/src/hooks/index.d.ts +0 -2
- package/dist/src/hooks/index.d.ts.map +1 -1
- package/dist/src/hooks/useDestructors.d.ts.map +1 -1
- package/dist/src/hooks/useDestructors.spec.d.ts +2 -0
- package/dist/src/hooks/useDestructors.spec.d.ts.map +1 -0
- package/dist/src/hooks/useResize.d.ts +1 -0
- package/dist/src/hooks/useResize.d.ts.map +1 -1
- package/dist/src/icon/registry.d.ts +1 -0
- package/dist/src/icon/registry.d.ts.map +1 -1
- package/dist/src/label/queries.d.ts +1 -1
- package/dist/src/label/queries.d.ts.map +1 -1
- package/dist/src/menu/ContextMenu.d.ts +1 -1
- package/dist/src/menu/ContextMenu.d.ts.map +1 -1
- package/dist/src/ontology/queries.d.ts +2 -2
- package/dist/src/ontology/queries.d.ts.map +1 -1
- package/dist/src/pluto/Pluto.d.ts +2 -0
- package/dist/src/pluto/Pluto.d.ts.map +1 -1
- package/dist/src/ranger/aether/queries.d.ts +1 -1
- package/dist/src/ranger/aether/queries.d.ts.map +1 -1
- package/dist/src/ranger/queries.d.ts +2 -2
- package/dist/src/ranger/queries.d.ts.map +1 -1
- package/dist/src/state/state.d.ts.map +1 -1
- package/dist/src/telem/control/aether/controller.d.ts +2 -2
- package/dist/src/telem/control/aether/legend.d.ts +2 -2
- package/dist/src/testutil/Synnax.d.ts +1 -1
- package/dist/src/testutil/Synnax.d.ts.map +1 -1
- package/dist/src/vis/legend/Container.d.ts +3 -29
- package/dist/src/vis/legend/Container.d.ts.map +1 -1
- package/dist/src/vis/legend/Entries.d.ts +22 -0
- package/dist/src/vis/legend/Entries.d.ts.map +1 -0
- package/dist/src/vis/legend/Grouped.d.ts +15 -0
- package/dist/src/vis/legend/Grouped.d.ts.map +1 -0
- package/dist/src/vis/legend/Simple.d.ts +5 -19
- package/dist/src/vis/legend/Simple.d.ts.map +1 -1
- package/dist/src/vis/legend/external.d.ts +1 -0
- package/dist/src/vis/legend/external.d.ts.map +1 -1
- package/dist/src/vis/light/aether/light.d.ts +4 -5
- package/dist/src/vis/light/aether/light.d.ts.map +1 -1
- package/dist/src/vis/light/use.d.ts +2 -2
- package/dist/src/vis/light/use.d.ts.map +1 -1
- package/dist/src/vis/lineplot/Legend.d.ts +3 -3
- package/dist/src/vis/lineplot/Legend.d.ts.map +1 -1
- package/dist/src/vis/lineplot/Line.d.ts +2 -1
- package/dist/src/vis/lineplot/Line.d.ts.map +1 -1
- package/dist/src/vis/lineplot/LinePlot.d.ts +1 -0
- package/dist/src/vis/lineplot/LinePlot.d.ts.map +1 -1
- package/dist/src/vis/schematic/Forms.d.ts.map +1 -1
- package/dist/src/workspace/queries.d.ts +1 -1
- package/dist/src/workspace/queries.d.ts.map +1 -1
- package/dist/tabs.cjs +1 -1
- package/dist/tabs.js +1 -1
- package/dist/text.cjs +1 -1
- package/dist/text.js +2 -2
- package/dist/theming.cjs +1 -1
- package/dist/theming.js +2 -2
- package/dist/tree.cjs +1 -1
- package/dist/tree.js +1 -1
- package/dist/triggers.cjs +1 -1
- package/dist/triggers.js +1 -1
- package/dist/{units-WWUmv-rf.cjs → units-Cqxg-SBx.cjs} +1 -1
- package/dist/{units-Dh7MflIZ.js → units-D8blpqyN.js} +1 -1
- package/dist/video.cjs +1 -1
- package/dist/video.js +1 -1
- package/package.json +6 -6
- package/dist/Editable-DUtJOqJ5.cjs +0 -92
- package/dist/LinePlot-6cl8_hmn.cjs +0 -53
- package/dist/css-DI0uCCGq.cjs +0 -8
- package/dist/eraser-B03ej59l.cjs +0 -63
- package/dist/external-BEd3F7zY.cjs +0 -1
- package/dist/external-D16M7vHB.js +0 -43
- package/dist/external-I_-aclFy.cjs +0 -1
- package/dist/src/hooks/useDelayedState.d.ts +0 -11
- package/dist/src/hooks/useDelayedState.d.ts.map +0 -1
- package/dist/src/hooks/useTransforms.d.ts +0 -16
- package/dist/src/hooks/useTransforms.d.ts.map +0 -1
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";const s=require("zod"),f=require("./css-CZ_XGkIB.cjs"),rs=require("react"),Zl=t=>{const e=t.replace(/_[a-z]/g,r=>r[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)},La=t=>{const e=(r,n=bn)=>{if(typeof r=="string")return t(r);if(Array.isArray(r))return r.map(o=>e(o,n));if(!Kr(r))return r;n=Vl(n);const a={},i=r;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=t(o);n.recursive&&(Kr(l)?Bs(l)||(l=e(l,n)):n.recursiveInArray&&$s(l)&&(l=[...l].map(u=>{let h=u;return Kr(u)?Bs(h)||(h=e(u,n)):$s(u)&&(h=e({key:u},n).key),h}))),a[c]=l}),a)};return e},Pa=La(Zl),ql=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}_${n.toLowerCase()}`),Yl=La(ql),Hl=[Number,String,Uint8Array],bn={recursive:!0,recursiveInArray:!0},Vl=(t=bn)=>(t.recursive==null?t=bn:t.recursiveInArray??=!1,t),$s=t=>t!=null&&Array.isArray(t),Kr=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Bs=t=>Hl.some(e=>t instanceof e);let _l=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t))}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const r=JSON.parse(t),n=Pa(r);return e!=null?e.parse(n):n}encodeString(t){const e=Yl(t);return JSON.stringify(e,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}};const vn=new _l;let ht=class{value;constructor(t){this.value=t}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const Wl=t=>t!=null&&typeof t=="object"&&"toString"in t,Gl=(t,e=!1)=>{const r=Wl(t)?"stringer":typeof t;let n;switch(r){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${r}`),()=>-1}return e?Kl(n):n},Kl=t=>(e,r)=>t(r,e),xr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const Da=s.z.object({width:s.z.number(),height:s.z.number()}),Jl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Xl=["width","height"];s.z.enum(Xl);const Ql=["start","center","end"],ec=["signedWidth","signedHeight"];s.z.enum(ec);const vr=s.z.object({x:s.z.number(),y:s.z.number()}),tc=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),rc=["x","y"],$a=s.z.enum(rc),Ba=["top","right","bottom","left"];s.z.enum(Ba);const nc=["left","right"],Fa=s.z.enum(nc),sc=["top","bottom"],Za=s.z.enum(sc),qa=["center"],Fs=s.z.enum(qa),ac=[...Ba,...qa],Ya=s.z.enum(ac);s.z.enum(Ql);const ic=["first","last"];s.z.enum(ic);const oc=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([oc,xr]);s.z.union([lc,xr]);s.z.enum([...$a.options,...Ya.options]);s.z.enum(["x","left","right"]);s.z.enum(["y","top","bottom"]);s.z.union([$a,Ya,s.z.instanceof(String)]);const Cr=t=>(e,r)=>{if(typeof e=="bigint"){if(cc(r))return t(e,BigInt(r));const n=t(Number(e),Number(r));return typeof n=="number"?BigInt(Math.round(n)):n}return t(Number(e),Number(r))},Ir=Cr((t,e)=>t-e),jr=Cr((t,e)=>t+e),cc=t=>typeof t=="bigint"?!0:Number.isInteger(t),de=Cr((t,e)=>t*e),Rr=Cr((t,e)=>t/e),Ze=(t,e,r)=>{const n={};if(typeof e=="object"&&(r=e,e=void 0),r={makeValid:!0,...r},typeof t=="number"||typeof t=="bigint")e!=null?(n.lower=t,n.upper=e):(n.lower=typeof t=="bigint"?0n:0,n.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=t}else n.lower=t.lower,n.upper=t.upper;return r?.makeValid?uc(n):n},uc=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,Zs=(t,e)=>{const r=Ze(t);return e<r.lower?r.lower:e>=r.upper?r.upper-(typeof r.upper=="number"?1:1n):e};s.z.object({x:Fa.or(Fs),y:Za.or(Fs)});const hc=s.z.object({x:Fa,y:Za}),dc=Object.freeze({x:"left",y:"top"}),fc=(t,e)=>t.x===e.x&&t.y===e.y,qs=s.z.union([s.z.number(),vr,xr,Da,Jl,tc]),pc=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},Ys=Object.freeze({x:0,y:0}),ar=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:ar,left:ar,width:ar,height:ar});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:vr,two:vr,root:hc});const ns=(t,e,r=0,n=0,a)=>{const i={one:{...Ys},two:{...Ys},root:a??dc};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:t,y:e},i.two={x:i.one.x+r,y:i.one.y+n},i}return"one"in t&&"two"in t&&"root"in t?{...t,root:a??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(i.one={x:t.left,y:t.top},i.two={x:t.right,y:t.bottom},i):(i.one=t,e==null?i.two={x:i.one.x+r,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+r}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},Jr=t=>{const e=ns(t);return{lower:e.one.x,upper:e.two.x}},Xr=t=>{const e=ns(t);return{lower:e.one.y,upper:e.two.y}},yc=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,gc=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([Da,gc,vr,xr]);const mc=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:qs,scale:qs});s.z.object({offset:s.z.number(),scale:s.z.number()});const wc=t=>(e,r,n,a)=>r==="dimension"?[e,n]:[e,a?n-t:n+t],bc=t=>(e,r,n,a)=>[e,a?n/t:n*t],vc=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=t,c=i-a,u=l-o;if(r==="dimension")return[t,n*(u/c)];const h=(n-a)*(u/c)+o;return[t,h]},Tc=t=>(e,r,n)=>[t,n],Oc=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:a}=t;return[t,a-(r-n)]},Sc=t=>(e,r,n)=>{const{lower:a,upper:i}=t;return n=mc(n,a,i),[e,n]};let Hs=class We{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new We().translate(e)}static magnify(e){return new We().magnify(e)}static scale(e,r){return new We().scale(e,r)}translate(e){const r=this.new(),n=wc(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=bc(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=Ze(e,r),a=this.new(),i=vc(n);return i.type="scale",a.ops.push(i),a}clamp(e,r){const n=Ze(e,r),a=this.new(),i=Sc(n);return i.type="clamp",a.ops.push(i),a}reBound(e,r){const n=Ze(e,r),a=this.new(),i=Tc(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=Oc();e.type="invert";const r=this.new();return r.ops.push(e),r}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new We;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,r){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||r.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&r.push([a,i])}),r.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new We};(class le{x;y;currRoot;constructor(e=new Hs,r=new Hs,n=null){this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new le().translate(e,r)}static translateX(e){return new le().translateX(e)}static translateY(e){return new le().translateY(e)}static clamp(e){return new le().clamp(e)}static magnify(e){return new le().magnify(e)}static scale(e){return new le().scale(e)}static reBound(e){return new le().reBound(e)}translate(e,r){const n=pc(e,r),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(yc(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!fc(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(Jr(e)),r.y=r.y.scale(Xr(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(Jr(e)),r.y=this.y.reBound(Xr(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(Jr(e)),r.y=this.y.clamp(Xr(e)),r}copy(){const e=new le;return e.currRoot=this.currRoot,e.x=this.x,e.y=this.y,e}reverse(){const e=this.copy();return e.x=this.x.reverse(),e.y=this.y.reverse(),e}pos(e){return{x:this.x.pos(e.x),y:this.y.pos(e.y)}}dim(e){return{x:this.x.dim(e.x),y:this.y.dim(e.y)}}box(e){return ns(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new le});let Ha=(t,e=21)=>(r=e)=>{let n="",a=r|0;for(;a--;)n+=t[Math.random()*t.length|0];return n};const Va="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",zc=`0123456789${Va}`,Ec=11,Nc=Ha(Va,1),Ac=Ha(zc,Ec-1),kc=()=>`${Nc()}${Ac()}`,xc=(t,e)=>r=>r instanceof e||typeof r=="object"&&r!==null&&"discriminator"in r&&r.discriminator===t,Cc=s.z.enum(["static","dynamic"]),Ic=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),_a=(t,e)=>{const r=new C(e);if(![A.DAY,A.HOUR,A.MINUTE,A.SECOND,A.MILLISECOND,A.MICROSECOND,A.NANOSECOND].some(a=>a.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof C?new C(n):new A(n)};let C=class w extends ht{constructor(e,r="UTC"){if(e==null)super(w.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*w.MILLISECOND.valueOf());else if(typeof e=="string")super(w.parseDateTimeString(e,r).valueOf());else if(Array.isArray(e))super(w.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=w.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=w.MAX:e=w.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,r=1,n=1]){const a=new Date(e,r-1,n,0,0,0,0);return new w(BigInt(a.getTime())*w.MILLISECOND.valueOf()).truncate(w.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,a,i]=e.split(":");let o="00",l="00";i!=null&&([o,l]=i.split("."));let c=w.hours(parseInt(n??"00")).add(w.minutes(parseInt(a??"00"))).add(w.seconds(parseInt(o??"00"))).add(w.milliseconds(parseInt(l??"00")));return r==="local"&&(c=c.add(w.utcOffset)),c.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return w.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new w(BigInt(n.getTime())*w.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(w.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new A(BigInt(new Date().getTimezoneOffset())*w.MINUTE.valueOf())}static since(e){return new w().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new w(e).valueOf()}span(e){return this.range(e).span}range(e){return new Et(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new w(e).valueOf()}afterEq(e){return this.valueOf()>=new w(e).valueOf()}before(e){return this.valueOf()<new w(e).valueOf()}beforeEq(e){return this.valueOf()<=new w(e).valueOf()}add(e){return new w(jr(this.valueOf(),new A(e).valueOf()))}sub(e){return new w(Ir(this.valueOf(),new A(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(A.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(A.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(A.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(A.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(w.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(w.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const r=this.date();return r.setUTCFullYear(e),new w(r)}get month(){return this.date().getUTCMonth()}setMonth(e){const r=this.date();return r.setUTCMonth(e),new w(r)}get day(){return this.date().getUTCDate()}setDay(e){const r=this.date();return r.setUTCDate(e),new w(r)}get hour(){return this.date().getUTCHours()}setHour(e){const r=this.date();return r.setUTCHours(e),new w(r,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const r=this.date();return r.setUTCMinutes(e),new w(r)}get second(){return this.date().getUTCSeconds()}setSecond(e){const r=this.date();return r.setUTCSeconds(e),new w(r)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const r=this.date();return r.setUTCMilliseconds(e),new w(r)}toString(){return this.date().toISOString()}remainder(e){return _a(this,e)}get isToday(){return this.truncate(A.DAY).equals(w.now().truncate(A.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new w(new Date)}static max(...e){let r=w.MIN;for(const n of e){const a=new w(n);a.after(r)&&(r=a)}return r}static min(...e){let r=w.MAX;for(const n of e){const a=new w(n);a.before(r)&&(r=a)}return r}static nanoseconds(e,r="UTC"){return new w(e,r)}static NANOSECOND=w.nanoseconds(1);static microseconds(e,r="UTC"){return w.nanoseconds(e*1e3,r)}static MICROSECOND=w.microseconds(1);static milliseconds(e,r="UTC"){return w.microseconds(e*1e3,r)}static MILLISECOND=w.milliseconds(1);static seconds(e,r="UTC"){return w.milliseconds(e*1e3,r)}static SECOND=w.seconds(1);static minutes(e,r="UTC"){return w.seconds(e*60,r)}static MINUTE=w.minutes(1);static hours(e,r="UTC"){return w.minutes(e*60,r)}static HOUR=w.hours(1);static days(e,r="UTC"){return w.hours(e*24,r)}static DAY=w.days(1);static MAX=new w((1n<<63n)-1n);static MIN=new w(0);static ZERO=new w(0);static z=s.z.union([s.z.instanceof(w),s.z.object({value:s.z.bigint()}).transform(e=>new w(e.value)),s.z.string().transform(e=>new w(BigInt(e))),s.z.number().transform(e=>new w(e)),s.z.bigint().transform(e=>new w(e)),s.z.date().transform(e=>new w(e)),s.z.custom(e=>e instanceof A).transform(e=>new w(e)),Ic.transform(e=>new w(e))]);static sort(e,r){return Number(e.valueOf()-r.valueOf())}},A=class v extends ht{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof Qr?e.period:e instanceof C?new v(e):["number","bigint"].includes(typeof e)?v.seconds(e):new v(e)}static fromMilliseconds(e){return e instanceof v?e:e instanceof Qr?e.period:e instanceof C?new v(e):["number","bigint"].includes(typeof e)?v.milliseconds(e):new v(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new v(e).valueOf()}greaterThan(e){return this.valueOf()>new v(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new v(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new v(e).valueOf()}remainder(e){return _a(this,e)}truncate(e){return new v(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(v.DAY),r=this.truncate(v.HOUR),n=this.truncate(v.MINUTE),a=this.truncate(v.SECOND),i=this.truncate(v.MILLISECOND),o=this.truncate(v.MICROSECOND),l=this.truncate(v.NANOSECOND),c=e,u=r.sub(e),h=n.sub(r),p=a.sub(n),d=i.sub(a),S=o.sub(i),N=l.sub(o);let x="";return c.isZero||(x+=`${c.days}d `),u.isZero||(x+=`${u.hours}h `),h.isZero||(x+=`${h.minutes}m `),p.isZero||(x+=`${p.seconds}s `),d.isZero||(x+=`${d.milliseconds}ms `),S.isZero||(x+=`${S.microseconds}µs `),N.isZero||(x+=`${N.nanoseconds}ns`),x.trim()}mult(e){return new v(de(this.valueOf(),e))}div(e){return new v(Rr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(v.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(v.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(v.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(v.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(v.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(v.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new v(e).valueOf()}add(e){return new v(this.valueOf()+new v(e).valueOf())}sub(e){return new v(this.valueOf()-new v(e).valueOf())}static nanoseconds(e=1){return new v(e)}static NANOSECOND=v.nanoseconds(1);static microseconds(e=1){return v.nanoseconds(de(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(de(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(de(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(de(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(de(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(de(e,24))}static DAY=v.days(1);static MAX=new v((1n<<63n)-1n);static MIN=new v(0);static ZERO=new v(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new v(e.value)),s.z.string().transform(e=>new v(BigInt(e))),s.z.number().transform(e=>new v(e)),s.z.bigint().transform(e=>new v(e)),s.z.instanceof(v),s.z.instanceof(C).transform(e=>new v(e)),s.z.custom(e=>e instanceof Qr).transform(e=>new v(e))])},Qr=class ce extends ht{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new ce(e).valueOf()}get period(){return A.seconds(1/this.valueOf())}sampleCount(e){return new A(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new V(r).valueOf()}span(e){return A.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}add(e){return new ce(jr(this.valueOf(),e.valueOf()))}sub(e){return new ce(Ir(this.valueOf(),e.valueOf()))}mult(e){return new ce(de(this.valueOf(),e))}div(e){return new ce(Rr(this.valueOf(),e))}static hz(e){return new ce(e)}static khz(e){return ce.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new ce(e)),s.z.instanceof(ce)])},V=class G extends ht{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new Tn(e*this.valueOf())}add(e){return new G(jr(this.valueOf(),e.valueOf()))}sub(e){return new G(Ir(this.valueOf(),e.valueOf()))}mult(e){return new G(de(this.valueOf(),e))}div(e){return new G(Rr(this.valueOf(),e))}static UNKNOWN=new G(0);static BIT128=new G(16);static BIT64=new G(8);static BIT32=new G(4);static BIT16=new G(2);static BIT8=new G(1);static z=s.z.union([s.z.number().transform(e=>new G(e)),s.z.instanceof(G)])},Et=class re{start;end;constructor(e,r){typeof e=="object"&&"start"in e?(this.start=new C(e.start),this.end=new C(e.end)):(this.start=new C(e),this.end=new C(r))}get span(){return new A(this.end.valueOf()-this.start.valueOf())}get isValid(){return this.start.valueOf()<=this.end.valueOf()}makeValid(){return this.isValid?this:this.swap()}get isZero(){return this.span.isZero}get numeric(){return{start:Number(this.start.valueOf()),end:Number(this.end.valueOf())}}swap(){return new re(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,r=A.ZERO){if(r.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=r.valueOf()&&a<=r.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,r=A.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const a=C.max(n.start,e.start),i=C.min(n.end,e.end);return i.before(a)?!1:new A(i.sub(a)).greaterThanOrEqual(r)}contains(e){return e instanceof re?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new re(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}static max(...e){return new re(C.min(...e.map(r=>r.start)),C.max(...e.map(r=>r.end)))}static MAX=new re(C.MIN,C.MAX);static MIN=new re(C.MAX,C.MIN);static ZERO=new re(C.ZERO,C.ZERO);static z=s.z.union([s.z.object({start:C.z,end:C.z}).transform(e=>new re(e.start,e.end)),s.z.instanceof(re)]);static sort(e,r){return C.sort(e.start,r.start)||C.sort(e.end,r.end)}static simplify(e){return e.map(r=>r.makeValid()).sort((r,n)=>re.sort(r,n)).reduce((r,n)=>{if(n.isZero)return r;if(r.length===0)return r.push(n),r;const a=r[r.length-1];return a.overlapsWith(n)||a.end.equals(n.start)?a.end=C.max(a.end,n.end):r.push(n),r},[])}},D=class y extends ht{constructor(e){if(e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const r=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r==null)throw new Error(`unable to find data type for ${e.toString()}`);super(r.valueOf())}}get Array(){const e=y.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(y.JSON)||this.equals(y.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(y.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=y.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(y.UINT8)||this.equals(y.UINT16)||this.equals(y.UINT32)||this.equals(y.UINT64)}get isSignedInteger(){return this.equals(y.INT8)||this.equals(y.INT16)||this.equals(y.INT32)||this.equals(y.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(y.INT32)&&e.equals(y.FLOAT64)||this.equals(y.INT8)&&e.equals(y.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return y.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new y("unknown");static FLOAT64=new y("float64");static FLOAT32=new y("float32");static INT64=new y("int64");static INT32=new y("int32");static INT16=new y("int16");static INT8=new y("int8");static UINT64=new y("uint64");static UINT32=new y("uint32");static UINT16=new y("uint16");static UINT8=new y("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new y("timestamp");static UUID=new y("uuid");static STRING=new y("string");static JSON=new y("json");static ARRAY_CONSTRUCTORS=new Map([[y.UINT8.toString(),Uint8Array],[y.UINT16.toString(),Uint16Array],[y.UINT32.toString(),Uint32Array],[y.UINT64.toString(),BigUint64Array],[y.FLOAT32.toString(),Float32Array],[y.FLOAT64.toString(),Float64Array],[y.INT8.toString(),Int8Array],[y.INT16.toString(),Int16Array],[y.INT32.toString(),Int32Array],[y.INT64.toString(),BigInt64Array],[y.TIMESTAMP.toString(),BigInt64Array],[y.STRING.toString(),Uint8Array],[y.JSON.toString(),Uint8Array],[y.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,y.UINT8],[Uint16Array.name,y.UINT16],[Uint32Array.name,y.UINT32],[BigUint64Array.name,y.UINT64],[Float32Array.name,y.FLOAT32],[Float64Array.name,y.FLOAT64],[Int8Array.name,y.INT8],[Int16Array.name,y.INT16],[Int32Array.name,y.INT32],[BigInt64Array.name,y.INT64]]);static DENSITIES=new Map([[y.UINT8.toString(),V.BIT8],[y.UINT16.toString(),V.BIT16],[y.UINT32.toString(),V.BIT32],[y.UINT64.toString(),V.BIT64],[y.FLOAT32.toString(),V.BIT32],[y.FLOAT64.toString(),V.BIT64],[y.INT8.toString(),V.BIT8],[y.INT16.toString(),V.BIT16],[y.INT32.toString(),V.BIT32],[y.INT64.toString(),V.BIT64],[y.TIMESTAMP.toString(),V.BIT64],[y.STRING.toString(),V.UNKNOWN],[y.JSON.toString(),V.UNKNOWN],[y.UUID.toString(),V.BIT128]]);static ALL=[y.UNKNOWN,y.FLOAT64,y.FLOAT32,y.INT64,y.INT32,y.INT16,y.INT8,y.UINT64,y.UINT32,y.UINT16,y.UINT8,y.TIMESTAMP,y.UUID,y.STRING,y.JSON];static BIG_INT_TYPES=[y.INT64,y.UINT64,y.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new y(e)),s.z.instanceof(y)])},Tn=class j extends ht{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new j(jr(this.valueOf(),e.valueOf()))}sub(e){return new j(Ir(this.valueOf(),e.valueOf()))}mult(e){return new j(de(this.valueOf(),e))}div(e){return new j(Rr(this.valueOf(),e))}truncate(e){return new j(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return j.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/j.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/j.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/j.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/j.TERABYTE.valueOf()}toString(){const e=this.truncate(j.TERABYTE),r=this.truncate(j.GIGABYTE),n=this.truncate(j.MEGABYTE),a=this.truncate(j.KILOBYTE),i=this.truncate(j.BYTE),o=e,l=r.sub(e),c=n.sub(r),u=a.sub(n),h=i.sub(a);let p="";return o.isZero||(p+=`${o.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),c.isZero||(p+=`${c.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new j(e)}static BYTE=new j(1);static kilobytes(e=1){return j.bytes(e.valueOf()*1e3)}static KILOBYTE=j.kilobytes(1);static megabytes(e=1){return j.kilobytes(e.valueOf()*1e3)}static MEGABYTE=j.megabytes(1);static gigabytes(e=1){return j.megabytes(e.valueOf()*1e3)}static GIGABYTE=j.gigabytes(1);static terabytes(e){return j.gigabytes(e.valueOf()*1e3)}static TERABYTE=j.terabytes(1);static ZERO=new j(0);static z=s.z.union([s.z.number().transform(e=>new j(e)),s.z.instanceof(j)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Wa=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof C||t instanceof A||t instanceof Date},jc=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r.valueOf())-BigInt(n.valueOf()):fr(r,-n),fr=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),Rc=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Uc(t){return typeof t=="string"&&Rc.test(t)}const F=[];for(let t=0;t<256;++t)F.push((t+256).toString(16).slice(1));function Mc(t,e=0){return(F[t[e+0]]+F[t[e+1]]+F[t[e+2]]+F[t[e+3]]+"-"+F[t[e+4]]+F[t[e+5]]+"-"+F[t[e+6]]+F[t[e+7]]+"-"+F[t[e+8]]+F[t[e+9]]+"-"+F[t[e+10]]+F[t[e+11]]+F[t[e+12]]+F[t[e+13]]+F[t[e+14]]+F[t[e+15]]).toLowerCase()}function Lc(t,e=0){const r=Mc(t,e);if(!Uc(r))throw TypeError("Stringified UUID is invalid");return r}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ga=(t,e)=>Lc(t,e),Se=-1,Pc=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Dc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),On=10,$c=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Ka="sy_x_telem_series";let Ja=class Ae{key;discriminator=Ka;dataType;sampleOffset;gl;_data;timeRange=Et.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=Se;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:Et.z.optional(),dataType:D.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Pc,Dc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Cc.optional().default("static").optional()});static z=Ae.crudeZ.transform(e=>new Ae(e));constructor(e){Bc(e)&&(e={data:e}),e.data??=[];const{dataType:r,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:l=1n,key:c=kc(),data:u}=e;if(Fc(u)){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.alignmentMultiple=d.alignmentMultiple,this.cachedMin=d.cachedMin,this.cachedMax=d.cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this.cachedLength=d.cachedLength;return}const h=Wa(u),p=Array.isArray(u);if(r!=null)this.dataType=new D(r);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(p||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=D.STRING;else if(typeof d=="number")this.dataType=D.FLOAT64;else if(typeof d=="bigint")this.dataType=D.INT64;else if(typeof d=="boolean")this.dataType=D.BOOLEAN;else if(d instanceof C||d instanceof Date||d instanceof C)this.dataType=D.TIMESTAMP;else if(typeof d=="object")this.dataType=D.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new D(u)}if(!p&&!h)this._data=u;else if(p&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[u]:u;const S=d[0];(S instanceof C||S instanceof Date||S instanceof A)&&(d=d.map(N=>new C(N).valueOf())),this.dataType.equals(D.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
2
|
+
`)}
|
|
3
|
+
`).buffer):this.dataType.equals(D.JSON)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(N=>vn.encodeString(N)).join(`
|
|
4
|
+
`)}
|
|
5
|
+
`).buffer):this.dataType.usesBigInt&&typeof S=="number"?this._data=new this.dataType.Array(d.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof S=="bigint"?this._data=new this.dataType.Array(d.map(Number)).buffer:this._data=new this.dataType.Array(d).buffer}this.key=c,this.alignment=o,this.alignmentMultiple=l,this.sampleOffset=a??0,this.timeRange=n??Et.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:r,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new D(r).Array(e),i=new Ae({data:a.buffer,dataType:r,...n});return i.writePos=0,i}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===Se)return 0;const r=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,r);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 r=this.capacity-this.writePos,n=e.sub(0,r);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(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
|
|
6
|
+
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(D.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(r=>e.parse(vn.decodeString(r)))}get byteCapacity(){return new Tn(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 Tn(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.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const r=[0];return this.data.forEach((n,a)=>{n===On&&(e++,r.push(a+1))}),this._cachedIndexes=r,this.cachedLength=e,e}convert(e,r=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=jc(this.dataType,e,this.data[a],r);return new Ae({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(D.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),fr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(D.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),fr(this.cachedMin,this.sampleOffset))}get bounds(){return Ze(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const r=e.cachedMin??e.calcRawMin();r<this.cachedMin&&(this.cachedMin=r)}if(this.cachedMax!=null){const r=e.cachedMax??e.calcRawMax();r>this.cachedMax&&(this.cachedMax=r)}}atAlignment(e,r){const n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(r===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,r)}at(e,r=!1){if(this.dataType.isVariable)return this.atVariable(e,r??!1);if(this.dataType.equals(D.UUID))return this.atUUID(e,r);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return fr(n,this.sampleOffset)}atUUID(e,r){e<0&&(e=this.length+e);const n=Ga(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(r)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,r){let n=0,a=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],a=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]===On){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(D.STRING)?new TextDecoder().decode(i):Pa(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let r=0,n=this.length-1;const a=Gl(e);for(;r<=n;){const i=Math.floor((r+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?r=i+1:n=i-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(D.FLOAT32)&&!this.dataType.equals(D.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:a}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==Se){a===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(a).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,i,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=Se}as(e){return $c(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:_s(this.alignmentBounds.lower),upper:_s(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return Ze(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Zc(this);return this.dataType.equals(D.JSON)?new qc(e):e}return this.dataType.equals(D.UUID)?new Yc(this):new Hc(this)}slice(e,r){return this.sliceSub(!1,e,r)}sub(e,r){return this.sliceSub(!0,e,r)}subIterator(e,r){return new Vs(this,e,r??this.length)}subAlignmentIterator(e,r){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),a=Math.ceil(Number(r-this.alignment)/Number(this.alignmentMultiple));return new Vs(this,n,a)}subBytes(e,r){if(e>=0&&(r==null||r>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,r);return new Ae({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,r,n){if(r<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(r,n):a=this.data.slice(r,n),new Ae({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(r)})}reAlign(e){return new Ae({data:this.buffer,dataType:this.dataType,timeRange:Et.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(r=>r.toString());else{for(let r=0;r<5;r++)e+=`${this.at(r)?.toString()}`,e+=",";e+="...,";for(let r=-5;r<0;r++)e+=this.at(r)?.toString(),r<-1&&(e+=",")}return e+="])",e}};const Bc=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Ja?!0:Wa(t),Fc=xc(Ka,Ja);class Vs{series;end;index;constructor(e,r,n){this.series=e;const a=Ze(0,e.length+1);this.end=Zs(a,n),this.index=Zs(a,r)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class Zc{series;index;decoder;constructor(e){if(!e.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=e,this.index=0,this.decoder=new TextDecoder}next(){const e=this.index,r=this.series.data;for(;this.index<r.length&&r[this.index]!==On;)this.index++;const n=this.index;return e===n?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(e,n))})}}let qc=class Xa{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:vn.decodeString(e.value,Xa.schema)}}};class Yc{series;index;data;density;constructor(e){if(!e.dataType.equals(D.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=D.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Ga(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Hc=class{series;index;constructor(t){this.series=t,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}};const _s=t=>{const e=t>>32n,r=t&0xffffffffn;return{domain:e,sample:r}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const Vc=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Vc();const _c=["macOS","Windows","Linux"],Wc=["macos","windows","linux"],Gc={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(_c).or(s.z.enum(Wc).transform(t=>Gc[t]));const Kc=(...t)=>t.map(Qa).join(""),Qa=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Jc=t=>t.endsWith("/")?t.slice(0,-1):t,Xc=(t,e="")=>t===null?"":`?${Object.entries(t).filter(([,r])=>r==null?!1:Array.isArray(r)?r.length>0:!0).map(([r,n])=>`${e}${r}=${n}`).join("&")}`;let Qc=class pr{protocol;host;port;path;constructor({host:e,port:r,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=r,this.path=Qa(a)}replace(e){return new pr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new pr({...this,pathPrefix:Kc(this.path,e)})}toString(){return Jc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new pr({host:"unknown",port:0})};const eu=async t=>await new Promise(e=>setTimeout(e,A.fromMilliseconds(t).milliseconds));let tu=class{config;retries;interval;constructor(t){this.config={baseInterval:new A(t?.baseInterval??A.seconds(1)),maxRetries:t?.maxRetries??5,scale:t?.scale??1,sleepFn:t?.sleepFn??eu},this.retries=0,this.interval=new A(this.config.baseInterval)}async wait(){const{maxRetries:t,scale:e,sleepFn:r}=this.config;return this.retries>=t?!1:(await r(this.interval),this.interval=this.interval.mult(e),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}};const ru=s.z.object({baseInterval:A.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),nu=Object.freeze(Object.defineProperty({__proto__:null,Breaker:tu,breakerConfigZ:ru},Symbol.toStringTag,{value:"Module"})),su=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,ei=s.z.string().regex(su),rt=s.z.number().min(0).max(255),ti=s.z.number().min(0).max(1),ri=s.z.tuple([rt,rt,rt,ti]),au=s.z.tuple([rt,rt,rt]),iu=s.z.object({rgba255:ri}),ou=s.z.number().min(0).max(360),lu=s.z.number().min(0).max(100),cu=s.z.number().min(0).max(100),uu=s.z.tuple([ou,lu,cu,ti]),ss=s.z.union([ei,au,ri,uu,iu]),hu=ss.transform(t=>as(t)),as=(t,e=1)=>{if(t=ss.parse(t),typeof t=="string")return du(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},du=(t,e=1)=>(t=ei.parse(t),t=fu(t),[ir(t,0),ir(t,2),ir(t,4),t.length===8?ir(t,6)/255:e]),ir=(t,e)=>parseInt(t.slice(e,e+2),16),fu=t=>t.startsWith("#")?t.slice(1):t;as("#000000");as("#ffffff");const pu=s.z.object({key:s.z.string(),color:ss,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(pu);const yu=s.z.object({key:s.z.string(),name:s.z.string(),color:hu});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(yu)});s.z.int().min(0).max(255);s.z.object({name:s.z.string(),key:s.z.string()});const gu=t=>Object.getOwnPropertySymbols(globalThis).includes(t),mu=(t,e)=>{const r=Symbol.for(t);if(!gu(r)){const n=e();Object.defineProperty(globalThis,r,{value:n})}return()=>globalThis[r]},ni="sy_x_error",wu=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),Zt=t=>class Nt extends Error{static discriminator=ni;discriminator=Nt.discriminator;static TYPE=t;type=Nt.TYPE;static matches=wu(t);matches=Nt.matches;constructor(r,n){super(r,n),this.name=Nt.TYPE}static sub(r){return Zt(`${t}.${r}`)}},si=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==ni)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Ge="unknown",Sn="nil";class bu{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Sn,data:""};if(si(e))for(const r of this.providers){const n=r.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Ge,data:e.message};if(typeof e=="string")return{type:Ge,data:e};try{return{type:Ge,data:JSON.stringify(e)}}catch{return{type:Ge,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Sn)return null;if(e.type===Ge)return new zn(e.data);for(const r of this.providers){const n=r.decode(e);if(n!=null)return n}return new zn(e.data)}}const is=mu("synnax-error-registry",()=>new bu),vu=({encode:t,decode:e})=>is().register({encode:t,decode:e}),Tu=t=>is().encode(t),Ou=t=>t==null?null:is().decode(t);let zn=class extends Zt("unknown"){};const Su=s.z.object({type:s.z.string(),data:s.z.string()});class zu extends Zt("canceled"){}class Eu extends Zt("not_implemented"){}const Ue=Object.freeze(Object.defineProperty({__proto__:null,Canceled:zu,NONE:Sn,NotImplemented:Eu,UNKNOWN:Ge,Unknown:zn,createTyped:Zt,decode:Ou,encode:Tu,isTyped:si,payloadZ:Su,register:vu},Symbol.toStringTag,{value:"Module"})),Nu=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),ai=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),Au=ai.extend({result:s.json()}),ku=ai.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),xu=s.union([Au,ku]);s.union([Nu,xu]);s.z.string().regex(/^\d+\.\d+\.\d+$/);const Cu=["standard","scientific","engineering"];s.z.enum(Cu);s.z.enum(["success","info","warning","error","loading","disabled"]);let qt=class extends Ue.createTyped("freighter"){},ae=class extends qt.sub("eof"){constructor(){super("EOF")}},st=class extends qt.sub("stream_closed"){constructor(){super("StreamClosed")}},Me=class extends qt.sub("unreachable"){url;constructor(t={}){const{message:e="Unreachable",url:r=Qc.UNKNOWN}=t;super(e),this.url=r}};const Iu=t=>{if(!t.type.startsWith(qt.TYPE))return null;if(ae.matches(t))return{type:ae.TYPE,data:"EOF"};if(st.matches(t))return{type:st.TYPE,data:"StreamClosed"};if(Me.matches(t))return{type:Me.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${t.type}: ${t.message}`)},ju=t=>{if(!t.type.startsWith(qt.TYPE))return null;switch(t.type){case ae.TYPE:return new ae;case st.TYPE:return new st;case Me.TYPE:return new Me;default:throw new Ue.Unknown(`Unknown error type: ${t.data}`)}};Ue.register({encode:Iu,decode:ju});class ii{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,r){let n=0;const a=async i=>{if(n===this.middleware.length)return await r(i);const o=this.middleware[n];return n++,await o(i,a)};return await a(e)}}const oi="Content-Type",Ru=new Set(["ECONNREFUSED","ECONNRESET","ETIMEDOUT","EPIPE","UND_ERR_CONNECT_TIMEOUT","UND_ERR_SOCKET"]),Uu=t=>{const e=t?.cause?.code??t?.code??t?.errno;if(typeof e=="string"&&Ru.has(e))return!0;if(t.name==="TypeError"){const r=String(t.message||"").toLowerCase();if(/load failed|failed to fetch|networkerror|network error/.test(r))return!0}return t?.name==="AbortError"||t?.code,!1},Mu=400;class Lu extends ii{endpoint;encoder;constructor(e,r,n=!1){return super(),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=r,new Proxy(this,{get:(a,i,o)=>i==="endpoint"?this.endpoint:Reflect.get(a,i,o)})}get headers(){return{[oi]:this.encoder.contentType}}async send(e,r,n,a){r=n?.parse(r);let i=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(r??{});const[,c]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async u=>{const h={...u,params:{}};l.headers={...this.headers,...u.params};let p;try{p=await fetch(u.target,l)}catch(S){if(!(S instanceof Error))throw S;return[h,Uu(S)?new Me({url:o}):S]}const d=await p.arrayBuffer();if(p?.ok)return a!=null&&(i=this.encoder.decode(d,a)),[h,null];try{if(p.status!==Mu)return[h,new Error(p.statusText)];const S=this.encoder.decode(d,Ue.payloadZ),N=Ue.decode(S);return[h,N]}catch(S){return[h,new Error(`[freighter] - failed to decode error: ${p.statusText}: ${S.message}`)]}});if(c!=null)return[null,c];if(i==null)throw new Error("Response must be defined");return[i,null]}}const Pu=(t,e)=>{class r{wrapped;constructor(a){this.wrapped=a}use(...a){this.wrapped.use(...a)}async send(a,i,o,l){const c=new nu.Breaker(e);do{const[u,h]=await this.wrapped.send(a,i,o,l);if(h==null)return[u,null];if(!Me.matches(h))return[null,h];if(console.warn(`[freighter] ${c.retryMessage}`,h),!await c.wait())return[u,h]}while(!0)}}return new r(t)},m=async(t,e,r,n,a)=>{const[i,o]=await t.send(e,r,n,a);if(o!=null)throw o;return i},Du=s.z.object({type:s.z.enum(["data","close","open"]),payload:s.z.unknown(),error:s.z.optional(Ue.payloadZ)});class $u{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,r,n,a){this.codec=r,this.reqSchema=n,this.resSchema=a,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 Ue.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new ae;if(this.sendClosed)throw new st;return this.ws.send(this.codec.encode({type:"data",payload:e})),null}async receive(){if(this.serverClosed!=null)return[null,this.serverClosed];const e=await this.receiveMsg();if(e.type==="close"){if(e.error==null)throw new Error("Message error must be defined");if(this.serverClosed=Ue.decode(e.error),this.serverClosed==null)throw new Error("Message error must be defined");return[null,this.serverClosed]}return[this.resSchema.parse(e.payload),null]}received(){return this.receiveDataQueue.length!==0}closeSend(){if(this.sendClosed||this.serverClosed!=null)return;const e={type:"close"};try{this.ws.send(this.codec.encode(e))}finally{this.sendClosed=!0}}async receiveMsg(){return this.receiveDataQueue.shift()??await new Promise((e,r)=>this.receiveCallbacksQueue.push({resolve:e,reject:r}))}addMessage(e){const r=this.receiveCallbacksQueue.shift();r!=null?r.resolve(e):this.receiveDataQueue.push(e)}listenForMessages(){this.ws.onmessage=this.onMessage.bind(this),this.ws.onclose=this.onClose.bind(this)}onMessage(e){this.addMessage(this.codec.decode(e.data,Du))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Fu?ae.TYPE:st.TYPE,data:""}})}}const Bu="freighterctx",Fu=1e3;let Zu=class En extends ii{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,r,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=r}withCodec(e){const r=new En(this.baseUrl,e,this.secure);return r.use(...this.middleware),r}async stream(e,r,n){let a;const[,i]=await this.executeMiddleware({target:e,protocol:"websocket",params:{},role:"client"},async o=>{const l=new WebSocket(this.buildURL(e,o)),c={...o,params:{}};l.binaryType=En.MESSAGE_TYPE;const u=await this.wrapSocket(l,r,n);return u instanceof Error?[c,u]:(a=u,[c,null])});if(i!=null)throw i;return a}buildURL(e,r){const n=Xc({[oi]:this.encoder.contentType,...r.params},Bu);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,r,n){return await new Promise(a=>{e.onopen=()=>{const i=new $u(e,this.encoder,r,n);i.receiveOpenAck().then(o=>{o!=null?a(o):a(i)}).catch(o=>a(o))},e.onerror=i=>{const o=i;a(new Error(o.message))}})}};const qu=t=>Array.isArray(t)?t:t==null?[]:[t],O=Object.freeze(Object.defineProperty({__proto__:null,toArray:qu},Symbol.toStringTag,{value:"Module"})),Yu=t=>{const e=t.replace(/_[a-z]/g,r=>r[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},os=t=>{const e=(r,n=Nn)=>{if(typeof r=="string")return t(r);if(Array.isArray(r))return r.map(o=>e(o,n));if(!en(r))return r;n=Wu(n);const a={},i=r;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=t(o);n.recursive&&(en(l)?Gs(l)||(l=e(l,n)):n.recursiveInArray&&Ws(l)&&(l=[...l].map(u=>{let h=u;return en(u)?Gs(h)||(h=e(u,n)):Ws(u)&&(h=e({key:u},n).key),h}))),a[c]=l}),a)};return e},ls=os(Yu),Hu=t=>t.replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}_${n.toLowerCase()}`),li=os(Hu),Vu=t=>t.length===0?t:t[0].toUpperCase()+t.slice(1),_u=[Number,String,Uint8Array],Nn={recursive:!0,recursiveInArray:!0},Wu=(t=Nn)=>(t.recursive==null?t=Nn:t.recursiveInArray??=!1,t),Ws=t=>t!=null&&Array.isArray(t),en=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Gs=t=>_u.some(e=>t instanceof e),Gu=t=>t.replace(/\s+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,r,n)=>`${r}-${n.toLowerCase()}`).toLowerCase(),Ku=os(Gu),Ju=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:li,capitalize:Vu,snakeToCamel:ls,toKebab:Ku},Symbol.toStringTag,{value:"Module"})),ci=t=>t!=null&&typeof t=="object"&&!Array.isArray(t);let ui=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(t){return this.encoder.encode(this.encodeString(t))}decode(t,e){return this.decodeString(this.decoder.decode(t),e)}decodeString(t,e){const r=JSON.parse(t),n=ls(r);return e!=null?e.parse(n):n}encodeString(t){const e=li(t);return JSON.stringify(e,(r,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}},hi=class{contentType="text/csv";encode(t){const e=this.encodeString(t);return new TextEncoder().encode(e)}decode(t,e){const r=new TextDecoder().decode(t);return this.decodeString(r,e)}encodeString(t){if(!Array.isArray(t)||t.length===0||!ci(t[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(t[0]),r=[e.join(",")];return t.forEach(n=>{const a=e.map(i=>JSON.stringify(n[i]??""));r.push(a.join(","))}),r.join(`
|
|
7
|
+
`)}decodeString(t,e){const[r,...n]=t.trim().split(`
|
|
8
|
+
`).map(o=>o.trim());if(r.length===0)return e!=null?e.parse({}):{};const a=r.split(",").map(o=>o.trim()),i={};return a.forEach(o=>{i[o]=[]}),n.forEach(o=>{const l=o.split(",").map(c=>c.trim());a.forEach((c,u)=>{const h=this.parseValue(l[u]);h!=null&&i[c].push(h)})}),e!=null?e.parse(i):i}parseValue(t){if(t==null||t.length===0)return null;const e=Number(t);return isNaN(e)?t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t:e}},di=class{contentType="text/plain";encode(t){if(typeof t!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(t)}decode(t,e){const r=new TextDecoder().decode(t);return e!=null?e.parse(r):r}};const It=new ui,Xu=new hi,Qu=new di,eh=[It],He=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:hi,CSV_CODEC:Xu,ENCODERS:eh,JSONCodec:ui,JSON_CODEC:It,TEXT_CODEC:Qu,TextCodec:di},Symbol.toStringTag,{value:"Module"})),An=t=>[...new Set(t)],th=(t,e,r=!0)=>{const n=new Map;return t.forEach(a=>{const i=e(a);if(n.has(i)){if(r)return;n.delete(i)}n.set(i,a)}),Array.from(n.values())},Ks=Object.freeze(Object.defineProperty({__proto__:null,by:th,unique:An},Symbol.toStringTag,{value:"Module"}));let dt=class{value;constructor(t){this.value=t}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const rh=t=>t!=null&&typeof t=="object"&&"toString"in t,Ur=(t,e=!1)=>{const r=rh(t)?"stringer":typeof t;let n;switch(r){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${r}`),()=>-1}return e?pi(n):n},nh=(t,e,r)=>{const n=Ur(e[t],r);return(a,i)=>n(a[t],i[t])},sh=(t,e)=>t.length!==e.length?t.length-e.length:t.every((r,n)=>r===e[n])?0:-1,fi=(t,e)=>{if(t.length!==e.length)return t.length-e.length;if(t.length===0)return 0;const r=Ur(t[0]),n=[...t].sort(r),a=[...e].sort(r);return n.every((i,o)=>i===a[o])?0:-1},ah=(t,e)=>{const r=An(t),n=An(e);return fi(r,n)},ih=(t,e)=>t===e?0:t==="first"&&e==="last"?1:-1,pi=t=>(e,r)=>t(r,e),ft=0,yr=-1,gr=1,yi=t=>t<ft,gi=t=>t>ft,oh=t=>t>=ft,mi=t=>t===ft,lh=(t,e)=>{const r=/([a-zA-Z]+)|(\d+)/g,n=t.replace(/[\s_.-]+/g,"").match(r),a=e.replace(/[\s_.-]+/g,"").match(r);if(!n||!a)return 0;for(let i=0;i<Math.min(n.length,a.length);i++){const o=n[i],l=a[i];if(isNaN(Number(o))&&isNaN(Number(l))){const c=o.localeCompare(l);if(c!==0)return c}else if(!isNaN(Number(o))&&!isNaN(Number(l))){const c=Number(o)-Number(l);if(c!==0)return c}else return isNaN(Number(o))?-1:1}return n.length-a.length},Js=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:ft,GREATER_THAN:gr,LESS_THAN:yr,isEqualTo:mi,isGreaterThan:gi,isGreaterThanEqual:oh,isLessThan:yi,newF:Ur,newFieldF:nh,order:ih,primitiveArrays:sh,reverseF:pi,stringsWithNumbers:lh,uniqueUnorderedPrimitiveArrays:ah,unorderedPrimitiveArrays:fi},Symbol.toStringTag,{value:"Module"})),Mr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const wi=s.z.object({width:s.z.number(),height:s.z.number()}),ch=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),uh=["width","height"];s.z.enum(uh);const hh=["start","center","end"],dh=["signedWidth","signedHeight"];s.z.enum(dh);const Tr=s.z.object({x:s.z.number(),y:s.z.number()}),fh=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),ph=["x","y"],bi=s.z.enum(ph),vi=["top","right","bottom","left"];s.z.enum(vi);const yh=["left","right"],Ti=s.z.enum(yh),gh=["top","bottom"],Oi=s.z.enum(gh),Si=["center"],Xs=s.z.enum(Si),mh=[...vi,...Si],zi=s.z.enum(mh);s.z.enum(hh);const wh=["first","last"];s.z.enum(wh);const bh=s.z.object({lower:s.z.number(),upper:s.z.number()}),vh=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([bh,Mr]);s.z.union([vh,Mr]);s.z.enum([...bi.options,...zi.options]);s.z.enum(["x","left","right"]);s.z.enum(["y","top","bottom"]);s.z.union([bi,zi,s.z.instanceof(String)]);const Yt=t=>(e,r)=>{if(typeof e=="bigint"){if(Ei(r))return t(e,BigInt(r));const n=t(Number(e),Number(r));return typeof n=="number"?BigInt(Math.round(n)):n}return t(Number(e),Number(r))},qe=Yt((t,e)=>t-e),Ht=Yt((t,e)=>t+e),Qs=(t,e)=>{const r=typeof t=="bigint";return r&&typeof e=="bigint"?t===e:r&&Ei(e)?t===BigInt(e):t===e},Th=Yt((t,e)=>t<=e?t:e),Ei=t=>typeof t=="bigint"?!0:Number.isInteger(t),Oh=t=>typeof t=="bigint"?t<0n?-t:t:t<0?-t:t,fe=Yt((t,e)=>t*e),Lr=Yt((t,e)=>t/e),q=(t,e,r)=>{const n={};if(typeof e=="object"&&(r=e,e=void 0),r={makeValid:!0,...r},typeof t=="number"||typeof t=="bigint")e!=null?(n.lower=t,n.upper=e):(n.lower=typeof t=="bigint"?0n:0,n.upper=t);else if(Array.isArray(t)){if(t.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=t}else n.lower=t.lower,n.upper=t.upper;return r?.makeValid?Sh(n):n},Sh=t=>t.lower>t.upper?{lower:t.upper,upper:t.lower}:t,ea=(t,e)=>{const r=q(t);return e<r.lower?r.lower:e>=r.upper?r.upper-(typeof r.upper=="number"?1:1n):e},or=(t,e)=>{const r=q(t);if(typeof e=="number"||typeof e=="bigint")return e>=r.lower&&e<r.upper;const n=q(e);return n.lower>=r.lower&&n.upper<=r.upper},zh=t=>({lower:Math.min(...t.map(e=>q(e).lower)),upper:Math.max(...t.map(e=>q(e).upper))}),Eh=(t,e,r)=>{const n=t.map(l=>q(l)),a=r>0?1:r<0?-1:0;if(a===0)return e;let i=r,o=e;for(;Qs(i,0)===!1;){const l=n.findIndex(c=>a>0?o>=c.lower&&o<c.upper:o>c.lower&&o<=c.upper);if(l!==-1){const c=n[l];let u;if(a>0?u=qe(c.upper,o):u=qe(o,c.lower),u>0){const h=Th(Oh(i),u);if(o=Ht(o,a>0?h:-h),i=qe(i,a>0?h:-h),Qs(i,0))return o;continue}}if(a>0){const c=n.filter(u=>u.lower>o);if(c.length>0)o=c[0].lower;else return o}else{const c=n.filter(u=>u.upper<o);if(c.length>0)o=c[c.length-1].upper;else return o}}return o},Nh=(t,e,r)=>{const n=t.map(o=>q(o));if(e===r)return typeof e=="bigint"?0n:0;const a=e<r?q([e,r]):q([r,e]);let i=typeof e=="bigint"?0n:0;for(const o of n){const l=o.lower>a.lower?o.lower:a.lower,c=o.upper<a.upper?o.upper:a.upper;if(l<c){const u=c-l;i=i+u}}return i};s.z.object({x:Ti.or(Xs),y:Oi.or(Xs)});const Ah=s.z.object({x:Ti,y:Oi}),kh=Object.freeze({x:"left",y:"top"}),xh=(t,e)=>t.x===e.x&&t.y===e.y,ta=s.z.union([s.z.number(),Tr,Mr,wi,ch,fh]),Ch=(t,e)=>{if(typeof t=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return t==="x"?{x:e,y:0}:{x:0,y:e}}return typeof t=="number"?{x:t,y:e??t}:Array.isArray(t)?{x:t[0],y:t[1]}:"signedWidth"in t?{x:t.signedWidth,y:t.signedHeight}:"clientX"in t?{x:t.clientX,y:t.clientY}:"width"in t?{x:t.width,y:t.height}:{x:t.x,y:t.y}},ra=Object.freeze({x:0,y:0}),lr=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:lr,left:lr,width:lr,height:lr});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:Tr,two:Tr,root:Ah});const cs=(t,e,r=0,n=0,a)=>{const i={one:{...ra},two:{...ra},root:a??kh};if(typeof t=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:t,y:e},i.two={x:i.one.x+r,y:i.one.y+n},i}return"one"in t&&"two"in t&&"root"in t?{...t,root:a??t.root}:("getBoundingClientRect"in t&&(t=t.getBoundingClientRect()),"left"in t?(i.one={x:t.left,y:t.top},i.two={x:t.right,y:t.bottom},i):(i.one=t,e==null?i.two={x:i.one.x+r,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+r}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},tn=t=>{const e=cs(t);return{lower:e.one.x,upper:e.two.x}},rn=t=>{const e=cs(t);return{lower:e.one.y,upper:e.two.y}},Ih=t=>typeof t!="object"||t==null?!1:"one"in t&&"two"in t&&"root"in t,jh=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([wi,jh,Tr,Mr]);const Rh=(t,e,r)=>e!==void 0&&t<e?e:r!==void 0&&t>r?r:t;s.z.object({offset:ta,scale:ta});s.z.object({offset:s.z.number(),scale:s.z.number()});const Uh=t=>(e,r,n,a)=>r==="dimension"?[e,n]:[e,a?n-t:n+t],Mh=t=>(e,r,n,a)=>[e,a?n/t:n*t],Lh=t=>(e,r,n)=>{if(e===null)return[t,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=t,c=i-a,u=l-o;if(r==="dimension")return[t,n*(u/c)];const h=(n-a)*(u/c)+o;return[t,h]},Ph=t=>(e,r,n)=>[t,n],Dh=()=>(t,e,r)=>{if(t===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[t,r];const{lower:n,upper:a}=t;return[t,a-(r-n)]},$h=t=>(e,r,n)=>{const{lower:a,upper:i}=t;return n=Rh(n,a,i),[e,n]};let na=class Ke{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new Ke().translate(e)}static magnify(e){return new Ke().magnify(e)}static scale(e,r){return new Ke().scale(e,r)}translate(e){const r=this.new(),n=Uh(e);return n.type="translate",r.ops.push(n),r}magnify(e){const r=this.new(),n=Mh(e);return n.type="magnify",r.ops.push(n),r}scale(e,r){const n=q(e,r),a=this.new(),i=Lh(n);return i.type="scale",a.ops.push(i),a}clamp(e,r){const n=q(e,r),a=this.new(),i=$h(n);return i.type="clamp",a.ops.push(i),a}reBound(e,r){const n=q(e,r),a=this.new(),i=Ph(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=Dh();e.type="invert";const r=this.new();return r.ops.push(e),r}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new Ke;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,r){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,r])[1]}reverse(){const e=this.new();e.ops.reverse();const r=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||r.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&r.push([a,i])}),r.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new Ke};(class ue{x;y;currRoot;constructor(e=new na,r=new na,n=null){this.x=e,this.y=r,this.currRoot=n}static translate(e,r){return new ue().translate(e,r)}static translateX(e){return new ue().translateX(e)}static translateY(e){return new ue().translateY(e)}static clamp(e){return new ue().clamp(e)}static magnify(e){return new ue().magnify(e)}static scale(e){return new ue().scale(e)}static reBound(e){return new ue().reBound(e)}translate(e,r){const n=Ch(e,r),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const r=this.copy();return r.x=this.x.translate(e),r}translateY(e){const r=this.copy();return r.y=this.y.translate(e),r}magnify(e){const r=this.copy();return r.x=this.x.magnify(e.x),r.y=this.y.magnify(e.y),r}scale(e){const r=this.copy();if(Ih(e)){const n=this.currRoot;return r.currRoot=e.root,n!=null&&!xh(n,e.root)&&(n.x!==e.root.x&&(r.x=r.x.invert()),n.y!==e.root.y&&(r.y=r.y.invert())),r.x=r.x.scale(tn(e)),r.y=r.y.scale(rn(e)),r}return r.x=r.x.scale(e.width),r.y=r.y.scale(e.height),r}reBound(e){const r=this.copy();return r.x=this.x.reBound(tn(e)),r.y=this.y.reBound(rn(e)),r}clamp(e){const r=this.copy();return r.x=this.x.clamp(tn(e)),r.y=this.y.clamp(rn(e)),r}copy(){const e=new ue;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 cs(this.pos(e.one),this.pos(e.two),0,0,this.currRoot??e.root)}get transform(){return{scale:this.dim({x:1,y:1}),offset:this.pos({x:0,y:0})}}static IDENTITY=new ue});let Ni=(t,e=21)=>(r=e)=>{let n="",a=r|0;for(;a--;)n+=t[Math.random()*t.length|0];return n};const Ai="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",Bh=`0123456789${Ai}`,ki=11,Fh=Ni(Ai,1),Zh=Ni(Bh,ki-1),us=()=>`${Fh()}${Zh()}`,qh=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:ki,create:us},Symbol.toStringTag,{value:"Module"})),Yh=(t,e)=>r=>r instanceof e||typeof r=="object"&&r!==null&&"discriminator"in r&&r.discriminator===t,Hh=s.z.enum(["static","dynamic"]),Vh=s.z.union([s.z.tuple([s.z.int()]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12)]),s.z.tuple([s.z.int(),s.z.int().min(1).max(12),s.z.int().min(1).max(31)])]),xi=(t,e)=>{const r=new E(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(a=>a.equals(r)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=t.valueOf()%r.valueOf();return t instanceof E?new E(n):new z(n)};let E=class b extends dt{constructor(e,r="UTC"){if(e==null)super(b.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*b.MILLISECOND.valueOf());else if(typeof e=="string")super(b.parseDateTimeString(e,r).valueOf());else if(Array.isArray(e))super(b.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),r==="local"&&(n=b.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=b.MAX:e=b.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,r=1,n=1]){const a=new Date(e,r-1,n,0,0,0,0);return new b(BigInt(a.getTime())*b.MILLISECOND.valueOf()).truncate(b.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,r="UTC"){const[n,a,i]=e.split(":");let o="00",l="00";i!=null&&([o,l]=i.split("."));let c=b.hours(parseInt(n??"00")).add(b.minutes(parseInt(a??"00"))).add(b.seconds(parseInt(o??"00"))).add(b.milliseconds(parseInt(l??"00")));return r==="local"&&(c=c.add(b.utcOffset)),c.valueOf()}static parseDateTimeString(e,r="UTC"){if(!e.includes("/")&&!e.includes("-"))return b.parseTimeString(e,r);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new b(BigInt(n.getTime())*b.MILLISECOND.valueOf(),r).valueOf()}fString(e="ISO",r="UTC"){switch(e){case"ISODate":return this.toISOString(r).slice(0,10);case"ISOTime":return this.toISOString(r).slice(11,23);case"time":return this.timeString(!1,r);case"preciseTime":return this.timeString(!0,r);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,r)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,r)}`;default:return this.toISOString(r)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(b.utcOffset).date().toISOString()}timeString(e=!1,r="UTC"){const n=this.toISOString(r);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),r=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${r} ${n}`}static get utcOffset(){return new z(BigInt(new Date().getTimezoneOffset())*b.MINUTE.valueOf())}static since(e){return new b().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new b(e).valueOf()}span(e){return this.range(e).span}range(e){return new L(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new b(e).valueOf()}afterEq(e){return this.valueOf()>=new b(e).valueOf()}before(e){return this.valueOf()<new b(e).valueOf()}beforeEq(e){return this.valueOf()<=new b(e).valueOf()}add(e){return new b(Ht(this.valueOf(),new z(e).valueOf()))}sub(e){return new b(qe(this.valueOf(),new z(e).valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(b.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(b.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const r=this.date();return r.setUTCFullYear(e),new b(r)}get month(){return this.date().getUTCMonth()}setMonth(e){const r=this.date();return r.setUTCMonth(e),new b(r)}get day(){return this.date().getUTCDate()}setDay(e){const r=this.date();return r.setUTCDate(e),new b(r)}get hour(){return this.date().getUTCHours()}setHour(e){const r=this.date();return r.setUTCHours(e),new b(r,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const r=this.date();return r.setUTCMinutes(e),new b(r)}get second(){return this.date().getUTCSeconds()}setSecond(e){const r=this.date();return r.setUTCSeconds(e),new b(r)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const r=this.date();return r.setUTCMilliseconds(e),new b(r)}toString(){return this.date().toISOString()}remainder(e){return xi(this,e)}get isToday(){return this.truncate(z.DAY).equals(b.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new b(new Date)}static max(...e){let r=b.MIN;for(const n of e){const a=new b(n);a.after(r)&&(r=a)}return r}static min(...e){let r=b.MAX;for(const n of e){const a=new b(n);a.before(r)&&(r=a)}return r}static nanoseconds(e,r="UTC"){return new b(e,r)}static NANOSECOND=b.nanoseconds(1);static microseconds(e,r="UTC"){return b.nanoseconds(e*1e3,r)}static MICROSECOND=b.microseconds(1);static milliseconds(e,r="UTC"){return b.microseconds(e*1e3,r)}static MILLISECOND=b.milliseconds(1);static seconds(e,r="UTC"){return b.milliseconds(e*1e3,r)}static SECOND=b.seconds(1);static minutes(e,r="UTC"){return b.seconds(e*60,r)}static MINUTE=b.minutes(1);static hours(e,r="UTC"){return b.minutes(e*60,r)}static HOUR=b.hours(1);static days(e,r="UTC"){return b.hours(e*24,r)}static DAY=b.days(1);static MAX=new b((1n<<63n)-1n);static MIN=new b(0);static ZERO=new b(0);static z=s.z.union([s.z.instanceof(b),s.z.object({value:s.z.bigint()}).transform(e=>new b(e.value)),s.z.string().transform(e=>new b(BigInt(e))),s.z.number().transform(e=>new b(e)),s.z.bigint().transform(e=>new b(e)),s.z.date().transform(e=>new b(e)),s.z.custom(e=>e instanceof z).transform(e=>new b(e)),Vh.transform(e=>new b(e))]);static sort(e,r){return Number(e.valueOf()-r.valueOf())}},z=class T extends dt{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof T?e:e instanceof nn?e.period:e instanceof E?new T(e):["number","bigint"].includes(typeof e)?T.seconds(e):new T(e)}static fromMilliseconds(e){return e instanceof T?e:e instanceof nn?e.period:e instanceof E?new T(e):["number","bigint"].includes(typeof e)?T.milliseconds(e):new T(e)}valueOf(){return this.value}lessThan(e){return this.valueOf()<new T(e).valueOf()}greaterThan(e){return this.valueOf()>new T(e).valueOf()}lessThanOrEqual(e){return this.valueOf()<=new T(e).valueOf()}greaterThanOrEqual(e){return this.valueOf()>=new T(e).valueOf()}remainder(e){return xi(this,e)}truncate(e){return new T(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(T.DAY),r=this.truncate(T.HOUR),n=this.truncate(T.MINUTE),a=this.truncate(T.SECOND),i=this.truncate(T.MILLISECOND),o=this.truncate(T.MICROSECOND),l=this.truncate(T.NANOSECOND),c=e,u=r.sub(e),h=n.sub(r),p=a.sub(n),d=i.sub(a),S=o.sub(i),N=l.sub(o);let x="";return c.isZero||(x+=`${c.days}d `),u.isZero||(x+=`${u.hours}h `),h.isZero||(x+=`${h.minutes}m `),p.isZero||(x+=`${p.seconds}s `),d.isZero||(x+=`${d.milliseconds}ms `),S.isZero||(x+=`${S.microseconds}µs `),N.isZero||(x+=`${N.nanoseconds}ns`),x.trim()}mult(e){return new T(fe(this.valueOf(),e))}div(e){return new T(Lr(this.valueOf(),e))}get days(){return Number(this.valueOf())/Number(T.DAY.valueOf())}get hours(){return Number(this.valueOf())/Number(T.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(T.MINUTE.valueOf())}get seconds(){return Number(this.valueOf())/Number(T.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(T.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(T.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get isZero(){return this.valueOf()===0n}equals(e){return this.valueOf()===new T(e).valueOf()}add(e){return new T(this.valueOf()+new T(e).valueOf())}sub(e){return new T(this.valueOf()-new T(e).valueOf())}static nanoseconds(e=1){return new T(e)}static NANOSECOND=T.nanoseconds(1);static microseconds(e=1){return T.nanoseconds(fe(e,1e3))}static MICROSECOND=T.microseconds(1);static milliseconds(e=1){return T.microseconds(fe(e,1e3))}static MILLISECOND=T.milliseconds(1);static seconds(e=1){return T.milliseconds(fe(e,1e3))}static SECOND=T.seconds(1);static minutes(e=1){return T.seconds(fe(e,60))}static MINUTE=T.minutes(1);static hours(e){return T.minutes(fe(e,60))}static HOUR=T.hours(1);static days(e){return T.hours(fe(e,24))}static DAY=T.days(1);static MAX=new T((1n<<63n)-1n);static MIN=new T(0);static ZERO=new T(0);static z=s.z.union([s.z.object({value:s.z.bigint()}).transform(e=>new T(e.value)),s.z.string().transform(e=>new T(BigInt(e))),s.z.number().transform(e=>new T(e)),s.z.bigint().transform(e=>new T(e)),s.z.instanceof(T),s.z.instanceof(E).transform(e=>new T(e)),s.z.custom(e=>e instanceof nn).transform(e=>new T(e))])},nn=class he extends dt{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new he(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,r){return this.sampleCount(e)*new _(r).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,r){return this.span(e.valueOf()/r.valueOf())}add(e){return new he(Ht(this.valueOf(),e.valueOf()))}sub(e){return new he(qe(this.valueOf(),e.valueOf()))}mult(e){return new he(fe(this.valueOf(),e))}div(e){return new he(Lr(this.valueOf(),e))}static hz(e){return new he(e)}static khz(e){return he.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new he(e)),s.z.instanceof(he)])},_=class K extends dt{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new at(e*this.valueOf())}add(e){return new K(Ht(this.valueOf(),e.valueOf()))}sub(e){return new K(qe(this.valueOf(),e.valueOf()))}mult(e){return new K(fe(this.valueOf(),e))}div(e){return new K(Lr(this.valueOf(),e))}static UNKNOWN=new K(0);static BIT128=new K(16);static BIT64=new K(8);static BIT32=new K(4);static BIT16=new K(2);static BIT8=new K(1);static z=s.z.union([s.z.number().transform(e=>new K(e)),s.z.instanceof(K)])},L=class ne{start;end;constructor(e,r){typeof e=="object"&&"start"in e?(this.start=new E(e.start),this.end=new E(e.end)):(this.start=new E(e),this.end=new E(r))}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 ne(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,r=z.ZERO){if(r.isZero)return this.start.equals(e.start)&&this.end.equals(e.end);let n=this.start.sub(e.start).valueOf(),a=this.end.sub(e.end).valueOf();return n<0&&(n=-n),a<0&&(a=-a),n<=r.valueOf()&&a<=r.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,r=z.ZERO){e=e.makeValid();const n=this.makeValid();if(this.equals(e))return!0;if(e.end.equals(n.start)||n.end.equals(e.start))return!1;const a=E.max(n.start,e.start),i=E.min(n.end,e.end);return i.before(a)?!1:new z(i.sub(a)).greaterThanOrEqual(r)}contains(e){return e instanceof ne?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const r=new ne(this.start,this.end);return e.start.after(this.start)&&(r.start=e.start),e.start.after(this.end)&&(r.end=e.start),e.end.before(this.end)&&(r.end=e.end),e.end.before(this.start)&&(r.start=e.end),r}static max(...e){return new ne(E.min(...e.map(r=>r.start)),E.max(...e.map(r=>r.end)))}static MAX=new ne(E.MIN,E.MAX);static MIN=new ne(E.MAX,E.MIN);static ZERO=new ne(E.ZERO,E.ZERO);static z=s.z.union([s.z.object({start:E.z,end:E.z}).transform(e=>new ne(e.start,e.end)),s.z.instanceof(ne)]);static sort(e,r){return E.sort(e.start,r.start)||E.sort(e.end,r.end)}static simplify(e){return e.map(r=>r.makeValid()).sort((r,n)=>ne.sort(r,n)).reduce((r,n)=>{if(n.isZero)return r;if(r.length===0)return r.push(n),r;const a=r[r.length-1];return a.overlapsWith(n)||a.end.equals(n.start)?a.end=E.max(a.end,n.end):r.push(n),r},[])}},k=class g extends dt{constructor(e){if(e instanceof g||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const r=g.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(r==null)throw new Error(`unable to find data type for ${e.toString()}`);super(r.valueOf())}}get Array(){const e=g.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(r=>this.equals(r))}toString(){return this.valueOf()}get isVariable(){return this.equals(g.JSON)||this.equals(g.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(g.UUID)}get isInteger(){const e=this.toString();return e.startsWith("int")||e.startsWith("uint")}get isFloat(){return this.toString().startsWith("float")}get density(){const e=g.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(g.UINT8)||this.equals(g.UINT16)||this.equals(g.UINT32)||this.equals(g.UINT64)}get isSignedInteger(){return this.equals(g.INT8)||this.equals(g.INT16)||this.equals(g.INT32)||this.equals(g.INT64)}canSafelyCastTo(e){return this.equals(e)?!0:!this.isNumeric||!e.isNumeric||this.isVariable||e.isVariable||this.isUnsignedInteger&&e.isSignedInteger?!1:this.isFloat?e.isFloat&&this.density.valueOf()<=e.density.valueOf():this.equals(g.INT32)&&e.equals(g.FLOAT64)||this.equals(g.INT8)&&e.equals(g.FLOAT32)?!0:this.isInteger&&e.isInteger?this.density.valueOf()<=e.density.valueOf()&&this.isUnsignedInteger===e.isUnsignedInteger:!1}canCastTo(e){return this.isNumeric&&e.isNumeric?!0:this.equals(e)}checkArray(e){return e.constructor===this.Array}get usesBigInt(){return g.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new g("unknown");static FLOAT64=new g("float64");static FLOAT32=new g("float32");static INT64=new g("int64");static INT32=new g("int32");static INT16=new g("int16");static INT8=new g("int8");static UINT64=new g("uint64");static UINT32=new g("uint32");static UINT16=new g("uint16");static UINT8=new g("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new g("timestamp");static UUID=new g("uuid");static STRING=new g("string");static JSON=new g("json");static ARRAY_CONSTRUCTORS=new Map([[g.UINT8.toString(),Uint8Array],[g.UINT16.toString(),Uint16Array],[g.UINT32.toString(),Uint32Array],[g.UINT64.toString(),BigUint64Array],[g.FLOAT32.toString(),Float32Array],[g.FLOAT64.toString(),Float64Array],[g.INT8.toString(),Int8Array],[g.INT16.toString(),Int16Array],[g.INT32.toString(),Int32Array],[g.INT64.toString(),BigInt64Array],[g.TIMESTAMP.toString(),BigInt64Array],[g.STRING.toString(),Uint8Array],[g.JSON.toString(),Uint8Array],[g.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,g.UINT8],[Uint16Array.name,g.UINT16],[Uint32Array.name,g.UINT32],[BigUint64Array.name,g.UINT64],[Float32Array.name,g.FLOAT32],[Float64Array.name,g.FLOAT64],[Int8Array.name,g.INT8],[Int16Array.name,g.INT16],[Int32Array.name,g.INT32],[BigInt64Array.name,g.INT64]]);static DENSITIES=new Map([[g.UINT8.toString(),_.BIT8],[g.UINT16.toString(),_.BIT16],[g.UINT32.toString(),_.BIT32],[g.UINT64.toString(),_.BIT64],[g.FLOAT32.toString(),_.BIT32],[g.FLOAT64.toString(),_.BIT64],[g.INT8.toString(),_.BIT8],[g.INT16.toString(),_.BIT16],[g.INT32.toString(),_.BIT32],[g.INT64.toString(),_.BIT64],[g.TIMESTAMP.toString(),_.BIT64],[g.STRING.toString(),_.UNKNOWN],[g.JSON.toString(),_.UNKNOWN],[g.UUID.toString(),_.BIT128]]);static ALL=[g.UNKNOWN,g.FLOAT64,g.FLOAT32,g.INT64,g.INT32,g.INT16,g.INT8,g.UINT64,g.UINT32,g.UINT16,g.UINT8,g.TIMESTAMP,g.UUID,g.STRING,g.JSON];static BIG_INT_TYPES=[g.INT64,g.UINT64,g.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new g(e)),s.z.instanceof(g)])},at=class R extends dt{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return new R(Ht(this.valueOf(),e.valueOf()))}sub(e){return new R(qe(this.valueOf(),e.valueOf()))}mult(e){return new R(fe(this.valueOf(),e))}div(e){return new R(Lr(this.valueOf(),e))}truncate(e){return new R(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return R.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/R.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/R.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/R.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/R.TERABYTE.valueOf()}toString(){const e=this.truncate(R.TERABYTE),r=this.truncate(R.GIGABYTE),n=this.truncate(R.MEGABYTE),a=this.truncate(R.KILOBYTE),i=this.truncate(R.BYTE),o=e,l=r.sub(e),c=n.sub(r),u=a.sub(n),h=i.sub(a);let p="";return o.isZero||(p+=`${o.terabytes}TB `),l.isZero||(p+=`${l.gigabytes}GB `),c.isZero||(p+=`${c.megabytes}MB `),u.isZero||(p+=`${u.kilobytes}KB `),(!h.isZero||p==="")&&(p+=`${h.valueOf()}B`),p.trim()}static bytes(e=1){return new R(e)}static BYTE=new R(1);static kilobytes(e=1){return R.bytes(e.valueOf()*1e3)}static KILOBYTE=R.kilobytes(1);static megabytes(e=1){return R.kilobytes(e.valueOf()*1e3)}static MEGABYTE=R.megabytes(1);static gigabytes(e=1){return R.megabytes(e.valueOf()*1e3)}static GIGABYTE=R.gigabytes(1);static terabytes(e){return R.gigabytes(e.valueOf()*1e3)}static TERABYTE=R.terabytes(1);static ZERO=new R(0);static z=s.z.union([s.z.number().transform(e=>new R(e)),s.z.instanceof(R)]);get isZero(){return this.valueOf()===0}};s.z.union([s.z.instanceof(Uint8Array),s.z.instanceof(Uint16Array),s.z.instanceof(Uint32Array),s.z.instanceof(BigUint64Array),s.z.instanceof(Float32Array),s.z.instanceof(Float64Array),s.z.instanceof(Int8Array),s.z.instanceof(Int16Array),s.z.instanceof(Int32Array),s.z.instanceof(BigInt64Array)]);const Ci=t=>{const e=typeof t;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||t instanceof E||t instanceof z||t instanceof Date},_h=(t,e,r,n=0)=>t.usesBigInt&&!e.usesBigInt?Number(r)-Number(n):!t.usesBigInt&&e.usesBigInt?BigInt(r.valueOf())-BigInt(n.valueOf()):mr(r,-n),mr=(t,e)=>e==0?t:t==0?e:typeof t=="bigint"&&typeof e=="bigint"||typeof t=="number"&&typeof e=="number"?t+e:Number(t)+Number(e),Wh=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function Gh(t){return typeof t=="string"&&Wh.test(t)}const Z=[];for(let t=0;t<256;++t)Z.push((t+256).toString(16).slice(1));function Kh(t,e=0){return(Z[t[e+0]]+Z[t[e+1]]+Z[t[e+2]]+Z[t[e+3]]+"-"+Z[t[e+4]]+Z[t[e+5]]+"-"+Z[t[e+6]]+Z[t[e+7]]+"-"+Z[t[e+8]]+Z[t[e+9]]+"-"+Z[t[e+10]]+Z[t[e+11]]+Z[t[e+12]]+Z[t[e+13]]+Z[t[e+14]]+Z[t[e+15]]).toLowerCase()}function Jh(t,e=0){const r=Kh(t,e);if(!Gh(r))throw TypeError("Stringified UUID is invalid");return r}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Ii=(t,e)=>Jh(t,e),ze=-1,kn={[Symbol.iterator]:()=>kn,next:()=>({done:!0,value:void 0})},Xh=s.z.string().transform(t=>new Uint8Array(atob(t).split("").map(e=>e.charCodeAt(0))).buffer),Qh=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),xn=10,ji=(t,e)=>{if(t==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(t==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Ri="sy_x_telem_series";let Ie=class ke{key;discriminator=Ri;dataType;sampleOffset;gl;_data;timeRange=L.ZERO;alignment=0n;alignmentMultiple=1n;cachedMin;cachedMax;writePos=ze;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:L.z.optional(),dataType:k.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Xh,Qh,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Hh.optional().default("static").optional()});static z=ke.crudeZ.transform(e=>new ke(e));constructor(e){ed(e)&&(e={data:e}),e.data??=[];const{dataType:r,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,alignmentMultiple:l=1n,key:c=us(),data:u}=e;if(Ui(u)){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.alignmentMultiple=d.alignmentMultiple,this.cachedMin=d.cachedMin,this.cachedMax=d.cachedMax,this.writePos=d.writePos,this._refCount=d._refCount,this.cachedLength=d.cachedLength;return}const h=Ci(u),p=Array.isArray(u);if(r!=null)this.dataType=new k(r);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(p||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=k.STRING;else if(typeof d=="number")this.dataType=k.FLOAT64;else if(typeof d=="bigint")this.dataType=k.INT64;else if(typeof d=="boolean")this.dataType=k.BOOLEAN;else if(d instanceof E||d instanceof Date||d instanceof E)this.dataType=k.TIMESTAMP;else if(typeof d=="object")this.dataType=k.JSON;else throw new Error(`cannot infer data type of ${typeof d} when constructing a Series from a JS array`)}else this.dataType=new k(u)}if(!p&&!h)this._data=u;else if(p&&u.length===0)this._data=new this.dataType.Array([]).buffer;else{let d=h?[u]:u;const S=d[0];(S instanceof E||S instanceof Date||S instanceof z)&&(d=d.map(N=>new E(N).valueOf())),this.dataType.equals(k.STRING)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.join(`
|
|
9
|
+
`)}
|
|
10
|
+
`).buffer):this.dataType.equals(k.JSON)?(this.cachedLength=d.length,this._data=new TextEncoder().encode(`${d.map(N=>It.encodeString(N)).join(`
|
|
11
|
+
`)}
|
|
12
|
+
`).buffer):this.dataType.usesBigInt&&typeof S=="number"?this._data=new this.dataType.Array(d.map(N=>BigInt(Math.round(N)))).buffer:!this.dataType.usesBigInt&&typeof S=="bigint"?this._data=new this.dataType.Array(d.map(Number)).buffer:this._data=new this.dataType.Array(d).buffer}this.key=c,this.alignment=o,this.alignmentMultiple=l,this.sampleOffset=a??0,this.timeRange=n??L.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:r,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new k(r).Array(e),i=new ke({data:a.buffer,dataType:r,...n});return i.writePos=0,i}get refCount(){return this._refCount}acquire(e){this._refCount++,e!=null&&this.updateGLBuffer(e)}release(){this._refCount--,this.refCount===0&&this.gl.control!=null?this.maybeGarbageCollectGLBuffer(this.gl.control):this.refCount<0&&console.warn("cannot release a series with a negative reference count")}write(e){if(!e.dataType.equals(this.dataType))throw new Error("buffer must be of the same type as this array");return this.dataType.isVariable?this.writeVariable(e):this.writeFixed(e)}writeVariable(e){if(this.writePos===ze)return 0;const r=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,r);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 r=this.capacity-this.writePos,n=e.sub(0,r);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(){return this.dataType.isVariable?new TextDecoder().decode(this.underlyingData).split(`
|
|
13
|
+
`).slice(0,-1):Array.from(this).map(e=>e.toString())}parseJSON(e){if(!this.dataType.equals(k.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(r=>e.parse(It.decodeString(r)))}get byteCapacity(){return new at(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 at(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.byteCapacity.valueOf()/this.dataType.density.valueOf():this.writePos}calculateCachedLength(){if(!this.dataType.isVariable)throw new Error("cannot calculate length of a non-variable length data type");let e=0;const r=[0];return this.data.forEach((n,a)=>{n===xn&&(e++,r.push(a+1))}),this._cachedIndexes=r,this.cachedLength=e,e}convert(e,r=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=_h(this.dataType,e,this.data[a],r);return new ke({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:r,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(k.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}else{const e=this.data;this.cachedMax=e.reduce((r,n)=>r>n?r:n)}return this.cachedMax}get max(){return this.calcMax()}calcMax(){if(this.dataType.isVariable)throw new Error("cannot calculate maximum on a variable length data type");return this.writePos===0?-1/0:(this.cachedMax??=this.calcRawMax(),mr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(k.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}else{const e=this.data;this.cachedMin=e.reduce((r,n)=>r<n?r:n)}return this.cachedMin}get min(){return this.calcMin()}calcMin(){if(this.dataType.isVariable)throw new Error("cannot calculate minimum on a variable length data type");return this.writePos===0?1/0:(this.cachedMin??=this.calcRawMin(),mr(this.cachedMin,this.sampleOffset))}get bounds(){return q(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const r=e.cachedMin??e.calcRawMin();r<this.cachedMin&&(this.cachedMin=r)}if(this.cachedMax!=null){const r=e.cachedMax??e.calcRawMax();r>this.cachedMax&&(this.cachedMax=r)}}atAlignment(e,r){const n=Number((e-this.alignment)/this.alignmentMultiple);if(n<0||n>=this.length){if(r===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,r)}at(e,r=!1){if(this.dataType.isVariable)return this.atVariable(e,r??!1);if(this.dataType.equals(k.UUID))return this.atUUID(e,r);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(r===!0)throw new Error(`[series] - no value at index ${e}`);return}return mr(n,this.sampleOffset)}atUUID(e,r){e<0&&(e=this.length+e);const n=Ii(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(r)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,r){let n=0,a=0;if(this._cachedIndexes!=null)n=this._cachedIndexes[e],a=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){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(r)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(k.STRING)?new TextDecoder().decode(i):ls(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let r=0,n=this.length-1;const a=Ur(e);for(;r<=n;){const i=Math.floor((r+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?r=i+1:n=i-1}return r}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(k.FLOAT32)&&!this.dataType.equals(k.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:r,bufferUsage:n,prevBuffer:a}=this.gl;if(r==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==ze){a===0&&e.bufferData(e.ARRAY_BUFFER,this.byteCapacity.valueOf(),e.STATIC_DRAW);const i=this.dataType.density.size(a).valueOf(),o=this.underlyingData.slice(this.gl.prevBuffer,this.writePos);e.bufferSubData(e.ARRAY_BUFFER,i,o.buffer),this.gl.prevBuffer=this.writePos}else e.bufferData(e.ARRAY_BUFFER,this.buffer,n==="static"?e.STATIC_DRAW:e.DYNAMIC_DRAW),this.gl.prevBuffer=ze}as(e){return ji(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:aa(this.alignmentBounds.lower),upper:aa(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return q(this.alignment,this.alignment+BigInt(this.length)*this.alignmentMultiple)}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new td(this);return this.dataType.equals(k.JSON)?new rd(e):e}return this.dataType.equals(k.UUID)?new nd(this):new sd(this)}slice(e,r){return this.sliceSub(!1,e,r)}sub(e,r){return this.sliceSub(!0,e,r)}subIterator(e,r){return new sa(this,e,r??this.length)}subAlignmentIterator(e,r){const n=Math.ceil(Number(e-this.alignment)/Number(this.alignmentMultiple)),a=Math.ceil(Number(r-this.alignment)/Number(this.alignmentMultiple));return new sa(this,n,a)}subBytes(e,r){if(e>=0&&(r==null||r>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,r);return new ke({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,r,n){if(r<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(r,n):a=this.data.slice(r,n),new ke({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(r)})}reAlign(e){return new ke({data:this.buffer,dataType:this.dataType,timeRange:L.ZERO,sampleOffset:this.sampleOffset,glBufferUsage:"static",alignment:e})}toString(){let e=`Series(${this.dataType.toString()} ${this.length} [`;if(this.length<=10)e+=Array.from(this).map(r=>r.toString());else{for(let r=0;r<5;r++)e+=`${this.at(r)?.toString()}`,e+=",";e+="...,";for(let r=-5;r<0;r++)e+=this.at(r)?.toString(),r<-1&&(e+=",")}return e+="])",e}};const ed=t=>t==null?!1:Array.isArray(t)||t instanceof ArrayBuffer||ArrayBuffer.isView(t)&&!(t instanceof DataView)||t instanceof Ie?!0:Ci(t),Ui=Yh(Ri,Ie);class sa{series;end;index;constructor(e,r,n){this.series=e;const a=q(0,e.length+1);this.end=ea(a,n),this.index=ea(a,r)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}let td=class{series;index;decoder;constructor(t){if(!t.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=t,this.index=0,this.decoder=new TextDecoder}next(){const t=this.index,e=this.series.data;for(;this.index<e.length&&e[this.index]!==xn;)this.index++;const r=this.index;return t===r?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(t,r))})}},rd=class Mi{wrapped;static schema=s.z.record(s.z.string(),s.z.unknown());constructor(e){this.wrapped=e}next(){const e=this.wrapped.next();return e.done===!0?{done:!0,value:void 0}:{done:!1,value:It.decodeString(e.value,Mi.schema)}}};class nd{series;index;data;density;constructor(e){if(!e.dataType.equals(k.UUID))throw new Error("cannot create a UUID series iterator for a non-UUID series");this.series=e,this.index=0,this.data=new Uint8Array(e.buffer),this.density=k.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Ii(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let sd=class{series;index;constructor(t){this.series=t,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},ad=class{series;constructor(t=[]){if(t.length!==0){const e=t[0].dataType;for(let r=1;r<t.length;r++)if(!t[r].dataType.equals(e))throw new Error("[multi-series] - series must have the same data type")}this.series=t}as(t){return ji(t,this.dataType),this}get dataType(){return this.series.length===0?k.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?L.ZERO:new L(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(t){const e=()=>new Error(`cannot push a ${t.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),r=t.dataType.equals(this.dataType);if(Ui(t)){if(this.series.length!==0&&!r)throw e();this.series.push(t)}else{if(this.series.length!==0&&t.series.length!==0&&!r)throw e();this.series.push(...t.series)}}get length(){return this.series.reduce((t,e)=>t+e.length,0)}atAlignment(t,e){for(const r of this.series)if(or(r.alignmentBounds,t))return r.atAlignment(t,e);if(e)throw new Error(`[series] - no value at alignment ${t}`)}at(t,e=!1){t<0&&(t=this.length+t);for(const r of this.series){if(t<r.length)return r.at(t,e);t-=r.length}if(e)throw new Error(`[series] - no value at index ${t}`)}subIterator(t,e){return new sn(this,t,e??this.length)}subAlignmentIterator(t,e){if(t>=this.alignmentBounds.upper||e<=this.alignmentBounds.lower)return kn;let r=0;for(let a=0;a<this.series.length;a++){const i=this.series[a];if(t<i.alignment)break;if(t>=i.alignmentBounds.upper)r+=i.length;else if(or(i.alignmentBounds,t)){r+=Math.ceil(Number(t-i.alignment)/Number(i.alignmentMultiple));break}}let n=0;for(let a=0;a<this.series.length;a++){const i=this.series[a];if(e<i.alignment)break;if(e>=i.alignmentBounds.upper)n+=i.length;else if(or(i.alignmentBounds,e)){n+=Math.ceil(Number(e-i.alignment)/Number(i.alignmentMultiple));break}}return new sn(this,r,n)}subAlignmentSpanIterator(t,e){if(t>=this.alignmentBounds.upper)return kn;e=Math.min(e,Number(this.distance(t,this.alignmentBounds.upper)));let r=0;for(let n=0;n<this.series.length;n++){const a=this.series[n];if(t<a.alignment)break;if(t>=a.alignmentBounds.upper)r+=a.length;else if(or(a.alignmentBounds,t)){r+=Number(t-a.alignment);break}}return new sn(this,r,r+e)}updateGLBuffer(t){this.series.forEach(e=>e.updateGLBuffer(t))}get bounds(){return zh(this.series.map(t=>t.bounds))}get byteLength(){return new at(this.series.reduce((t,e)=>t+e.byteLength.valueOf(),0))}get data(){const t=new this.dataType.Array(this.length);let e=0;for(const r of this.series)t.set(r.data,e),e+=r.length;return new this.dataType.Array(t.buffer)}traverseAlignment(t,e){const r=this.series.map(n=>n.alignmentBounds);return Eh(r,t,e)}acquire(t){this.series.forEach(e=>e.acquire(t))}release(){this.series.forEach(t=>t.release())}distance(t,e){const r=this.series.map(n=>n.alignmentBounds);return Nh(r,t,e)}parseJSON(t){if(!this.dataType.equals(k.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(e=>e.parseJSON(t))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new id(this.series)}toStrings(){return this.series.flatMap(t=>t.toStrings())}},id=class{series;seriesIndex;internal;constructor(t){this.series=t,this.seriesIndex=0,this.internal=t[0][Symbol.iterator]()}next(){const t=this.internal.next();return t.done===!1?t:this.seriesIndex===this.series.length-1?{done:!0,value:void 0}:(this.internal=this.series[++this.seriesIndex][Symbol.iterator](),this.next())}[Symbol.iterator](){return this}};class sn{series;index;end;constructor(e,r,n){this.series=e,this.end=n,this.index=r}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 aa=t=>{const e=t>>32n,r=t&0xffffffffn;return{domain:e,sample:r}},od=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},ld=(t,e,r=".")=>{const n=t.split(r);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(r)}).filter(a=>a!=null).join(r)},cd=(t,e)=>{if(!Array.isArray(t))return t[e];const r=t[e];if(r!=null||t.length==0)return r;const n=t[0];if(typeof n=="object"&&"key"in n)return t.find(a=>a.key===e)},ud=(t,e,r={optional:!1,separator:"."})=>{r.separator??=".";const{optional:n,getter:a=cd}=r,i=e.split(r.separator);if(i.length===1&&i[0]==="")return t;let o=t;for(const l of i){const c=a(o,l);if(c==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=c}return o};s.z.object({key:s.z.string(),value:s.z.string()});let hd=class{handlers;transform;closer;constructor(t,e){this.transform=t,this.handlers=e??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){let e=t;if(this.transform!=null){const[r,n]=this.transform(t);if(!n)return;e=r}this.handlers.forEach((r,n)=>n(e))}setCloser(t){this.closer=t}async close(){return await this.closer?.()}},dd=class{handlers;constructor(t){this.handlers=t??new Map}onChange(t){return this.handlers.set(t,null),()=>this.handlers.delete(t)}notify(t){this.handlers.forEach((e,r)=>r(t))}};const fd=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:dd,Observer:hd},Symbol.toStringTag,{value:"Module"})),pd=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),hs=t=>Object.entries(t),yd=(t,e)=>Object.fromEntries(hs(t).map(([r,n])=>[r,e(n,r)])),gd=t=>Object.fromEntries(hs(t).filter(([e,r])=>r!==void 0)),md=(t,...e)=>{const r={...t};for(const n of e)delete r[n];return r},ve=Object.freeze(Object.defineProperty({__proto__:null,entries:hs,map:yd,omit:md,purgeUndefined:gd,unknownZ:pd},Symbol.toStringTag,{value:"Module"})),wd=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";wd();const bd=["macOS","Windows","Linux"],vd=["macos","windows","linux"],Td={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(bd).or(s.z.enum(vd).transform(t=>Td[t]));const Od=(...t)=>t.map(Li).join(""),Li=t=>(t.endsWith("/")||(t+="/"),t.startsWith("/")&&(t=t.slice(1)),t),Sd=t=>t.endsWith("/")?t.slice(0,-1):t;class kt{protocol;host;port;path;constructor({host:e,port:r,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=r,this.path=Li(a)}replace(e){return new kt({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new kt({...this,pathPrefix:Od(this.path,e)})}toString(){return Sd(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new kt({host:"unknown",port:0})}const zd=t=>t.nullable().transform(e=>e===null?void 0:e).optional(),Ed=t=>s.array(t).or(t.transform(e=>[e])),Pi=t=>ld(t,(e,r,n)=>{const a=r===n.length-1,i=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[r+1]));return i&&(e="element"),a||o?e:[e,"shape"]}),ia=(t,e)=>{if(t==null)return null;const r=t[e];return r==null&&typeof t=="object"&&"sourceType"in t?t.sourceType()[e]:r},Nd=(t,e,r)=>e===""?t:ud(ia(t,"shape"),Pi(e),{...r,getter:ia}),xt=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:Nd,getFieldSchemaPath:Pi,nullToUndefined:zd,toArray:Ed},Symbol.toStringTag,{value:"Module"})),Ad=async t=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(t).milliseconds));class kd{config;retries;interval;constructor(e){this.config={baseInterval:new z(e?.baseInterval??z.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Ad},this.retries=0,this.interval=new z(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:r,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(r),this.retries++,!0)}get retryMessage(){return`breaker triggered ${this.retries+1}/${this.config.maxRetries} times, retrying in ${this.interval.toString()}`}reset(){this.retries=0,this.interval=this.config.baseInterval}}const xd=s.z.object({baseInterval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Di=Object.freeze(Object.defineProperty({__proto__:null,Breaker:kd,breakerConfigZ:xd},Symbol.toStringTag,{value:"Module"})),Cd=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,$i=s.z.string().regex(Cd),nt=s.z.number().min(0).max(255),Bi=s.z.number().min(0).max(1),Fi=s.z.tuple([nt,nt,nt,Bi]),Id=s.z.tuple([nt,nt,nt]),jd=s.z.object({rgba255:Fi}),Rd=s.z.number().min(0).max(360),Ud=s.z.number().min(0).max(100),Md=s.z.number().min(0).max(100),Ld=s.z.tuple([Rd,Ud,Md,Bi]),ds=s.z.union([$i,Id,Fi,Ld,jd]),Pd=ds.transform(t=>fs(t)),fs=(t,e=1)=>{if(t=ds.parse(t),typeof t=="string")return Dd(t,e);if(Array.isArray(t)){if(t.length<3||t.length>4)throw new Error(`Invalid color: [${t.join(", ")}]`);return t.length===3?[...t,e]:t}return t.rgba255},Dd=(t,e=1)=>(t=$i.parse(t),t=$d(t),[cr(t,0),cr(t,2),cr(t,4),t.length===8?cr(t,6)/255:e]),cr=(t,e)=>parseInt(t.slice(e,e+2),16),$d=t=>t.startsWith("#")?t.slice(1):t;fs("#000000");fs("#ffffff");const Bd=s.z.object({key:s.z.string(),color:ds,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(Bd);const Fd=s.z.object({key:s.z.string(),name:s.z.string(),color:Pd});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(Fd)});const Zi=s.z.int().min(0).max(255),qi=255,Yi=0,Zd={lower:Yi,upper:qi+1},Hi=s.z.object({name:s.z.string(),key:s.z.string()}),jt=t=>s.z.object({subject:Hi,resource:t,authority:Zi}),qd=(...t)=>e=>e.filter(r=>{let n=!1;return r.to!=null&&(n=t.includes(r.to.resource)),r.from!=null&&!n&&(n=t.includes(r.from.resource)),n}),Vi=t=>s.z.object({from:jt(t),to:s.z.null()}),_i=t=>s.z.object({from:s.z.null(),to:jt(t)}),Yd=t=>s.z.union([Vi(t),_i(t),s.z.object({from:jt(t),to:jt(t)})]),ee=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:qi,AUTHORITY_BOUNDS:Zd,ZERO_AUTHORITY:Yi,acquireZ:_i,authorityZ:Zi,filterTransfersByChannelKey:qd,releaseZ:Vi,stateZ:jt,subjectZ:Hi,transferZ:Yd},Symbol.toStringTag,{value:"Module"})),Hd=t=>Object.getOwnPropertySymbols(globalThis).includes(t),Vd=(t,e)=>{const r=Symbol.for(t);if(!Hd(r)){const n=e();Object.defineProperty(globalThis,r,{value:n})}return()=>globalThis[r]},Wi="sy_x_error",_d=t=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(t):e instanceof Error?e.message.startsWith(t):typeof e!="string"?!1:e.startsWith(t),Vt=t=>class At extends Error{static discriminator=Wi;discriminator=At.discriminator;static TYPE=t;type=At.TYPE;static matches=_d(t);matches=At.matches;constructor(r,n){super(r,n),this.name=At.TYPE}static sub(r){return Vt(`${t}.${r}`)}},Gi=t=>{if(t==null||typeof t!="object")return!1;const e=t;if(e.discriminator!==Wi)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Je="unknown",Cn="nil";class Wd{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:Cn,data:""};if(Gi(e))for(const r of this.providers){const n=r.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Je,data:e.message};if(typeof e=="string")return{type:Je,data:e};try{return{type:Je,data:JSON.stringify(e)}}catch{return{type:Je,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===Cn)return null;if(e.type===Je)return new In(e.data);for(const r of this.providers){const n=r.decode(e);if(n!=null)return n}return new In(e.data)}}const ps=Vd("synnax-error-registry",()=>new Wd),Gd=({encode:t,decode:e})=>ps().register({encode:t,decode:e}),Kd=t=>ps().encode(t),Jd=t=>t==null?null:ps().decode(t);class In extends Vt("unknown"){}const Xd=s.z.object({type:s.z.string(),data:s.z.string()});class Qd extends Vt("canceled"){}class ef extends Vt("not_implemented"){}const be=Object.freeze(Object.defineProperty({__proto__:null,Canceled:Qd,NONE:Cn,NotImplemented:ef,UNKNOWN:Je,Unknown:In,createTyped:Vt,decode:Jd,encode:Kd,isTyped:Gi,payloadZ:Xd,register:Gd},Symbol.toStringTag,{value:"Module"})),tf=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Ki=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),rf=Ki.extend({result:s.json()}),nf=Ki.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),sf=s.union([rf,nf]);s.union([tf,sf]);const jn=s.z.string().regex(/^\d+\.\d+\.\d+$/),_t=(t,e,r={})=>{r.checkMajor??=!0,r.checkMinor??=!0,r.checkPatch??=!0;const n=jn.parse(t),a=jn.parse(e),[i,o,l]=n.split(".").map(Number),[c,u,h]=a.split(".").map(Number);if(r.checkMajor){if(i<c)return yr;if(i>c)return gr}if(r.checkMinor){if(o<u)return yr;if(o>u)return gr}if(r.checkPatch){if(l<h)return yr;if(l>h)return gr}return ft},af=(t,e,r={})=>mi(_t(t,e,r)),Ji=(t,e,r={})=>gi(_t(t,e,r)),of=(t,e,r={})=>yi(_t(t,e,r)),lf=({name:t,migrate:e})=>r=>{try{const n=e(r);return console.log(`${t} migrated: ${r.version} -> ${n.version}`),n}catch(n){throw console.log(`${t} failed to migrate from ${r.version}`),console.error(n),n}},cf=({name:t,migrations:e,targetSchema:r,defaultVersion:n,def:a})=>{const i=Object.keys(e).sort(_t).pop();if(i==null)return u=>{if(u.version??=n,u.version!==a.version)return console.log(`${t} version ${u.version} is newer than latest version of ${a.version}.
|
|
14
|
+
Returning default instead.
|
|
15
|
+
`),a;try{return r!=null?r.parse(u):u}catch(h){return console.log(`${t} failed to parse default. Exiting with default`),console.error(h),a}};const o=Object.keys(e).length;let l=!1;const c=u=>{try{if(o===0||Ji(u.version,i))return console.log(l?`${t} ${u.version} now up to date`:`${t} version ${u.version} is up to date with target version ${a.version}`),u;const h=u.version,p=e[h],d=p(u);return l=!0,c(d)}catch(h){return console.log(`${t} failed to migrate from ${u.version} to ${i}`),console.error(h),a}};return u=>{try{if(u.version==null)if(n!=null)console.log(`${t} version is null. Setting version to default of ${n}`),u.version=n;else return console.log(`${t} version is null and no default version set. Exiting with default`),a;return c(u)}catch(h){return console.log(`${t} failed to parse final result. Exiting with default`),console.error(h),a}}},oa=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:_t,createMigration:lf,migrator:cf,semVerNewer:Ji,semVerOlder:of,semVerZ:jn,versionsEqual:af},Symbol.toStringTag,{value:"Module"})),uf=["standard","scientific","engineering"];s.z.enum(uf);const Xi=s.z.enum(["success","info","warning","error","loading","disabled"]),hf=t=>s.z.object({key:s.z.string(),variant:Xi,message:s.z.string(),description:s.z.string().optional(),time:E.z,details:t??s.z.unknown().optional()}),df=(t,e)=>{if(!(t instanceof Error))throw t;return Qi({variant:"error",message:e??t.message,description:e!=null?t.message:void 0,details:{stack:t.stack??""}})},Qi=t=>({key:us(),time:E.now(),...t}),ff=(t,e=[])=>Array.isArray(e)?e.includes(t)?t:void 0:e===t?t:void 0,Wt=Object.freeze(Object.defineProperty({__proto__:null,create:Qi,filterVariant:ff,fromException:df,statusZ:hf,variantZ:Xi},Symbol.toStringTag,{value:"Module"})),pf=(t,e="")=>{if(typeof t=="string")return t;const r=t.length;return r===0?e:r===1?t[0]:r===2?`${t[0]} and ${t[1]}`:`${t.slice(0,-1).join(", ")}, and ${t[r-1]}`},yf=t=>{const e=t.split(" "),r=new Set,n=e.map(o=>o.charAt(0).toLowerCase()).join("");r.add(n.replace(/-/g,"_")),r.add(n.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const a=/\d+/g;t.match(a)&&e.forEach((o,l)=>{if(a.test(o)){const c=e.map((u,h)=>h!==l?u.charAt(0).toLowerCase():u).join("");r.add(c.replace(/-/g,"_")),r.add(c.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const i=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return r.add(i.join("").replace(/-/g,"_")),r.add(i.join("_").replace(/-/g,"_")),Array.from(r).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},gf=(t,e)=>t.startsWith(e)?t.slice(e.length):t,Rn=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:yf,naturalLanguageJoin:pf,trimPrefix:gf},Symbol.toStringTag,{value:"Module"})),mf="all",wf="create",bf="delete",vf="retrieve",Tf="update",Un=s.z.enum([mf,wf,bf,vf,Tf]);let pe=class extends be.createTyped("sy"){},B=class extends pe.sub("validation"){};class Rt extends B.sub("path"){path;error;static encodedSchema=s.z.object({path:s.z.string().array(),error:be.payloadZ});constructor(e,r){const n=O.toArray(e);super(`${n.join(".")}: ${r.message}`),this.path=n.flatMap(a=>a.split(".")),this.error=r}static decode(e){const r=Rt.encodedSchema.parse(JSON.parse(e.data));return new Rt(r.path,be.decode(r.error))}}class Or extends pe.sub("auth"){}class Mn extends Or.sub("invalid_token"){}class Ln extends Or.sub("expired_token"){}class W extends pe.sub("unexpected"){constructor(e){super(`
|
|
16
|
+
Unexpected error encountered:
|
|
17
|
+
|
|
18
|
+
${e}
|
|
19
|
+
|
|
20
|
+
Please report this to the Synnax team.
|
|
21
|
+
`)}}class Le extends pe.sub("query"){}class it extends Le.sub("not_found"){}class Sr extends Le.sub("multiple_results"){}class la extends pe.sub("route"){path;constructor(e,r){super(e),this.path=r}}class Pn extends pe.sub("control"){}class ca extends Pn.sub("unauthorized"){}class Of extends pe.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class fT extends pe.sub("contiguity"){}const Sf=t=>t.type.startsWith(pe.TYPE)?t.type.startsWith(B.TYPE)?t.type===Rt.TYPE?Rt.decode(t):new B(t.data):t.type.startsWith(Or.TYPE)?t.type.startsWith(Mn.TYPE)?new Mn(t.data):t.type.startsWith(Ln.TYPE)?new Ln(t.data):new Or(t.data):t.type.startsWith(W.TYPE)?new W(t.data):t.type.startsWith(Le.TYPE)?t.type.startsWith(it.TYPE)?new it(t.data):t.type.startsWith(Sr.TYPE)?new Sr(t.data):new Le(t.data):t.type.startsWith(Pn.TYPE)?t.type.startsWith(ca.TYPE)?new ca(t.data):new Pn(t.data):t.type.startsWith(la.TYPE)?new la(t.data,t.data):new W(t.data):null,zf=()=>{throw new be.NotImplemented};be.register({encode:zf,decode:Sf});const Ef=async(t,e)=>{const[r,n]=await e(t);return n==null?[r,n]:n instanceof Me?[r,new Me({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[r,n]};class ys{key;name;constructor(e,r){this.key=r,this.name=e}get ontologyID(){return eo(this.key)}}const eo=t=>({type:"group",key:t}),Gt=s.z.uuid(),Pr=s.z.string(),gs=s.z.object({key:Gt,name:Pr}),to="builtin",Nf="cluster",Af="node",Dr=s.z.enum(["label","log","allow_all","builtin","cluster","channel","node","group","range","framer","range-alias","user","workspace","schematic","lineplot","rack","device","task","policy","table"]),kf=s.z.string().transform(t=>{const[e,r]=t.split(":");return{type:Dr.parse(e),key:r??""}}),M=s.z.object({type:Dr,key:s.z.string()}).or(kf),xf={type:to,key:"root"},Ut=t=>`${t.type}:${t.key}`,Cf=(t,e)=>t.type===e.type&&t.key===e.key,ro=t=>{const e=O.toArray(t);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:r})=>r):e.map(r=>M.parse(r))},no=s.z.object({id:M,name:s.z.string(),data:ve.unknownZ.optional().nullable()}).transform(t=>({key:Ut(t.id),...t})),If=t=>t==="to"?"from":"to",jf=s.z.object({from:M,type:s.z.string(),to:M}).or(s.z.string().transform(t=>{const[e,r,n]=t.split("->");return{from:M.parse(e),type:r,to:M.parse(n)}})),Rf=t=>`${Ut(t.from)}->${t.type}->${Ut(t.to)}`,Uf="parent",Mf=(t,e)=>!(e.type!=null&&e.type!==t.type||e.from?.type!=null&&e.from.type!==t.from.type||e.to?.type!=null&&e.to.type!==t.to.type||e.from?.key!=null&&e.from.key!==t.from.key||e.to?.key!=null&&e.to.key!==t.to.key),Lf=s.z.object({group:gs}),Pf=s.z.object({parent:M,key:Gt.optional(),name:Pr}),Df=s.z.object({key:Gt,name:Pr}),$f=s.z.object({keys:s.z.array(Gt)});let Bf=class wr{static CREATE_ENDPOINT="/ontology/create-group";static RENAME_ENDPOINT="/ontology/rename-group";static DELETE_ENDPOINT="/ontology/delete-group";client;constructor(e){this.client=e}async create(e,r,n){return(await m(this.client,wr.CREATE_ENDPOINT,{parent:e,name:r,key:n},Pf,Lf)).group}async rename(e,r){await m(this.client,wr.RENAME_ENDPOINT,{key:e,name:r},Df,s.z.object({}))}async delete(e){await m(this.client,wr.DELETE_ENDPOINT,{keys:e},$f,s.z.object({}))}};const Ff="sy_group_set",Zf="sy_group_delete";let so=class{creator;constructor(t){this.creator=new Bf(t)}async create(t,e,r){return this.sugar(await this.creator.create(t,e,r))}async rename(t,e){return await this.creator.rename(t,e)}async delete(...t){return await this.creator.delete(t)}sugar(t){return new ys(t.name,t.key)}};const qf=Object.freeze(Object.defineProperty({__proto__:null,Client:so,DELETE_CHANNEL_NAME:Zf,Group:ys,SET_CHANNEL_NAME:Ff,groupZ:gs,keyZ:Gt,nameZ:Pr,ontologyID:eo},Symbol.toStringTag,{value:"Module"})),Yf="/ontology/add-children",Hf="/ontology/remove-children",Vf="/ontology/move-children",ua=s.z.object({id:M,children:M.array()}),_f=s.z.object({from:M,to:M,children:M.array()}),an=s.z.object({});let Wf=class{client;constructor(t){this.client=t}async addChildren(t,...e){await m(this.client,Yf,{id:t,children:e},ua,an)}async removeChildren(t,...e){await m(this.client,Hf,{id:t,children:e},ua,an)}async moveChildren(t,e,...r){await m(this.client,Vf,{from:t,to:e,children:r},_f,an)}};const Gf="/ontology/retrieve",Kf=s.z.object({ids:M.array().optional(),children:s.z.boolean().optional(),parents:s.z.boolean().optional(),excludeFieldData:s.z.boolean().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),types:Dr.array().optional()}),Jf=s.z.object({resources:no.array()});let ao=class{type="ontology";groups;client;writer;framer;constructor(t,e){this.client=t,this.writer=new Wf(t),this.groups=new so(t),this.framer=e}async retrieve(t,e){if(!Array.isArray(t)&&typeof t=="object"&&!("key"in t))return this.execRetrieve(t);const r=ro(t),n=await this.execRetrieve({ids:r,...e});if(Array.isArray(t))return n;if(n.length===0)throw new Le(`No resource found with ID ${Rn.naturalLanguageJoin(r.map(a=>Ut(a)))}`);return n[0]}async retrieveChildren(t,e){return await this.execRetrieve({ids:O.toArray(t),children:!0,...e})}async retrieveParents(t,e){return await this.execRetrieve({ids:O.toArray(t),parents:!0,...e})}async addChildren(t,...e){return await this.writer.addChildren(t,...e)}async removeChildren(t,...e){return await this.writer.removeChildren(t,...e)}async moveChildren(t,e,...r){return await this.writer.moveChildren(t,e,...r)}async execRetrieve(t){const{resources:e}=await m(this.client,Gf,t,Kf,Jf);return e}};const Xf="sy_ontology_resource_set",Qf="sy_ontology_resource_delete",ep="sy_ontology_relationship_set",tp="sy_ontology_relationship_delete",rp=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:to,CLUSTER_TYPE:Nf,Client:ao,NODE_TYPE:Af,PARENT_OF_RELATIONSHIP_TYPE:Uf,RELATIONSHIP_DELETE_CHANNEL_NAME:tp,RELATIONSHIP_SET_CHANNEL_NAME:ep,RESOURCE_DELETE_CHANNEL_NAME:Qf,RESOURCE_SET_CHANNEL_NAME:Xf,ROOT_ID:xf,idToString:Ut,idZ:M,idsEqual:Cf,matchRelationship:Mf,oppositeRelationshipDirection:If,parseIDs:ro,relationshipToString:Rf,relationshipZ:jf,resourceTypeZ:Dr,resourceZ:no},Symbol.toStringTag,{value:"Module"})),Y=t=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),t.array()]),Kt=s.z.uuid(),ms=s.z.object({key:Kt,subjects:Y(M),objects:Y(M),actions:Y(Un)}),np=s.z.object({key:Kt.optional(),subjects:M.array().or(M),objects:M.array().or(M),actions:Un.array().or(Un)}),sp=s.z.object({keys:Kt.array().optional(),subjects:M.array().optional()}),ap=s.z.object({key:Kt}).transform(({key:t})=>({keys:[t]})),ip=s.z.union([s.z.object({for:M}).transform(({for:t})=>({subjects:[t]})),s.z.object({for:M.array()}).transform(({for:t})=>({subjects:t})),sp]),op=s.z.union([ap,ip]),lp=s.z.object({policies:Y(ms)}),cp=s.z.object({policies:ms.partial({key:!0}).array()}),up=s.z.object({policies:ms.array()}),hp=s.z.object({keys:Kt.array()}),dp=s.z.object({}),fp="/access/policy/retrieve",pp="/access/policy/create",yp="/access/policy/delete";let gp=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),r=np.array().parse(O.toArray(t)).map(a=>({objects:O.toArray(a.objects),actions:O.toArray(a.actions),subjects:O.toArray(a.subjects)})),n=await m(this.client,pp,{policies:r},cp,up);return e?n.policies:n.policies[0]}async retrieve(t){const e="key"in t,r=await m(this.client,fp,t,op,lp);return e?r.policies[0]:r.policies}async delete(t){await m(this.client,yp,{keys:O.toArray(t)},hp,dp)}},mp=class{policy;constructor(t){this.policy=new gp(t)}};const ha="Channel key must be a valid uint32.",U=s.z.uint32().or(s.z.string().refine(t=>!isNaN(Number(t)),{message:ha}).transform(Number).refine(t=>t<2**32-1,{message:ha})),we=s.z.string(),io=Wt.statusZ(),pt=s.z.object({name:we,key:U,dataType:k.z,leaseholder:s.z.number(),index:U,isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:Y(U),status:io.optional()}),oo=pt.extend({key:U.optional(),leaseholder:s.z.number().optional(),index:U.optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional().default(!1),virtual:s.z.boolean().optional().default(!1),expression:s.z.string().optional().default(""),requires:Y(U).optional().default([])}),Ve=s.z.union([xt.toArray(U),xt.toArray(we),xt.toArray(pt).transform(t=>t.map(e=>e.key))]),wp=new Error("request for lock canceled");var bp=function(t,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(h){try{u(n.next(h))}catch(p){o(p)}}function c(h){try{u(n.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):a(h.value).then(l,c)}u((n=n.apply(t,e||[])).next())})};class vp{constructor(e,r=wp){this._value=e,this._cancelError=r,this._queue=[],this._weightedWaiters=[]}acquire(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,a)=>{const i={resolve:n,reject:a,weight:e,priority:r},o=lo(this._queue,l=>r<=l.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return bp(this,arguments,void 0,function*(r,n=1,a=0){const[i,o]=yield this.acquire(n,a);try{return yield r(i)}finally{o()}})}waitForUnlock(e=1,r=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,r)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Tp(this._weightedWaiters[e-1],{resolve:n,priority:r})})}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 r=this._value;this._value-=e.weight,e.resolve([r,this._newReleaser(e.weight)])}_newReleaser(e){let r=!1;return()=>{r||(r=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const r=this._weightedWaiters[e-1];r&&(r.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let r=this._value;r>0;r--){const n=this._weightedWaiters[r-1];if(!n)continue;const a=n.findIndex(i=>i.priority<=e);(a===-1?n:n.splice(0,a)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,r){return(this._queue.length===0||this._queue[0].priority<r)&&e<=this._value}}function Tp(t,e){const r=lo(t,n=>e.priority<=n.priority);t.splice(r+1,0,e)}function lo(t,e){for(let r=t.length-1;r>=0;r--)if(e(t[r]))return r;return-1}var Op=function(t,e,r,n){function a(i){return i instanceof r?i:new r(function(o){o(i)})}return new(r||(r=Promise))(function(i,o){function l(h){try{u(n.next(h))}catch(p){o(p)}}function c(h){try{u(n.throw(h))}catch(p){o(p)}}function u(h){h.done?i(h.value):a(h.value).then(l,c)}u((n=n.apply(t,e||[])).next())})};class Sp{constructor(e){this._semaphore=new vp(1,e)}acquire(){return Op(this,arguments,void 0,function*(e=0){const[,r]=yield this._semaphore.acquire(1,e);return r})}runExclusive(e,r=0){return this._semaphore.runExclusive(()=>e(),1,r)}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 zp=(t,e,{convertNumericStrings:r=!0}={})=>{const n=!Array.isArray(t);let a=O.toArray(t);const i=a[0],o=typeof i;let l;return o==="string"&&r&&!isNaN(parseInt(i))&&"number"in e?(l=e.number,a=a.map(c=>parseInt(c))):l=e[o],{single:n,variant:l,normalized:a,actual:t}},yt=(t,e,r,n)=>{if(n){if(r.length===0)throw new it(`${t} not found matching ${JSON.stringify(e)}`);if(r.length>1)throw new Sr(`Expected one ${t} matching ${JSON.stringify(e)}, but found ${r.length}`)}},Ep=s.z.object({leaseholder:s.z.number().optional(),keys:U.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),rangeKey:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),dataTypes:k.z.array().optional(),notDataTypes:k.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional(),calculated:s.z.boolean().optional()}),Np=s.z.object({channels:Y(pt)}),se=t=>(Array.isArray(t)&&t.length>0&&typeof t[0]=="object"?t=t.map(e=>e.key):typeof t=="object"&&"key"in t&&(t=[t.key]),zp(t,{number:"keys",string:"names"}));class Jt{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,r){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const n=se(e),{variant:a}=n;let{normalized:i}=n;return a==="keys"&&i.indexOf(0)!==-1&&(i=i.filter(o=>o!==0)),i.length===0?[]:await this.execute({[a]:i,...r})}async execute(e){const[r,n]=await this.client.send(Jt.ENDPOINT,e,Ep,Np);if(n!=null)throw n;return r.channels}}class ws{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,r){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n}=se(e),a=[],i=[];if(n.forEach(l=>{const c=this.get(l);c!=null?a.push(...c):i.push(l)}),i.length===0)return a;const o=await this.wrapped.retrieve(i,r);return this.set(o),a.concat(o)}delete(e){const{variant:r,normalized:n}=se(e);r==="names"?n.forEach(a=>{const i=this.namesToKeys.get(a);i!=null&&(i.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(a))}):n.forEach(a=>{const i=this.cache.get(a);i!=null&&(this.cache.delete(a),this.namesToKeys.delete(i.name))})}rename(e,r){e.forEach((n,a)=>{const i=r[a],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=i,this.cache.set(n,o);const c=this.namesToKeys.get(i);c==null?this.namesToKeys.set(i,new Set([n])):c.add(n)})}set(e){e.forEach(r=>{this.cache.set(r.key,r);const n=this.namesToKeys.get(r.name);n==null?this.namesToKeys.set(r.name,new Set([r.key])):n.add(r.key)})}get(e){if(typeof e=="number"){const a=this.cache.get(e);return a==null?void 0:[a]}const r=this.namesToKeys.get(e);if(r==null)return;const n=[];if(r.forEach(a=>{const i=this.cache.get(a);i!=null&&n.push(i)}),n.length!==0)return n}}class co{mu=new Sp;requests=new Map;wrapped;debouncedRun;constructor(e,r){this.wrapped=e,this.debouncedRun=od(()=>{this.run()},r)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:r,variant:n}=se(e);return n==="names"?await this.wrapped.retrieve(r):await new Promise((a,i)=>{this.mu.runExclusive(()=>{this.requests.set(r,{resolve:a,reject:i}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((r,n)=>n.forEach(a=>e.add(a)));try{const r=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,a)=>n.resolve(r.filter(i=>a.includes(i.key))))}catch(r){this.requests.forEach(n=>n.reject(r))}finally{this.requests.clear()}})}}const uo=async(t,e)=>{const{normalized:r}=se(e),n=await t.retrieve(r),a=[];if(r.forEach(i=>{n.find(o=>o.name===i||o.key===i)==null&&a.push(i)}),a.length>0)throw new Le(`Could not find channels: ${JSON.stringify(a)}`);return n},Ap="sy_channel_set",kp="sy_channel_delete";class Dn{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;requires;status;constructor({dataType:e,name:r,leaseholder:n=0,key:a=0,isIndex:i=!1,index:o=0,internal:l=!1,virtual:c=!1,frameClient:u,alias:h,status:p,expression:d="",requires:S=[]}){this.key=U.parse(a),this.name=r,this.dataType=new k(e),this.leaseholder=n,this.index=U.parse(o),this.isIndex=i,this.internal=l,this.alias=h,this.virtual=c,this.expression=d,this.requires=U.array().parse(S??[]),p!=null&&(this.status=Wt.create(p)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new B("cannot read from a channel that has not been created");return this._frameClient}get payload(){return pt.parse({key:this.key,name:this.name,dataType:this.dataType.valueOf(),leaseholder:this.leaseholder,index:this.index,isIndex:this.isIndex,internal:this.internal,virtual:this.virtual,expression:this.expression,requires:this.requires,status:this.status})}get isCalculated(){return zr(this.payload)}get ontologyID(){return po(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,r){return await this.framer.write(e,this.key,r)}}const xp="sy_calculation_status",Cp="/channel/retrieve-group",Ip=s.z.object({}),jp=s.z.object({group:gs});let ho=class{type="channel";frameClient;client;retriever;writer;constructor(t,e,r,n){this.frameClient=t,this.retriever=e,this.client=r,this.writer=n}async create(t,e={}){const{retrieveIfNameExists:r=!1}=e,n=!Array.isArray(t);let a=O.toArray(t),i=[];if(r){const o=await this.retriever.retrieve(a.map(c=>c.name)),l=new Set(o.map(c=>c.name));a=a.filter(c=>!l.has(c.name)),i=this.sugar(o)}return i=i.concat(this.sugar(await this.writer.create(a))),n?i[0]:i}async retrieve(t,e){if(typeof t=="object"&&!Array.isArray(t))return this.sugar(await this.retriever.retrieve(t));const r=!Array.isArray(t),n=this.sugar(await this.retriever.retrieve(t,e));return yt("channel",t,n,r),r?n[0]:n}async delete(t){const{normalized:e,variant:r}=se(t);return r==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(t,e){return await this.writer.rename(O.toArray(t),O.toArray(e))}createDebouncedBatchRetriever(t=10){return new ws(new co(new Jt(this.client),t))}sugar(t){const{frameClient:e}=this;return Array.isArray(t)?t.map(r=>new Dn({...r,frameClient:e})):new Dn({...t,frameClient:e})}async retrieveGroup(){const t=await m(this.client,Cp,{},Ip,jp);return new ys(t.group.name,t.group.key)}};const zr=({virtual:t,expression:e})=>t&&e!=="",fo=async(t,e)=>{if(!zr(e))return e.index;for(const r of e.requires){const n=await t(r);if(n==null)return null;if(!n.virtual)return n.index}for(const r of e.requires){const n=await t(r);if(n==null)return null;if(zr(n)){const a=await fo(t,n);if(a!=null)return a}}return null},po=t=>({type:"channel",key:t.toString()}),Rp=s.z.object({channels:oo.array()}),Up=s.z.object({channels:pt.array()}),Mp=s.z.object({keys:U.array().optional(),names:we.array().optional()}),Lp=s.z.object({}),Pp=s.z.object({keys:U.array(),names:we.array()}),Dp=s.z.object({}),$p="/channel/create",Bp="/channel/delete",Fp="/channel/rename";let yo=class{client;cache;constructor(t,e){this.client=t,this.cache=e}async create(t){const{channels:e}=await m(this.client,$p,{channels:t.map(r=>({...r,dataType:r.dataType}))},Rp,Up);return this.cache.set(e),e}async delete(t){const e=U.array().parse(t.keys??[]);await m(this.client,Bp,t,Mp,Lp),e.length>0&&this.cache.delete(e),t.names!=null&&this.cache.delete(t.names)}async rename(t,e){await m(this.client,Fp,{keys:t,names:e},Pp,Dp),this.cache.rename(t,e)}};const Zp=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:xp,CacheRetriever:ws,Channel:Dn,Client:ho,ClusterRetriever:Jt,DELETE_CHANNEL_NAME:kp,DebouncedBatchRetriever:co,SET_CHANNEL_NAME:Ap,Writer:yo,analyzeParams:se,isCalculated:zr,keyZ:U,nameZ:we,newZ:oo,ontologyID:po,paramsZ:Ve,payloadZ:pt,resolveCalculatedIndex:fo,retrieveRequired:uo,statusZ:io},Symbol.toStringTag,{value:"Module"})),_e=s.z.uuid(),$r=s.z.object({key:_e,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),qp=$r.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Yp=s.z.object({keys:_e.array().optional(),usernames:s.z.string().array().optional()}),Hp=s.z.object({key:_e}).transform(({key:t})=>({keys:[t]})),Vp=s.z.object({username:s.z.string()}).transform(({username:t})=>({usernames:[t]})),_p=s.z.object({usernames:s.z.string().array()}).transform(({usernames:t})=>({usernames:t})),Wp=s.z.union([Hp,Vp,_p,Yp]),Gp=s.z.object({users:Y($r)}),Kp=s.z.object({users:qp.array()}),Jp=s.z.object({users:$r.array()}),Xp=s.z.object({key:_e,username:s.z.string().min(1)}),Qp=s.z.object({}),ey=s.z.object({key:_e,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),ty=s.z.object({}),ry=s.z.object({keys:_e.array()}),ny=s.z.object({}),sy="/user/retrieve",ay="/user/create",iy="/user/change-username",oy="/user/rename",ly="/user/delete";let cy=class{client;constructor(t){this.client=t}async create(t){const e=Array.isArray(t),r=await m(this.client,ay,{users:O.toArray(t)},Kp,Jp);return e?r.users:r.users[0]}async changeUsername(t,e){await m(this.client,iy,{key:t,username:e},Xp,Qp)}async retrieve(t){const e="key"in t||"username"in t,r=await m(this.client,sy,t,Wp,Gp);if(!e)return r.users;if(r.users.length===0){const n="key"in t?`key ${t.key}`:`username ${t.username}`;throw new it(`No user with ${n} found`)}if(r.users.length>1){const n="key"in t?`key ${t.key}`:`username ${t.username}`;throw new Sr(`Multiple users found with ${n}`)}return r.users[0]}async rename(t,e,r){await m(this.client,oy,{key:t,firstName:e,lastName:r},ey,ty)}async delete(t){await m(this.client,ly,{keys:O.toArray(t)},ry,ny)}};const uy=s.z.object({username:s.z.string(),password:s.z.string()}),hy=s.z.object({token:s.z.string(),user:$r}),da="/auth/login",dy=3,fy="/auth/change-password",py=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),yy=s.z.object({}),gy=[Mn,Ln];let my=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(t,e){this.client=t,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(t){if(!this.authenticated)throw new Error("Not authenticated");await m(this.client,fy,{username:this.credentials.username,password:this.credentials.password,newPassword:t},py,yy),this.credentials.password=t}middleware(){const t=async(e,r)=>{if(!this.authenticated&&!e.target.endsWith(da)){this.authenticating??=new Promise((o,l)=>{this.client.send(da,this.credentials,uy,hy).then(([c,u])=>{if(u!=null)return o(u);this.token=c?.token,this.user=c?.user,this.authenticated=!0,o(null)}).catch(l)});const i=await this.authenticating;if(i!=null)return[e,i]}e.params.Authorization=`Bearer ${this.token}`;const[n,a]=await r(e);return gy.some(i=>i.matches(a))&&this.retryCount<dy?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,t(e,r)):(this.retryCount=0,[n,a])};return t}};const wy=s.z.enum(["disconnected","connecting","connected","failed"]),by=s.z.object({status:wy,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()}),vy=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),fa={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.44.4"},pa=(t,e,r)=>{const n=r?"cluster":"client";return`Synnax cluster node version ${t!=null?`${t} `:""}is too ${r?"old":"new"} for client version ${e}.
|
|
22
|
+
This may cause compatibility issues. We recommend updating the ${n}. For more information, see
|
|
23
|
+
https://docs.synnaxlabs.com/reference/typescript-client/troubleshooting#old-${n}-version`};class Er{static ENDPOINT="/connectivity/check";static DEFAULT=fa;_state;pollFrequency=z.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=by;versionWarned=!1;constructor(e,r=z.seconds(30),n,a){this._state={...fa},this.client=e,this.pollFrequency=r,this.clientVersion=n,this.name=a,this.check(),this.startChecking()}stopChecking(){this.interval!=null&&clearInterval(this.interval)}async check(){const e=this._state.status;try{const[r,n]=await this.client.send(Er.ENDPOINT,{},s.z.object({}),vy);if(n!=null)throw n;const a=r.nodeVersion,i=this.clientVersion,o=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,o||(console.warn(pa(null,i,!0)),this.versionWarned=!0)):oa.versionsEqual(i,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,o||(console.warn(pa(a,i,oa.semVerNewer(i,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=this.state.error?.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)}}const Ty=s.z.object({keys:U.array().optional(),bounds:L.z,names:we.array().optional()}),Oy=s.z.object({}),Sy="/frame/delete";class zy{client;constructor(e){this.client=e}async delete(e){await m(this.client,Sy,e,Ty,Oy)}}const ya=t=>{const e=O.toArray(t);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ga=(t,e)=>{const r=O.toArray(t);if(r.length===e.length)return;const n=ya(t);throw ya===null?new B("[Frame] - channel keys or names must be provided when constructing a frame."):new B(`[Frame] - ${n}s and series must be the same length.
|
|
24
|
+
Got ${r.length} ${n}s and ${e.length} series.`)};let X=class Xe{columns=[];series=[];constructor(e=[],r=[]){if(e instanceof Xe){this.columns=e.columns,this.series=e.series;return}if(e instanceof Map){e.forEach((n,a)=>this.push(a,...O.toArray(n)));return}if(typeof e=="object"&&!Array.isArray(e)){if("keys"in e&&"series"in e){const n=e;n.series??=[],n.keys??=[];const a=n.series.map(i=>go(i));ga(n.keys,a),n.keys.forEach((i,o)=>this.push(i,a[o]))}else Object.entries(e).forEach(([n,a])=>{const i=parseInt(n);if(!isNaN(i))return this.push(i,...O.toArray(a));this.push(n,...O.toArray(a))});return}if(Array.isArray(e)||["string","number"].includes(typeof e)){const n=O.toArray(r),a=O.toArray(e);ga(a,n),n.forEach((i,o)=>this.push(a[o],i));return}throw new B(`[Frame] - invalid frame construction parameters. data parameter ust be a frame
|
|
25
|
+
payload, a list of lazy series, a lazy array, a map, or a record keyed by channel
|
|
26
|
+
name. keys parameter must be a set of channel keys or channel names.`)}get colType(){return this.columns.length===0?null:typeof this.columns[0]=="string"?"name":"key"}get keys(){if(this.colType==="name")throw new W("colType is not key");return this.columns??[]}get uniqueKeys(){return Ks.unique(this.keys)}get names(){if(this.colType==="key")throw new W("colType is not name");return this.columns??[]}get uniqueNames(){return Ks.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>mo(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(r=>r.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return L.ZERO;const n=E.min(...this.series.map(i=>i.timeRange.start)),a=E.max(...this.series.map(i=>i.timeRange.end));return new L(n,a)}const r=this.get(e);return r==null?L.ZERO:r.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(r=>e.includes(r)):new ad(this.series.filter((r,n)=>this.columns[n]===e))}push(e,...r){if(e instanceof Xe){if(this.colType!==null&&e.colType!==this.colType)throw new B("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...r),typeof e=="string"&&this.colType==="key")throw new B("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new B("keyVariant must match");this.columns.push(...Array.from({length:r.length},()=>e))}}concat(e){return new Xe([...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 r=new Xe;return this.forEach((n,a,i)=>r.push(...e(n,a,i))),r}forEach(e){this.columns.forEach((r,n)=>{const a=this.series[n];e(r,a,n)})}at(e,r=!1){const n={};return this.uniqueColumns.forEach(a=>{n[a]=this.get(a).at(e,r)}),n}filter(e){const r=new Xe;return this.columns.forEach((n,a)=>{const i=this.series[a];e(n,i,a)&&r.push(n,i)}),r}get byteLength(){return new at(this.series.reduce((e,r)=>e.add(r.byteLength),at.ZERO))}get digest(){const e={};return this.keys.forEach((r,n)=>{const a=this.series[n].digest;r in e?e[r].push(a):e[r]=[a]}),e}get length(){return this.series.reduce((e,r)=>e+r.length,0)}toString(){let e=`Frame{
|
|
27
|
+
`;return this.uniqueColumns.forEach(r=>{e+=` ${r}: ${this.get(r).series.map(n=>n.toString()).join(",")}
|
|
28
|
+
`}),e+="}",e}};const Br=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(()=>[]),Ie.crudeZ.array().optional().default([])])}),go=t=>{const{dataType:e,data:r,timeRange:n,alignment:a}=t;return new Ie({data:r,dataType:e,timeRange:n,glBufferUsage:"static",alignment:a})},mo=t=>({timeRange:t.timeRange,dataType:t.dataType,data:new Uint8Array(t.data.buffer),alignment:t.alignment});var ot=(t=>(t[t.Open=0]="Open",t[t.Write=1]="Write",t[t.Commit=2]="Commit",t[t.SetAuthority=3]="SetAuthority",t))(ot||{}),Mt=(t=>(t[t.PersistStream=1]="PersistStream",t[t.Persist=2]="Persist",t[t.Stream=3]="Stream",t))(Mt||{});const Ey=new z(-1);class $n extends pe.sub("writer_closed"){constructor(){super("WriterClosed")}}const Ny=s.z.enum(Mt).or(s.z.enum(["persist","stream","persistStream"]).transform(t=>{switch(t){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),wo=s.z.object({start:E.z.optional(),controlSubject:ee.subjectZ.optional(),authorities:s.z.union([ee.authorityZ.transform(t=>[t]),ee.authorityZ.array()]).default([ee.ABSOLUTE_AUTHORITY]),mode:Ny.default(1),errOnUnauthorized:s.z.boolean().default(!1),enableAutoCommit:s.z.boolean().default(!1),autoIndexPersistInterval:z.z.default(z.SECOND),useHighPerformanceCodec:s.z.boolean().default(!0)}),Ay=wo.extend({keys:U.array().optional()}),ma=wo.extend({channels:Ve}),bo=ma.or(Ve.transform(t=>ma.parse({channels:t,start:E.now()}))),ky=s.z.object({command:s.z.enum(ot),config:Ay.optional(),frame:Br.optional(),buffer:s.z.instanceof(Uint8Array).optional()}),xy=s.z.object({command:s.z.enum(ot),end:E.z,err:be.payloadZ.optional()}),Cy=s.z.tuple([s.z.union([s.z.record(U.or(we),ee.authorityZ),U.or(we),ee.authorityZ]),ee.authorityZ.optional()]).transform(([t,e])=>{if(ee.authorityZ.safeParse(t).success)return{keys:[],authorities:[t]};if(U.or(we).safeParse(t).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[t],authorities:[e]}}const r=t;return{keys:Object.keys(r),authorities:Object.values(r)}});let vo=class Bn{static ENDPOINT="/frame/write";stream;adapter;closeErr=null;constructor(e,r){this.stream=e,this.adapter=r}static async _open(e,r,n){const a=bo.parse(n),i=await vs.open(e,a.channels);a.useHighPerformanceCodec&&(r=r.withCodec(new Ly(i.codec)));const o=await r.stream(Bn.ENDPOINT,ky,xy),l=new Bn(o,i);return await l.execute({command:0,config:{...a,keys:i.keys}}),l}async write(e,r){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const n=await this.adapter.adapt(e,r);this.stream.send({command:1,frame:n.toPayload()})}async setAuthority(e,r){if(this.closeErr!=null)throw this.closeErr;const n=Cy.parse([e,r]),a={keys:await this.adapter.adaptParams(n.keys),authorities:n.authorities};await this.execute({command:3,config:a})}async commit(){if(this.closeErr!=null)throw this.closeErr;return this.stream.received()?(await this.closeInternal(null),E.ZERO):(await this.execute({command:2})).end}async close(){await this.closeInternal(null)}async closeInternal(e){if(this.closeErr!=null)throw this.closeErr;for(this.closeErr=e,this.stream.closeSend();;){if(this.closeErr!=null){if($n.matches(this.closeErr))return null;throw this.closeErr}const[r,n]=await this.stream.receive();n!=null?this.closeErr=ae.matches(n)?new $n:n:this.closeErr=be.decode(r?.err)}}async execute(e){const r=this.stream.send(e);for(r!=null&&await this.closeInternal(r);;){const[n,a]=await this.stream.receive();a!=null&&await this.closeInternal(a);const i=be.decode(n?.err);if(i!=null&&await this.closeInternal(i),n?.command==e.command)return n}}};const wa=t=>t.data.byteLength/t.dataType.density.valueOf(),Iy=t=>{const{keys:e,series:r}=t;e.forEach((n,a)=>{r[a].key=n}),r.sort((n,a)=>n.key-a.key),e.sort((n,a)=>n-a),r.forEach(n=>delete n.key)},ba=5,va=4,Ta=3,Oa=2,Sa=1,za=0,oe=k.TIMESTAMP.density.valueOf(),Ee=8,Ne=4,on=4,ln=4,jy=1;class To{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],r=[]){(e.length>0||r.length>0)&&this.update(e,r)}update(e,r){this.seqNum++;const n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((a,i)=>{const o=r[i];n.keyDataTypes.set(a,o),o.isVariable&&(n.hasVariableDataTypes=!0)}),n.keys.sort(),this.states.set(this.seqNum,n),this.currState=n}throwIfNotUpdated(e){if(this.seqNum<1)throw new B(`
|
|
29
|
+
The codec has not been updated with a list of channels and data types.
|
|
30
|
+
Please call the update method before calling ${e}.
|
|
31
|
+
`)}encode(e,r=0){this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),Iy(n);let a=-1,i,o,l,c=r+jy+ln,u=!this.currState?.hasVariableDataTypes,h=!0,p=!0,d=!0,S=!0,N=!0;n.keys.length!==this.currState?.keys.length&&(d=!1,c+=n.keys.length*on),n.series.forEach((P,ie)=>{const te=wa(P),bt=n.keys[ie],De=this.currState?.keyDataTypes.get(bt);if(De==null)throw new B(`Channel ${bt} was not provided in the list of channels when opening the writer`);if(!De.equals(P.dataType))throw new B(`Series data type of ${P.dataType.toString()} does not match the data type of ${De.toString()} for channel ${bt}`);if(c+=P.data.byteLength,a===-1){a=te,i=P.timeRange?.start,o=P.timeRange?.end,l=BigInt(P.alignment??0n);return}a!==te&&(u=!1),(i?.valueOf()!==P.timeRange?.start.valueOf()||o?.valueOf()!==P.timeRange?.end.valueOf())&&(h=!1),l!==BigInt(P.alignment??0)&&(S=!1)}),p=h&&i==null&&o==null,N=S&&(l===void 0||l===0n),u?c+=Ne:c+=n.keys.length*Ne,p||(h?c+=oe*2:c+=n.keys.length*oe*2),N||(S?c+=Ee:c+=n.keys.length*Ee);const x=new Uint8Array(c),$=new DataView(x.buffer);let I=r;return x[I]=Number(N)<<ba|Number(S)<<va|Number(u)<<Ta|Number(h)<<Oa|Number(p)<<Sa|Number(d)<<za,I++,$.setUint32(I,this.seqNum,!0),I+=ln,u&&($.setUint32(I,a,!0),I+=Ne),h&&!p&&($.setBigUint64(I,i?.valueOf()??0n,!0),$.setBigUint64(I,o?.valueOf()??0n,!0),I+=oe*2),S&&!N&&($.setBigUint64(I,l??0n,!0),I+=Ee),n.series.forEach((P,ie)=>{if(d||($.setUint32(I,n.keys[ie],!0),I+=on),!u){let te=P.data.byteLength;P.dataType.isVariable||(te=wa(P)),$.setUint32(I,te,!0),I+=Ne}x.set(new Uint8Array(P.data),I),I+=P.data.byteLength,!h&&!p&&($.setBigUint64(I,P.timeRange?.start.valueOf()??0n,!0),$.setBigUint64(I,P.timeRange?.end.valueOf()??0n,!0),I+=oe*2),!S&&!N&&($.setBigUint64(I,P.alignment??0n,!0),I+=Ee)}),x}decode(e,r=0){this.throwIfNotUpdated("decode");const n=e instanceof Uint8Array?e:new Uint8Array(e),a={keys:[],series:[]};let i=r,o=0,l=0,c,u,h;const p=new DataView(n.buffer,n.byteOffset,n.byteLength),d=!!(n[i]>>ba&1),S=!!(n[i]>>va&1),N=!!(n[i]>>Ta&1),x=!!(n[i]>>Oa&1),$=!!(n[i]>>Sa&1),I=!!(n[i]>>za&1);i++;const P=p.getUint32(i,!0);i+=ln;const ie=this.states.get(P);if(ie==null)return a;if(N){if(i+Ne>p.byteLength)return a;o=p.getUint32(i,!0),i+=Ne}if(x&&!$){if(i+oe>p.byteLength)return a;c=new E(p.getBigUint64(i,!0)),i+=oe,u=new E(p.getBigUint64(i,!0)),i+=oe}if(S&&!d){if(i+Ee>p.byteLength)return a;h=p.getBigUint64(i,!0),i+=Ee}return I&&(a.keys=[...ie.keys]),ie.keys.forEach((te,bt)=>{if(!I){if(i>=p.byteLength||p.getUint32(i,!0)!==te)return;i+=on,a.keys.push(te)}const De=ie.keyDataTypes.get(te);if(l=0,N)l=o;else{if(i+Ne>p.byteLength)return;l=p.getUint32(i,!0),i+=Ne}let sr=l;if(De.isVariable||(sr*=De.density.valueOf()),i+sr>p.byteLength){a.keys.splice(bt,1);return}const $e={dataType:De,data:n.slice(i,i+sr).buffer};if(i+=sr,!x&&!$){if(i+oe*2>p.byteLength)return;const Bl=p.getBigUint64(i,!0);i+=oe;const Fl=p.getBigUint64(i,!0);i+=oe,$e.timeRange=new L({start:Bl,end:Fl})}else $?$e.timeRange=new L({start:0n,end:0n}):$e.timeRange=new L({start:c?.valueOf()??0n,end:u?.valueOf()??0n});if(!S&&!d){if(i+Ee>p.byteLength)return;h=p.getBigUint64(i,!0),i+=Ee,$e.alignment=h}else d?$e.alignment=0n:$e.alignment=h;a.series.push($e)}),a}}const bs=254,Ry=new Uint8Array([bs]),Uy=255,My=new Uint8Array([Uy]),Oo="application/sy-framer";class Ly{contentType=Oo;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=He.JSON_CODEC}encode(e){const r=e;if(r.type=="close"||r.payload?.command!=ot.Write){const a=this.lowPerfCodec.encode(r),i=new Uint8Array({length:a.byteLength+1});return i.set(Ry,0),i.set(new Uint8Array(a),1),i}const n=this.base.encode(r.payload?.frame,1);return n.set(My,0),n}decode(e,r){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===bs)return this.lowPerfCodec.decode(e.slice(1),r);const n={type:"data"},a=this.base.decode(e,1);return n.payload={command:ot.Write,frame:a},n}}class Py{contentType=Oo;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=He.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,r){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===bs?this.lowPerfCodec.decode(e.slice(1),r):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Fr{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new To}static async open(e,r){const n=new Fr(e);return await n.update(r),n}async update(e){const{variant:r,normalized:n}=se(e),a=await this.retriever.retrieve(n),i=a.map(l=>l.key);if(Js.uniqueUnorderedPrimitiveArrays(this.keys,i)===Js.EQUAL)return!1;if(this.codec.update(i,a.map(l=>l.dataType)),r==="keys")return this.adapter=null,this.keys=n,!0;const o=new Map;return this.adapter=o,n.forEach(l=>{const c=a.find(u=>u.name===l);if(c==null)throw new Error(`Channel ${l} not found`);o.set(c.key,c.name)}),this.keys=Array.from(this.adapter.keys()),!0}adapt(e){if(this.adapter==null)return e;const r=this.adapter;return e.map((n,a)=>{if(typeof n=="number"){const i=r.get(n);if(i==null)throw new Error(`Channel ${n} not found`);return[i,a]}return[n,a]})}}class vs{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new To}static async open(e,r){const n=new vs(e);return await n.update(r),n}async adaptParams(e){const r=Ve.parse(e);return await Promise.all(r.map(async n=>await this.adaptToKey(n)))}async update(e){const r=await uo(this.retriever,e),n=r.map(c=>c.key),a=new Set(this.keys),i=new Set(n),o=!i.isSubsetOf(a),l=!a.isSubsetOf(i);return o||l?(this.adapter=new Map(r.map(c=>[c.name,c.key])),this.keys=n,this.codec.update(this.keys,r.map(c=>c.dataType)),!0):!1}async fetchChannel(e){const r=await this.retriever.retrieve(e);if(r.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return r[0]}async adaptToKey(e){return typeof e=="number"?e:(await this.fetchChannel(e)).key}encode(e){return this.codec.encode(e.toPayload())}async adapt(e,r){if(typeof e=="string"||typeof e=="number"){if(r==null)throw new B(`
|
|
32
|
+
Received a single channel name or key but no series.
|
|
33
|
+
`);if(Array.isArray(r)){if(r.some(c=>c instanceof Ie||Array.isArray(c)))throw new B(`
|
|
34
|
+
Received a single channel name or key but multiple series.
|
|
35
|
+
`);r=r}const o=await this.fetchChannel(e),l=new Ie({data:r,dataType:o.dataType});return new X(o.key,l)}if(Array.isArray(e)){if(r==null)throw new B(`
|
|
36
|
+
Received an array of channel names or keys but no series.
|
|
37
|
+
`);if(!Array.isArray(r))throw new B(`
|
|
38
|
+
Received an array of channel names or keys but no array of series.
|
|
39
|
+
`);const o=[],l=[];for(let c=0;c<e.length;c++){const u=await this.fetchChannel(e[c]);if(c>=r.length)throw new B(`
|
|
40
|
+
Received an array of channel names or keys but not enough series.
|
|
41
|
+
`);const h=new Ie({data:r[c],dataType:u.dataType});o.push(u.key),l.push(h)}return new X(o,l)}if(e instanceof X||e instanceof Map){const o=new X(e);if(this.adapter==null)return o;const l=o.columns.map(c=>{const u=typeof c=="string"?this.adapter?.get(c):c;if(u==null)throw new B(`
|
|
42
|
+
Channel ${c} was not provided in the list of channels when opening the writer
|
|
43
|
+
`);return u});return new X(l,o.series)}const n=[],a=[],i=Object.entries(e);for(let o=0;o<i.length;o++){const[l,c]=i[o],u=await this.fetchChannel(l),h=new Ie({data:c,dataType:u.dataType});n.push(u.key),a.push(h)}return new X(n,a)}}class So{name;stream;constructor(e,r){this.stream=r,this.name=e}async receive(){const[e,r]=await this.stream.receive();if(r!=null)throw r;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,r]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
|
|
44
|
+
Please report this error to the Synnax team.`),r!=null){if(ae.matches(r))return;throw r}}}closeSend(){this.stream.closeSend()}send(e){const r=this.stream.send(e);if(r!=null)throw r}}const Nr=new z(-1);var Ts=(t=>(t[t.Open=0]="Open",t[t.Next=1]="Next",t[t.Prev=2]="Prev",t[t.SeekFirst=3]="SeekFirst",t[t.SeekLast=4]="SeekLast",t[t.SeekLE=5]="SeekLE",t[t.SeekGE=6]="SeekGE",t[t.Valid=7]="Valid",t[t.Error=8]="Error",t))(Ts||{}),zo=(t=>(t[t.None=0]="None",t[t.Ack=1]="Ack",t[t.Data=2]="Data",t))(zo||{});const Dy=s.z.object({command:s.z.enum(Ts),span:z.z.optional(),bounds:L.z.optional(),stamp:E.z.optional(),keys:U.array().optional(),chunkSize:s.z.number().optional()}),$y=s.z.object({variant:s.z.enum(zo),ack:s.z.boolean(),command:s.z.enum(Ts),error:be.payloadZ.optional().nullable(),frame:Br.optional()});class Lt{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,r){this.stream=new So("Iterator",e),this.value=new X,this.adapter=r}static async _open(e,r,n,a,i={}){const o=await Fr.open(n,r),l=await a.stream(Lt.ENDPOINT,Dy,$y),c=new Lt(l,o);return await c.execute({command:0,keys:o.keys,bounds:new L(e),chunkSize:i.chunkSize??1e5}),c}async next(e=Nr){return await this.execute({command:1,span:new z(e)})}async prev(e=Nr){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 E(e)})}async seekGE(e){return await this.execute({command:6,stamp:new E(e)})}async valid(){return await this.execute({command:7})}async close(){await this.stream.closeAndAck()}[Symbol.asyncIterator](){return new By(this)}async execute(e){for(this.stream.send(e),this.value=new X;;){const r=await this.stream.receive();if(r.variant===1)return r.ack;this.value.push(this.adapter.adapt(new X(r.frame)))}}}class By{iter;open=!1;constructor(e){this.iter=e}async next(){try{let e=!0;return this.open||(await this.iter.seekFirst()||(e=!1),this.open=!0),await this.iter.next()||(e=!1),e||await this.iter.close(),{done:!e,value:this.iter.value}}catch(e){throw await this.iter.close(),e}}}const Fy=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),Zy=s.z.object({frame:Br}),qy="/frame/stream",Ea=s.z.object({channels:Ve,downsampleFactor:s.z.number().optional().default(1),useHighPerformanceCodec:s.z.boolean().optional().default(!0)}),Os=Ea.or(Ve.transform(t=>Ea.parse({channels:t}))),Eo=(t,e)=>async r=>{const n=Os.parse(r),a=await Fr.open(t,n.channels);n.useHighPerformanceCodec&&(e=e.withCodec(new Py(a.codec)));const i=await e.stream(qy,Fy,Zy),o=new Yy(i,a);i.send({keys:a.keys,downsampleFactor:n.downsampleFactor??1});const[,l]=await i.receive();if(l!=null)throw l;return o},No=async(t,e,r)=>await Eo(t,e)(r);class Yy{stream;adapter;downsampleFactor;constructor(e,r){this.stream=new So("Streamer",e),this.adapter=r,this.downsampleFactor=1}get keys(){return this.adapter.keys}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ae.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new X((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 Zr{wrapped_=null;breaker;opener;config;constructor(e,r,n={}){this.opener=e,this.config=Os.parse(r);const{maxRetries:a=5e3,baseInterval:i=z.seconds(1),scale:o=1}=n??{};this.breaker=new Di.Breaker({maxRetries:a,baseInterval:i,scale:o})}static async open(e,r,n){const a=new Zr(e,r,n);return await a.runStreamer(),a}async runStreamer(){for(;;)try{this.wrapped_!=null&&this.wrapped_.close(),this.wrapped_=await this.opener(this.config),this.breaker.reset();return}catch(e){if(this.wrapped_=null,!await this.breaker.wait())throw e;console.error("failed to open streamer",e);continue}}get wrapped(){if(this.wrapped_==null)throw new Error("stream closed");return this.wrapped_}async update(e){this.config.channels=Ve.parse(e);try{await this.wrapped.update(e)}catch{return await this.runStreamer(),await this.update(e)}}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(ae.matches(e))return{done:!0,value:void 0};throw e}}async read(){try{const e=await this.wrapped.read();return this.breaker.reset(),e}catch(e){if(ae.matches(e))throw e;return await this.runStreamer(),await this.read()}}close(){this.wrapped.close()}get keys(){return this.wrapped.keys}[Symbol.asyncIterator](){return this}}class Ao extends fd.Observer{streamer;closePromise;constructor(e,r){super(r),this.streamer=e,this.closePromise=this.stream()}async update(e){await this.streamer.update(e)}async close(){this.streamer.close(),await this.closePromise}async stream(){for await(const e of this.streamer)this.notify(e)}}const Hy=t=>({type:"framer",key:t.toString()});let ko=class{streamClient;retriever;deleter;constructor(t,e,r){this.streamClient=t,this.retriever=r,this.deleter=new zy(e)}async openIterator(t,e,r){return await Lt._open(t,e,this.retriever,this.streamClient,r)}async openWriter(t){return await vo._open(this.retriever,this.streamClient,t)}async openStreamer(t){return await No(this.retriever,this.streamClient,t)}async write(t,e,r){if(r==null){const a=e,i=await this.openWriter({start:t,channels:Object.keys(a),mode:Mt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});return await i.write(a),await i.close()}const n=await this.openWriter({start:t,channels:e,mode:Mt.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});await n.write(e,r),await n.close()}async read(t,e){const{single:r}=se(e),n=await this.readFrame(t,e);return r?n.get(e):n}async readFrame(t,e){const r=await this.openIterator(t,e),n=new X;try{for await(const a of r)n.push(a)}finally{await r.close()}return n}async readLatest(t,e=1){const{single:r}=se(t),n=await this.readLatestNFrame(t,e);return r?n.get(t):n}async readLatestNFrame(t,e){const r=await this.openIterator(L.MAX,t,{chunkSize:e}),n=new X;if(e>0)try{await r.seekLast(),await r.prev(Nr),n.push(r.value)}finally{await r.close()}return n}async delete(t,e){const{normalized:r,variant:n}=se(t);return n==="keys"?await this.deleter.delete({keys:r,bounds:e}):await this.deleter.delete({names:r,bounds:e})}};const Vy=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:Ey,AUTO_SPAN:Nr,Client:ko,Frame:X,HardenedStreamer:Zr,Iterator:Lt,ObservableStreamer:Ao,Writer:vo,WriterClosedError:$n,WriterCommand:ot,WriterMode:Mt,createStreamOpener:Eo,frameZ:Br,ontologyID:Hy,openStreamer:No,seriesFromPayload:go,seriesToPayload:mo,streamerConfigZ:Os,writerConfigZ:bo},Symbol.toStringTag,{value:"Module"})),_y=ee.ABSOLUTE_AUTHORITY,Wy=ee.ZERO_AUTHORITY,Gy=ee.stateZ(s.z.number()),Ky=t=>t.to==null?`${t.from?.resource} - ${t.from?.subject.name} -> released`:t.from==null?`${t.to.resource} - released -> ${t.to.subject.name} (${t.to.authority.toString()})`:`${t.to.resource} - ${t.from.subject.name} -> ${t.to.subject.name} (${t.to.authority.toString()})`,Jy=s.z.object({transfers:s.z.array(ee.transferZ(U))});class xo extends Ao{states;codec;constructor(e){super(e,r=>{const n=this.codec.decode(r.series[0].buffer,Jy);return this.merge(n),[n.transfers,!0]}),this.states=new Map,this.codec=new He.JSONCodec}subjects(){const e=new Map;return this.states.forEach(r=>e.set(r.subject.key,r.subject)),Array.from(e.values())}merge(e){e.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 Co="sy_node_1_control";let Io=class{framer;constructor(t){this.framer=t}async openStateTracker(){const t=await Zr.open(async e=>await this.framer.openStreamer(e),Co);return new xo(t)}};const Xy=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:_y,CONTROL_STATE_CHANNEL_NAME:Co,Client:Io,StateTracker:xo,ZERO_AUTHORITY:Wy,stateZ:Gy,transferString:Ky},Symbol.toStringTag,{value:"Module"}));let Qy=class{tasks;racks;devices;constructor(t,e,r){this.tasks=t,this.racks=e,this.devices=r}};const ye=s.z.uint32(),jo=Wt.statusZ(s.z.object({rack:ye})),qr=s.z.object({key:ye,name:s.z.string(),status:xt.nullToUndefined(jo)}),Ro=qr.partial({key:!0}),Uo=t=>t?He.JSON_CODEC.decodeString(t,ve.unknownZ):{},gt=s.z.string(),Mo=Wt.statusZ(s.z.object({rack:ye,device:gt})),Yr=s.z.object({key:gt,rack:ye,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:ve.unknownZ.or(s.z.string().transform(Uo)),status:xt.nullToUndefined(Mo)}),Lo=Yr.extend({properties:s.z.unknown().transform(t=>He.JSON_CODEC.encodeString(t))}),eg="sy_device_set",tg="sy_device_delete",rg="sy_device_status",ng="/hardware/device/retrieve",sg="/hardware/device/create",ag="/hardware/device/delete",ig=s.z.object({devices:Lo.array()}),og=s.z.object({devices:Yr.array()}),lg=s.z.object({keys:gt.array()}),cg=s.z.object({}),ug=s.z.object({keys:gt.array().optional(),names:s.z.string().array().optional(),makes:s.z.string().array().optional(),models:s.z.string().array().optional(),locations:s.z.string().array().optional(),racks:ye.array().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),hg=s.z.object({devices:Y(Yr)}),dg=s.z.object({key:gt,includeStatus:s.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),fg=s.z.union([dg,ug]);let Po=class{type="device";client;constructor(t){this.client=t}async retrieve(t){const e=typeof t=="object"&&"key"in t,r=await m(this.client,ng,t,fg,hg);yt("Device",t,r.devices,e);const n=r.devices;return e?n[0]:n}async create(t){const e=!Array.isArray(t),r=(await m(this.client,sg,{devices:O.toArray(t)},ig,og)).devices;return e?r[0]:r}async delete(t){await m(this.client,ag,{keys:O.toArray(t)},lg,cg)}};const pg=t=>({type:"device",key:t}),yg=Object.freeze(Object.defineProperty({__proto__:null,Client:Po,DELETE_CHANNEL_NAME:tg,SET_CHANNEL_NAME:eg,STATUS_CHANNEL_NAME:rg,deviceZ:Yr,keyZ:gt,newZ:Lo,ontologyID:pg,statusZ:Mo},Symbol.toStringTag,{value:"Module"})),gg="/hardware/rack/retrieve",mg="/hardware/rack/create",wg="/hardware/rack/delete",bg="sy_rack_status",vg="sy_rack_set",Tg="sy_rack_delete",Og=s.z.object({keys:ye.array().optional(),names:s.z.string().array().optional(),searchTerm:s.z.string().optional(),embedded:s.z.boolean().optional(),hostIsNode:s.z.boolean().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),Sg=s.z.object({racks:Y(qr)}),zg=s.z.union([s.z.object({key:ye,includeStatus:s.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),Eg=Og,Ng=s.z.union([zg,Eg]),Ag=s.z.object({racks:Ro.array()}),kg=s.z.object({racks:qr.array()}),xg=s.z.object({keys:ye.array()}),Cg=s.z.object({});let Do=class{type="rack";client;tasks;constructor(t,e){this.client=t,this.tasks=e}async delete(t){await m(this.client,wg,{keys:O.toArray(t)},xg,Cg)}async create(t){const e=!Array.isArray(t),r=await m(this.client,mg,{racks:O.toArray(t)},Ag,kg),n=this.sugar(r.racks);return e?n[0]:n}async retrieve(t){const e="key"in t||"name"in t,r=await m(this.client,gg,t,Ng,Sg),n=this.sugar(r.racks);return yt("Rack",t,n,e),e?n[0]:n}sugar(t){const e=!Array.isArray(t),r=O.toArray(t).map(({key:n,name:a,status:i})=>new $o(n,a,this.tasks,i));return e?r[0]:r}};class $o{key;name;status;tasks;constructor(e,r,n,a){this.key=e,this.name=r,this.tasks=n,this.status=a}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,r){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,r)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const Ig=t=>({type:"rack",key:t.toString()}),jg=Object.freeze(Object.defineProperty({__proto__:null,Client:Do,DELETE_CHANNEL_NAME:Tg,Rack:$o,SET_CHANNEL_NAME:vg,STATUS_CHANNEL_NAME:bg,keyZ:ye,newZ:Ro,ontologyID:Ig,rackZ:qr,statusZ:jo},Symbol.toStringTag,{value:"Module"})),Te=t=>t?JSON.parse(t):{},Oe=s.z.union([s.z.string(),s.z.bigint().transform(t=>t.toString()),s.z.number().transform(t=>t.toString())]),Bo=t=>s.z.object({task:Oe,running:s.z.boolean(),data:t}),Ss=t=>Wt.statusZ(Bo(t)),Xt=(t={typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()})=>s.z.object({key:Oe,name:s.z.string(),type:t.typeSchema,internal:s.z.boolean().optional(),config:s.z.string().transform(Uo).or(t.configSchema),status:Ss(t.statusDataSchema).optional().nullable(),snapshot:s.z.boolean().optional()}),Fo=t=>Xt(t).omit({key:!0}).extend({key:Oe.transform(e=>e.toString()).optional(),config:s.z.unknown().transform(e=>He.JSON_CODEC.encodeString(e))}),Rg=s.z.object({task:Oe,type:s.z.string(),key:s.z.string(),args:ve.unknownZ.or(s.z.string().transform(Te)).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),Ug=t=>Number(BigInt(t)>>32n),Fn="sy_task_status",Zn="sy_task_cmd",Mg="sy_task_set",Lg="sy_task_delete",Be=new Error("Task not created"),Zo=async(t,e)=>{const r=await e.retrieveParents(zs(t));return r.length===0?null:r[0]};class qo{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Be;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Be;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Be;return this.rangeClient_}constructor({key:e,type:r,name:n,config:a,internal:i=!1,snapshot:o=!1,status:l},c,u,h,p){this.key=e,this.name=n,this.type=r,this.config=a,this.schemas=c??{typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()},this.internal=i,this.snapshot=o,this.status=l,this.frameClient_=u,this.ontologyClient_=h,this.rangeClient_=p}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return zs(this.key)}async executeCommand(e,r){return await Ho(this.frameClient,this.key,e,r)}async executeCommandSync(e,r,n){return await Vo(this.frameClient,this.key,e,r,this.name,this.schemas?.statusDataSchema,n)}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Be;return this.snapshot?await Zo(this.key,this.ontologyClient):null}}const Pg=s.z.object({rack:ye.optional(),keys:Oe.array().optional(),names:s.z.string().array().optional(),types:s.z.string().array().optional(),includeStatus:s.z.boolean().optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Dg=s.z.union([s.z.object({key:Oe,includeStatus:s.z.boolean().optional()}).transform(({key:t,includeStatus:e})=>({keys:[t],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:t,includeStatus:e})=>({names:[t],includeStatus:e}))]),$g=Pg,Bg=s.z.union([Dg,$g]),Fg=t=>s.z.object({tasks:Y(Xt(t))}),Zg="/hardware/task/retrieve",qg="/hardware/task/create",Yg="/hardware/task/delete",Hg="/hardware/task/copy",Vg=t=>s.z.object({tasks:Fo(t).array()}),_g=t=>s.z.object({tasks:Xt(t).array()}),Wg=s.z.object({keys:Oe.array()}),Gg=s.z.object({}),Kg=s.z.object({key:Oe,name:s.z.string(),snapshot:s.z.boolean()}),Jg=t=>s.z.object({task:Xt(t)});let Yo=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(t,e,r,n){this.client=t,this.frameClient=e,this.ontologyClient=r,this.rangeClient=n}async create(t,e){const r=!Array.isArray(t),n=Vg(e),a=_g(e),i=await m(this.client,qg,{tasks:O.toArray(t)},n,a),o=this.sugar(i.tasks,e);return r?o[0]:o}async delete(t){await m(this.client,Yg,{keys:O.toArray(t)},Wg,Gg)}async retrieve({schemas:t,...e}){const r="key"in e||"name"in e,n=(await m(this.client,Zg,e,Bg,Fg(t))).tasks,a=this.sugar(n,t);return yt("Task",e,a,r),r?a[0]:a}async copy(t,e,r){const n=Jg(),a=await m(this.client,Hg,{key:t,name:e,snapshot:r},Kg,n);return this.sugar(a.task)}async retrieveSnapshottedTo(t){if(this.ontologyClient==null)throw Be;return await Zo(t,this.ontologyClient)}sugar(t,e){const r=!Array.isArray(t),n=O.toArray(t).map(({key:a,name:i,type:o,config:l,status:c,internal:u,snapshot:h})=>new qo({key:a,name:i,type:o,config:l,internal:u,snapshot:h,status:c},e,this.frameClient,this.ontologyClient,this.rangeClient));return r?n[0]:n}async executeCommand(t,e,r){if(Array.isArray(t))return await Es(this.frameClient,t);if(e==null)throw new Error("Type is required");return await Ho(this.frameClient,t,e,r)}async executeCommandSync(t,e,r,n,a,i=s.z.unknown()){if(Array.isArray(t)){const l=async()=>(await this.retrieve({keys:t.map(c=>c.task)})).map(c=>c.name);return await _o(this.frameClient,t,e,i,l)}const o=async()=>(await this.retrieve({key:t})).name;return await Vo(this.frameClient,t,e,r,a??o,i,n)}};const zs=t=>({type:"task",key:t}),Ho=async(t,e,r,n)=>(await Es(t,[{args:n,task:e,type:r}]))[0],Es=async(t,e)=>{if(t==null)throw Be;const r=await t.openWriter(Zn),n=e.map(a=>({...a,key:qh.create()}));return await r.write(Zn,n),await r.close(),n.map(a=>a.key)},Vo=async(t,e,r,n,a,i,o)=>(await _o(t,[{args:o,task:e,type:r}],n,i,a))[0],_o=async(t,e,r,n,a)=>{if(t==null)throw Be;const i=await t.openStreamer(Fn),o=await Es(t,e),l=new z(r);let c=[],u;const h=new Promise((p,d)=>{u=setTimeout(()=>{(async()=>{const S=e.map(N=>N.task);d(await Xg("command",a,l,S))})()},l.milliseconds)});try{for(;;){const p=await Promise.race([i.read(),h]),d=Ss(n).parse(p.at(-1)[Fn]);if(o.includes(d.key)&&(c=[...c.filter(S=>S.key!==d.key),d],c.length===o.length))return c}}finally{clearTimeout(u),i.close()}},Xg=async(t,e,r,n)=>{const a=Ju.capitalize(t),i=r.toString();try{let o;typeof e=="string"?o=[e]:Array.isArray(e)?o=e:o=O.toArray(await e());const l=Rn.naturalLanguageJoin(o);return new Error(`${a} command to ${l} timed out after ${i}`)}catch(o){return console.error("Failed to retrieve task name for timeout error:",o),new Error(`${a} command to task with key ${Rn.naturalLanguageJoin(n)} timed out after ${i}`)}},Qg=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:Zn,Client:Yo,DELETE_CHANNEL_NAME:Lg,SET_CHANNEL_NAME:Mg,STATUS_CHANNEL_NAME:Fn,Task:qo,commandZ:Rg,keyZ:Oe,newZ:Fo,ontologyID:zs,rackKey:Ug,statusDetailsZ:Bo,statusZ:Ss,taskZ:Xt},Symbol.toStringTag,{value:"Module"})),Pe=s.z.uuid(),Qt=s.z.object({key:Pe,name:s.z.string().min(1),color:s.z.string()}),em="labeled_by",tm="sy_label_set",rm="sy_label_delete",Wo=Qt.extend({key:Pe.optional()}),nm=s.object({labels:Wo.array()}),sm=s.object({labels:Qt.array()}),am=s.object({keys:Pe.array()}),Go=s.object({id:M,labels:Pe.array(),replace:s.boolean().optional()}),im=Go.omit({replace:!0}),cn=s.object({}),om="/label/create",lm="/label/delete",cm="/label/set",um="/label/remove",hm="/label/retrieve",dm=s.object({keys:Pe.array().optional(),for:M.optional(),searchTerm:s.string().optional(),offset:s.number().optional(),limit:s.number().optional()}),fm=s.object({key:Pe}).transform(({key:t})=>({keys:[t]})),pm=s.union([fm,dm]),ym=s.object({labels:Y(Qt)});let Ko=class{type="label";client;constructor(t){this.client=t}async retrieve(t){const e="key"in t,r=await m(this.client,hm,t,pm,ym);return yt("Label",t,r.labels,e),e?r.labels[0]:r.labels}async label(t,e,r={}){await m(this.client,cm,{id:t,labels:e,replace:r.replace},Go,cn)}async remove(t,e){await m(this.client,um,{id:t,labels:e},im,cn)}async create(t){const e=Array.isArray(t),r=await m(this.client,om,{labels:O.toArray(t)},nm,sm);return e?r.labels:r.labels[0]}async delete(t){await m(this.client,lm,{keys:O.toArray(t)},am,cn)}};const gm=t=>({type:"label",key:t}),mm=Object.freeze(Object.defineProperty({__proto__:null,Client:Ko,DELETE_CHANNEL_NAME:rm,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:em,SET_CHANNEL_NAME:tm,keyZ:Pe,labelZ:Qt,newZ:Wo,ontologyID:gm},Symbol.toStringTag,{value:"Module"})),H=s.z.uuid(),Ns=s.z.string().min(1),er=s.z.object({key:H,name:Ns,timeRange:L.z,color:s.z.string().optional(),labels:Qt.array().or(s.z.null().transform(()=>{})).optional(),get parent(){return er.optional().nullable().transform(t=>t===void 0?null:t)}}),Jo=er.omit({parent:!0,labels:!0}).partial({key:!0}),wm="sy_range_alias_set",bm="sy_range_alias_delete",vm=s.z.object({range:H,aliases:s.z.string().array()}),Tm=s.z.object({aliases:s.z.record(s.z.string(),U)}),Om=s.z.object({range:H,aliases:s.z.record(U,s.z.string())}),Sm=s.z.unknown(),zm=s.z.object({range:H,channels:U.array()}),Em=s.z.unknown(),Nm=s.z.object({range:H}),Am=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),km=s.z.object({range:H,channels:U.array()}),xm=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())});let Qe=class et{static SET_ENDPOINT="/range/alias/set";static RESOLVE_ENDPOINT="/range/alias/resolve";static LIST_ENDPOINT="/range/alias/list";static RETRIEVE_ENDPOINT="/range/alias/retrieve";static DELETE_ENDPOINT="/range/alias/delete";frameClient;cache=new Map;client;rangeKey;constructor(e,r,n){this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=r}async resolve(e){const r=[],n=typeof e=="string",a={};if(n){const o=this.cache.get(e);if(o!=null)return o;r.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?a[o]=l:r.push(o)});if(r.length===0)return a;const i=await m(this.client,et.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:r},vm,Tm);return Object.entries(i.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?i.aliases[r[0]]:{...a,...i.aliases}}async set(e){await m(this.client,et.SET_ENDPOINT,{range:this.rangeKey,aliases:e},Om,Sm)}async list(){return(await m(this.client,et.LIST_ENDPOINT,{range:this.rangeKey},Nm,Am)).aliases}async retrieve(e){const r=typeof e=="number",n=await m(this.client,et.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:O.toArray(e)},km,xm);return r?n.aliases[e]:n.aliases}async delete(e){await m(this.client,et.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},zm,Em)}};const Cm=s.z.object({alias:s.z.string().optional(),channel:U,range:H}),Xo="---",Im=t=>`${t.range}${Xo}${t.channel}`,jm=t=>{const[e,r]=t.split(Xo);return{range:e,channel:Number(r)}},Rm="sy_range_kv_set",Um="sy_range_kv_delete",As=s.z.object({range:H,key:s.z.string(),value:s.z.string()}),Mm=({range:t,key:e})=>`${t}<--->${e}`,Lm=s.z.object({range:H,keys:s.z.string().array()}),Pm=s.z.object({pairs:Y(As)}),Dm=s.z.object({range:H,pairs:As.array()}),$m=s.z.object({range:H,keys:s.z.string().array()});class Ye{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,r){this.rangeKey=e,this.client=r}async get(e){const r=await m(this.client,Ye.GET_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},Lm,Pm);return typeof e=="string"?r.pairs[0].value:Object.fromEntries(r.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,r=""){let n;ci(e)?n=Object.entries(e).map(([a,i])=>({range:this.rangeKey,key:a,value:i})):n=[{range:this.rangeKey,key:e,value:r}],await m(this.client,Ye.SET_ENDPOINT,{range:this.rangeKey,pairs:n},Dm,s.z.unknown())}async delete(e){await m(this.client,Ye.DELETE_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},$m,s.z.unknown())}}const Bm="sy_range_set",Fm="sy_range_delete";class Qo{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:r=L.ZERO,key:n,color:a,parent:i,labels:o},{frameClient:l,kv:c,aliaser:u,channels:h,labelClient:p,ontologyClient:d,rangeClient:S}){this.key=n,this.name=e,this.timeRange=r,this.parent=i,this.labels=o,this.frameClient=l,this.color=a,this.kv=c,this.aliaser=u,this.channels=h,this.labelClient=p,this.ontologyClient=d,this.rangeClient=S}get ontologyID(){return tt(this.key)}get payload(){let e=null;return this.parent!=null&&("payload"in this.parent?e=this.parent.payload:e=this.parent),{key:this.key,name:this.name,timeRange:this.timeRange,color:this.color,labels:this.labels,parent:e}}async setAlias(e,r){const n=await this.channels.retrieve(e);if(n.length===0)throw new Le(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:r})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(r=>r.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:tt(this.key)})}async addLabel(...e){await this.labelClient.label(tt(this.key),e)}async removeLabel(...e){await this.labelClient.remove(tt(this.key),e)}static sort(e,r){return L.sort(e.timeRange,r.timeRange)}}const Zm=s.z.object({keys:H.array().optional(),names:s.z.array(s.z.string()).optional(),searchTerm:s.z.string().optional(),overlapsWith:L.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional(),hasLabels:Pe.array().optional(),includeLabels:s.z.boolean().optional(),includeParent:s.z.boolean().optional()}),qm=Zm.or(H.array().transform(t=>({keys:t}))).or(H.transform(t=>({keys:[t]}))).or(s.z.string().transform(t=>({names:[t]}))).or(s.z.string().array().transform(t=>({names:t}))).or(L.z.transform(t=>({overlapsWith:t}))),Ym="/range/retrieve",Hm=s.z.object({ranges:Y(er)});let el=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(t,e,r,n,a,i){this.frameClient=t,this.writer=e,this.unaryClient=r,this.channels=n,this.labelClient=a,this.ontologyClient=i}async create(t,e){const r=!Array.isArray(t),n=this.sugarMany(await this.writer.create(O.toArray(t),e));return r?n[0]:n}async rename(t,e){await this.writer.rename(t,e)}async delete(t){await this.writer.delete(O.toArray(t))}async retrieve(t){const e=typeof t=="string",{ranges:r}=await m(this.unaryClient,Ym,t,qm,Hm);return yt("Range",t,r,e),e?this.sugarMany(r)[0]:this.sugarMany(r)}getKV(t){return new Ye(t,this.unaryClient)}async retrieveParent(t){const e=await this.ontologyClient.retrieveParents(tt(t));if(e.length===0)return null;const r=e[0];return r.id.type!=="range"?null:await this.retrieve(r.id.key)}sugarOntologyResource(t){return this.sugarOne(tl(t))}async retrieveAlias(t,e){return await new Qe(t,this.frameClient,this.unaryClient).retrieve(e)}async retrieveAliases(t,e){return await new Qe(t,this.frameClient,this.unaryClient).retrieve(e)}async listAliases(t){return await new Qe(t,this.frameClient,this.unaryClient).list()}async setAlias(t,e,r){await new Qe(t,this.frameClient,this.unaryClient).set({[e]:r})}sugarOne(t){return new Qo(t,{frameClient:this.frameClient,kv:new Ye(t.key,this.unaryClient),aliaser:new Qe(t.key,this.frameClient,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(t){return t.map(e=>this.sugarOne(e))}resourceToRange(t){return this.sugarOne({key:t.id.key,name:t.data?.name,timeRange:new L(t.data?.timeRange),color:t.data?.color,labels:[],parent:null})}};const tt=t=>({type:"range",key:t}),Vm=t=>({type:"range-alias",key:t}),tl=({data:t,id:{key:e},name:r})=>{const n=L.z.parse(t?.timeRange);return{key:e,name:r,timeRange:n,color:typeof t?.color=="string"?t.color:void 0,labels:[],parent:null}},_m=s.z.object({ranges:er.array()}),Wm=s.z.object({parent:M.optional(),ranges:Jo.array()}),Gm=s.z.object({keys:H.array()}),Km=s.z.object({}),Jm=s.z.object({key:H,name:Ns}),Xm=s.z.object({}),Qm="/range/create",ew="/range/delete",tw="/range/rename";class rl{client;constructor(e){this.client=e}async rename(e,r){await m(this.client,tw,{key:e,name:r},Jm,Xm)}async create(e,r){return(await m(this.client,Qm,{ranges:e,...r},Wm,_m)).ranges}async delete(e){await m(this.client,ew,{keys:e},Gm,Km)}}const rw=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:Qe,Client:el,DELETE_ALIAS_CHANNEL_NAME:bm,DELETE_CHANNEL_NAME:Fm,KV:Ye,KV_DELETE_CHANNEL:Um,KV_SET_CHANNEL:Rm,Range:Qo,SET_ALIAS_CHANNEL_NAME:wm,SET_CHANNEL_NAME:Bm,Writer:rl,aliasKey:Im,aliasOntologyID:Vm,aliasZ:Cm,convertOntologyResourceToPayload:tl,decodeDeleteAliasChange:jm,keyZ:H,kvPairKey:Mm,kvPairZ:As,nameZ:Ns,newZ:Jo,ontologyID:tt,payloadZ:er},Symbol.toStringTag,{value:"Module"})),nw="/api/v1/";class sw{url;unary;stream;secure;constructor(e,r={},n=!1){this.secure=n,this.url=e.child(nw);const a=new He.JSONCodec;this.unary=Pu(new Lu(this.url,a,this.secure),r),this.stream=new Zu(this.url,a,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const tr=s.z.uuid(),ks=s.z.object({key:tr,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te))}),aw=ks.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ge=s.z.uuid(),Hr=s.z.object({key:ge,name:s.z.string(),layout:ve.unknownZ.or(s.z.string().transform(Te))}),nl=Hr.partial({key:!0}).transform(t=>({...t,layout:JSON.stringify(t.layout)})),sl=Hr.omit({layout:!0}).extend({layout:s.z.string().transform(Te)}),iw="/workspace/lineplot/retrieve",ow="/workspace/lineplot/create",lw="/workspace/lineplot/rename",cw="/workspace/lineplot/set-data",uw="/workspace/lineplot/delete",hw=s.z.object({keys:tr.array()}),dw=s.z.object({workspace:ge,linePlots:aw.array()}),fw=s.z.object({key:tr,name:s.z.string()}),pw=s.z.object({key:tr,data:s.z.string()}),yw=s.z.object({keys:tr.array()}),gw=s.z.object({linePlots:Y(ks)}),mw=s.z.object({linePlots:ks.array()}),un=s.z.object({});let ww=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,ow,{workspace:t,linePlots:O.toArray(e)},dw,mw);return r?n.linePlots:n.linePlots[0]}async rename(t,e){await m(this.client,lw,{key:t,name:e},fw,un)}async setData(t,e){await m(this.client,cw,{key:t,data:JSON.stringify(e)},pw,un)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,iw,{keys:O.toArray(t)},hw,gw);return e?r.linePlots:r.linePlots[0]}async delete(t){await m(this.client,uw,{keys:O.toArray(t)},yw,un)}};const rr=s.z.uuid(),xs=s.z.object({key:rr,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te))}),bw=xs.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),vw="/workspace/log/retrieve",Tw="/workspace/log/create",Ow="/workspace/log/rename",Sw="/workspace/log/set-data",zw="/workspace/log/delete",Ew=s.z.object({keys:rr.array()}),Nw=s.z.object({workspace:ge,logs:bw.array()}),Aw=s.z.object({key:rr,name:s.z.string()}),kw=s.z.object({key:rr,data:s.z.string()}),xw=s.z.object({keys:rr.array()}),Cw=s.z.object({logs:xs.array()}),Iw=s.z.object({logs:xs.array()}),hn=s.z.object({});let jw=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,Tw,{workspace:t,logs:O.toArray(e)},Nw,Iw);return r?n.logs:n.logs[0]}async rename(t,e){await m(this.client,Ow,{key:t,name:e},Aw,hn)}async setData(t,e){await m(this.client,Sw,{key:t,data:JSON.stringify(e)},kw,hn)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,vw,{keys:O.toArray(t)},Ew,Cw);return e?r.logs:r.logs[0]}async delete(t){await m(this.client,zw,{keys:O.toArray(t)},xw,hn)}};const mt=s.z.uuid(),Cs=s.z.object({key:mt,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te)),snapshot:s.z.boolean()}),Rw=Cs.partial({key:!0,snapshot:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),al=Cs.extend({data:s.z.string().transform(Te)}),Uw="/workspace/schematic/retrieve",Mw="/workspace/schematic/create",Lw="/workspace/schematic/rename",Pw="/workspace/schematic/set-data",Dw="/workspace/schematic/delete",$w="/workspace/schematic/copy",Bw=s.z.object({keys:mt.array()}),Fw=s.z.object({workspace:ge,schematics:Rw.array()}),Zw=s.z.object({key:mt,name:s.z.string()}),qw=s.z.object({key:mt,data:s.z.string()}),Yw=s.z.object({keys:mt.array()}),Hw=s.z.object({key:mt,name:s.z.string(),snapshot:s.z.boolean()}),Vw=s.z.object({schematics:Y(al)}),_w=s.z.object({schematics:al.array()}),Ww=s.z.object({schematic:Cs}),dn=s.z.object({});let Gw=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,Mw,{workspace:t,schematics:O.toArray(e)},Fw,_w);return r?n.schematics:n.schematics[0]}async rename(t,e){await m(this.client,Lw,{key:t,name:e},Zw,dn)}async setData(t,e){await m(this.client,Pw,{key:t,data:JSON.stringify(e)},qw,dn)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,Uw,{keys:O.toArray(t)},Bw,Vw);return e?r.schematics:r.schematics[0]}async delete(t){await m(this.client,Dw,{keys:O.toArray(t)},Yw,dn)}async copy(t,e,r){return(await m(this.client,$w,{key:t,name:e,snapshot:r},Hw,Ww)).schematic}};const nr=s.z.uuid(),il=s.z.object({key:nr,name:s.z.string(),data:ve.unknownZ.or(s.z.string().transform(Te))}),Kw=il.partial({key:!0}).transform(t=>({...t,data:JSON.stringify(t.data)})),ol=il.extend({data:s.z.string().transform(Te)}),Jw="/workspace/table/retrieve",Xw="/workspace/table/create",Qw="/workspace/table/rename",eb="/workspace/table/set-data",tb="/workspace/table/delete",rb=s.z.object({keys:nr.array()}),nb=s.z.object({workspace:ge,tables:Kw.array()}),sb=s.z.object({key:nr,name:s.z.string()}),ab=s.z.object({key:nr,data:s.z.string()}),ib=s.z.object({keys:nr.array()}),ob=s.z.object({tables:ol.array()}),lb=s.z.object({tables:ol.array()}),fn=s.z.object({});let cb=class{client;constructor(t){this.client=t}async create(t,e){const r=Array.isArray(e),n=await m(this.client,Xw,{workspace:t,tables:O.toArray(e)},nb,lb);return r?n.tables:n.tables[0]}async rename(t,e){await m(this.client,Qw,{key:t,name:e},sb,fn)}async setData(t,e){await m(this.client,eb,{key:t,data:JSON.stringify(e)},ab,fn)}async retrieve(t){const e=Array.isArray(t),r=await m(this.client,Jw,{keys:O.toArray(t)},rb,ob);return e?r.tables:r.tables[0]}async delete(t){await m(this.client,tb,{keys:O.toArray(t)},ib,fn)}};const Na="/workspace/retrieve",ub="/workspace/create",hb="/workspace/rename",db="/workspace/set-layout",fb="/workspace/delete",Aa=s.z.object({keys:ge.array().optional(),searchTerm:s.z.string().optional(),author:_e.optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),pb=s.z.object({workspaces:nl.array()}),yb=s.z.object({key:ge,name:s.z.string()}),gb=s.z.object({key:ge,layout:s.z.string()}),mb=s.z.object({keys:ge.array()}),ka=s.z.object({workspaces:Y(Hr)}),wb=s.z.object({workspaces:sl.array()}),pn=s.z.object({}),bb="sy_workspace_set",vb="sy_workspace_delete";class ll{type="workspace";schematic;linePlot;log;table;client;constructor(e){this.client=e,this.schematic=new Gw(e),this.linePlot=new ww(e),this.log=new jw(e),this.table=new cb(e)}async create(e){const r=Array.isArray(e),n=await m(this.client,ub,{workspaces:O.toArray(e)},pb,wb);return r?n.workspaces:n.workspaces[0]}async rename(e,r){await m(this.client,hb,{key:e,name:r},yb,pn)}async setLayout(e,r){await m(this.client,db,{key:e,layout:JSON.stringify(r)},gb,pn)}async retrieve(e){let r;const n=typeof e!="string";typeof e=="string"||Array.isArray(e)?r={keys:O.toArray(e)}:r=e;const a=await m(this.client,Na,r,Aa,ka);return n?a.workspaces:a.workspaces[0]}async retrieveByAuthor(e){return(await m(this.client,Na,{author:e},Aa,ka)).workspaces}async delete(e){await m(this.client,fb,{keys:O.toArray(e)},mb,pn)}}const Tb=t=>({type:"workspace",key:t}),Ob=Object.freeze(Object.defineProperty({__proto__:null,Client:ll,DELETE_CHANNEL_NAME:vb,SET_CHANNEL_NAME:bb,keyZ:ge,newZ:nl,ontologyID:Tb,remoteZ:sl,workspaceZ:Hr},Symbol.toStringTag,{value:"Module"})),cl=s.z.object({host:s.z.string({error:"Host is required"}).min(1,"Host is required"),port:s.z.number({error:"Port is required"}).or(s.z.string({error:"Port is required"})),username:s.z.string().min(1,"Username is required"),password:s.z.string().min(1,"Password is required"),connectivityPollFrequency:z.z.default(z.seconds(30)),secure:s.z.boolean().optional().default(!1),name:s.z.string().optional(),retry:Di.breakerConfigZ.optional()});class Sb extends ko{createdAt;props;ranges;channels;auth;user;access;connectivity;ontology;workspaces;labels;hardware;control;static connectivity=Er;transport;clientVersion="0.44.4";constructor(e){const r=cl.parse(e),{host:n,port:a,username:i,password:o,connectivityPollFrequency:l,secure:c,retry:u}=r,h=new sw(new kt({host:n,port:Number(a)}),u,c);h.use(Ef);let p;i!=null&&o!=null&&(p=new my(h.unary,{username:i,password:o}),h.use(p.middleware()));const d=new ws(new Jt(h.unary)),S=new yo(h.unary,d);super(h.stream,h.unary,d),this.createdAt=E.now(),this.props=r,this.auth=p,this.transport=h,this.channels=new ho(this,d,h.unary,S),this.connectivity=new Er(h.unary,l,this.clientVersion,r.name),this.control=new Io(this),this.ontology=new ao(h.unary,this);const N=new rl(this.transport.unary);this.labels=new Ko(this.transport.unary),this.ranges=new el(this,N,this.transport.unary,d,this.labels,this.ontology),this.access=new mp(this.transport.unary),this.user=new cy(this.transport.unary),this.workspaces=new ll(this.transport.unary);const x=new Po(this.transport.unary),$=new Yo(this.transport.unary,this,this.ontology,this.ranges),I=new Do(this.transport.unary,$);this.hardware=new Qy($,I,x)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}z.seconds(1);const zb=t=>Array.isArray(t)?t:t==null?[]:[t],Eb=Object.freeze(Object.defineProperty({__proto__:null,toArray:zb},Symbol.toStringTag,{value:"Module"})),yn=t=>t!=null&&typeof t=="object"&&!Array.isArray(t),Nb=(t,e)=>{let r=null;return e===0?t:(...n)=>{r!==null&&(clearTimeout(r),r=null),r=setTimeout(()=>t(...n),e)}},Ab=(t,e)=>{let r=null;return e===0?t:(...n)=>{r===null&&(r=setTimeout(()=>{t(...n),r=null},e))}},ul=(t,e,r=".")=>{const n=t.split(r);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(r)}).filter(a=>a!=null).join(r)},Is=(t,e)=>{if(!Array.isArray(t))return t[e];const r=t[e];if(r!=null||t.length==0)return r;const n=t[0];if(typeof n=="object"&&"key"in n)return t.find(a=>a.key===e)},kb=(t,e)=>{const r=t.split(".");return r.forEach((n,a)=>{e=Is(e,n),e!=null&&typeof e=="object"&&"key"in e&&(r[a]=e.key)}),r.join(".")},js=(t,e,r={optional:!1,separator:"."})=>{r.separator??=".";const{optional:n,getter:a=Is}=r,i=e.split(r.separator);if(i.length===1&&i[0]==="")return t;let o=t;for(const l of i){const c=a(o,l);if(c==null){if(n)return null;throw new Error(`Path ${e} does not exist. ${l} is null`)}o=c}return o},xb=t=>{for(const e of t)if(isNaN(parseInt(e)))return null;return parseInt(t)},Cb=(t,e,r)=>{const n=e.split(".");let a=t;for(let i=0;i<n.length-1;i++){const o=n[i],l=Is(a,o);if(l==null)throw new Error(`Path ${e} does not exist. ${o} is null`);a=l}try{if(!Array.isArray(a)){a[n[n.length-1]]=r;return}if(a.length===0)return;const i=xb(n[n.length-1]);if(i==null){const o=a[0];if(typeof o=="object"&&"key"in o){const l=a.findIndex(c=>c.key===n[n.length-1]);if(l!==-1){a[l]=r;return}}return}a[i]=r}catch(i){throw console.error("failed to set value",r,"at path",e,"on object",t),i}},Ib=(t,e)=>{const r=e.split(".");let n=t;for(let a=0;a<r.length-1;a++){const i=r[a];if(n[i]==null)return;n=n[i]}if(Array.isArray(n)){const a=parseInt(r[r.length-1]);if(isNaN(a))return;n.splice(a,1);return}delete n[r[r.length-1]]},jb=(t,e)=>{const r=t.split(".");return e<0?r[r.length+e]:r[e]},Rb=(t,e)=>{try{return js(t,e),!0}catch{return!1}},Ub=(t,e)=>{if(e.length===0)return!0;const r=t.split("."),n=e.split(".");if(n.length>r.length)return!1;for(let a=0;a<n.length;a++){const i=r[a],o=n[a];if(o!=="*"&&i!==o)return!1}return!0},Mb=t=>{try{return structuredClone(t)}catch{return console.warn("Failed to deep copy object, falling back to JSON.parse(JSON.stringify)",t),console.trace(),JSON.parse(JSON.stringify(t))}},Lb=(t,...e)=>(e.forEach(r=>{let n=t;const a=r.split(".");a.forEach((i,o)=>{typeof n!="object"||n===null||(o===a.length-1?delete n[i]:i in n&&(n=n[i]))})}),t),Pb=(t,e,r="")=>{const n={},a=(i,o,l)=>{if(typeof i!=typeof o||i===null||o===null){n[l]=[i,o];return}if(typeof i=="object"&&typeof o=="object")if(Array.isArray(i)&&Array.isArray(o)){if(i.length!==o.length){n[l]=[i,o];return}for(let c=0;c<i.length;c++)a(i[c],o[c],`${l}[${c}]`)}else new Set([...Object.keys(i),...Object.keys(o)]).forEach(c=>{a(i[c],o[c],l!==""?`${l}.${c}`:c)});else i!==o&&(n[l]=[i,o])};return a(t,e,r),n},qn=(t,e)=>{const r=Array.isArray(t),n=Array.isArray(e);if(r!==n)return!1;if(r&&n){const o=t,l=e;if(o.length!==l.length)return!1;for(let c=0;c<o.length;c++)if(!qn(o[c],l[c]))return!1;return!0}if(t==null||e==null||typeof t!="object"||typeof e!="object")return t===e;if("equals"in t)return t.equals(e);const a=Object.keys(t),i=Object.keys(e);if(a.length!==i.length)return!1;for(const o of a){const l=t[o],c=e[o];if(typeof l=="object"&&typeof c=="object"){if(!qn(l,c))return!1}else if(l!==c)return!1}return!0},hl=(t,e)=>{if(typeof t!="object"||t==null)return t===e;const r=Object.keys(t),n=Object.keys(e);if(n.length>r.length)return!1;for(const a of n){const i=t[a],o=e[a];if(typeof i=="object"&&typeof o=="object"){if(!hl(i,o))return!1}else if(i!==o)return!1}return!0},Yn=(t,...e)=>{if(e.length===0)return t;const r=e.shift();if(yn(t)&&yn(r))for(const n in r)try{yn(r[n])?(n in t||Object.assign(t,{[n]:{}}),Yn(t[n],r[n])):Object.assign(t,{[n]:r[n]})}catch(a){throw a instanceof TypeError?new TypeError(`.${n}: ${a.message}`):a}return Yn(t,...e)},Db=(t,e,r)=>{const n=(a,i,o)=>{if(o.def?.type==="union")return o.def.options.reduce((l,c)=>n(l,i,c),a);if(o.def?.type==="intersection"){const l=n(a,i,o.def.left);return n(l,i,o.def.right)}for(const l in i){const c=i[l];let u=o?.shape;if(u!=null)for(;u!=null;){if(u[l]!=null){const h=u[l].safeParse(c);if(h.success){a[l]=h.data;break}}u=u.def?.shape}typeof c=="object"&&!Array.isArray(c)&&c!==null&&o&&o.shape&&o.shape[l]&&(a[l]||={},n(a[l],c,o.shape[l]))}return a};return n({...t},e,r)},dl=Object.freeze(Object.defineProperty({__proto__:null,copy:Mb,deleteD:Lb,difference:Pb,element:jb,equal:qn,get:js,has:Rb,override:Yn,overrideValidItems:Db,partialEqual:hl,pathsMatch:Ub,remove:Ib,resolvePath:kb,set:Cb,transformPath:ul},Symbol.toStringTag,{value:"Module"}));let $b=class{sender;handlers;constructor(e){this.sender=e,this.handlers=new Map}handle({data:e}){const r=this.handlers.get(e.type)?.handler;r==null?console.warn(`No handler for ${e.type}`):r(e.payload)}route(e){const r=Bb(e,this.sender),n=new Fb(r);return this.handlers.set(e,n),n}};const Bb=(t,e)=>(r,n)=>e({type:t,payload:r},n);class Fb{_send;handler;constructor(e){this._send=e,this.handler=null}send(e,r=[]){this._send(e,r)}handle(e){this.handler=e}}const Hn=(t,e,r="")=>{try{return t.parse(e)}catch(n){if(n instanceof s.z.ZodError){const a=n.issues.map(i=>i.path.length===0?i.message:`${i.path.join(".")}: ${i.message}`);throw new Error(`${r} - ${a.join(`
|
|
45
|
+
`)}`)}else throw n}},fl=t=>typeof t=="function",Rs=(t,e)=>fl(t)?t(e):t,Vr=t=>pl(t)?t():t,pl=t=>typeof t=="function",yl=({initial:t,value:e,onChange:r})=>{const[n,a]=rs.useState(e??t);return e!=null&&r!=null?[e,r]:[n,a]},gl=({initial:t,value:e,onChange:r})=>{const[n,a]=rs.useState(Vr(e??t));return e!=null&&r!=null?[e,r]:[n,a]},Zb=(t,e)=>{const[r,n]=rs.useState(()=>{const a=localStorage.getItem(e);return a==null?Vr(t):JSON.parse(a)});return[r,a=>{n(a),localStorage.setItem(e,JSON.stringify(a))}]},qb=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:Vr,executeSetter:Rs,isInitialSetter:pl,isSetter:fl,usePassthrough:yl,usePersisted:Zb,usePurePassthrough:gl},Symbol.toStringTag,{value:"Module"}));let xa=null;const Yb=()=>(xa??=document.createElement("canvas"),xa),Hb=(t,e,r)=>{if(f.S.RUNTIME==="node")return{width:0,height:0};r??=Yb().getContext("2d"),r.font=e;const n=r.measureText(t);return _r(n)},_r=t=>({width:Math.trunc(Math.abs(t.actualBoundingBoxLeft)+Math.abs(t.actualBoundingBoxRight)),height:Math.trunc(Math.abs(t.actualBoundingBoxAscent)+Math.abs(t.actualBoundingBoxDescent))}),Ct=["h1","h2","h3","h4","h5","p","small"],Vb=s.z.enum(Ct),_b=t=>{const e=Ct.indexOf(t);return e===-1||e===Ct.length-1?t:Ct[e+1]},Wb=s.z.union([s.z.number(),s.z.enum(["normal","bold","bolder","lighter"])]),xe=s.z.object({size:s.z.number(),weight:s.z.union([s.z.number(),s.z.string()]),lineHeight:s.z.number(),textTransform:s.z.string().optional()}),Gb={tiny:"small",small:"small",medium:"p",large:"h5",huge:"h2"},Kb={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"},Jb=s.z.object({l0:f.cr.colorZ,l1:f.cr.colorZ,l2:f.cr.colorZ,l3:f.cr.colorZ,l4:f.cr.colorZ,l5:f.cr.colorZ,l6:f.cr.colorZ,l7:f.cr.colorZ,l8:f.cr.colorZ,l9:f.cr.colorZ,l10:f.cr.colorZ,l11:f.cr.colorZ}),Q=(t,e)=>[t[0],t[1],e,t[3]],Xb=s.z.object({m2:f.cr.colorZ,m1:f.cr.colorZ,z:f.cr.colorZ,p1:f.cr.colorZ,p2:f.cr.colorZ}),ur=Xb.or(f.cr.colorZ.transform(t=>{const e=f.cr.hsla(t);return{m2:f.cr.fromHSLA(Q(e,40)),m1:f.cr.fromHSLA(Q(e,45)),z:t,p1:f.cr.fromHSLA(Q(e,55)),p2:f.cr.fromHSLA(Q(e,65))}})),ml=s.z.object({name:s.z.string(),key:s.z.string(),colors:s.z.object({border:f.cr.colorZ,primary:ur,gray:Jb,error:ur,secondary:ur,warning:ur,palettes:s.z.record(s.z.string(),f.cr.paletteZ),visualization:s.z.object({palettes:s.z.record(s.z.string(),s.z.array(f.cr.colorZ))}).optional().default({palettes:{}}),white:f.cr.colorZ,black:f.cr.colorZ,text:f.cr.colorZ,textInverted:f.cr.colorZ,textOnPrimary:f.cr.colorZ.optional().default(f.cr.ZERO),logo:s.z.string()}),sizes:s.z.object({base:s.z.number(),border:s.z.object({radius:s.z.number(),width:s.z.number(),thickWidth:s.z.number()}),schematic:s.z.object({elementStrokeWidth:s.z.number()})}),typography:s.z.object({family:s.z.string(),codeFamily:s.z.string(),h1:xe,h2:xe,h3:xe,h4:xe,h5:xe,p:xe,small:xe})}).transform(t=>((t.colors.textOnPrimary==null||f.cr.isZero(t.colors.textOnPrimary))&&(t.colors.textOnPrimary=f.cr.pickByContrast(t.colors.primary.z,t.colors.text,t.colors.textInverted)),t)),Qb="'Inter Variable', sans-serif",ev="'Geist Mono', monospace",tv=6,vt=[357,91,55,1],Tt=[48,90,55,1],rv=["#FEFEFE","#FAFAFA","#F2F2F2","#ECECEC","#E4E4E4","#D1D1D1","#BCBCBC","#ACACAC","#8F8F8F","#4F4F4F","#292929","#050505"],Ot=Object.fromEntries(rv.map((t,e)=>[`l${e}`,t])),nv=()=>typeof window>"u"?!1:window.devicePixelRatio>1,sv=nv(),Vn={key:"synnaxBase",name:"Synnax Base",colors:{primary:{m2:"#041B3D",m1:"#356fc5",z:"#3774D0",p1:"#5E94EE",p2:"#8AB8FF"},secondary:{m2:"#2D8F4E",m1:"#38B261",z:"#50C878",p1:"#73D393",p2:"#96DEAE"},gray:Ot,border:Ot.l4,error:{m2:f.cr.fromHSLA(Q(vt,30)),m1:f.cr.fromHSLA(Q(vt,40)),z:f.cr.fromHSLA(vt),p1:f.cr.fromHSLA(Q(vt,65)),p2:f.cr.fromHSLA(Q(vt,77))},warning:{m2:f.cr.fromHSLA(Q(Tt,30)),m1:f.cr.fromHSLA(Q(Tt,40)),z:f.cr.fromHSLA(Tt),p1:f.cr.fromHSLA(Q(Tt,65)),p2:f.cr.fromHSLA(Q(Tt,75))},palettes:{recent:{key:"recent",name:"Recent",swatches:[]}},visualization:{palettes:{default:["#DC136C","#20A4F3","#7AC74F","#FFC43D","#FE5F55","#8075FF","#D90429","#f7aef8","#f18f01","#791e94","#279af1","#d9fff5","#ff6b6b","#52ffb8"]}},logo:"url(#synnax-linear-gradient)",white:"#FFFFFF",black:"#000000",text:Ot.l11,textInverted:Ot.l0,textOnPrimary:Ot.l0},sizes:{base:tv,border:{radius:3,width:sv?.5:1,thickWidth:1},schematic:{elementStrokeWidth:2}},typography:{family:Qb,codeFamily:ev,h1:{size:6,weight:"500",lineHeight:6*1.5},h2:{size:4.5,weight:"medium",lineHeight:4.5*1.5},h3:{size:3.5,weight:"medium",lineHeight:3.5*1.5},h4:{size:2.6666,weight:"medium",lineHeight:2.6666*1.5},h5:{size:2.333333,weight:450,lineHeight:2.333333*1.5},p:{size:2.1666666666,weight:"regular",lineHeight:2*1.5},small:{size:1.916666,weight:"regular",lineHeight:2.3333333}}},wl=Object.freeze({...Vn,key:"synnaxLight",name:"Synnax Light"}),av=["#020202","#080808","#151515","#242424","#2F2F2F","#3B3B3B","#4A4A4A","#5C5C5C","#767676","#959595","#dadada","#FAFAFA"],St=Object.fromEntries(av.map((t,e)=>[`l${e}`,t])),bl=Object.freeze({...Vn,key:"synnaxDark",name:"Synnax Dark",colors:{...Vn.colors,gray:St,logo:"var(--pluto-text-color)",border:St.l3,text:St.l11,textInverted:St.l0,textOnPrimary:St.l11}}),iv={synnaxDark:bl,synnaxLight:wl},vl=["tiny","small","medium","large","huge"],Tl=s.z.enum(vl),ov=t=>Tl.safeParse(t).success;class lt{_noop=!1;key;path;serviceName;constructor(e,r,n="",a=!1){this.key=e,this.path=r,this.serviceName=n,this._noop=a}child(e){return new lt(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}static NOOP=new lt("","","")}const _n=["debug","info","warn","error"],Ol=t=>{const e=_n.indexOf(t);return({level:r})=>_n.indexOf(r)>=e},lv=t=>{const{include:e,exclude:r}=t;return({path:n})=>!(e!=null&&!e.some(a=>n.startsWith(a))||r!=null&&r.some(a=>n.startsWith(a)))};class ct{meta=lt.NOOP;filters;constructor(e={}){const{filters:r=[]}=e;this.filters=r}filter(e){return!this.meta.noop&&this.filters.every(r=>r({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const r=new ct({filters:this.filters});return r.meta=e,r}debug(e,r,n=!1){!this.filter("debug")&&!n||(r==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,hr(r)))}info(e,r,n=!1){!this.filter("info")&&!n||(r==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,hr(r)))}warn(e,r,n=!1){!this.filter("warn")&&!n||(r==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,hr(r)))}error(e,r,n=!1){!this.filter("error")&&!n||(r==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,hr(r)))}static NOOP=new ct}const hr=t=>typeof t=="function"?t():t;var cv=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Fe="1.9.0",Ca=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function uv(t){var e=new Set([t]),r=new Set,n=t.match(Ca);if(!n)return function(){return!1};var a={major:+n[1],minor:+n[2],patch:+n[3],prerelease:n[4]};if(a.prerelease!=null)return function(l){return l===t};function i(l){return r.add(l),!1}function o(l){return e.add(l),!0}return function(l){if(e.has(l))return!0;if(r.has(l))return!1;var c=l.match(Ca);if(!c)return i(l);var u={major:+c[1],minor:+c[2],patch:+c[3],prerelease:c[4]};return u.prerelease!=null||a.major!==u.major?i(l):a.major===0?a.minor===u.minor&&a.patch<=u.patch?o(l):i(l):a.minor<=u.minor?o(l):i(l)}}var hv=uv(Fe),dv=Fe.split(".")[0],Pt=Symbol.for("opentelemetry.js.api."+dv),Dt=cv;function Us(t,e,r,n){var a;n===void 0&&(n=!1);var i=Dt[Pt]=(a=Dt[Pt])!==null&&a!==void 0?a:{version:Fe};if(!n&&i[t]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+t);return r.error(o.stack||o.message),!1}if(i.version!==Fe){var o=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+t+" does not match previously registered API v"+Fe);return r.error(o.stack||o.message),!1}return i[t]=e,r.debug("@opentelemetry/api: Registered a global for "+t+" v"+Fe+"."),!0}function $t(t){var e,r,n=(e=Dt[Pt])===null||e===void 0?void 0:e.version;if(!(!n||!hv(n)))return(r=Dt[Pt])===null||r===void 0?void 0:r[t]}function Ms(t,e){e.debug("@opentelemetry/api: Unregistering a global for "+t+" v"+Fe+".");var r=Dt[Pt];r&&delete r[t]}var fv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},pv=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},yv=function(){function t(e){this._namespace=e.namespace||"DiagComponentLogger"}return t.prototype.debug=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("debug",this._namespace,e)},t.prototype.error=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("error",this._namespace,e)},t.prototype.info=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("info",this._namespace,e)},t.prototype.warn=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("warn",this._namespace,e)},t.prototype.verbose=function(){for(var e=[],r=0;r<arguments.length;r++)e[r]=arguments[r];return zt("verbose",this._namespace,e)},t}();function zt(t,e,r){var n=$t("diag");if(n)return r.unshift(e),n[t].apply(n,pv([],fv(r),!1))}var J;(function(t){t[t.NONE=0]="NONE",t[t.ERROR=30]="ERROR",t[t.WARN=50]="WARN",t[t.INFO=60]="INFO",t[t.DEBUG=70]="DEBUG",t[t.VERBOSE=80]="VERBOSE",t[t.ALL=9999]="ALL"})(J||(J={}));function gv(t,e){t<J.NONE?t=J.NONE:t>J.ALL&&(t=J.ALL),e=e||{};function r(n,a){var i=e[n];return typeof i=="function"&&t>=a?i.bind(e):function(){}}return{error:r("error",J.ERROR),warn:r("warn",J.WARN),info:r("info",J.INFO),debug:r("debug",J.DEBUG),verbose:r("verbose",J.VERBOSE)}}var mv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},wv=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},bv="diag",Bt=function(){function t(){function e(a){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var l=$t("diag");if(l)return l[a].apply(l,wv([],mv(i),!1))}}var r=this,n=function(a,i){var o,l,c;if(i===void 0&&(i={logLevel:J.INFO}),a===r){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return r.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof i=="number"&&(i={logLevel:i});var h=$t("diag"),p=gv((l=i.logLevel)!==null&&l!==void 0?l:J.INFO,a);if(h&&!i.suppressOverrideMessage){var d=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";h.warn("Current logger will be overwritten from "+d),p.warn("Current logger will overwrite one already registered from "+d)}return Us("diag",p,r,!0)};r.setLogger=n,r.disable=function(){Ms(bv,r)},r.createComponentLogger=function(a){return new yv(a)},r.verbose=e("verbose"),r.debug=e("debug"),r.info=e("info"),r.warn=e("warn"),r.error=e("error")}return t.instance=function(){return this._instance||(this._instance=new t),this._instance},t}(),vv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},Tv=function(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Ov=function(){function t(e){this._entries=e?new Map(e):new Map}return t.prototype.getEntry=function(e){var r=this._entries.get(e);if(r)return Object.assign({},r)},t.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var r=vv(e,2),n=r[0],a=r[1];return[n,a]})},t.prototype.setEntry=function(e,r){var n=new t(this._entries);return n._entries.set(e,r),n},t.prototype.removeEntry=function(e){var r=new t(this._entries);return r._entries.delete(e),r},t.prototype.removeEntries=function(){for(var e,r,n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];var i=new t(this._entries);try{for(var o=Tv(n),l=o.next();!l.done;l=o.next()){var c=l.value;i._entries.delete(c)}}catch(u){e={error:u}}finally{try{l&&!l.done&&(r=o.return)&&r.call(o)}finally{if(e)throw e.error}}return i},t.prototype.clear=function(){return new t},t}();Bt.instance();function Sv(t){return t===void 0&&(t={}),new Ov(new Map(Object.entries(t)))}function zv(t){return Symbol.for(t)}var Ev=function(){function t(e){var r=this;r._currentContext=e?new Map(e):new Map,r.getValue=function(n){return r._currentContext.get(n)},r.setValue=function(n,a){var i=new t(r._currentContext);return i._currentContext.set(n,a),i},r.deleteValue=function(n){var a=new t(r._currentContext);return a._currentContext.delete(n),a}}return t}(),Nv=new Ev,Av={get:function(t,e){if(t!=null)return t[e]},keys:function(t){return t==null?[]:Object.keys(t)}},kv={set:function(t,e,r){t!=null&&(t[e]=r)}},xv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},Cv=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},Iv=function(){function t(){}return t.prototype.active=function(){return Nv},t.prototype.with=function(e,r,n){for(var a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return r.call.apply(r,Cv([n],xv(a),!1))},t.prototype.bind=function(e,r){return r},t.prototype.enable=function(){return this},t.prototype.disable=function(){return this},t}(),jv=function(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),a,i=[],o;try{for(;(e===void 0||e-- >0)&&!(a=n.next()).done;)i.push(a.value)}catch(l){o={error:l}}finally{try{a&&!a.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return i},Rv=function(t,e,r){if(arguments.length===2)for(var n=0,a=e.length,i;n<a;n++)(i||!(n in e))&&(i||(i=Array.prototype.slice.call(e,0,n)),i[n]=e[n]);return t.concat(i||Array.prototype.slice.call(e))},gn="context",Uv=new Iv,Sl=function(){function t(){}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalContextManager=function(e){return Us(gn,e,Bt.instance())},t.prototype.active=function(){return this._getContextManager().active()},t.prototype.with=function(e,r,n){for(var a,i=[],o=3;o<arguments.length;o++)i[o-3]=arguments[o];return(a=this._getContextManager()).with.apply(a,Rv([e,r,n],jv(i),!1))},t.prototype.bind=function(e,r){return this._getContextManager().bind(e,r)},t.prototype._getContextManager=function(){return $t(gn)||Uv},t.prototype.disable=function(){this._getContextManager().disable(),Ms(gn,Bt.instance())},t}(),Wn;(function(t){t[t.UNSET=0]="UNSET",t[t.OK=1]="OK",t[t.ERROR=2]="ERROR"})(Wn||(Wn={}));var Mv=Sl.getInstance(),Lv=function(){function t(){}return t.prototype.inject=function(e,r){},t.prototype.extract=function(e,r){return e},t.prototype.fields=function(){return[]},t}(),Ls=zv("OpenTelemetry Baggage Key");function zl(t){return t.getValue(Ls)||void 0}function Pv(){return zl(Sl.getInstance().active())}function Dv(t,e){return t.setValue(Ls,e)}function $v(t){return t.deleteValue(Ls)}var mn="propagation",Bv=new Lv,Fv=function(){function t(){this.createBaggage=Sv,this.getBaggage=zl,this.getActiveBaggage=Pv,this.setBaggage=Dv,this.deleteBaggage=$v}return t.getInstance=function(){return this._instance||(this._instance=new t),this._instance},t.prototype.setGlobalPropagator=function(e){return Us(mn,e,Bt.instance())},t.prototype.inject=function(e,r,n){return n===void 0&&(n=kv),this._getGlobalPropagator().inject(e,r,n)},t.prototype.extract=function(e,r,n){return n===void 0&&(n=Av),this._getGlobalPropagator().extract(e,r,n)},t.prototype.fields=function(){return this._getGlobalPropagator().fields()},t.prototype.disable=function(){Ms(mn,Bt.instance())},t.prototype._getGlobalPropagator=function(){return $t(mn)||Bv},t}(),Zv=Fv.getInstance();const Ia=["bench","debug","prod"],qv=t=>e=>Ia.indexOf(e)>=Ia.indexOf(t);class Ft{meta=lt.NOOP;otelTracer;filter;constructor(e,r=qv("debug")){this.otelTracer=e,this.filter=r}child(e){const r=new Ft(this.otelTracer,this.filter);return r.meta=e,r}debug(e,r){return this.trace(e,"debug",r)}bench(e,r){return this.trace(e,"bench",r)}prod(e,r){return this.trace(e,"prod",r)}trace(e,r,n){const a=this.meta.noop||!this.filter(r)||this.otelTracer==null;if(n==null){if(a)return()=>{};const i=new Gn(e,this.otelTracer.startSpan(e));return i.start(),()=>i.end()}return a?n(new El(e)):this.otelTracer.startActiveSpan(e,i=>{const o=new Gn(e,i);return n(o)})}propagate(e){if(this.meta.noop)return;const r=Mv.active();Zv.inject(r,e,{set:(n,a,i)=>{n[a]=i}})}static NOOP=new Ft}class Gn{key;otel;constructor(e,r){this.key=e,this.otel=r}set(e,r){this.otel.setAttribute(e,r)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:Wn.ERROR}))}start(){performance.mark(`alamos.trace.start.${this.key}`)}end(){try{performance.mark(`alamos.trace.end.${this.key}`);const e=performance.measure(`alamos.trace.duration.${this.key}`,`alamos.trace.start.${this.key}`,`alamos.trace.end.${this.key}`);this.set("duration",e.duration),this.otel.end()}catch(e){console.error(e)}}}class El{key;constructor(e){this.key=e}set(){}recordError(e){}}class ut{meta;T;L;constructor({key:e="",serviceName:r="",logger:n=ct.NOOP,tracer:a=Ft.NOOP,noop:i=!1,__meta:o}){this.meta=o??new lt(e,e,r,i),this.T=a.child(this.meta),this.L=n.child(this.meta)}child(e){const r=this.meta.child(e);return new ut({__meta:r,tracer:this.T,logger:this.L})}static NOOP=new ut({noop:!0})}const Yv=ut.NOOP,je=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:ut,LOG_LEVELS:_n,Logger:ct,NOOP:Yv,NoopSpan:El,Tracer:Ft,_Span:Gn,logLevelKeyFiler:lv,logThresholdFilter:Ol},Symbol.toStringTag,{value:"Module"})),wn=(t,e)=>t instanceof Error?(t.message=`[${e}] - ${t.message}`,t):new Error(e??"unknown error",{cause:t});class Wr{type;key;sender;_internalState;_state;_prevState;_deleted=!1;parentCtxValues;childCtxValues;childCtxChangedKeys;instrumentation;schema=void 0;constructor({key:e,type:r,sender:n,instrumentation:a,parentCtxValues:i}){this.type=r,this.key=e,this.sender=n,this._internalState={},this.instrumentation=a.child(this.toString()),this.parentCtxValues=new Map,i?.forEach((o,l)=>this.parentCtxValues.set(l,o)),this.childCtxValues=new Map,this.childCtxChangedKeys=new Set}get _schema(){if(this.schema==null)throw new B(`[AetherLeaf] - expected subclass to define component schema, but none was found.
|
|
46
|
+
Make sure to define a property 'schema' on the class.`);return this.schema}setState(e){const r=Rs(e,this.state);this._prevState=f.yr(this._state),this._state=Hn(this._schema,r,`${this.toString()}`),this.sender.send({variant:"update",key:this.key,state:this._state})}get state(){if(this._state==null)throw new W(`[AetherLeaf] - state not defined in ${this.toString()}`);return this._state}get internal(){return this._internalState}get prevState(){if(this._prevState===void 0)throw new Error("prevState not defined");return this._prevState}get deleted(){return this._deleted}get ctx(){return{get:e=>{const r=this.parentCtxValues.get(e);if(r===void 0)throw new it(`Context value for ${e} not found on ${this.toString()}`);return r},getOptional:e=>this.parentCtxValues.get(e),has:e=>this.parentCtxValues.has(e),wasSetPreviously:e=>this.childCtxValues.has(e),set:(e,r,n=!0)=>{this.childCtxValues.set(e,r),n&&this.childCtxChangedKeys.add(e)}}}toString(){return`${this.type}(${this.key})`}_updateState({path:e,state:r}){if(!this.deleted)try{const n=this.instrumentation.T.debug(`${this.toString()}:updateState`);this.validatePath(e);const a=Hn(this._schema,r,`${this.toString()}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:dl.difference(this.state,a)})):this.instrumentation.L.debug("setting initial state",{state:r,path:e}),this._prevState=this._state??a,this._state=a,this.afterUpdate(this.ctx),n()}catch(n){throw wn(n,`${this.toString()}.updateState`)}}_updateContext(e){try{const r=this.instrumentation.T.debug(`${this.toString()}:updateContext`);e.forEach((n,a)=>this.parentCtxValues.set(a,n)),this.afterUpdate(this.ctx),r()}catch(r){throw wn(r,`${this.type}.${this.key}.updateContext`)}}_delete(e){try{const r=this.instrumentation.T.debug(`${this.toString()}:delete`);this.validatePath(e),this._deleted=!0,this.afterDelete(this.ctx),r()}catch(r){throw wn(r,`[${this.toString()}:delete]`)}}afterUpdate(e){}afterDelete(e){}validatePath(e){if(e.length===0)throw new W(`[Leaf.setState] - ${this.toString()} received an empty path`);const r=e[e.length-1];if(e.length>1)throw new W(`[Leaf.setState] - ${this.toString()} received a subPath ${e.join(".")} but is a leaf`);if(r!==this.key)throw new W(`[Leaf.setState] - ${this.toString()} received a key ${r} but expected ${this.key}`)}}class wt extends Wr{_children=new Map;get children(){return Array.from(this._children.values())}getChild(e){return this._children.get(e)??null}childrenOfType(...e){return this.children.filter(r=>e.includes(r.type))}_updateState(e){const{path:r,type:n,create:a}=e;if(this.deleted)return;const i=this.parsePath(r);if(i.length===0){if(this.childCtxChangedKeys.clear(),super._updateState(e),this.childCtxChangedKeys.size==0)return;this.updateChildContexts();return}const l=i[0],c=this.getChild(l);if(c!=null)return c._updateState({...e,path:i});if(i.length>1){const h=r.slice(0,r.indexOf(l)+1).join("."),p=r.join(".");throw new W(`Child of ${this.toString()} at path ${h} does not exist,
|
|
47
|
+
but an extended path ${p} was provided. This means that the aether
|
|
48
|
+
tree is attempting to create a new child of type ${n} (or nested children)
|
|
49
|
+
on a child that does not exist.
|
|
50
|
+
|
|
51
|
+
Children present: ${this.children.map(d=>`${d.type}:${d.key}`).join(".")}
|
|
52
|
+
|
|
53
|
+
`)}const u=a(this.childCtx());u._updateState({...e,path:i}),this._children.set(l,u)}_updateContext(e){super._updateContext(e),this.updateChildContexts()}childCtx(){return{get:e=>this.childCtxValues.get(e)??this.parentCtxValues.get(e),forEach:e=>{this.childCtxValues.forEach((r,n)=>e(r,n,this.childCtxValues)),this.parentCtxValues.forEach((r,n)=>{this.childCtxValues.has(n)||e(r,n,this.parentCtxValues)})}}}updateChildContexts(){const e=this.childCtx();this.children.forEach(r=>r._updateContext(e))}_delete(e){const r=this.parsePath(e);if(r.length===0){for(const a of this.children)a._delete([a.key]);this._children.clear(),super._delete([this.key])}const n=this.getChild(r[0]);if(n!=null){if(r.length>1)return n._delete(r);this._children.delete(n.key),n._delete(r)}}parsePath(e,r){const[n,...a]=e;if(n==null)throw new Error(`Composite ${this.toString()} received an empty path${r!=null?` for ${r}`:""}`);if(n!==this.key)throw new W(`[Composite.getRequiredKey] - ${this.toString()} received a key ${n} but expected ${this.key}`);return a}}const Hv=s.z.object({}),Vv=()=>{throw new Error("should not call create")};class Re extends wt{static TYPE="root";static KEY="root";comms;registry;schema=Hv;constructor({comms:e,instrumentation:r=je.Instrumentation.NOOP,registry:n}){super({key:Re.KEY,type:Re.TYPE,sender:e,instrumentation:r,parentCtxValues:null}),this.comms=e,this.registry=n}static render(e){const r=new Re(e);return r._updateState({path:[Re.KEY],type:"",state:{},create:Vv}),r.comms.handle(n=>{try{r.handle(n)}catch(a){const i={name:"unknown",message:JSON.stringify(a),stack:"unknown"};a instanceof Error&&(i.name=a.name,i.message=a.message,i.stack=a.stack),r.comms.send({variant:"error",error:i})}}),r}handle(e){const{path:r,variant:n,type:a}=e;if(n==="delete"){this._delete(r);return}const{state:i}=e;this._updateState({path:r,type:a,state:i,create:o=>{const l=r[r.length-1];return this.create({key:l,type:a,parentCtxValues:o})}})}create({key:e,type:r,parentCtxValues:n}){const a=this.registry[r];if(a==null)throw new W(`[Root.create] - ${r} not found in registry`);return new a({key:e,type:r,sender:this.comms,instrumentation:this.instrumentation,parentCtxValues:n})}}const Nl=Re.render.bind(Re),_v=Object.freeze(Object.defineProperty({__proto__:null,Composite:wt,Leaf:Wr,Root:Re,render:Nl},Symbol.toStringTag,{value:"Module"})),Wv=(t,e)=>Array.isArray(e)?e.some(r=>r.matches(t)):e?.matches(t)??!1,Al=(t,e,r)=>{const n=f.wr.fromException(t,e);return console.error(n),Wv(t,r)?null:n},kl=(t,e,r,n)=>{if(typeof t=="function")return!0;const a=Al(t,r,n);return a!=null&&e(a),!1},xl=async(t,e,r,n)=>{try{const a=t();a!=null&&await a}catch(a){const i=Al(a,r,n);if(i!=null)return e(i)}},Cl=t=>(e,r,n)=>{kl(e,t,r,n)&&xl(e,t,r,n)},Il=t=>async(e,r,n)=>{kl(e,t,r,n)&&await xl(e,t,r,n)},jl=s.z.object({statuses:f.wr.statusZ().array()}),Ar="status.aggregator";class Kn extends wt{static TYPE="status.Aggregator";schema=jl;afterUpdate(e){e.wasSetPreviously(Ar)||e.set(Ar,{add:this.add.bind(this),create:f.wr.create})}add(e){this.setState(r=>({...r,statuses:[...r.statuses,f.wr.create(e)]}))}}const Gr=t=>t.get(Ar).add,Gv=t=>{const e=t.getOptional(Ar);return e!=null?e.add:()=>{}},Ps=t=>Cl(Gr(t)),Kv=t=>Il(Gr(t)),Jv={[Kn.TYPE]:Kn},Jn="pluto-theming-context",Rl=s.z.object({name:s.z.string(),url:s.z.string()}),Xv=s.z.object({theme:ml,fontURLs:s.z.array(Rl)});let Xn=class Ul extends wt{static TYPE="theming.Provider";static z=Xv;schema=Ul.z;afterUpdate(e){if(e.getOptional(Jn)!=null&&this.state.theme.key===this.prevState.theme.key)return;e.set(Jn,this.state.theme),Ps(e)(async()=>{await this.loadFonts()},"failed to load theme fonts")}async loadFonts(){await Promise.all(this.state.fontURLs.map(async({name:e,url:r})=>{const n=new FontFace(e,`url(${r})`);try{await n.load(),self.fonts.add(n)}catch(a){console.error(a)}}))}};const Qv=t=>t.get(Jn),eT={[Xn.TYPE]:Xn},Ml=s.z.object({include:s.z.string().array().optional(),exclude:s.z.string().array().optional(),level:s.z.enum(je.LOG_LEVELS).optional().default("info")}),Qn="alamos-provider";class es extends wt{static TYPE="alamos.Provider";schema=Ml;afterUpdate(e){if(e.getOptional(Qn)!=null)return;const n=[],{include:a,exclude:i,level:o}=this.state;(a!=null||i!=null)&&n.push(je.logLevelKeyFiler({include:a,exclude:i})),o!=null&&n.push(je.logThresholdFilter(o)),n.length===0&&n.push(()=>!1),this.internal.ins=new je.Instrumentation({key:"aether",logger:new je.Logger({filters:n})}),e.set(Qn,this.internal.ins)}}const Ll=(t,e)=>{const r=t.get(Qn);if(r==null)throw new Error("No instrumentation provider");return e==null?r:r.child(e)},tT={[es.TYPE]:es},br=(t,e)=>f.Ho.construct(f.Ho.left(t)-e.x,f.Ho.top(t)-e.y,f.Ho.width(t)+e.x*2,f.Ho.height(t)+e.y*2);class kr{scale_;wrapped;atlasRegistry;cachedFont=null;cachedFillStyle=null;cachedStrokeStyle=null;cachedLineWidth=null;cachedGlobalAlpha=null;cachedTextAlign=null;cachedTextBaseline=null;cachedLineCap=null;cachedLineJoin=null;cachedMiterLimit=null;dpr;constructor(e,r,n,a=f.C.XY.IDENTITY){this.wrapped=e,this.scale_=a,this.atlasRegistry=r,this.dpr=n}get fontStretch(){return this.wrapped.fontStretch}set fontStretch(e){this.wrapped.fontStretch=e}get fontVariantCaps(){return this.wrapped.fontVariantCaps}set fontVariantCaps(e){this.wrapped.fontVariantCaps=e}isContextLost(){return this.wrapped.isContextLost()}get wordSpacing(){return this.wrapped.wordSpacing}set wordSpacing(e){this.wrapped.wordSpacing=e}get letterSpacing(){return this.wrapped.letterSpacing}set letterSpacing(e){this.wrapped.letterSpacing=e}get textRendering(){return this.wrapped.textRendering}set textRendering(e){this.wrapped.textRendering=e}checkAtlasFillStyle(e=!1){return e&&typeof this.fillStyle=="string"?[!0,this.fillStyle]:(e&&console.warn("attempted to use a text atlas with a gradient fill style. This is not supported. Falling back to default canvas fill."),[!1,null])}reset(){this.wrapped.reset()}applyScale(e){return new kr(this,this.atlasRegistry,this.dpr,e)}get canvas(){return this.wrapped.canvas}get miterLimit(){return this.cachedMiterLimit??this.wrapped.miterLimit}set miterLimit(e){const r=this.scale_.x.dim(e);r!==this.cachedMiterLimit&&(this.cachedMiterLimit=r,this.wrapped.miterLimit=r)}get globalAlpha(){return this.cachedGlobalAlpha??this.wrapped.globalAlpha}set globalAlpha(e){e!==this.cachedGlobalAlpha&&(this.cachedGlobalAlpha=e,this.wrapped.globalAlpha=e)}get globalCompositeOperation(){return this.wrapped.globalCompositeOperation}set globalCompositeOperation(e){this.wrapped.globalCompositeOperation=e}get fillStyle(){return this.cachedFillStyle??this.wrapped.fillStyle}set fillStyle(e){e!==this.cachedFillStyle&&(this.cachedFillStyle=e,this.wrapped.fillStyle=e)}get strokeStyle(){return this.cachedStrokeStyle??this.wrapped.strokeStyle}set strokeStyle(e){e!==this.cachedStrokeStyle&&(this.cachedStrokeStyle=e,this.wrapped.strokeStyle=e)}drawImage(e,r,n,a,i,o,l,c,u){this.wrapped.drawImage(e,r,n,a,i,o!=null?this.scale_.x.pos(o):o,l!=null?this.scale_.y.pos(l):l,c!=null?this.scale_.x.dim(c):c,u!=null?this.scale_.y.dim(u):u)}beginPath(){this.wrapped.beginPath()}clip(e,r){this.wrapped.clip(e,r)}fill(e,r){if(e==null)return this.wrapped.fill();this.wrapped.fill(e,r)}isPointInPath(e,r,n,a){return this.wrapped.isPointInPath(e,r,n,a)}isPointInStroke(e,r,n){return this.wrapped.isPointInStroke(e,r,n)}stroke(e){if(e==null)return this.wrapped.stroke();this.wrapped.stroke(e)}createConicGradient(e,r,n){return this.wrapped.createConicGradient(e,r,n)}createLinearGradient(e,r,n,a){return this.wrapped.createLinearGradient(e,r,n,a)}createPattern(e,r){return this.wrapped.createPattern(e,r)}createRadialGradient(e,r,n,a,i,o){return this.wrapped.createRadialGradient(e,r,n,a,i,o)}get filter(){return this.wrapped.filter}set filter(e){this.wrapped.filter=e}createImageData(e,r,n){return this.wrapped.createImageData(e,r,n)}getImageData(e,r,n,a,i){return this.wrapped.getImageData(e,r,n,a,i)}putImageData(e,r,n,a,i,o,l){this.wrapped.putImageData(e,r,n,a,i,o,l)}get imageSmoothingEnabled(){return this.wrapped.imageSmoothingEnabled}set imageSmoothingEnabled(e){this.wrapped.imageSmoothingEnabled=e}get imageSmoothingQuality(){return this.wrapped.imageSmoothingQuality}set imageSmoothingQuality(e){this.wrapped.imageSmoothingQuality=e}arc(e,r,n,a,i,o){this.wrapped.arc(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),a,i,o)}arcTo(e,r,n,a,i){this.wrapped.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,r,n,a,i,o){this.wrapped.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.wrapped.closePath()}ellipse(e,r,n,a,i,o,l,c){this.wrapped.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,r){this.wrapped.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}moveTo(e,r){this.wrapped.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}quadraticCurveTo(e,r,n,a){this.wrapped.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,r,n,a){this.wrapped.rect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,r,n,a,i){this.wrapped.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),typeof i=="number"?this.scale_.x.dim(i):i)}get lineCap(){return this.cachedLineCap??this.wrapped.lineCap}set lineCap(e){e!==this.cachedLineCap&&(this.cachedLineCap=e,this.wrapped.lineCap=e)}get lineDashOffset(){return this.wrapped.lineDashOffset}set lineDashOffset(e){this.wrapped.lineDashOffset=this.scale_.x.dim(e)}get lineJoin(){return this.cachedLineJoin??this.wrapped.lineJoin}set lineJoin(e){e!==this.cachedLineJoin&&(this.cachedLineJoin=e,this.wrapped.lineJoin=e)}get lineWidth(){return this.cachedLineWidth??this.wrapped.lineWidth}set lineWidth(e){const r=this.scale_.x.dim(e);r!==this.cachedLineWidth&&(this.cachedLineWidth=r,this.wrapped.lineWidth=r)}getLineDash(){return this.wrapped.getLineDash()}setLineDash(e){const r=Array.from(e).map(n=>this.scale_.x.dim(n));this.wrapped.setLineDash(r)}clearRect(e,r,n,a){this.wrapped.clearRect(e,r,n,a)}fillRect(e,r,n,a){this.wrapped.fillRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}strokeRect(e,r,n,a){this.wrapped.strokeRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}get shadowBlur(){return this.wrapped.shadowBlur}set shadowBlur(e){this.wrapped.shadowBlur=e}get shadowColor(){return this.wrapped.shadowColor}set shadowColor(e){this.wrapped.shadowColor=e}get shadowOffsetX(){return this.wrapped.shadowOffsetX}set shadowOffsetX(e){this.wrapped.shadowOffsetX=e}get shadowOffsetY(){return this.wrapped.shadowOffsetY}restore(){this.cachedFillStyle=null,this.cachedStrokeStyle=null,this.cachedLineWidth=null,this.cachedGlobalAlpha=null,this.cachedTextAlign=null,this.cachedTextBaseline=null,this.cachedLineCap=null,this.cachedLineJoin=null,this.cachedMiterLimit=null,this.cachedFont=null,this.wrapped.restore()}save(){this.wrapped.save()}fillText(e,r,n,a,i={}){const[o,l]=this.checkAtlasFillStyle(i.useAtlas);if(o){this.atlasRegistry.get({font:this.font,textColor:l}).fillText(this,e,r,n);return}this.wrapped.fillText(e,this.scale_.x.pos(r),this.scale_.y.pos(n),a!=null?this.scale_.x.dim(a):void 0)}measureText(e){return this.wrapped.measureText(e)}textDimensions(e,r={}){const[n,a]=this.checkAtlasFillStyle(r.useAtlas);return n?this.atlasRegistry.get({font:this.font,textColor:a}).measureText(e):_r(this.measureText(e))}strokeText(e,r,n,a){this.wrapped.strokeText(e,this.scale_.x.pos(r),this.scale_.y.pos(n),a!=null?this.scale_.x.dim(a):void 0)}get direction(){return this.wrapped.direction}set direction(e){this.wrapped.direction=e}get font(){return this.cachedFont!=null?this.cachedFont:this.wrapped.font}set font(e){e!==this.cachedFont&&(this.cachedFont=e,this.wrapped.font=this.cachedFont)}get fontKerning(){return this.wrapped.fontKerning}set fontKerning(e){this.wrapped.fontKerning=e}get textAlign(){return this.cachedTextAlign??this.wrapped.textAlign}set textAlign(e){e!==this.cachedTextAlign&&(this.cachedTextAlign=e,this.wrapped.textAlign=e)}get textBaseline(){return this.cachedTextBaseline??this.wrapped.textBaseline}set textBaseline(e){e!==this.cachedTextBaseline&&(this.cachedTextBaseline=e,this.wrapped.textBaseline=e)}getTransform(){return this.wrapped.getTransform()}resetTransform(){this.wrapped.resetTransform()}rotate(e){this.wrapped.rotate(e)}scale(e,r){this.wrapped.scale(e,r),this.dpr=e}scissor(e,r=f.K.ZERO){const n=new rT(this.scale_);return e=br(e,r),n.rect(...f.K.couple(f.Ho.topLeft(e)),...f._.couple(f.Ho.dims(e))),this.save(),this.clip(n.getPath()),()=>this.restore()}setTransform(e,r,n,a,i,o){this.wrapped.setTransform(e,r,n,a,i,o)}transform(e,r,n,a,i,o){this.wrapped.transform(e,r,n,a,i,o)}translate(e,r){this.wrapped.translate(e,r)}}class rT{scale_;path;constructor(e=f.C.XY.IDENTITY,r){this.scale_=e,r instanceof Path2D||typeof r=="string"?this.path=new Path2D(r):this.path=new Path2D}addPath(e,r){this.path.addPath(e,r)}arc(e,r,n,a,i,o){this.path.arc(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),a,i,o)}arcTo(e,r,n,a,i){this.path.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,r,n,a,i,o){this.path.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.pos(i),this.scale_.y.pos(o))}closePath(){this.path.closePath()}ellipse(e,r,n,a,i,o,l,c){this.path.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,r){this.path.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}moveTo(e,r){this.path.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(r))}quadraticCurveTo(e,r,n,a){this.path.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,r,n,a){this.path.rect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,r,n,a,i){const o=this.scaleRadii(i);this.path.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(r),this.scale_.x.dim(n),this.scale_.y.dim(a),o)}scaleRadii(e){return e==null?e:typeof e=="number"?this.scale_.x.dim(e):Array.isArray(e)?e.map(r=>this.scaleRadius(r)):this.scaleRadius(e)}scaleRadius(e){return typeof e=="number"?this.scale_.x.dim(e):{x:this.scale_.x.dim(e.x??0),y:this.scale_.y.dim(e.y??0)}}getPath(){return this.path}}const nT=`precision mediump float;
|
|
54
|
+
|
|
55
|
+
void main(void) {
|
|
56
|
+
gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
|
|
57
|
+
}
|
|
58
|
+
`,sT=`attribute vec4 a_position;
|
|
59
|
+
|
|
60
|
+
void main(void) {
|
|
61
|
+
gl_Position = a_position;
|
|
62
|
+
}
|
|
63
|
+
`,ja=t=>new Error(`failed to compile webgl program: ${t}`),aT=new Error("null shader encountered");let Pl=class{renderCtx;prog;vertShader;fragShader;uniformLocCache=new Map;constructor(e,r,n){this.renderCtx=e;const a=e.gl.createProgram();if(a==null)throw ja("failed to create program");this.prog=a,this.vertShader=r,this.fragShader=n,this.compile()}setAsActive(){return this.renderCtx.gl.useProgram(this.prog),()=>this.renderCtx.gl.useProgram(null)}uniformXY(e,r){this.renderCtx.gl.uniform2fv(this.getUniformLoc(e),f.K.couple(r))}uniformColor(e,r){this.renderCtx.gl.uniform4fv(this.getUniformLoc(e),f.cr.rgba1(r))}getUniformLoc(e){const r=this.uniformLocCache.get(e);if(r!=null)return r;const n=this.renderCtx.gl.getUniformLocation(this.prog,e);if(n==null)throw new Error(`unexpected missing uniform ${e}`);return this.uniformLocCache.set(e,n),n}compile(){const e=this.renderCtx.gl;this.compileShader(this.vertShader,e.VERTEX_SHADER),this.compileShader(this.fragShader,e.FRAGMENT_SHADER),e.linkProgram(this.prog)}compileShader(e,r){const n=this.renderCtx.gl,a=n.createShader(r);if(a==null)throw aT;if(n.shaderSource(a,e),n.compileShader(a),!n.getShaderParameter(a,n.COMPILE_STATUS)){const o=n.getShaderInfoLog(a);throw n.deleteShader(a),ja(o??"unknown")}n.attachShader(this.prog,a)}};const iT=new Float32Array([0,0,0,0,0,0]);class oT extends Pl{positionBuffer;constructor(e){super(e,sT,nT);const r=e.gl.createBuffer();if(r==null)throw new W("webgl: failed to create buffer");this.positionBuffer=r,e.gl.bindBuffer(e.gl.ARRAY_BUFFER,this.positionBuffer),e.gl.bufferData(e.gl.ARRAY_BUFFER,iT,e.gl.STATIC_DRAW)}exec(){const{gl:e}=this.renderCtx,r=e.getAttribLocation(this.prog,"a_position");e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer);const n=e.createVertexArray();e.bindVertexArray(n),e.enableVertexAttribArray(r),e.vertexAttribPointer(r,2,e.FLOAT,!1,0,0),this.setAsActive(),e.drawArrays(e.TRIANGLES,0,3)}}const Ra={high:1,low:0};class Dl{requests=new Map;cleanup=new Map;afterRender;instrumentation;handleError;constructor({afterRender:e,instrumentation:r=je.Instrumentation.NOOP,handleError:n}){this.afterRender=e,this.instrumentation=r,this.handleError=n,this.start()}set(e){const r=this.requests.get(e.key);if(r==null)this.requests.set(e.key,e);else{const n=Ra[e.priority]>=Ra[r.priority],a=e.canvases.length>=r.canvases.length;n&&a&&this.requests.set(e.key,e)}}render(){const{requests:e}=this;e.size!==0&&(this.runCleanupsSync(),this.renderSync(),this.requests.clear(),this.afterRender?.())}runCleanupsSync(){const{cleanup:e,requests:r}=this;e.forEach((n,a)=>{const i=r.get(a);i!=null&&(n(i),e.delete(a))})}renderSync(){const{requests:e}=this;e.forEach(r=>{try{const n=r.render();n!=null&&this.cleanup.set(r.key,n)}catch(n){this.handleError(n,"render loop failed")}})}start(){const e=()=>{try{this.render()}catch(r){this.handleError(r,"render loop failed")}requestAnimationFrame(e)};requestAnimationFrame(e)}}const dr=2,me=2;class Ds{atlas;charDims;charMap;static DEFAULT_CHARS="0123456789.:-µmsNa∞ᴇ";constructor(e){const{font:r,characters:n=Ds.DEFAULT_CHARS,textColor:a}=e;this.charMap=new Map;const i=f.c.unique(Array.from(n)),l=new OffscreenCanvas(1,1).getContext("2d");l.font=r;const c=l.measureText("0");this.charDims=_r(c),this.charDims.width+=dr,this.charDims.height+=dr;const u=i.length,h=this.charDims.width,p=this.charDims.height,d=Math.ceil(Math.sqrt(u)),S=Math.ceil(u/d);this.atlas=new OffscreenCanvas(h*d*me,p*(S+1)*me);const N=this.atlas.getContext("2d");N.scale(me,me),N.font=r,N.textBaseline="alphabetic",N.textAlign="left",N.fillStyle=f.cr.hex(a),N.clearRect(0,0,this.atlas.width,this.atlas.height),i.forEach((x,$)=>{const I=$%d,P=Math.floor($/d),ie=I*h,te=(P+1)*p;N.fillText(x,ie,te),this.charMap.set(x,$)})}fillText(e,r,n,a){const{width:i,height:o}=this.charDims,l=Math.ceil(Math.sqrt(this.charMap.size));for(let c=0;c<r.length;c++){const u=r[c],h=this.charMap.get(u);if(h===void 0)continue;const p=h%l,d=Math.floor(h/l);e.drawImage(this.atlas,p*i*me,d*o*me+dr,i*me,o*me,n+c*i,a-o-dr/me,i,o)}}measureText(e){return{width:e.length*this.charDims.width,height:this.charDims.height}}}class lT{atlases;constructor(){this.atlases=new Map}get(e){const r=`${e.font}-${f.cr.hex(e.textColor)}-${e.characters}`;if(this.atlases.has(r))return this.atlases.get(r);const n=new Ds(e);return this.atlases.set(r,n),n}}const Ua=t=>(t.textRendering="optimizeSpeed",t.imageSmoothingEnabled=!1,t);class Ce{glCanvas;upper2dCanvas;lower2dCanvas;gl;lower2d;upper2d;region;dpr;loop;clearProgram;os;static CONTEXT_KEY=f.CSS.B("render-context");instrumentation;static create(e,r,n,a,i){const o=Ll(e,"render_context"),l=new Ce(r,n,a,i,o,Gr(e),Ps(e));return e.set(Ce.CONTEXT_KEY,l),l}constructor(e,r,n,a,i,o,l){this.upper2dCanvas=n,this.lower2dCanvas=r,this.glCanvas=e,this.os=a,this.instrumentation=i,this.dpr=1;const c=this.lower2dCanvas.getContext("2d");if(c==null)throw new Error("Could not get 2D context");const u=new lT;this.lower2d=Ua(new kr(c,u,this.dpr));const h=this.upper2dCanvas.getContext("2d");if(h==null)throw new Error("Could not get 2D context");this.upper2d=Ua(new kr(h,u,this.dpr));const p={preserveDrawingBuffer:!0,powerPreference:"high-performance",stencil:!1,depth:!1},d=this.glCanvas.getContext("webgl2",p);if(d==null)throw new Error("Could not get WebGL context");d.disable(d.DEPTH_TEST),d.disable(d.STENCIL_TEST),d.disable(d.CULL_FACE),d.disable(d.DITHER),this.gl=d,this.glCanvas.oncontextlost=()=>o({variant:"error",message:"WebGL context lost"});const S=()=>{this.gl.flush(),this.gl.finish()};this.loop=new Dl({afterRender:S,instrumentation:this.instrumentation,handleError:l}),this.region=f.Ho.ZERO,this.os==="Windows"&&(this.clearProgram=new oT(this))}static useOptional(e){return e.getOptional(Ce.CONTEXT_KEY)}static use(e){return e.get(Ce.CONTEXT_KEY)}update(e){e.set(Ce.CONTEXT_KEY,this)}resize(e,r){f.Ho.equals(this.region,e)&&this.dpr===r||(this.region=e,this.dpr=r,this.resizeCanvas(this.glCanvas),this.resizeCanvas(this.upper2dCanvas),this.resizeCanvas(this.lower2dCanvas),this.lower2d.scale(this.dpr,this.dpr),this.upper2d.scale(this.dpr,this.dpr),this.gl.viewport(0,0,f.Ho.width(e)*r,f.Ho.height(e)*r))}resizeCanvas(e){e.width=f.Ho.width(this.region)*this.dpr,e.height=f.Ho.height(this.region)*this.dpr}get aspect(){return f.Ho.aspect(this.region)}scaleRegion(e){return new f.C.XY(f.C.Scale.scale(0,1).scale(f.Ho.width(e)).translate(f.Ho.left(e)).reBound(f.Ho.width(this.region)).scale(-1,1),f.C.Scale.scale(0,1).scale(f.Ho.height(e)).invert().translate(f.Ho.top(e)).reBound(f.Ho.height(this.region)).scale(-1,1).invert())}scissor(e,r=f.K.ZERO,n){const a=[];return n.includes("upper2d")&&a.push(this.upper2d.scissor(e,r)),n.includes("lower2d")&&a.push(this.lower2d.scissor(e,r)),n.includes("gl")&&a.push(this.scissorGL(e,r)),()=>a.forEach(i=>i())}scissorGL(e,r=f.K.ZERO){return this.gl.enable(this.gl.SCISSOR_TEST),e=br(e,r),this.gl.scissor(f.Ho.left(e)*this.dpr,(f.Ho.height(this.region)-f.Ho.bottom(e))*this.dpr,f.Ho.width(e)*this.dpr,f.Ho.height(e)*this.dpr),()=>this.gl.disable(this.gl.SCISSOR_TEST)}erase(e,r=f.K.ZERO,...n){r=f.K.construct(r),n.length===0&&(n=["upper2d","lower2d","gl"]),n.includes("upper2d")&&this.eraseCanvas(this.upper2d,e,r),n.includes("lower2d")&&this.eraseCanvas(this.lower2d,e,r),n.includes("gl")&&this.eraseGL(e,r)}eraseGL(e,r=f.K.ZERO){const{gl:n}=this,a=this.scissorGL(br(e,r));n.clearColor(...f.cr.rgba1(f.cr.ZERO)),n.clear(n.COLOR_BUFFER_BIT),this.os==="Windows"&&this.clearProgram?.exec(),a()}eraseCanvas(e,r,n=f.K.ZERO){const a=br(r,n);e.clearRect(...f.K.couple(f.Ho.topLeft(a)),...f._.couple(f.Ho.dims(a)))}}const $l=s.z.object({region:f.Ho.box,enabled:s.z.boolean().optional().default(!1)}),Ma=["gl","lower2d","upper2d"];class ts extends Wr{static TYPE="eraser";schema=$l;afterUpdate(e){this.deleted||(this.internal.renderCtx=Ce.use(e),this.renderOnLifecycleChange())}afterDelete(){this.renderOnLifecycleChange()}renderOnLifecycleChange(){this.internal.renderCtx.loop.set({key:`${this.type}-${this.key}`,render:this.render.bind(this),priority:"high",canvases:Ma})}render(){this.deleted||!this.state.enabled||this.internal.renderCtx.erase(this.state.region,f.K.construct(0),...Ma)}}const cT={[ts.TYPE]:ts};exports.Aggregator=Kn;exports.COMPONENT_SIZE_LEVELS=Gb;exports.Composite=wt;exports.Context=Ce;exports.Dw=Ob;exports.Eraser=ts;exports.GLProgram=Pl;exports.I=k;exports.Iw=rw;exports.Jm=qf;exports.LEVELS=Ct;exports.LEVEL_COMPONENT_SIZES=Kb;exports.Leaf=Wr;exports.Loop=Dl;exports.N=dl;exports.Nm=cl;exports.O=ut;exports.O$1=z;exports.Ow=Qg;exports.P=B;exports.Provider=Xn;exports.Provider$1=es;exports.REGISTRY=eT;exports.REGISTRY$1=Jv;exports.REGISTRY$2=cT;exports.REGISTRY$3=tT;exports.SIZES=vl;exports.SYNNAX_DARK=bl;exports.SYNNAX_LIGHT=wl;exports.SYNNAX_THEMES=iv;exports.Sm=Sb;exports.Sw=mm;exports.Ue=Le;exports._=ct;exports._m=Of;exports._t=it;exports.aether=_v;exports.aggregatorStateZ=jl;exports.be=Ol;exports.bw=yg;exports.c=js;exports.createAsyncErrorHandler=Il;exports.createErrorHandler=Cl;exports.d=$b;exports.d$1=E;exports.dimensions=Hb;exports.dimensionsFromMetrics=_r;exports.downLevel=_b;exports.eraserStateZ=$l;exports.ew=rp;exports.executeInitialSetter=Vr;exports.executeSetter=Rs;exports.fontSpecZ=Rl;exports.fw=Vy;exports.g=je;exports.gw=Xy;exports.ht=W;exports.isSize=ov;exports.levelZ=Vb;exports.o=Nb;exports.ow=Zp;exports.p=ul;exports.prettyParse=Hn;exports.providerStateZ=Ml;exports.r=Ab;exports.render=Nl;exports.size=Tl;exports.specZ=xe;exports.state=qb;exports.t=Eb;exports.themeZ=ml;exports.use=Qv;exports.useAdder=Gr;exports.useAsyncErrorHandler=Kv;exports.useErrorHandler=Ps;exports.useInstrumentation=Ll;exports.useOptionalAdder=Gv;exports.usePassthrough=yl;exports.usePurePassthrough=gl;exports.vw=jg;exports.weightZ=Wb;
|