@synnaxlabs/pluto 0.44.3 → 0.44.5
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 +1 -0
- package/dist/{Animated-BHxq6Pmm.js → Animated-fI-NFaha.js} +2 -2
- package/dist/{symbols-aLnytgtc.js → Editable-C1g_CFYk.js} +5898 -5888
- package/dist/{symbols-DWZqHjhU.cjs → Editable-DUtJOqJ5.cjs} +41 -41
- package/dist/{LinePlot-BJ10hKs7.cjs → LinePlot-6cl8_hmn.cjs} +5 -5
- package/dist/{LinePlot-VIcFjuPQ.js → LinePlot-Ck0rhtFk.js} +712 -728
- package/dist/{Toggle-C--I90ch.js → Toggle-DEJ8Uvun.js} +1 -1
- package/dist/Toggle-DUKDeqpe.cjs +1 -0
- package/dist/{Video-DdsVXhnt.js → Video-B6tujjr8.js} +1 -1
- package/dist/{Video-BbRLzkdH.cjs → Video-BjRd9sFv.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-DI0uCCGq.cjs +8 -0
- package/dist/{css-BKrX40Df.js → css-DvIPI3Qm.js} +1383 -1252
- 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-B03ej59l.cjs +63 -0
- package/dist/{eraser-DtXU7kOS.js → eraser-CnRJY__h.js} +4999 -4687
- package/dist/ether.cjs +1 -1
- package/dist/ether.js +6 -6
- package/dist/{external-BT0nByPv.js → external-B3dPSZUg.js} +7 -8
- package/dist/external-BEd3F7zY.cjs +1 -0
- package/dist/external-BS9S-b49.cjs +1 -0
- package/dist/external-BVDQNHbo.cjs +1 -0
- package/dist/external-BenP6Hcm.cjs +1 -0
- package/dist/external-Blrrgnzw.cjs +1 -0
- package/dist/{external-tHxdTvxn.js → external-BzV_PGNe.js} +2 -2
- package/dist/{external-ONwuyKzG.js → external-C2iqWGd2.js} +22 -22
- package/dist/external-CAAPXpVr.cjs +1 -0
- package/dist/{external-n4gJTJfw.js → external-CKhbbig_.js} +15 -15
- package/dist/external-CNF5TNBY.cjs +1 -0
- package/dist/{external-Bt-WjDvD.js → external-D16M7vHB.js} +9 -9
- package/dist/{external-dkXc0y5z.js → external-D6hAP7eJ.js} +7 -7
- package/dist/external-D98a3YQJ.cjs +1 -0
- package/dist/external-DKh0JhWO.cjs +1 -0
- package/dist/external-DNO3FJLl.cjs +1 -0
- package/dist/{external-yddEc8os.cjs → external-DOEaBrpz.cjs} +2 -2
- package/dist/external-DRuZ24L7.js +78 -0
- package/dist/{external-CEMgElRx.js → external-Daage1AI.js} +10 -10
- package/dist/{external-BApQK7XP.js → external-Db9iKa8k.js} +3 -3
- package/dist/{external-BmfZaFKB.js → external-Dfr7xymv.js} +3 -3
- package/dist/external-DwRvB5ZT.cjs +1 -0
- package/dist/{external-NUi5IwGn.js → external-GR-20z_c.js} +14 -14
- package/dist/external-I_-aclFy.cjs +1 -0
- package/dist/{external-Dgui980d.js → external-R9a28aP6.js} +24 -24
- package/dist/{external-Dwfn2jsF.js → external-dew29Q0v.js} +9 -9
- package/dist/flex.cjs +1 -1
- package/dist/flex.js +1 -1
- package/dist/{fontString-D2-HUuI_.js → fontString-CW0wLG5g.js} +2 -2
- package/dist/{fontString-BWGnZU-8.cjs → fontString-aK--tYMM.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 +6084 -5944
- 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/queries.d.ts.map +1 -1
- package/dist/src/flux/form.d.ts +39 -10
- package/dist/src/flux/form.d.ts.map +1 -1
- package/dist/src/flux/retrieve.d.ts +4 -2
- package/dist/src/flux/retrieve.d.ts.map +1 -1
- package/dist/src/flux/update.d.ts +13 -0
- package/dist/src/flux/update.d.ts.map +1 -1
- package/dist/src/form/Context.d.ts +6 -2
- package/dist/src/form/Context.d.ts.map +1 -1
- package/dist/src/form/state.d.ts +1 -0
- package/dist/src/form/state.d.ts.map +1 -1
- package/dist/src/form/use.d.ts.map +1 -1
- package/dist/src/hardware/device/queries.d.ts.map +1 -1
- package/dist/src/hardware/rack/queries.d.ts.map +1 -1
- package/dist/src/hardware/task/queries.d.ts +22 -1
- package/dist/src/hardware/task/queries.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.map +1 -1
- package/dist/src/mosaic/Mosaic.d.ts +1 -1
- package/dist/src/mosaic/Mosaic.d.ts.map +1 -1
- package/dist/src/ontology/queries.d.ts.map +1 -1
- package/dist/src/ranger/queries.d.ts +3 -3
- package/dist/src/ranger/queries.d.ts.map +1 -1
- package/dist/src/select/Button.d.ts +3 -2
- package/dist/src/select/Button.d.ts.map +1 -1
- package/dist/src/select/use.d.ts +7 -4
- package/dist/src/select/use.d.ts.map +1 -1
- package/dist/src/showcase/TextShowcase.d.ts.map +1 -1
- package/dist/src/status/Summary.d.ts.map +1 -1
- package/dist/src/synnax/Provider.d.ts.map +1 -1
- package/dist/src/synnax/aether/provider.d.ts +6 -6
- package/dist/src/telem/aether/remote.d.ts +4 -4
- package/dist/src/telem/aether/transformers.d.ts +0 -2
- package/dist/src/telem/aether/transformers.d.ts.map +1 -1
- package/dist/src/telem/aether/transformers.spec.d.ts +2 -0
- package/dist/src/telem/aether/transformers.spec.d.ts.map +1 -0
- package/dist/src/text/external.d.ts +0 -1
- package/dist/src/text/external.d.ts.map +1 -1
- package/dist/src/triggers/Text.d.ts.map +1 -1
- package/dist/src/triggers/triggers.d.ts +3 -0
- package/dist/src/triggers/triggers.d.ts.map +1 -1
- package/dist/src/viewport/SelectMode.d.ts +10 -2
- package/dist/src/viewport/SelectMode.d.ts.map +1 -1
- package/dist/src/vis/diagram/Diagram.d.ts.map +1 -1
- package/dist/src/vis/legend/Simple.d.ts.map +1 -1
- package/dist/src/vis/line/aether/line.d.ts +0 -1
- package/dist/src/vis/line/aether/line.d.ts.map +1 -1
- package/dist/src/vis/lineplot/Legend.d.ts.map +1 -1
- package/dist/src/vis/lineplot/aether/XAxis.d.ts +2 -2
- package/dist/src/vis/lineplot/aether/YAxis.d.ts +2 -2
- package/dist/src/vis/lineplot/aether/axis.d.ts +2 -2
- package/dist/src/vis/lineplot/aether/axis.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-ny6lkoIv.js → units-Dh7MflIZ.js} +3 -3
- package/dist/units-WWUmv-rf.cjs +1 -0
- package/dist/video.cjs +1 -1
- package/dist/video.js +1 -1
- package/package.json +6 -6
- package/dist/Animated-DEXELMDa.cjs +0 -1
- package/dist/Toggle-CCsw0kkq.cjs +0 -1
- package/dist/css-TyQvZIXQ.cjs +0 -8
- package/dist/eraser-Bxknv-HS.cjs +0 -63
- package/dist/external-BBXhtVjD.cjs +0 -1
- package/dist/external-BOmNpcyI.js +0 -75
- package/dist/external-BPF50O_x.cjs +0 -1
- package/dist/external-BUAnicLg.cjs +0 -1
- package/dist/external-BaRBYE0N.cjs +0 -1
- package/dist/external-BsyCwXWB.cjs +0 -1
- package/dist/external-COBt6FnN.cjs +0 -1
- package/dist/external-CZSk2V5E.cjs +0 -1
- package/dist/external-Cw5iYImi.cjs +0 -1
- package/dist/external-EMhi5ISu.cjs +0 -1
- package/dist/external-Jee63xkv.cjs +0 -1
- package/dist/external-TAYJZFme.cjs +0 -1
- package/dist/external-bvOijYCw.cjs +0 -1
- package/dist/src/text/symbols.d.ts +0 -3
- package/dist/src/text/symbols.d.ts.map +0 -1
- package/dist/units-XE06scfL.cjs +0 -1
package/dist/eraser-Bxknv-HS.cjs
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
"use strict";const s=require("zod"),f=require("./css-TyQvZIXQ.cjs"),_n=require("react"),zl=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Na=r=>{const e=(t,n=cn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Fr(t))return t;n=kl(n);const a={},i=t;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=r(o);n.recursive&&(Fr(l)?xs(l)||(l=e(l,n)):n.recursiveInArray&&ks(l)&&(l=[...l].map(u=>{let d=u;return Fr(u)?xs(d)||(d=e(u,n)):ks(u)&&(d=e({key:u},n).key),d}))),a[c]=l}),a)};return e},Aa=Na(zl),El=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Nl=Na(El),Al=[Number,String,Uint8Array],cn={recursive:!0,recursiveInArray:!0},kl=(r=cn)=>(r.recursive==null?r=cn:r.recursiveInArray??=!1,r),ks=r=>r!=null&&Array.isArray(r),Fr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),xs=r=>Al.some(e=>r instanceof e);let xl=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r))}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Aa(t);return e!=null?e.parse(n):n}encodeString(r){const e=Nl(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}};const un=new xl;let ut=class{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}};const Cl=r=>r!=null&&typeof r=="object"&&"toString"in r,Il=(r,e=!1)=>{const t=Cl(r)?"stringer":typeof r;let n;switch(t){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?jl(n):n},jl=r=>(e,t)=>r(t,e),Nr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ka=s.z.object({width:s.z.number(),height:s.z.number()}),Rl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Ul=["width","height"];s.z.enum(Ul);const Ml=["start","center","end"],Ll=["signedWidth","signedHeight"];s.z.enum(Ll);const mr=s.z.object({x:s.z.number(),y:s.z.number()}),Pl=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Dl=["x","y"],xa=s.z.enum(Dl),Ca=["top","right","bottom","left"];s.z.enum(Ca);const Bl=["left","right"],Ia=s.z.enum(Bl),$l=["top","bottom"],ja=s.z.enum($l),Ra=["center"],Cs=s.z.enum(Ra),Fl=[...Ca,...Ra],Ua=s.z.enum(Fl);s.z.enum(Ml);const ql=["first","last"];s.z.enum(ql);const Zl=s.z.object({lower:s.z.number(),upper:s.z.number()}),Yl=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Zl,Nr]);s.z.union([Yl,Nr]);s.z.enum([...xa.options,...Ua.options]);s.z.union([xa,Ua,s.z.instanceof(String)]);const Ze=(r,e)=>typeof r=="bigint"?r*BigInt(e):r*Number(e),De=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?_l(n):n},_l=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Is=(r,e)=>{const t=De(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e};s.z.object({x:Ia.or(Cs),y:ja.or(Cs)});const Vl=s.z.object({x:Ia,y:ja}),Hl=Object.freeze({x:"left",y:"top"}),Wl=(r,e)=>r.x===e.x&&r.y===e.y,js=s.z.union([s.z.number(),mr,Nr,ka,Rl,Pl]),Gl=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Rs=Object.freeze({x:0,y:0}),rr=s.z.union([s.z.number(),s.z.string()]);s.z.object({top:rr,left:rr,width:rr,height:rr});s.z.object({left:s.z.number(),top:s.z.number(),right:s.z.number(),bottom:s.z.number()});s.z.object({one:mr,two:mr,root:Vl});const Vn=(r,e,t=0,n=0,a)=>{const i={one:{...Rs},two:{...Rs},root:a??Hl};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:r,y:e},i.two={x:i.one.x+t,y:i.one.y+n},i}return"one"in r&&"two"in r&&"root"in r?{...r,root:a??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(i.one={x:r.left,y:r.top},i.two={x:r.right,y:r.bottom},i):(i.one=r,e==null?i.two={x:i.one.x+t,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+t}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},qr=r=>{const e=Vn(r);return{lower:e.one.x,upper:e.two.x}},Zr=r=>{const e=Vn(r);return{lower:e.one.y,upper:e.two.y}},Kl=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,Jl=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ka,Jl,mr,Nr]);const Xl=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:js,scale:js});s.z.object({offset:s.z.number(),scale:s.z.number()});const Ql=r=>(e,t,n,a)=>t==="dimension"?[e,n]:[e,a?n-r:n+r],ec=r=>(e,t,n,a)=>[e,a?n/r:n*r],tc=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=r,c=i-a,u=l-o;if(t==="dimension")return[r,n*(u/c)];const d=(n-a)*(u/c)+o;return[r,d]},rc=r=>(e,t,n)=>[r,n],nc=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:a}=r;return[r,a-(t-n)]},sc=r=>(e,t,n)=>{const{lower:a,upper:i}=r;return n=Xl(n,a,i),[e,n]};let Us=class _e{ops=[];currBounds=null;currType=null;reversed=!1;constructor(){this.ops=[]}static translate(e){return new _e().translate(e)}static magnify(e){return new _e().magnify(e)}static scale(e,t){return new _e().scale(e,t)}translate(e){const t=this.new(),n=Ql(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=ec(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=De(e,t),a=this.new(),i=tc(n);return i.type="scale",a.ops.push(i),a}clamp(e,t){const n=De(e,t),a=this.new(),i=sc(n);return i.type="clamp",a.ops.push(i),a}reBound(e,t){const n=De(e,t),a=this.new(),i=rc(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=nc();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new _e;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||t.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&t.push([a,i])}),t.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new _e};(class se{x;y;currRoot;constructor(e=new Us,t=new Us,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new se().translate(e,t)}static translateX(e){return new se().translateX(e)}static translateY(e){return new se().translateY(e)}static clamp(e){return new se().clamp(e)}static magnify(e){return new se().magnify(e)}static scale(e){return new se().scale(e)}static reBound(e){return new se().reBound(e)}translate(e,t){const n=Gl(e,t),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(Kl(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!Wl(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(qr(e)),t.y=t.y.scale(Zr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(qr(e)),t.y=this.y.reBound(Zr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(qr(e)),t.y=this.y.clamp(Zr(e)),t}copy(){const e=new se;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 Vn(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 se});let ac=(r,e=21)=>(t=e)=>{let n="",a=t|0;for(;a--;)n+=r[Math.random()*r.length|0];return n};const ic="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",oc=11,lc=ac(ic,oc),cc=()=>lc(),uc=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,hc=s.z.enum(["static","dynamic"]),dc=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)])]),Ma=(r,e)=>{const t=new C(e);if(![k.DAY,k.HOUR,k.MINUTE,k.SECOND,k.MILLISECOND,k.MICROSECOND,k.NANOSECOND].some(a=>a.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof C?new C(n):new k(n)};let C=class m extends ut{constructor(e,t="UTC"){if(e==null)super(m.now().valueOf());else if(e instanceof Date)super(BigInt(e.getTime())*m.MILLISECOND.valueOf());else if(typeof e=="string")super(m.parseDateTimeString(e,t).valueOf());else if(Array.isArray(e))super(m.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="local"&&(n=m.utcOffset.valueOf()),typeof e=="number"&&(isFinite(e)?e=Math.trunc(e):(isNaN(e)&&(e=0),e===1/0?e=m.MAX:e=m.MIN)),super(BigInt(e.valueOf())+n)}}static parseDate([e=1970,t=1,n=1]){const a=new Date(e,t-1,n,0,0,0,0);return new m(BigInt(a.getTime())*m.MILLISECOND.valueOf()).truncate(m.DAY).valueOf()}valueOf(){return this.value}static parseTimeString(e,t="UTC"){const[n,a,i]=e.split(":");let o="00",l="00";i!=null&&([o,l]=i.split("."));let c=m.hours(parseInt(n??"00")).add(m.minutes(parseInt(a??"00"))).add(m.seconds(parseInt(o??"00"))).add(m.milliseconds(parseInt(l??"00")));return t==="local"&&(c=c.add(m.utcOffset)),c.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return m.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new m(BigInt(n.getTime())*m.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(m.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new k(BigInt(new Date().getTimezoneOffset())*m.MINUTE.valueOf())}static since(e){return new m().span(e)}date(){return new Date(this.milliseconds)}equals(e){return this.valueOf()===new m(e).valueOf()}span(e){return this.range(e).span}range(e){return new zt(this,e).makeValid()}spanRange(e){return this.range(this.add(e)).makeValid()}get isZero(){return this.valueOf()===0n}after(e){return this.valueOf()>new m(e).valueOf()}afterEq(e){return this.valueOf()>=new m(e).valueOf()}before(e){return this.valueOf()<new m(e).valueOf()}beforeEq(e){return this.valueOf()<=new m(e).valueOf()}add(e){return new m(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new m(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(k.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(k.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(k.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(k.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(m.MILLISECOND.valueOf())}get microseconds(){return Number(this.valueOf())/Number(m.MICROSECOND.valueOf())}get nanoseconds(){return Number(this.valueOf())}get year(){return this.date().getUTCFullYear()}setYear(e){const t=this.date();return t.setUTCFullYear(e),new m(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new m(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new m(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new m(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new m(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new m(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new m(t)}toString(){return this.date().toISOString()}remainder(e){return Ma(this,e)}get isToday(){return this.truncate(k.DAY).equals(m.now().truncate(k.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new m(new Date)}static max(...e){let t=m.MIN;for(const n of e){const a=new m(n);a.after(t)&&(t=a)}return t}static min(...e){let t=m.MAX;for(const n of e){const a=new m(n);a.before(t)&&(t=a)}return t}static nanoseconds(e,t="UTC"){return new m(e,t)}static NANOSECOND=m.nanoseconds(1);static microseconds(e,t="UTC"){return m.nanoseconds(e*1e3,t)}static MICROSECOND=m.microseconds(1);static milliseconds(e,t="UTC"){return m.microseconds(e*1e3,t)}static MILLISECOND=m.milliseconds(1);static seconds(e,t="UTC"){return m.milliseconds(e*1e3,t)}static SECOND=m.seconds(1);static minutes(e,t="UTC"){return m.seconds(e*60,t)}static MINUTE=m.minutes(1);static hours(e,t="UTC"){return m.minutes(e*60,t)}static HOUR=m.hours(1);static days(e,t="UTC"){return m.hours(e*24,t)}static DAY=m.days(1);static MAX=new m((1n<<63n)-1n);static MIN=new m(0);static ZERO=new m(0);static z=s.z.union([s.z.instanceof(m),s.z.object({value:s.z.bigint()}).transform(e=>new m(e.value)),s.z.string().transform(e=>new m(BigInt(e))),s.z.number().transform(e=>new m(e)),s.z.bigint().transform(e=>new m(e)),s.z.date().transform(e=>new m(e)),s.z.custom(e=>e instanceof k).transform(e=>new m(e)),dc.transform(e=>new m(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},k=class v extends ut{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof v?e:e instanceof Ms?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 Ms?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 Ma(this,e)}truncate(e){return new v(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(v.DAY),t=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=t.sub(e),d=n.sub(t),h=a.sub(n),b=i.sub(a),S=o.sub(i),R=l.sub(o);let A="";return c.isZero||(A+=`${c.days}d `),u.isZero||(A+=`${u.hours}h `),d.isZero||(A+=`${d.minutes}m `),h.isZero||(A+=`${h.seconds}s `),b.isZero||(A+=`${b.milliseconds}ms `),S.isZero||(A+=`${S.microseconds}µs `),R.isZero||(A+=`${R.nanoseconds}ns`),A.trim()}mult(e){return new v(this.valueOf()*BigInt(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(Ze(e,1e3))}static MICROSECOND=v.microseconds(1);static milliseconds(e=1){return v.microseconds(Ze(e,1e3))}static MILLISECOND=v.milliseconds(1);static seconds(e=1){return v.milliseconds(Ze(e,1e3))}static SECOND=v.seconds(1);static minutes(e=1){return v.seconds(Ze(e,60))}static MINUTE=v.minutes(1);static hours(e){return v.minutes(Ze(e,60))}static HOUR=v.hours(1);static days(e){return v.hours(Ze(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.instanceof(v)])},Ms=class Ve extends ut{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Ve(e).valueOf()}get period(){return k.seconds(1/this.valueOf())}sampleCount(e){return new k(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new V(t).valueOf()}span(e){return k.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Ve(e)}static khz(e){return Ve.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new Ve(e)),s.z.instanceof(Ve)])},V=class de extends ut{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new hn(e*this.valueOf())}static UNKNOWN=new de(0);static BIT128=new de(16);static BIT64=new de(8);static BIT32=new de(4);static BIT16=new de(2);static BIT8=new de(1);static z=s.z.union([s.z.number().transform(e=>new de(e)),s.z.instanceof(de)])},zt=class ae{start;end;constructor(e,t){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(t))}get span(){return new k(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 ae(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=k.ZERO){if(t.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<=t.valueOf()&&a<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=k.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 k(i.sub(a)).greaterThanOrEqual(t)}contains(e){return e instanceof ae?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new ae(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new ae(C.min(...e.map(t=>t.start)),C.max(...e.map(t=>t.end)))}static MAX=new ae(C.MIN,C.MAX);static MIN=new ae(C.MAX,C.MIN);static ZERO=new ae(C.ZERO,C.ZERO);static z=s.z.union([s.z.object({start:C.z,end:C.z}).transform(e=>new ae(e.start,e.end)),s.z.instanceof(ae)]);static sort(e,t){return C.sort(e.start,t.start)||C.sort(e.end,t.end)}},P=class p extends ut{constructor(e){if(e instanceof p||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=p.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.valueOf())}}get Array(){const e=p.ARRAY_CONSTRUCTORS.get(this.toString());if(e==null)throw new Error(`unable to find array constructor for ${this.valueOf()}`);return e}equals(e){return this.valueOf()===e.valueOf()}matches(...e){return e.some(t=>this.equals(t))}toString(){return this.valueOf()}get isVariable(){return this.equals(p.JSON)||this.equals(p.STRING)}get isNumeric(){return!this.isVariable&&!this.equals(p.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=p.DENSITIES.get(this.toString());if(e==null)throw new Error(`unable to find density for ${this.valueOf()}`);return e}get isUnsignedInteger(){return this.equals(p.UINT8)||this.equals(p.UINT16)||this.equals(p.UINT32)||this.equals(p.UINT64)}get isSignedInteger(){return this.equals(p.INT8)||this.equals(p.INT16)||this.equals(p.INT32)||this.equals(p.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(p.INT32)&&e.equals(p.FLOAT64)||this.equals(p.INT8)&&e.equals(p.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 p.BIG_INT_TYPES.some(e=>e.equals(this))}static UNKNOWN=new p("unknown");static FLOAT64=new p("float64");static FLOAT32=new p("float32");static INT64=new p("int64");static INT32=new p("int32");static INT16=new p("int16");static INT8=new p("int8");static UINT64=new p("uint64");static UINT32=new p("uint32");static UINT16=new p("uint16");static UINT8=new p("uint8");static BOOLEAN=this.UINT8;static TIMESTAMP=new p("timestamp");static UUID=new p("uuid");static STRING=new p("string");static JSON=new p("json");static ARRAY_CONSTRUCTORS=new Map([[p.UINT8.toString(),Uint8Array],[p.UINT16.toString(),Uint16Array],[p.UINT32.toString(),Uint32Array],[p.UINT64.toString(),BigUint64Array],[p.FLOAT32.toString(),Float32Array],[p.FLOAT64.toString(),Float64Array],[p.INT8.toString(),Int8Array],[p.INT16.toString(),Int16Array],[p.INT32.toString(),Int32Array],[p.INT64.toString(),BigInt64Array],[p.TIMESTAMP.toString(),BigInt64Array],[p.STRING.toString(),Uint8Array],[p.JSON.toString(),Uint8Array],[p.UUID.toString(),Uint8Array]]);static ARRAY_CONSTRUCTOR_DATA_TYPES=new Map([[Uint8Array.name,p.UINT8],[Uint16Array.name,p.UINT16],[Uint32Array.name,p.UINT32],[BigUint64Array.name,p.UINT64],[Float32Array.name,p.FLOAT32],[Float64Array.name,p.FLOAT64],[Int8Array.name,p.INT8],[Int16Array.name,p.INT16],[Int32Array.name,p.INT32],[BigInt64Array.name,p.INT64]]);static DENSITIES=new Map([[p.UINT8.toString(),V.BIT8],[p.UINT16.toString(),V.BIT16],[p.UINT32.toString(),V.BIT32],[p.UINT64.toString(),V.BIT64],[p.FLOAT32.toString(),V.BIT32],[p.FLOAT64.toString(),V.BIT64],[p.INT8.toString(),V.BIT8],[p.INT16.toString(),V.BIT16],[p.INT32.toString(),V.BIT32],[p.INT64.toString(),V.BIT64],[p.TIMESTAMP.toString(),V.BIT64],[p.STRING.toString(),V.UNKNOWN],[p.JSON.toString(),V.UNKNOWN],[p.UUID.toString(),V.BIT128]]);static ALL=[p.UNKNOWN,p.FLOAT64,p.FLOAT32,p.INT64,p.INT32,p.INT16,p.INT8,p.UINT64,p.UINT32,p.UINT16,p.UINT8,p.TIMESTAMP,p.UUID,p.STRING,p.JSON];static BIG_INT_TYPES=[p.INT64,p.UINT64,p.TIMESTAMP];static z=s.z.union([s.z.string().transform(e=>new p(e)),s.z.instanceof(p)])},hn=class I extends ut{constructor(e){super(e.valueOf())}largerThan(e){return this.valueOf()>e.valueOf()}smallerThan(e){return this.valueOf()<e.valueOf()}add(e){return I.bytes(this.valueOf()+e.valueOf())}sub(e){return I.bytes(this.valueOf()-e.valueOf())}truncate(e){return new I(Math.trunc(this.valueOf()/e.valueOf())*e.valueOf())}remainder(e){return I.bytes(this.valueOf()%e.valueOf())}get gigabytes(){return this.valueOf()/I.GIGABYTE.valueOf()}get megabytes(){return this.valueOf()/I.MEGABYTE.valueOf()}get kilobytes(){return this.valueOf()/I.KILOBYTE.valueOf()}get terabytes(){return this.valueOf()/I.TERABYTE.valueOf()}toString(){const e=this.truncate(I.TERABYTE),t=this.truncate(I.GIGABYTE),n=this.truncate(I.MEGABYTE),a=this.truncate(I.KILOBYTE),i=this.truncate(I.BYTE),o=e,l=t.sub(e),c=n.sub(t),u=a.sub(n),d=i.sub(a);let h="";return o.isZero||(h+=`${o.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),c.isZero||(h+=`${c.megabytes}MB `),u.isZero||(h+=`${u.kilobytes}KB `),(!d.isZero||h==="")&&(h+=`${d.valueOf()}B`),h.trim()}static bytes(e=1){return new I(e)}static BYTE=new I(1);static kilobytes(e=1){return I.bytes(e.valueOf()*1e3)}static KILOBYTE=I.kilobytes(1);static megabytes(e=1){return I.kilobytes(e.valueOf()*1e3)}static MEGABYTE=I.megabytes(1);static gigabytes(e=1){return I.megabytes(e.valueOf()*1e3)}static GIGABYTE=I.gigabytes(1);static terabytes(e){return I.gigabytes(e.valueOf()*1e3)}static TERABYTE=I.terabytes(1);static ZERO=new I(0);static z=s.z.union([s.z.number().transform(e=>new I(e)),s.z.instanceof(I)]);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 La=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof C||r instanceof k||r instanceof Date},fc=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):ur(t,-n),ur=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),pc=/^(?:[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 yc(r){return typeof r=="string"&&pc.test(r)}const F=[];for(let r=0;r<256;++r)F.push((r+256).toString(16).slice(1));function gc(r,e=0){return(F[r[e+0]]+F[r[e+1]]+F[r[e+2]]+F[r[e+3]]+"-"+F[r[e+4]]+F[r[e+5]]+"-"+F[r[e+6]]+F[r[e+7]]+"-"+F[r[e+8]]+F[r[e+9]]+"-"+F[r[e+10]]+F[r[e+11]]+F[r[e+12]]+F[r[e+13]]+F[r[e+14]]+F[r[e+15]]).toLowerCase()}function mc(r,e=0){const t=gc(r,e);if(!yc(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Pa=(r,e)=>mc(r,e),be=-1,wc=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),bc=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),dn=10,vc=(r,e)=>{if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},Da="sy_x_telem_series";let Ba=class Se{key;discriminator=Da;dataType;sampleOffset;gl;_data;timeRange=zt.ZERO;alignment=0n;cachedMin;cachedMax;writePos=be;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:zt.z.optional(),dataType:P.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([wc,bc,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:hc.optional().default("static").optional()});static z=Se.crudeZ.transform(e=>new Se(e));constructor(e){Tc(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,key:l=cc(),data:c}=e;if(Oc(c)){const h=c;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this.timeRange=h.timeRange,this.alignment=h.alignment,this.cachedMin=h.cachedMin,this.cachedMax=h.cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this.cachedLength=h.cachedLength;return}const u=La(c),d=Array.isArray(c);if(t!=null)this.dataType=new P(t);else{if(c instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||u){let h=c;if(!u){if(c.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");h=c[0]}if(typeof h=="string")this.dataType=P.STRING;else if(typeof h=="number")this.dataType=P.FLOAT64;else if(typeof h=="bigint")this.dataType=P.INT64;else if(typeof h=="boolean")this.dataType=P.BOOLEAN;else if(h instanceof C||h instanceof Date||h instanceof C)this.dataType=P.TIMESTAMP;else if(typeof h=="object")this.dataType=P.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new P(c)}if(!d&&!u)this._data=c;else if(d&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let h=u?[c]:c;const b=h[0];(b instanceof C||b instanceof Date||b instanceof k)&&(h=h.map(S=>new C(S).valueOf())),this.dataType.equals(P.STRING)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.join(`
|
|
2
|
-
`)}
|
|
3
|
-
`).buffer):this.dataType.equals(P.JSON)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.map(S=>un.encodeString(S)).join(`
|
|
4
|
-
`)}
|
|
5
|
-
`).buffer):this.dataType.usesBigInt&&typeof b=="number"?this._data=new this.dataType.Array(h.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof b=="bigint"?this._data=new this.dataType.Array(h.map(Number)).buffer:this._data=new this.dataType.Array(h).buffer}this.key=l,this.alignment=o,this.sampleOffset=a??0,this.timeRange=n??zt.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new P(t).Array(e),i=new Se({data:a.buffer,dataType:t,...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===be)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===be)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return typeof this._data=="object"&&"buffer"in this._data?this._data.buffer:this._data}get underlyingData(){return new this.dataType.Array(this._data)}get data(){return this.writePos===be?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(P.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(un.decodeString(t)))}get byteCapacity(){return new hn(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===be?this.byteCapacity:this.dataType.isVariable?new hn(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===be?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 t=[0];return this.data.forEach((n,a)=>{n===dn&&(e++,t.push(a+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=fc(this.dataType,e,this.data[a],t);return new Se({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(P.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}return this.cachedMax}get max(){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(),ur(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(P.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}return this.cachedMin}get min(){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(),ur(this.cachedMin,this.sampleOffset))}get bounds(){return De(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){const t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(P.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return ur(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=Pa(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){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]===dn){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(P.STRING)?new TextDecoder().decode(i):Aa(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1;const a=Il(e);for(;t<=n;){const i=Math.floor((t+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(P.FLOAT32)&&!this.dataType.equals(P.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:a}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==be){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=be}as(e){return vc(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ps(this.alignmentBounds.lower),upper:Ps(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return De(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Sc(this);return this.dataType.equals(P.JSON)?new zc(e):e}return this.dataType.equals(P.UUID)?new Ec(this):new Nc(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Ls(this,e,t??this.length)}subAlignmentIterator(e,t){return new Ls(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new Se({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(t,n):a=this.data.slice(t,n),new Se({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new Se({data:this.buffer,dataType:this.dataType,timeRange:zt.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(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}};const Tc=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Ba?!0:La(r),Oc=uc(Da,Ba);let Ls=class{series;end;index;constructor(r,e,t){this.series=r;const n=De(0,r.length);this.end=Is(n,t),this.index=Is(n,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},Sc=class{series;index;decoder;constructor(r){if(!r.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=r,this.index=0,this.decoder=new TextDecoder}next(){const r=this.index,e=this.series.data;for(;this.index<e.length&&e[this.index]!==dn;)this.index++;const t=this.index;return r===t?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(r,t))})}},zc=class $a{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:un.decodeString(e.value,$a.schema)}}};class Ec{series;index;data;density;constructor(e){if(!e.dataType.equals(P.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=P.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=Pa(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}let Nc=class{series;index;constructor(r){this.series=r,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 Ps=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}};s.z.object({key:s.z.string(),value:s.z.string()});s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown());const Ac=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Ac();const kc=["macOS","Windows","Linux"],xc=["macos","windows","linux"],Cc={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(kc).or(s.z.enum(xc).transform(r=>Cc[r]));const Ic=(...r)=>r.map(Fa).join(""),Fa=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),jc=r=>r.endsWith("/")?r.slice(0,-1):r,Rc=(r,e="")=>r===null?"":`?${Object.entries(r).filter(([,t])=>t==null?!1:Array.isArray(t)?t.length>0:!0).map(([t,n])=>`${e}${t}=${n}`).join("&")}`;let Uc=class hr{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=t,this.path=Fa(a)}replace(e){return new hr({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new hr({...this,pathPrefix:Ic(this.path,e)})}toString(){return jc(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new hr({host:"unknown",port:0})};const Mc=async r=>await new Promise(e=>setTimeout(e,k.fromMilliseconds(r).milliseconds));class Lc{config;retries;interval;constructor(e){this.config={baseInterval:new k(e?.baseInterval??k.seconds(1)),maxRetries:e?.maxRetries??5,scale:e?.scale??1,sleepFn:e?.sleepFn??Mc},this.retries=0,this.interval=new k(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const Pc=s.z.object({baseInterval:k.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Dc=Object.freeze(Object.defineProperty({__proto__:null,Breaker:Lc,breakerConfigZ:Pc},Symbol.toStringTag,{value:"Module"})),Bc=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,qa=s.z.string().regex(Bc),tt=s.z.number().min(0).max(255),Za=s.z.number().min(0).max(1),Ya=s.z.tuple([tt,tt,tt,Za]),$c=s.z.tuple([tt,tt,tt]),Fc=s.z.object({rgba255:Ya}),qc=s.z.number().min(0).max(360),Zc=s.z.number().min(0).max(100),Yc=s.z.number().min(0).max(100),_c=s.z.tuple([qc,Zc,Yc,Za]),Hn=s.z.union([qa,$c,Ya,_c,Fc]),Vc=Hn.transform(r=>Wn(r)),Wn=(r,e=1)=>{if(r=Hn.parse(r),typeof r=="string")return Hc(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}return r.rgba255},Hc=(r,e=1)=>(r=qa.parse(r),r=Wc(r),[nr(r,0),nr(r,2),nr(r,4),r.length===8?nr(r,6)/255:e]),nr=(r,e)=>parseInt(r.slice(e,e+2),16),Wc=r=>r.startsWith("#")?r.slice(1):r;Wn("#000000");Wn("#ffffff");const Gc=s.z.object({key:s.z.string(),color:Hn,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(Gc);const Kc=s.z.object({key:s.z.string(),name:s.z.string(),color:Vc});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(Kc)});s.z.int().min(0).max(255);s.z.object({name:s.z.string(),key:s.z.string()});const Jc=r=>Object.getOwnPropertySymbols(globalThis).includes(r),Xc=(r,e)=>{const t=Symbol.for(r);if(!Jc(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},_a="sy_x_error",Qc=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Ft=r=>class Et extends Error{static discriminator=_a;discriminator=Et.discriminator;static TYPE=r;type=Et.TYPE;static matches=Qc(r);matches=Et.matches;constructor(t,n){super(t,n),this.name=Et.TYPE}static sub(t){return Ft(`${r}.${t}`)}},Va=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==_a)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},He="unknown",fn="nil";class eu{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:fn,data:""};if(Va(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:He,data:e.message};if(typeof e=="string")return{type:He,data:e};try{return{type:He,data:JSON.stringify(e)}}catch{return{type:He,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===fn)return null;if(e.type===He)return new pn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new pn(e.data)}}const Gn=Xc("synnax-error-registry",()=>new eu),tu=({encode:r,decode:e})=>Gn().register({encode:r,decode:e}),ru=r=>Gn().encode(r),nu=r=>r==null?null:Gn().decode(r);let pn=class extends Ft("unknown"){};const su=s.z.object({type:s.z.string(),data:s.z.string()});class au extends Ft("canceled"){}class iu extends Ft("not_implemented"){}const Ce=Object.freeze(Object.defineProperty({__proto__:null,Canceled:au,NONE:fn,NotImplemented:iu,UNKNOWN:He,Unknown:pn,createTyped:Ft,decode:nu,encode:ru,isTyped:Va,payloadZ:su,register:tu},Symbol.toStringTag,{value:"Module"})),ou=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Ha=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),lu=Ha.extend({result:s.json()}),cu=Ha.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),uu=s.union([lu,cu]);s.union([ou,uu]);s.z.string().regex(/^\d+\.\d+\.\d+$/);const hu=["standard","scientific","engineering"];s.z.enum(hu);s.z.enum(["success","info","warning","error","loading","disabled"]);let qt=class extends Ce.createTyped("freighter"){},te=class extends qt.sub("eof"){constructor(){super("EOF")}},nt=class extends qt.sub("stream_closed"){constructor(){super("StreamClosed")}},Ie=class extends qt.sub("unreachable"){url;constructor(r={}){const{message:e="Unreachable",url:t=Uc.UNKNOWN}=r;super(e),this.url=t}};const du=r=>{if(!r.type.startsWith(qt.TYPE))return null;if(te.matches(r))return{type:te.TYPE,data:"EOF"};if(nt.matches(r))return{type:nt.TYPE,data:"StreamClosed"};if(Ie.matches(r))return{type:Ie.TYPE,data:"Unreachable"};throw new Error(`Unknown error type: ${r.type}: ${r.message}`)},fu=r=>{if(!r.type.startsWith(qt.TYPE))return null;switch(r.type){case te.TYPE:return new te;case nt.TYPE:return new nt;case Ie.TYPE:return new Ie;default:throw new Ce.Unknown(`Unknown error type: ${r.data}`)}};Ce.register({encode:du,decode:fu});class Wa{middleware=[];use(...e){this.middleware.push(...e)}async executeMiddleware(e,t){let n=0;const a=async i=>{if(n===this.middleware.length)return await t(i);const o=this.middleware[n];return n++,await o(i,a)};return await a(e)}}const Ga="Content-Type",pu=r=>typeof r.cause=="object"&&r.cause!==null&&"code"in r.cause&&r.cause.code==="ECONNREFUSED",yu=400;class gu extends Wa{endpoint;encoder;constructor(e,t,n=!1){return super(),this.endpoint=e.replace({protocol:n?"https":"http"}),this.encoder=t,new Proxy(this,{get:(a,i,o)=>i==="endpoint"?this.endpoint:Reflect.get(a,i,o)})}get headers(){return{[Ga]:this.encoder.contentType}}async send(e,t,n,a){t=n?.parse(t);let i=null;const o=this.endpoint.child(e),l={};l.method="POST",l.body=this.encoder.encode(t??{});const[,c]=await this.executeMiddleware({target:o.toString(),protocol:this.endpoint.protocol,params:{},role:"client"},async u=>{const d={...u,params:{}};l.headers={...this.headers,...u.params};let h;try{h=await fetch(u.target,l)}catch(S){if(!(S instanceof Error))throw S;return[d,pu(S)?new Ie({url:o}):S]}const b=await h.arrayBuffer();if(h?.ok)return a!=null&&(i=this.encoder.decode(b,a)),[d,null];try{if(h.status!==yu)return[d,new Error(h.statusText)];const S=this.encoder.decode(b,Ce.payloadZ),R=Ce.decode(S);return[d,R]}catch(S){return[d,new Error(`[freighter] - failed to decode error: ${h.statusText}: ${S.message}`)]}});if(c!=null)return[null,c];if(i==null)throw new Error("Response must be defined");return[i,null]}}const mu=(r,e)=>{class t{wrapped;constructor(a){this.wrapped=a}use(...a){this.wrapped.use(...a)}async send(a,i,o,l){const c=new Dc.Breaker(e);do{const[u,d]=await this.wrapped.send(a,i,o,l);if(d==null)return[u,null];if(!Ie.matches(d))return[null,d];if(!await c.wait())return[u,d]}while(!0)}}return new t(r)},g=async(r,e,t,n,a)=>{const[i,o]=await r.send(e,t,n,a);if(o!=null)throw o;return i},wu=s.z.object({type:s.z.enum(["data","close","open"]),payload:s.z.unknown(),error:s.z.optional(Ce.payloadZ)});class bu{codec;reqSchema;resSchema;ws;serverClosed;sendClosed;receiveDataQueue=[];receiveCallbacksQueue=[];constructor(e,t,n,a){this.codec=t,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 Ce.decode(e.error)}return null}send(e){if(this.serverClosed!=null)return new te;if(this.sendClosed)throw new nt;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=Ce.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,t)=>this.receiveCallbacksQueue.push({resolve:e,reject:t}))}addMessage(e){const t=this.receiveCallbacksQueue.shift();t!=null?t.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,wu))}onClose(e){this.addMessage({type:"close",error:{type:e.code===Tu?te.TYPE:nt.TYPE,data:""}})}}const vu="freighterctx",Tu=1e3;let Ou=class yn extends Wa{baseUrl;encoder;secure;static MESSAGE_TYPE="arraybuffer";constructor(e,t,n=!1){super(),this.secure=n,this.baseUrl=e.replace({protocol:n?"wss":"ws"}),this.encoder=t}withCodec(e){const t=new yn(this.baseUrl,e,this.secure);return t.use(...this.middleware),t}async stream(e,t,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=yn.MESSAGE_TYPE;const u=await this.wrapSocket(l,t,n);return u instanceof Error?[c,u]:(a=u,[c,null])});if(i!=null)throw i;return a}buildURL(e,t){const n=Rc({[Ga]:this.encoder.contentType,...t.params},vu);return this.baseUrl.child(e).toString()+n}async wrapSocket(e,t,n){return await new Promise(a=>{e.onopen=()=>{const i=new bu(e,this.encoder,t,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 Su=r=>Array.isArray(r)?r:r==null?[]:[r],O=Object.freeze(Object.defineProperty({__proto__:null,toArray:Su},Symbol.toStringTag,{value:"Module"})),zu=r=>{const e=r.replace(/_[a-z]/g,t=>t[1].toUpperCase());return e.length>1&&e[0]===e[0].toUpperCase()&&e[1]===e[1].toUpperCase()||e.length===0?e:e[0].toLowerCase()+e.slice(1)},Kn=r=>{const e=(t,n=gn)=>{if(typeof t=="string")return r(t);if(Array.isArray(t))return t.map(o=>e(o,n));if(!Yr(t))return t;n=ku(n);const a={},i=t;return"toJSON"in i&&typeof i.toJSON=="function"?e(i.toJSON(),n):(Object.keys(i).forEach(o=>{let l=i[o];const c=r(o);n.recursive&&(Yr(l)?Bs(l)||(l=e(l,n)):n.recursiveInArray&&Ds(l)&&(l=[...l].map(u=>{let d=u;return Yr(u)?Bs(d)||(d=e(u,n)):Ds(u)&&(d=e({key:u},n).key),d}))),a[c]=l}),a)};return e},Jn=Kn(zu),Eu=r=>r.replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}_${n.toLowerCase()}`),Ka=Kn(Eu),Nu=r=>r.length===0?r:r[0].toUpperCase()+r.slice(1),Au=[Number,String,Uint8Array],gn={recursive:!0,recursiveInArray:!0},ku=(r=gn)=>(r.recursive==null?r=gn:r.recursiveInArray??=!1,r),Ds=r=>r!=null&&Array.isArray(r),Yr=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),Bs=r=>Au.some(e=>r instanceof e),xu=r=>r.replace(/\s+/g,"-").replace(/([a-z0-9])([A-Z])/g,(e,t,n)=>`${t}-${n.toLowerCase()}`).toLowerCase(),Cu=Kn(xu),Iu=Object.freeze(Object.defineProperty({__proto__:null,camelToSnake:Ka,capitalize:Nu,snakeToCamel:Jn,toKebab:Cu},Symbol.toStringTag,{value:"Module"})),Ja=r=>r!=null&&typeof r=="object"&&!Array.isArray(r);let Xa=class{contentType="application/json";decoder;encoder;constructor(){this.decoder=new TextDecoder,this.encoder=new TextEncoder}encode(r){return this.encoder.encode(this.encodeString(r))}decode(r,e){return this.decodeString(this.decoder.decode(r),e)}decodeString(r,e){const t=JSON.parse(r),n=Jn(t);return e!=null?e.parse(n):n}encodeString(r){const e=Ka(r);return JSON.stringify(e,(t,n)=>ArrayBuffer.isView(n)?Array.from(n):typeof n=="bigint"?n.toString():n)}},Qa=class{contentType="text/csv";encode(r){const e=this.encodeString(r);return new TextEncoder().encode(e)}decode(r,e){const t=new TextDecoder().decode(r);return this.decodeString(t,e)}encodeString(r){if(!Array.isArray(r)||r.length===0||!Ja(r[0]))throw new Error("Payload must be an array of objects");const e=Object.keys(r[0]),t=[e.join(",")];return r.forEach(n=>{const a=e.map(i=>JSON.stringify(n[i]??""));t.push(a.join(","))}),t.join(`
|
|
7
|
-
`)}decodeString(r,e){const[t,...n]=r.trim().split(`
|
|
8
|
-
`).map(o=>o.trim());if(t.length===0)return e!=null?e.parse({}):{};const a=t.split(",").map(o=>o.trim()),i={};return a.forEach(o=>{i[o]=[]}),n.forEach(o=>{const l=o.split(",").map(c=>c.trim());a.forEach((c,u)=>{const d=this.parseValue(l[u]);d!=null&&i[c].push(d)})}),e!=null?e.parse(i):i}parseValue(r){if(r==null||r.length===0)return null;const e=Number(r);return isNaN(e)?r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r:e}},ei=class{contentType="text/plain";encode(r){if(typeof r!="string")throw new Error("TextCodec.encode payload must be a string");return new TextEncoder().encode(r)}decode(r,e){const t=new TextDecoder().decode(r);return e!=null?e.parse(t):t}};const Ct=new Xa,ju=new Qa,Ru=new ei,Uu=[Ct],$e=Object.freeze(Object.defineProperty({__proto__:null,CSVCodec:Qa,CSV_CODEC:ju,ENCODERS:Uu,JSONCodec:Xa,JSON_CODEC:Ct,TEXT_CODEC:Ru,TextCodec:ei},Symbol.toStringTag,{value:"Module"})),mn=r=>[...new Set(r)],Mu=(r,e,t=!0)=>{const n=new Map;return r.forEach(a=>{const i=e(a);if(n.has(i)){if(t)return;n.delete(i)}n.set(i,a)}),Array.from(n.values())},$s=Object.freeze(Object.defineProperty({__proto__:null,by:Mu,unique:mn},Symbol.toStringTag,{value:"Module"}));class ht{value;constructor(e){this.value=e}valueOf(){return this.value}toJSON(){return this.value}toString(){return this.value.toString()}}const Lu=r=>r!=null&&typeof r=="object"&&"toString"in r,Ar=(r,e=!1)=>{const t=Lu(r)?"stringer":typeof r;let n;switch(t){case"string":n=(a,i)=>a.localeCompare(i);break;case"stringer":n=(a,i)=>a.toString().localeCompare(i.toString());break;case"number":n=(a,i)=>Number(a)-Number(i);break;case"bigint":n=(a,i)=>BigInt(a)-BigInt(i)>0n?1:-1;break;case"boolean":n=(a,i)=>Number(a)-Number(i);break;case"undefined":n=()=>0;break;default:return console.warn(`sortFunc: unknown type ${t}`),()=>-1}return e?ri(n):n},Pu=(r,e,t)=>{const n=Ar(e[r],t);return(a,i)=>n(a[r],i[r])},Du=(r,e)=>r.length!==e.length?r.length-e.length:r.every((t,n)=>t===e[n])?0:-1,ti=(r,e)=>{if(r.length!==e.length)return r.length-e.length;if(r.length===0)return 0;const t=Ar(r[0]),n=[...r].sort(t),a=[...e].sort(t);return n.every((i,o)=>i===a[o])?0:-1},Bu=(r,e)=>{const t=mn(r),n=mn(e);return ti(t,n)},$u=(r,e)=>r===e?0:r==="first"&&e==="last"?1:-1,ri=r=>(e,t)=>r(t,e),dt=0,dr=-1,fr=1,ni=r=>r<dt,si=r=>r>dt,Fu=r=>r>=dt,ai=r=>r===dt,qu=(r,e)=>{const t=/([a-zA-Z]+)|(\d+)/g,n=r.replace(/[\s_.-]+/g,"").match(t),a=e.replace(/[\s_.-]+/g,"").match(t);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},Fs=Object.freeze(Object.defineProperty({__proto__:null,EQUAL:dt,GREATER_THAN:fr,LESS_THAN:dr,isEqualTo:ai,isGreaterThan:si,isGreaterThanEqual:Fu,isLessThan:ni,newF:Ar,newFieldF:Pu,order:$u,primitiveArrays:Du,reverseF:ri,stringsWithNumbers:qu,uniqueUnorderedPrimitiveArrays:Bu,unorderedPrimitiveArrays:ti},Symbol.toStringTag,{value:"Module"})),kr=s.z.tuple([s.z.number(),s.z.number()]);s.z.tuple([s.z.bigint(),s.z.bigint()]);const ii=s.z.object({width:s.z.number(),height:s.z.number()}),Zu=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()}),Yu=["width","height"];s.z.enum(Yu);const _u=["start","center","end"],Vu=["signedWidth","signedHeight"];s.z.enum(Vu);const wr=s.z.object({x:s.z.number(),y:s.z.number()}),Hu=s.z.object({clientX:s.z.number(),clientY:s.z.number()}),Wu=["x","y"],oi=s.z.enum(Wu),li=["top","right","bottom","left"];s.z.enum(li);const Gu=["left","right"],ci=s.z.enum(Gu),Ku=["top","bottom"],ui=s.z.enum(Ku),hi=["center"],qs=s.z.enum(hi),Ju=[...li,...hi],di=s.z.enum(Ju);s.z.enum(_u);const Xu=["first","last"];s.z.enum(Xu);const Qu=s.z.object({lower:s.z.number(),upper:s.z.number()}),eh=s.z.object({lower:s.z.bigint(),upper:s.z.bigint()});s.z.union([Qu,kr]);s.z.union([eh,kr]);s.z.enum([...oi.options,...di.options]);s.z.union([oi,di,s.z.instanceof(String)]);const _r=(r,e)=>typeof r=="bigint"?r-BigInt(e):r-Number(e),th=(r,e)=>typeof r=="bigint"?r+BigInt(e):r+Number(e),Zs=(r,e)=>typeof r=="bigint"?r===BigInt(e):r===Number(e),rh=(r,e)=>r<=e?r:typeof r=="bigint"?r<=e?r:BigInt(e):r<=e?r:Number(e),nh=r=>r<0?-r:r,Ye=(r,e)=>typeof r=="bigint"?r*BigInt(e):r*Number(e),Z=(r,e,t)=>{const n={};if(typeof e=="object"&&(t=e,e=void 0),t={makeValid:!0,...t},typeof r=="number"||typeof r=="bigint")e!=null?(n.lower=r,n.upper=e):(n.lower=typeof r=="bigint"?0n:0,n.upper=r);else if(Array.isArray(r)){if(r.length!==2)throw new Error("bounds: expected array of length 2");[n.lower,n.upper]=r}else n.lower=r.lower,n.upper=r.upper;return t?.makeValid?sh(n):n},sh=r=>r.lower>r.upper?{lower:r.upper,upper:r.lower}:r,Ys=(r,e)=>{const t=Z(r);return e<t.lower?t.lower:e>=t.upper?t.upper-(typeof t.upper=="number"?1:1n):e},sr=(r,e)=>{const t=Z(r);if(typeof e=="number"||typeof e=="bigint")return e>=t.lower&&e<t.upper;const n=Z(e);return n.lower>=t.lower&&n.upper<=t.upper},ah=r=>({lower:Math.min(...r.map(e=>Z(e).lower)),upper:Math.max(...r.map(e=>Z(e).upper))}),ih=(r,e,t)=>{const n=r.map(l=>Z(l)),a=t>0?1:t<0?-1:0;if(a===0)return e;let i=t,o=e;for(;Zs(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=_r(c.upper,o):u=_r(o,c.lower),u>0){const d=rh(nh(i),u);if(o=th(o,a>0?d:-d),i=_r(i,a>0?d:-d),Zs(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},oh=(r,e,t)=>{const n=r.map(o=>Z(o));if(e===t)return typeof e=="bigint"?0n:0;const a=e<t?Z([e,t]):Z([t,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:ci.or(qs),y:ui.or(qs)});const lh=s.z.object({x:ci,y:ui}),ch=Object.freeze({x:"left",y:"top"}),uh=(r,e)=>r.x===e.x&&r.y===e.y,_s=s.z.union([s.z.number(),wr,kr,ii,Zu,Hu]),hh=(r,e)=>{if(typeof r=="string"){if(e===void 0)throw new Error("The y coordinate must be given.");return r==="x"?{x:e,y:0}:{x:0,y:e}}return typeof r=="number"?{x:r,y:e??r}:Array.isArray(r)?{x:r[0],y:r[1]}:"signedWidth"in r?{x:r.signedWidth,y:r.signedHeight}:"clientX"in r?{x:r.clientX,y:r.clientY}:"width"in r?{x:r.width,y:r.height}:{x:r.x,y:r.y}},Vs=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:wr,two:wr,root:lh});const Xn=(r,e,t=0,n=0,a)=>{const i={one:{...Vs},two:{...Vs},root:a??ch};if(typeof r=="number"){if(typeof e!="number")throw new Error("Box constructor called with invalid arguments");return i.one={x:r,y:e},i.two={x:i.one.x+t,y:i.one.y+n},i}return"one"in r&&"two"in r&&"root"in r?{...r,root:a??r.root}:("getBoundingClientRect"in r&&(r=r.getBoundingClientRect()),"left"in r?(i.one={x:r.left,y:r.top},i.two={x:r.right,y:r.bottom},i):(i.one=r,e==null?i.two={x:i.one.x+t,y:i.one.y+n}:typeof e=="number"?i.two={x:i.one.x+e,y:i.one.y+t}:"width"in e?i.two={x:i.one.x+e.width,y:i.one.y+e.height}:"signedWidth"in e?i.two={x:i.one.x+e.signedWidth,y:i.one.y+e.signedHeight}:i.two=e,i))},Vr=r=>{const e=Xn(r);return{lower:e.one.x,upper:e.two.x}},Hr=r=>{const e=Xn(r);return{lower:e.one.y,upper:e.two.y}},dh=r=>typeof r!="object"||r==null?!1:"one"in r&&"two"in r&&"root"in r,fh=s.z.object({signedWidth:s.z.number(),signedHeight:s.z.number()});s.z.union([ii,fh,wr,kr]);const ph=(r,e,t)=>e!==void 0&&r<e?e:t!==void 0&&r>t?t:r;s.z.object({offset:_s,scale:_s});s.z.object({offset:s.z.number(),scale:s.z.number()});const yh=r=>(e,t,n,a)=>t==="dimension"?[e,n]:[e,a?n-r:n+r],gh=r=>(e,t,n,a)=>[e,a?n/r:n*r],mh=r=>(e,t,n)=>{if(e===null)return[r,n];const{lower:a,upper:i}=e,{lower:o,upper:l}=r,c=i-a,u=l-o;if(t==="dimension")return[r,n*(u/c)];const d=(n-a)*(u/c)+o;return[r,d]},wh=r=>(e,t,n)=>[r,n],bh=()=>(r,e,t)=>{if(r===null)throw new Error("cannot invert without bounds");if(e==="dimension")return[r,t];const{lower:n,upper:a}=r;return[r,a-(t-n)]},vh=r=>(e,t,n)=>{const{lower:a,upper:i}=r;return n=ph(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,t){return new We().scale(e,t)}translate(e){const t=this.new(),n=yh(e);return n.type="translate",t.ops.push(n),t}magnify(e){const t=this.new(),n=gh(e);return n.type="magnify",t.ops.push(n),t}scale(e,t){const n=Z(e,t),a=this.new(),i=mh(n);return i.type="scale",a.ops.push(i),a}clamp(e,t){const n=Z(e,t),a=this.new(),i=vh(n);return i.type="clamp",a.ops.push(i),a}reBound(e,t){const n=Z(e,t),a=this.new(),i=wh(n);return i.type="re-bound",a.ops.push(i),a}invert(){const e=bh();e.type="invert";const t=this.new();return t.ops.push(e),t}pos(e){return this.exec("position",e)}dim(e){return this.exec("dimension",e)}new(){const e=new We;return e.ops=this.ops.slice(),e.reversed=this.reversed,e}exec(e,t){return this.currBounds=null,this.ops.reduce(([n,a],i)=>i(n,e,a,this.reversed),[null,t])[1]}reverse(){const e=this.new();e.ops.reverse();const t=[];return e.ops.forEach((n,a)=>{if(n.type==="scale"||t.some(([o,l])=>a>=o&&a<=l))return;const i=e.ops.findIndex((o,l)=>o.type==="scale"&&l>a);i!==-1&&t.push([a,i])}),t.forEach(([n,a])=>{const i=e.ops.slice(n,a);i.unshift(e.ops[a]),e.ops.splice(n,a-n+1,...i)}),e.reversed=!e.reversed,e}get transform(){return{scale:this.dim(1),offset:this.pos(0)}}static IDENTITY=new We};(class ie{x;y;currRoot;constructor(e=new Hs,t=new Hs,n=null){this.x=e,this.y=t,this.currRoot=n}static translate(e,t){return new ie().translate(e,t)}static translateX(e){return new ie().translateX(e)}static translateY(e){return new ie().translateY(e)}static clamp(e){return new ie().clamp(e)}static magnify(e){return new ie().magnify(e)}static scale(e){return new ie().scale(e)}static reBound(e){return new ie().reBound(e)}translate(e,t){const n=hh(e,t),a=this.copy();return a.x=this.x.translate(n.x),a.y=this.y.translate(n.y),a}translateX(e){const t=this.copy();return t.x=this.x.translate(e),t}translateY(e){const t=this.copy();return t.y=this.y.translate(e),t}magnify(e){const t=this.copy();return t.x=this.x.magnify(e.x),t.y=this.y.magnify(e.y),t}scale(e){const t=this.copy();if(dh(e)){const n=this.currRoot;return t.currRoot=e.root,n!=null&&!uh(n,e.root)&&(n.x!==e.root.x&&(t.x=t.x.invert()),n.y!==e.root.y&&(t.y=t.y.invert())),t.x=t.x.scale(Vr(e)),t.y=t.y.scale(Hr(e)),t}return t.x=t.x.scale(e.width),t.y=t.y.scale(e.height),t}reBound(e){const t=this.copy();return t.x=this.x.reBound(Vr(e)),t.y=this.y.reBound(Hr(e)),t}clamp(e){const t=this.copy();return t.x=this.x.clamp(Vr(e)),t.y=this.y.clamp(Hr(e)),t}copy(){const e=new ie;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 Xn(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 ie});let Th=(r,e=21)=>(t=e)=>{let n="",a=t|0;for(;a--;)n+=r[Math.random()*r.length|0];return n};const Oh="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",fi=11,Sh=Th(Oh,fi),Qn=()=>Sh(),zh=Object.freeze(Object.defineProperty({__proto__:null,LENGTH:fi,create:Qn},Symbol.toStringTag,{value:"Module"})),Eh=(r,e)=>t=>t instanceof e||typeof t=="object"&&t!==null&&"discriminator"in t&&t.discriminator===r,Nh=s.z.enum(["static","dynamic"]),Ah=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)])]),pi=(r,e)=>{const t=new E(e);if(![z.DAY,z.HOUR,z.MINUTE,z.SECOND,z.MILLISECOND,z.MICROSECOND,z.NANOSECOND].some(a=>a.equals(t)))throw new Error("Invalid argument for remainder. Must be an even TimeSpan or Timestamp");const n=r.valueOf()%t.valueOf();return r instanceof E?new E(n):new z(n)};let E=class w extends ht{constructor(e,t="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,t).valueOf());else if(Array.isArray(e))super(w.parseDate(e));else{let n=0n;e instanceof Number&&(e=e.valueOf()),t==="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,t=1,n=1]){const a=new Date(e,t-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,t="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 t==="local"&&(c=c.add(w.utcOffset)),c.valueOf()}static parseDateTimeString(e,t="UTC"){if(!e.includes("/")&&!e.includes("-"))return w.parseTimeString(e,t);const n=new Date(e);return e.includes(":")||n.setUTCHours(0,0,0,0),new w(BigInt(n.getTime())*w.MILLISECOND.valueOf(),t).valueOf()}fString(e="ISO",t="UTC"){switch(e){case"ISODate":return this.toISOString(t).slice(0,10);case"ISOTime":return this.toISOString(t).slice(11,23);case"time":return this.timeString(!1,t);case"preciseTime":return this.timeString(!0,t);case"date":return this.dateString();case"preciseDate":return`${this.dateString()} ${this.timeString(!0,t)}`;case"dateTime":return`${this.dateString()} ${this.timeString(!1,t)}`;default:return this.toISOString(t)}}toISOString(e="UTC"){return e==="UTC"?this.date().toISOString():this.sub(w.utcOffset).date().toISOString()}timeString(e=!1,t="UTC"){const n=this.toISOString(t);return e?n.slice(11,23):n.slice(11,19)}dateString(){const e=this.date(),t=e.toLocaleString("default",{month:"short"}),n=e.toLocaleString("default",{day:"numeric"});return`${t} ${n}`}static get utcOffset(){return new z(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 M(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(this.valueOf()+BigInt(e.valueOf()))}sub(e){return new w(this.valueOf()-BigInt(e.valueOf()))}get hours(){return Number(this.valueOf())/Number(z.HOUR.valueOf())}get minutes(){return Number(this.valueOf())/Number(z.MINUTE.valueOf())}get days(){return Number(this.valueOf())/Number(z.DAY.valueOf())}get seconds(){return Number(this.valueOf())/Number(z.SECOND.valueOf())}get milliseconds(){return Number(this.valueOf())/Number(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 t=this.date();return t.setUTCFullYear(e),new w(t)}get month(){return this.date().getUTCMonth()}setMonth(e){const t=this.date();return t.setUTCMonth(e),new w(t)}get day(){return this.date().getUTCDate()}setDay(e){const t=this.date();return t.setUTCDate(e),new w(t)}get hour(){return this.date().getUTCHours()}setHour(e){const t=this.date();return t.setUTCHours(e),new w(t,"UTC")}get minute(){return this.date().getUTCMinutes()}setMinute(e){const t=this.date();return t.setUTCMinutes(e),new w(t)}get second(){return this.date().getUTCSeconds()}setSecond(e){const t=this.date();return t.setUTCSeconds(e),new w(t)}get millisecond(){return this.date().getUTCMilliseconds()}setMillisecond(e){const t=this.date();return t.setUTCMilliseconds(e),new w(t)}toString(){return this.date().toISOString()}remainder(e){return pi(this,e)}get isToday(){return this.truncate(z.DAY).equals(w.now().truncate(z.DAY))}truncate(e){return this.sub(this.remainder(e))}static now(){return new w(new Date)}static max(...e){let t=w.MIN;for(const n of e){const a=new w(n);a.after(t)&&(t=a)}return t}static min(...e){let t=w.MAX;for(const n of e){const a=new w(n);a.before(t)&&(t=a)}return t}static nanoseconds(e,t="UTC"){return new w(e,t)}static NANOSECOND=w.nanoseconds(1);static microseconds(e,t="UTC"){return w.nanoseconds(e*1e3,t)}static MICROSECOND=w.microseconds(1);static milliseconds(e,t="UTC"){return w.microseconds(e*1e3,t)}static MILLISECOND=w.milliseconds(1);static seconds(e,t="UTC"){return w.milliseconds(e*1e3,t)}static SECOND=w.seconds(1);static minutes(e,t="UTC"){return w.seconds(e*60,t)}static MINUTE=w.minutes(1);static hours(e,t="UTC"){return w.minutes(e*60,t)}static HOUR=w.hours(1);static days(e,t="UTC"){return w.hours(e*24,t)}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 z).transform(e=>new w(e)),Ah.transform(e=>new w(e))]);static sort(e,t){return Number(e.valueOf()-t.valueOf())}},z=class T extends ht{constructor(e){typeof e=="number"&&(e=Math.trunc(e.valueOf())),super(BigInt(e.valueOf()))}static fromSeconds(e){return e instanceof T?e:e instanceof Ws?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 Ws?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 pi(this,e)}truncate(e){return new T(BigInt(Math.trunc(Number(this.valueOf()/e.valueOf())))*e.valueOf())}toString(){const e=this.truncate(T.DAY),t=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=t.sub(e),d=n.sub(t),h=a.sub(n),b=i.sub(a),S=o.sub(i),R=l.sub(o);let A="";return c.isZero||(A+=`${c.days}d `),u.isZero||(A+=`${u.hours}h `),d.isZero||(A+=`${d.minutes}m `),h.isZero||(A+=`${h.seconds}s `),b.isZero||(A+=`${b.milliseconds}ms `),S.isZero||(A+=`${S.microseconds}µs `),R.isZero||(A+=`${R.nanoseconds}ns`),A.trim()}mult(e){return new T(this.valueOf()*BigInt(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(Ye(e,1e3))}static MICROSECOND=T.microseconds(1);static milliseconds(e=1){return T.microseconds(Ye(e,1e3))}static MILLISECOND=T.milliseconds(1);static seconds(e=1){return T.milliseconds(Ye(e,1e3))}static SECOND=T.seconds(1);static minutes(e=1){return T.seconds(Ye(e,60))}static MINUTE=T.minutes(1);static hours(e){return T.minutes(Ye(e,60))}static HOUR=T.hours(1);static days(e){return T.hours(Ye(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.instanceof(T)])},Ws=class Ge extends ht{constructor(e){super(e.valueOf())}toString(){return`${this.valueOf()} Hz`}equals(e){return this.valueOf()===new Ge(e).valueOf()}get period(){return z.seconds(1/this.valueOf())}sampleCount(e){return new z(e).seconds*this.valueOf()}byteCount(e,t){return this.sampleCount(e)*new H(t).valueOf()}span(e){return z.seconds(e/this.valueOf())}byteSpan(e,t){return this.span(e.valueOf()/t.valueOf())}static hz(e){return new Ge(e)}static khz(e){return Ge.hz(e*1e3)}static z=s.z.union([s.z.number().transform(e=>new Ge(e)),s.z.instanceof(Ge)])},H=class fe extends ht{constructor(e){super(e.valueOf())}length(e){return e.valueOf()/this.valueOf()}size(e){return new st(e*this.valueOf())}static UNKNOWN=new fe(0);static BIT128=new fe(16);static BIT64=new fe(8);static BIT32=new fe(4);static BIT16=new fe(2);static BIT8=new fe(1);static z=s.z.union([s.z.number().transform(e=>new fe(e)),s.z.instanceof(fe)])},M=class oe{start;end;constructor(e,t){typeof e=="object"&&"start"in e?(this.start=new E(e.start),this.end=new E(e.end)):(this.start=new E(e),this.end=new E(t))}get span(){return new 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 oe(this.end,this.start)}get numericBounds(){return{lower:Number(this.start.valueOf()),upper:Number(this.end.valueOf())}}equals(e,t=z.ZERO){if(t.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<=t.valueOf()&&a<=t.valueOf()}toString(){return`${this.start.toString()} - ${this.end.toString()}`}toPrettyString(){return`${this.start.fString("preciseDate")} - ${this.span.toString()}`}overlapsWith(e,t=z.ZERO){e=e.makeValid();const 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(t)}contains(e){return e instanceof oe?this.contains(e.start)&&this.contains(e.end):this.start.beforeEq(e)&&this.end.after(e)}boundBy(e){const t=new oe(this.start,this.end);return e.start.after(this.start)&&(t.start=e.start),e.start.after(this.end)&&(t.end=e.start),e.end.before(this.end)&&(t.end=e.end),e.end.before(this.start)&&(t.start=e.end),t}static max(...e){return new oe(E.min(...e.map(t=>t.start)),E.max(...e.map(t=>t.end)))}static MAX=new oe(E.MIN,E.MAX);static MIN=new oe(E.MAX,E.MIN);static ZERO=new oe(E.ZERO,E.ZERO);static z=s.z.union([s.z.object({start:E.z,end:E.z}).transform(e=>new oe(e.start,e.end)),s.z.instanceof(oe)]);static sort(e,t){return E.sort(e.start,t.start)||E.sort(e.end,t.end)}},N=class y extends ht{constructor(e){if(e instanceof y||typeof e=="string"||typeof e.valueOf()=="string")super(e.valueOf());else{const t=y.ARRAY_CONSTRUCTOR_DATA_TYPES.get(e.constructor.name);if(t==null)throw new Error(`unable to find data type for ${e.toString()}`);super(t.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(t=>this.equals(t))}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(),H.BIT8],[y.UINT16.toString(),H.BIT16],[y.UINT32.toString(),H.BIT32],[y.UINT64.toString(),H.BIT64],[y.FLOAT32.toString(),H.BIT32],[y.FLOAT64.toString(),H.BIT64],[y.INT8.toString(),H.BIT8],[y.INT16.toString(),H.BIT16],[y.INT32.toString(),H.BIT32],[y.INT64.toString(),H.BIT64],[y.TIMESTAMP.toString(),H.BIT64],[y.STRING.toString(),H.UNKNOWN],[y.JSON.toString(),H.UNKNOWN],[y.UUID.toString(),H.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)])},st=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 j.bytes(this.valueOf()+e.valueOf())}sub(e){return j.bytes(this.valueOf()-e.valueOf())}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),t=this.truncate(j.GIGABYTE),n=this.truncate(j.MEGABYTE),a=this.truncate(j.KILOBYTE),i=this.truncate(j.BYTE),o=e,l=t.sub(e),c=n.sub(t),u=a.sub(n),d=i.sub(a);let h="";return o.isZero||(h+=`${o.terabytes}TB `),l.isZero||(h+=`${l.gigabytes}GB `),c.isZero||(h+=`${c.megabytes}MB `),u.isZero||(h+=`${u.kilobytes}KB `),(!d.isZero||h==="")&&(h+=`${d.valueOf()}B`),h.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 yi=r=>{const e=typeof r;return e==="string"||e==="number"||e==="boolean"||e==="bigint"||r instanceof E||r instanceof z||r instanceof Date},kh=(r,e,t,n=0)=>r.usesBigInt&&!e.usesBigInt?Number(t)-Number(n):!r.usesBigInt&&e.usesBigInt?BigInt(t.valueOf())-BigInt(n.valueOf()):pr(t,-n),pr=(r,e)=>e==0?r:r==0?e:typeof r=="bigint"&&typeof e=="bigint"||typeof r=="number"&&typeof e=="number"?r+e:Number(r)+Number(e),xh=/^(?:[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 Ch(r){return typeof r=="string"&&xh.test(r)}const q=[];for(let r=0;r<256;++r)q.push((r+256).toString(16).slice(1));function Ih(r,e=0){return(q[r[e+0]]+q[r[e+1]]+q[r[e+2]]+q[r[e+3]]+"-"+q[r[e+4]]+q[r[e+5]]+"-"+q[r[e+6]]+q[r[e+7]]+"-"+q[r[e+8]]+q[r[e+9]]+"-"+q[r[e+10]]+q[r[e+11]]+q[r[e+12]]+q[r[e+13]]+q[r[e+14]]+q[r[e+15]]).toLowerCase()}function jh(r,e=0){const t=Ih(r,e);if(!Ch(t))throw TypeError("Stringified UUID is invalid");return t}typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const gi=(r,e)=>jh(r,e),ve=-1,wn={[Symbol.iterator]:()=>wn,next:()=>({done:!0,value:void 0})},Rh=s.z.string().transform(r=>new Uint8Array(atob(r).split("").map(e=>e.charCodeAt(0))).buffer),Uh=s.z.union([s.z.null(),s.z.undefined()]).transform(()=>new Uint8Array().buffer),bn=10,mi=(r,e)=>{if(r==="number"&&!e.isNumeric)throw new Error(`cannot convert series of type ${e.toString()} to number`);if(r==="bigint"&&!e.usesBigInt)throw new Error(`cannot convert series of type ${e.toString()} to bigint`)},wi="sy_x_telem_series";let Ae=class ze{key;discriminator=wi;dataType;sampleOffset;gl;_data;timeRange=M.ZERO;alignment=0n;cachedMin;cachedMax;writePos=ve;_refCount=0;cachedLength;_cachedIndexes;static crudeZ=s.z.object({timeRange:M.z.optional(),dataType:N.z,alignment:s.z.coerce.bigint().optional(),data:s.z.union([Rh,Uh,s.z.instanceof(ArrayBuffer),s.z.instanceof(Uint8Array)]),glBufferUsage:Nh.optional().default("static").optional()});static z=ze.crudeZ.transform(e=>new ze(e));constructor(e){Mh(e)&&(e={data:e}),e.data??=[];const{dataType:t,timeRange:n,sampleOffset:a=0,glBufferUsage:i="static",alignment:o=0n,key:l=Qn(),data:c}=e;if(bi(c)){const h=c;this.key=h.key,this.dataType=h.dataType,this.sampleOffset=h.sampleOffset,this.gl=h.gl,this._data=h._data,this.timeRange=h.timeRange,this.alignment=h.alignment,this.cachedMin=h.cachedMin,this.cachedMax=h.cachedMax,this.writePos=h.writePos,this._refCount=h._refCount,this.cachedLength=h.cachedLength;return}const u=yi(c),d=Array.isArray(c);if(t!=null)this.dataType=new N(t);else{if(c instanceof ArrayBuffer)throw new Error("cannot infer data type from an ArrayBuffer instance when constructing a Series. Please provide a data type.");if(d||u){let h=c;if(!u){if(c.length===0)throw new Error("cannot infer data type from a zero length JS array when constructing a Series. Please provide a data type.");h=c[0]}if(typeof h=="string")this.dataType=N.STRING;else if(typeof h=="number")this.dataType=N.FLOAT64;else if(typeof h=="bigint")this.dataType=N.INT64;else if(typeof h=="boolean")this.dataType=N.BOOLEAN;else if(h instanceof E||h instanceof Date||h instanceof E)this.dataType=N.TIMESTAMP;else if(typeof h=="object")this.dataType=N.JSON;else throw new Error(`cannot infer data type of ${typeof h} when constructing a Series from a JS array`)}else this.dataType=new N(c)}if(!d&&!u)this._data=c;else if(d&&c.length===0)this._data=new this.dataType.Array([]).buffer;else{let h=u?[c]:c;const b=h[0];(b instanceof E||b instanceof Date||b instanceof z)&&(h=h.map(S=>new E(S).valueOf())),this.dataType.equals(N.STRING)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.join(`
|
|
9
|
-
`)}
|
|
10
|
-
`).buffer):this.dataType.equals(N.JSON)?(this.cachedLength=h.length,this._data=new TextEncoder().encode(`${h.map(S=>Ct.encodeString(S)).join(`
|
|
11
|
-
`)}
|
|
12
|
-
`).buffer):this.dataType.usesBigInt&&typeof b=="number"?this._data=new this.dataType.Array(h.map(S=>BigInt(Math.round(S)))).buffer:!this.dataType.usesBigInt&&typeof b=="bigint"?this._data=new this.dataType.Array(h.map(Number)).buffer:this._data=new this.dataType.Array(h).buffer}this.key=l,this.alignment=o,this.sampleOffset=a??0,this.timeRange=n??M.ZERO,this.gl={control:null,buffer:null,prevBuffer:0,bufferUsage:i}}static alloc({capacity:e,dataType:t,...n}){if(e===0)throw new Error("[Series] - cannot allocate an array of length 0");const a=new new N(t).Array(e),i=new ze({data:a.buffer,dataType:t,...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===ve)return 0;const t=this.byteCapacity.valueOf()-this.writePos,n=e.subBytes(0,t);return this.writeToUnderlyingData(n),this.writePos+=n.byteLength.valueOf(),this.cachedLength!=null&&(this.cachedLength+=n.length,this.calculateCachedLength()),n.length}writeFixed(e){if(this.writePos===ve)return 0;const t=this.capacity-this.writePos,n=e.sub(0,t);return this.writeToUnderlyingData(n),this.cachedLength=void 0,this.maybeRecomputeMinMax(n),this.writePos+=n.length,n.length}writeToUnderlyingData(e){this.underlyingData.set(e.data,this.writePos)}get buffer(){return 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===ve?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(N.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.toStrings().map(t=>e.parse(Ct.decodeString(t)))}get byteCapacity(){return new st(this.underlyingData.byteLength)}get capacity(){return this.dataType.isVariable?this.byteCapacity.valueOf():this.dataType.density.length(this.byteCapacity)}get byteLength(){return this.writePos===ve?this.byteCapacity:this.dataType.isVariable?new st(this.writePos):this.dataType.density.size(this.writePos)}get length(){return this.cachedLength!=null?this.cachedLength:this.dataType.isVariable?this.calculateCachedLength():this.writePos===ve?this.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 t=[0];return this.data.forEach((n,a)=>{n===bn&&(e++,t.push(a+1))}),this._cachedIndexes=t,this.cachedLength=e,e}convert(e,t=0){if(this.dataType.equals(e))return this;const n=new e.Array(this.length);for(let a=0;a<this.length;a++)n[a]=kh(this.dataType,e,this.data[a],t);return new ze({data:n.buffer,dataType:e,timeRange:this.timeRange,sampleOffset:t,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment})}calcRawMax(){if(this.length===0)return-1/0;if(this.dataType.equals(N.TIMESTAMP))this.cachedMax=this.data[this.data.length-1];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}else{const e=this.data;this.cachedMax=e.reduce((t,n)=>t>n?t:n)}return this.cachedMax}get max(){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(),pr(this.cachedMax,this.sampleOffset))}calcRawMin(){if(this.length===0)return 1/0;if(this.dataType.equals(N.TIMESTAMP))this.cachedMin=this.data[0];else if(this.dataType.usesBigInt){const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}else{const e=this.data;this.cachedMin=e.reduce((t,n)=>t<n?t:n)}return this.cachedMin}get min(){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(),pr(this.cachedMin,this.sampleOffset))}get bounds(){return Z(Number(this.min),Number(this.max),{makeValid:!1})}maybeRecomputeMinMax(e){if(this.cachedMin!=null){const t=e.cachedMin??e.calcRawMin();t<this.cachedMin&&(this.cachedMin=t)}if(this.cachedMax!=null){const t=e.cachedMax??e.calcRawMax();t>this.cachedMax&&(this.cachedMax=t)}}atAlignment(e,t){const n=Number(e-this.alignment);if(n<0||n>=this.length){if(t===!0)throw new Error(`[series] - no value at index ${n}`);return}return this.at(n,t)}at(e,t=!1){if(this.dataType.isVariable)return this.atVariable(e,t??!1);if(this.dataType.equals(N.UUID))return this.atUUID(e,t);e<0&&(e=this.length+e);const n=this.data[e];if(n==null){if(t===!0)throw new Error(`[series] - no value at index ${e}`);return}return pr(n,this.sampleOffset)}atUUID(e,t){e<0&&(e=this.length+e);const n=gi(new Uint8Array(this.buffer,e*this.dataType.density.valueOf()));if(n==null){if(t)throw new Error(`[series] - no value at index ${e}`);return}return n}atVariable(e,t){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]===bn){if(e===0){a=o;break}n=o+1,e--}if(a===0&&(a=this.data.length),n>=a||e>0){if(t)throw new Error(`[series] - no value at index ${e}`);return}}const i=this.data.slice(n,a);return this.dataType.equals(N.STRING)?new TextDecoder().decode(i):Jn(JSON.parse(new TextDecoder().decode(i)))}binarySearch(e){let t=0,n=this.length-1;const a=Ar(e);for(;t<=n;){const i=Math.floor((t+n)/2),o=a(this.at(i,!0),e);if(o===0)return i;o<0?t=i+1:n=i-1}return t}updateGLBuffer(e){if(this.gl.control=e,!this.dataType.equals(N.FLOAT32)&&!this.dataType.equals(N.UINT8))throw new Error("Only FLOAT32 and UINT8 arrays can be used in WebGL");const{buffer:t,bufferUsage:n,prevBuffer:a}=this.gl;if(t==null&&(this.gl.buffer=e.createBuffer()),this.writePos!==a)if(e.bindBuffer(e.ARRAY_BUFFER,this.gl.buffer),this.writePos!==ve){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=ve}as(e){return mi(e,this.dataType),this}get digest(){return{key:this.key,dataType:this.dataType.toString(),sampleOffset:this.sampleOffset,alignment:{lower:Ks(this.alignmentBounds.lower),upper:Ks(this.alignmentBounds.upper)},timeRange:this.timeRange.toString(),length:this.length,capacity:this.capacity}}get alignmentBounds(){return Z(this.alignment,this.alignment+BigInt(this.length))}maybeGarbageCollectGLBuffer(e){this.gl.buffer!=null&&(e.deleteBuffer(this.gl.buffer),this.gl.buffer=null,this.gl.prevBuffer=0,this.gl.control=null)}get glBuffer(){if(this.gl.buffer==null)throw new Error("gl buffer not initialized");return this.gl.prevBuffer!==this.writePos&&console.warn("buffer not updated"),this.gl.buffer}[Symbol.iterator](){if(this.dataType.isVariable){const e=new Lh(this);return this.dataType.equals(N.JSON)?new es(e):e}return this.dataType.equals(N.UUID)?new Ph(this):new Dh(this)}slice(e,t){return this.sliceSub(!1,e,t)}sub(e,t){return this.sliceSub(!0,e,t)}subIterator(e,t){return new Gs(this,e,t??this.length)}subAlignmentIterator(e,t){return new Gs(this,Number(e-this.alignment),Number(t-this.alignment))}subBytes(e,t){if(e>=0&&(t==null||t>=this.byteLength.valueOf()))return this;const n=this.data.subarray(e,t);return new ze({data:n,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(e)})}sliceSub(e,t,n){if(t<=0&&(n==null||n>=this.length))return this;let a;return e?a=this.data.subarray(t,n):a=this.data.slice(t,n),new ze({data:a,dataType:this.dataType,timeRange:this.timeRange,sampleOffset:this.sampleOffset,glBufferUsage:this.gl.bufferUsage,alignment:this.alignment+BigInt(t)})}reAlign(e){return new ze({data:this.buffer,dataType:this.dataType,timeRange:M.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(t=>t.toString());else{for(let t=0;t<5;t++)e+=`${this.at(t)?.toString()}`,e+=",";e+="...,";for(let t=-5;t<0;t++)e+=this.at(t)?.toString(),t<-1&&(e+=",")}return e+="])",e}};const Mh=r=>r==null?!1:Array.isArray(r)||r instanceof ArrayBuffer||ArrayBuffer.isView(r)&&!(r instanceof DataView)||r instanceof Ae?!0:yi(r),bi=Eh(wi,Ae);let Gs=class{series;end;index;constructor(r,e,t){this.series=r;const n=Z(0,r.length);this.end=Ys(n,t),this.index=Ys(n,e)}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}},Lh=class{series;index;decoder;constructor(r){if(!r.dataType.isVariable)throw new Error("cannot create a variable series iterator for a non-variable series");this.series=r,this.index=0,this.decoder=new TextDecoder}next(){const r=this.index,e=this.series.data;for(;this.index<e.length&&e[this.index]!==bn;)this.index++;const t=this.index;return r===t?{done:!0,value:void 0}:(this.index++,{done:!1,value:this.decoder.decode(this.series.buffer.slice(r,t))})}};class es{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:Ct.decodeString(e.value,es.schema)}}}class Ph{series;index;data;density;constructor(e){if(!e.dataType.equals(N.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=N.UUID.density.valueOf()}next(){if(this.index>=this.series.length)return{done:!0,value:void 0};const e=gi(this.data,this.index*this.density);return this.index++,{done:!1,value:e}}}class Dh{series;index;constructor(e){this.series=e,this.index=0}next(){return this.index>=this.series.length?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}}class Bh{series;constructor(e=[]){if(e.length!==0){const t=e[0].dataType;for(let n=1;n<e.length;n++)if(!e[n].dataType.equals(t))throw new Error("[multi-series] - series must have the same data type")}this.series=e}as(e){return mi(e,this.dataType),this}get dataType(){return this.series.length===0?N.UNKNOWN:this.series[0].dataType}get timeRange(){return this.series.length===0?M.ZERO:new M(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?Z(0n,0n):Z(this.series[0].alignmentBounds.lower,this.series[this.series.length-1].alignmentBounds.upper)}push(e){const t=()=>new Error(`cannot push a ${e.dataType.toString()} series to a ${this.dataType.toString()} multi-series`),n=e.dataType.equals(this.dataType);if(bi(e)){if(this.series.length!==0&&!n)throw t();this.series.push(e)}else{if(this.series.length!==0&&e.series.length!==0&&!n)throw t();this.series.push(...e.series)}}get length(){return this.series.reduce((e,t)=>e+t.length,0)}atAlignment(e,t){for(const n of this.series)if(sr(n.alignmentBounds,e))return n.atAlignment(e,t);if(t)throw new Error(`[series] - no value at alignment ${e}`)}at(e,t=!1){e<0&&(e=this.length+e);for(const n of this.series){if(e<n.length)return n.at(e,t);e-=n.length}if(t)throw new Error(`[series] - no value at index ${e}`)}subIterator(e,t){return new Wr(this,e,t??this.length)}subAlignmentIterator(e,t){if(e>=this.alignmentBounds.upper||t<=this.alignmentBounds.lower)return wn;let n=0;for(let i=0;i<this.series.length;i++){const o=this.series[i];if(e<o.alignment)break;if(e>=o.alignmentBounds.upper)n+=o.length;else if(sr(o.alignmentBounds,e)){n+=Number(e-o.alignment);break}}let a=0;for(let i=0;i<this.series.length;i++){const o=this.series[i];if(t<o.alignment)break;if(t>=o.alignmentBounds.upper)a+=o.length;else if(sr(o.alignmentBounds,t)){a+=Number(t-o.alignment);break}}return new Wr(this,n,a)}subAlignmentSpanIterator(e,t){if(e>=this.alignmentBounds.upper)return wn;t=Math.min(t,Number(this.distance(e,this.alignmentBounds.upper)));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(sr(i.alignmentBounds,e)){n+=Number(e-i.alignment);break}}return new Wr(this,n,n+t)}updateGLBuffer(e){this.series.forEach(t=>t.updateGLBuffer(e))}get bounds(){return ah(this.series.map(e=>e.bounds))}get byteLength(){return new st(this.series.reduce((e,t)=>e+t.byteLength.valueOf(),0))}get data(){const e=new this.dataType.Array(this.length);let t=0;for(const n of this.series)e.set(n.data,t),t+=n.length;return new this.dataType.Array(e.buffer)}traverseAlignment(e,t){const n=this.series.map(a=>a.alignmentBounds);return ih(n,e,t)}acquire(e){this.series.forEach(t=>t.acquire(e))}release(){this.series.forEach(e=>e.release())}distance(e,t){const n=this.series.map(a=>a.alignmentBounds);return oh(n,e,t)}parseJSON(e){if(!this.dataType.equals(N.JSON))throw new Error("cannot parse non-JSON series as JSON");return this.series.flatMap(t=>t.parseJSON(e))}[Symbol.iterator](){return this.series.length===0?{next(){return{done:!0,value:void 0}}}:new $h(this.series)}toStrings(){return this.series.flatMap(e=>e.toStrings())}}let $h=class{series;seriesIndex;internal;constructor(r){this.series=r,this.seriesIndex=0,this.internal=r[0][Symbol.iterator]()}next(){const r=this.internal.next();return r.done===!1?r: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 Wr{series;index;end;constructor(e,t,n){this.series=e,this.end=n,this.index=t}next(){return this.index>=this.end?{done:!0,value:void 0}:{done:!1,value:this.series.at(this.index++,!0)}}[Symbol.iterator](){return this}}const Ks=r=>{const e=r>>32n,t=r&0xffffffffn;return{domain:e,sample:t}},Fh=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},qh=(r,e,t=".")=>{const n=r.split(t);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(a=>a!=null).join(t)},Zh=(r,e)=>{if(!Array.isArray(r))return r[e];const t=r[e];if(t!=null||r.length==0)return t;const n=r[0];if(typeof n=="object"&&"key"in n)return r.find(a=>a.key===e)},Yh=(r,e,t={optional:!1,separator:"."})=>{t.separator??=".";const{optional:n,getter:a=Zh}=t,i=e.split(t.separator);if(i.length===1&&i[0]==="")return r;let o=r;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()});class _h{handlers;transform;closer;constructor(e,t){this.transform=e,this.handlers=t??new Map}onChange(e){return this.handlers.set(e,null),()=>this.handlers.delete(e)}notify(e){let t=e;if(this.transform!=null){const[n,a]=this.transform(e);if(!a)return;t=n}this.handlers.forEach((n,a)=>a(t))}setCloser(e){this.closer=e}async close(){return await this.closer?.()}}let Vh=class{handlers;constructor(r){this.handlers=r??new Map}onChange(r){return this.handlers.set(r,null),()=>this.handlers.delete(r)}notify(r){this.handlers.forEach((e,t)=>t(r))}};const Hh=Object.freeze(Object.defineProperty({__proto__:null,BaseObserver:Vh,Observer:_h},Symbol.toStringTag,{value:"Module"})),Wh=s.z.record(s.z.union([s.z.number(),s.z.string(),s.z.symbol()]),s.z.unknown()),ts=r=>Object.entries(r),Gh=(r,e)=>Object.fromEntries(ts(r).map(([t,n])=>[t,e(n,t)])),Kh=r=>Object.fromEntries(ts(r).filter(([e,t])=>t!==void 0)),ge=Object.freeze(Object.defineProperty({__proto__:null,entries:ts,map:Gh,purgeUndefined:Kh,unknownZ:Wh},Symbol.toStringTag,{value:"Module"})),Jh=()=>typeof process<"u"&&process.versions!=null&&process.versions.node!=null?"node":typeof window>"u"||window.document===void 0?"webworker":"browser";Jh();const Xh=["macOS","Windows","Linux"],Qh=["macos","windows","linux"],ed={macos:"macOS",windows:"Windows",linux:"Linux"};s.z.enum(Xh).or(s.z.enum(Qh).transform(r=>ed[r]));const td=(...r)=>r.map(vi).join(""),vi=r=>(r.endsWith("/")||(r+="/"),r.startsWith("/")&&(r=r.slice(1)),r),rd=r=>r.endsWith("/")?r.slice(0,-1):r;class At{protocol;host;port;path;constructor({host:e,port:t,protocol:n="",pathPrefix:a=""}){this.protocol=n,this.host=e,this.port=t,this.path=vi(a)}replace(e){return new At({host:e.host??this.host,port:e.port??this.port,protocol:e.protocol??this.protocol,pathPrefix:e.pathPrefix??this.path})}child(e){return new At({...this,pathPrefix:td(this.path,e)})}toString(){return rd(`${this.protocol}://${this.host}:${this.port}/${this.path}`)}static UNKNOWN=new At({host:"unknown",port:0})}const nd=r=>r.nullable().transform(e=>e===null?void 0:e).optional(),sd=r=>s.array(r).or(r.transform(e=>[e])),Ti=r=>qh(r,(e,t,n)=>{const a=t===n.length-1,i=!isNaN(parseInt(e)),o=!isNaN(parseInt(n[t+1]));return i&&(e="element"),a||o?e:[e,"shape"]}),Js=(r,e)=>{if(r==null)return null;const t=r[e];return t==null&&typeof r=="object"&&"sourceType"in r?r.sourceType()[e]:t},ad=(r,e,t)=>Yh(Js(r,"shape"),Ti(e),{...t,getter:Js}),kt=Object.freeze(Object.defineProperty({__proto__:null,getFieldSchema:ad,getFieldSchemaPath:Ti,nullToUndefined:nd,toArray:sd},Symbol.toStringTag,{value:"Module"})),id=async r=>await new Promise(e=>setTimeout(e,z.fromMilliseconds(r).milliseconds));class od{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??id},this.retries=0,this.interval=new z(this.config.baseInterval)}async wait(){const{maxRetries:e,scale:t,sleepFn:n}=this.config;return this.retries>=e?!1:(await n(this.interval),this.interval=this.interval.mult(t),this.retries++,!0)}reset(){this.retries=0,this.interval=this.config.baseInterval}}const ld=s.z.object({baseInterval:z.z.optional(),maxRetries:s.z.number().optional(),scale:s.z.number().optional()}),Oi=Object.freeze(Object.defineProperty({__proto__:null,Breaker:od,breakerConfigZ:ld},Symbol.toStringTag,{value:"Module"})),cd=/^#?([0-9a-f]{6}|[0-9a-f]{8})$/i,Si=s.z.string().regex(cd),rt=s.z.number().min(0).max(255),zi=s.z.number().min(0).max(1),Ei=s.z.tuple([rt,rt,rt,zi]),ud=s.z.tuple([rt,rt,rt]),hd=s.z.object({rgba255:Ei}),dd=s.z.number().min(0).max(360),fd=s.z.number().min(0).max(100),pd=s.z.number().min(0).max(100),yd=s.z.tuple([dd,fd,pd,zi]),rs=s.z.union([Si,ud,Ei,yd,hd]),gd=rs.transform(r=>ns(r)),ns=(r,e=1)=>{if(r=rs.parse(r),typeof r=="string")return md(r,e);if(Array.isArray(r)){if(r.length<3||r.length>4)throw new Error(`Invalid color: [${r.join(", ")}]`);return r.length===3?[...r,e]:r}return r.rgba255},md=(r,e=1)=>(r=Si.parse(r),r=wd(r),[ir(r,0),ir(r,2),ir(r,4),r.length===8?ir(r,6)/255:e]),ir=(r,e)=>parseInt(r.slice(e,e+2),16),wd=r=>r.startsWith("#")?r.slice(1):r;ns("#000000");ns("#ffffff");const bd=s.z.object({key:s.z.string(),color:rs,position:s.z.number(),switched:s.z.boolean().optional()});s.z.array(bd);const vd=s.z.object({key:s.z.string(),name:s.z.string(),color:gd});s.z.object({key:s.z.string(),name:s.z.string(),swatches:s.z.array(vd)});const Ni=s.z.int().min(0).max(255),Ai=255,ki=0,Td={lower:ki,upper:Ai+1},xi=s.z.object({name:s.z.string(),key:s.z.string()}),It=r=>s.z.object({subject:xi,resource:r,authority:Ni}),Od=(...r)=>e=>e.filter(t=>{let n=!1;return t.to!=null&&(n=r.includes(t.to.resource)),t.from!=null&&!n&&(n=r.includes(t.from.resource)),n}),Ci=r=>s.z.object({from:It(r),to:s.z.null()}),Ii=r=>s.z.object({from:s.z.null(),to:It(r)}),Sd=r=>s.z.union([Ci(r),Ii(r),s.z.object({from:It(r),to:It(r)})]),X=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Ai,AUTHORITY_BOUNDS:Td,ZERO_AUTHORITY:ki,acquireZ:Ii,authorityZ:Ni,filterTransfersByChannelKey:Od,releaseZ:Ci,stateZ:It,subjectZ:xi,transferZ:Sd},Symbol.toStringTag,{value:"Module"})),zd=r=>Object.getOwnPropertySymbols(globalThis).includes(r),Ed=(r,e)=>{const t=Symbol.for(r);if(!zd(t)){const n=e();Object.defineProperty(globalThis,t,{value:n})}return()=>globalThis[t]},ji="sy_x_error",Nd=r=>e=>e!=null&&typeof e=="object"&&"type"in e&&typeof e.type=="string"?e.type.startsWith(r):e instanceof Error?e.message.startsWith(r):typeof e!="string"?!1:e.startsWith(r),Zt=r=>class Nt extends Error{static discriminator=ji;discriminator=Nt.discriminator;static TYPE=r;type=Nt.TYPE;static matches=Nd(r);matches=Nt.matches;constructor(t,n){super(t,n),this.name=Nt.TYPE}static sub(t){return Zt(`${r}.${t}`)}},Ri=r=>{if(r==null||typeof r!="object")return!1;const e=r;if(e.discriminator!==ji)return!1;if(!("type"in e))throw new Error(`X Error is missing its type property: ${JSON.stringify(e)}`);return!0},Ke="unknown",vn="nil";class Ad{providers=[];register(e){this.providers.push(e)}encode(e){if(e==null)return{type:vn,data:""};if(Ri(e))for(const t of this.providers){const n=t.encode(e);if(n!=null)return n}if(e instanceof Error)return{type:Ke,data:e.message};if(typeof e=="string")return{type:Ke,data:e};try{return{type:Ke,data:JSON.stringify(e)}}catch{return{type:Ke,data:"unable to encode error information"}}}decode(e){if(e==null||e.type===vn)return null;if(e.type===Ke)return new Tn(e.data);for(const t of this.providers){const n=t.decode(e);if(n!=null)return n}return new Tn(e.data)}}const ss=Ed("synnax-error-registry",()=>new Ad),kd=({encode:r,decode:e})=>ss().register({encode:r,decode:e}),xd=r=>ss().encode(r),Cd=r=>r==null?null:ss().decode(r);class Tn extends Zt("unknown"){}const Id=s.z.object({type:s.z.string(),data:s.z.string()});class jd extends Zt("canceled"){}class Rd extends Zt("not_implemented"){}const ye=Object.freeze(Object.defineProperty({__proto__:null,Canceled:jd,NONE:vn,NotImplemented:Rd,UNKNOWN:Ke,Unknown:Tn,createTyped:Zt,decode:Cd,encode:xd,isTyped:Ri,payloadZ:Id,register:kd},Symbol.toStringTag,{value:"Module"})),Ud=s.object({jsonrpc:s.literal("2.0"),method:s.string(),params:s.any().optional(),id:s.union([s.string(),s.number(),s.null()]).optional()}),Ui=s.object({jsonrpc:s.literal("2.0"),id:s.union([s.string(),s.number(),s.null()])}),Md=Ui.extend({result:s.json()}),Ld=Ui.extend({error:s.object({code:s.number().int(),message:s.string().optional(),data:s.json().optional()})}),Pd=s.union([Md,Ld]);s.union([Ud,Pd]);const On=s.z.string().regex(/^\d+\.\d+\.\d+$/),Yt=(r,e,t={})=>{t.checkMajor??=!0,t.checkMinor??=!0,t.checkPatch??=!0;const n=On.parse(r),a=On.parse(e),[i,o,l]=n.split(".").map(Number),[c,u,d]=a.split(".").map(Number);if(t.checkMajor){if(i<c)return dr;if(i>c)return fr}if(t.checkMinor){if(o<u)return dr;if(o>u)return fr}if(t.checkPatch){if(l<d)return dr;if(l>d)return fr}return dt},Dd=(r,e,t={})=>ai(Yt(r,e,t)),Mi=(r,e,t={})=>si(Yt(r,e,t)),Bd=(r,e,t={})=>ni(Yt(r,e,t)),$d=({name:r,migrate:e})=>t=>{try{const n=e(t);return console.log(`${r} migrated: ${t.version} -> ${n.version}`),n}catch(n){throw console.log(`${r} failed to migrate from ${t.version}`),console.error(n),n}},Fd=({name:r,migrations:e,targetSchema:t,defaultVersion:n,def:a})=>{const i=Object.keys(e).sort(Yt).pop();if(i==null)return u=>{if(u.version??=n,u.version!==a.version)return console.log(`${r} version ${u.version} is newer than latest version of ${a.version}.
|
|
14
|
-
Returning default instead.
|
|
15
|
-
`),a;try{return t!=null?t.parse(u):u}catch(d){return console.log(`${r} failed to parse default. Exiting with default`),console.error(d),a}};const o=Object.keys(e).length;let l=!1;const c=u=>{try{if(o===0||Mi(u.version,i))return console.log(l?`${r} ${u.version} now up to date`:`${r} version ${u.version} is up to date with target version ${a.version}`),u;const d=u.version,h=e[d],b=h(u);return l=!0,c(b)}catch(d){return console.log(`${r} failed to migrate from ${u.version} to ${i}`),console.error(d),a}};return u=>{try{if(u.version==null)if(n!=null)console.log(`${r} version is null. Setting version to default of ${n}`),u.version=n;else return console.log(`${r} version is null and no default version set. Exiting with default`),a;return c(u)}catch(d){return console.log(`${r} failed to parse final result. Exiting with default`),console.error(d),a}}},Xs=Object.freeze(Object.defineProperty({__proto__:null,compareSemVer:Yt,createMigration:$d,migrator:Fd,semVerNewer:Mi,semVerOlder:Bd,semVerZ:On,versionsEqual:Dd},Symbol.toStringTag,{value:"Module"})),qd=["standard","scientific","engineering"];s.z.enum(qd);const Li=s.z.enum(["success","info","warning","error","loading","disabled"]),Zd=r=>s.z.object({key:s.z.string(),variant:Li,message:s.z.string(),description:s.z.string().optional(),time:E.z,details:r??s.z.unknown().optional()}),Yd=(r,e)=>{if(!(r instanceof Error))throw r;return Pi({variant:"error",message:e??r.message,description:e!=null?r.message:void 0,details:{stack:r.stack??""}})},Pi=r=>({key:Qn(),time:E.now(),...r}),_t=Object.freeze(Object.defineProperty({__proto__:null,create:Pi,fromException:Yd,statusZ:Zd,variantZ:Li},Symbol.toStringTag,{value:"Module"})),_d=(r,e="")=>{const t=r.length;return t===0?e:t===1?r[0]:t===2?`${r[0]} and ${r[1]}`:`${r.slice(0,-1).join(", ")}, and ${r[t-1]}`},Vd=r=>{const e=r.split(" "),t=new Set,n=e.map(o=>o.charAt(0).toLowerCase()).join("");t.add(n.replace(/-/g,"_")),t.add(n.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"));const a=/\d+/g;r.match(a)&&e.forEach((o,l)=>{if(a.test(o)){const c=e.map((u,d)=>d!==l?u.charAt(0).toLowerCase():u).join("");t.add(c.replace(/-/g,"_")),t.add(c.replace(/(.)(.)/g,"$1_$2").replace(/-/g,"_"))}});const i=e.map(o=>(o.length>3?o.substring(0,3):o).toLowerCase());return t.add(i.join("").replace(/-/g,"_")),t.add(i.join("_").replace(/-/g,"_")),Array.from(t).filter(o=>o.length>=2&&o.length<=12&&!/^\d/.test(o))},Hd=(r,e)=>r.startsWith(e)?r.slice(e.length):r,Wd=Object.freeze(Object.defineProperty({__proto__:null,createShortIdentifiers:Vd,naturalLanguageJoin:_d,trimPrefix:Hd},Symbol.toStringTag,{value:"Module"})),Gd="all",Kd="create",Jd="delete",Xd="retrieve",Qd="update",Sn=s.z.enum([Gd,Kd,Jd,Xd,Qd]);let le=class extends ye.createTyped("sy"){},$=class extends le.sub("validation"){};class jt extends $.sub("path"){path;error;static encodedSchema=s.z.object({path:s.z.string().array(),error:ye.payloadZ});constructor(e,t){const n=O.toArray(e);super(`${n.join(".")}: ${t.message}`),this.path=n.flatMap(a=>a.split(".")),this.error=t}static decode(e){const t=jt.encodedSchema.parse(JSON.parse(e.data));return new jt(t.path,ye.decode(t.error))}}class br extends le.sub("auth"){}class zn extends br.sub("invalid_token"){}class En extends br.sub("expired_token"){}class W extends le.sub("unexpected"){constructor(e){super(`
|
|
16
|
-
Unexpected error encountered:
|
|
17
|
-
|
|
18
|
-
${e}
|
|
19
|
-
|
|
20
|
-
Please report this to the Synnax team.
|
|
21
|
-
`)}}class je extends le.sub("query"){}class at extends je.sub("not_found"){}class vr extends je.sub("multiple_results"){}class Qs extends le.sub("route"){path;constructor(e,t){super(e),this.path=t}}class Nn extends le.sub("control"){}class ea extends Nn.sub("unauthorized"){}class ef extends le.sub("disconnected"){constructor(e="Operation failed because no cluster is connected."){super(e)}}class _v extends le.sub("contiguity"){}const tf=r=>r.type.startsWith(le.TYPE)?r.type.startsWith($.TYPE)?r.type===jt.TYPE?jt.decode(r):new $(r.data):r.type.startsWith(br.TYPE)?r.type.startsWith(zn.TYPE)?new zn(r.data):r.type.startsWith(En.TYPE)?new En(r.data):new br(r.data):r.type.startsWith(W.TYPE)?new W(r.data):r.type.startsWith(je.TYPE)?r.type.startsWith(at.TYPE)?new at(r.data):r.type.startsWith(vr.TYPE)?new vr(r.data):new je(r.data):r.type.startsWith(Nn.TYPE)?r.type.startsWith(ea.TYPE)?new ea(r.data):new Nn(r.data):r.type.startsWith(Qs.TYPE)?new Qs(r.data,r.data):new W(r.data):null,rf=()=>{throw new ye.NotImplemented};ye.register({encode:rf,decode:tf});const nf=async(r,e)=>{const[t,n]=await e(r);return n==null?[t,n]:n instanceof Ie?[t,new Ie({message:`Cannot reach cluster at ${n.url.host}:${n.url.port}`,url:n.url})]:[t,n]};class Di{key;name;constructor(e,t){this.key=t,this.name=e}get ontologyID(){return sf(this.key)}}const sf=r=>({type:"group",key:r}),xr=s.z.uuid(),as=s.z.string(),Bi=s.z.object({key:xr,name:as}),$i="builtin",af="cluster",of="node",Cr=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"]),lf=s.z.string().transform(r=>{const[e,t]=r.split(":");return{type:Cr.parse(e),key:t??""}}),U=s.z.object({type:Cr,key:s.z.string()}).or(lf),cf={type:$i,key:"root"},Rt=r=>`${r.type}:${r.key}`,uf=(r,e)=>r.type===e.type&&r.key===e.key,Fi=r=>{const e=O.toArray(r);return e.length===0?[]:typeof e[0]=="object"&&"id"in e[0]?e.map(({id:t})=>t):e.map(t=>U.parse(t))},qi=s.z.object({id:U,name:s.z.string(),data:ge.unknownZ.optional().nullable()}).transform(r=>({key:Rt(r.id),...r})),hf=r=>r==="to"?"from":"to",df=s.z.object({from:U,type:s.z.string(),to:U}).or(s.z.string().transform(r=>{const[e,t,n]=r.split("->");return{from:U.parse(e),type:t,to:U.parse(n)}})),ff=r=>`${Rt(r.from)}->${r.type}->${Rt(r.to)}`,pf="parent",yf=(r,e)=>!(e.type!=null&&e.type!==r.type||e.from?.type!=null&&e.from.type!==r.from.type||e.to?.type!=null&&e.to.type!==r.to.type||e.from?.key!=null&&e.from.key!==r.from.key||e.to?.key!=null&&e.to.key!==r.to.key),gf=s.z.object({group:Bi}),mf=s.z.object({parent:U,key:xr.optional(),name:as}),wf=s.z.object({key:xr,name:as}),bf=s.z.object({keys:s.z.array(xr)});let vf=class yr{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,t,n){return(await g(this.client,yr.CREATE_ENDPOINT,{parent:e,name:t,key:n},mf,gf)).group}async rename(e,t){await g(this.client,yr.RENAME_ENDPOINT,{key:e,name:t},wf,s.z.object({}))}async delete(e){await g(this.client,yr.DELETE_ENDPOINT,{keys:e},bf,s.z.object({}))}},Tf=class{creator;constructor(r){this.creator=new vf(r)}async create(r,e,t){return this.sugar(await this.creator.create(r,e,t))}async rename(r,e){return await this.creator.rename(r,e)}async delete(...r){return await this.creator.delete(r)}sugar(r){return new Di(r.name,r.key)}};const Of="/ontology/add-children",Sf="/ontology/remove-children",zf="/ontology/move-children",ta=s.z.object({id:U,children:U.array()}),Ef=s.z.object({from:U,to:U,children:U.array()}),Gr=s.z.object({});let Nf=class{client;constructor(r){this.client=r}async addChildren(r,...e){await g(this.client,Of,{id:r,children:e},ta,Gr)}async removeChildren(r,...e){await g(this.client,Sf,{id:r,children:e},ta,Gr)}async moveChildren(r,e,...t){await g(this.client,zf,{from:r,to:e,children:t},Ef,Gr)}};const Af="/ontology/retrieve",kf=s.z.object({ids:U.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:Cr.array().optional()}),xf=s.z.object({resources:qi.array()});let Zi=class{type="ontology";groups;client;writer;framer;constructor(r,e){this.client=r,this.writer=new Nf(r),this.groups=new Tf(r),this.framer=e}async retrieve(r,e){if(!Array.isArray(r)&&typeof r=="object"&&!("key"in r))return this.execRetrieve(r);const t=Fi(r),n=await this.execRetrieve({ids:t,...e});if(Array.isArray(r))return n;if(n.length===0)throw new je(`No resource found with ID ${Wd.naturalLanguageJoin(t.map(a=>Rt(a)))}`);return n[0]}async retrieveChildren(r,e){return await this.execRetrieve({ids:O.toArray(r),children:!0,...e})}async retrieveParents(r,e){return await this.execRetrieve({ids:O.toArray(r),parents:!0,...e})}async addChildren(r,...e){return await this.writer.addChildren(r,...e)}async removeChildren(r,...e){return await this.writer.removeChildren(r,...e)}async moveChildren(r,e,...t){return await this.writer.moveChildren(r,e,...t)}async execRetrieve(r){const{resources:e}=await g(this.client,Af,r,kf,xf);return e}};const Cf="sy_ontology_resource_set",If="sy_ontology_resource_delete",jf="sy_ontology_relationship_set",Rf="sy_ontology_relationship_delete",Uf=Object.freeze(Object.defineProperty({__proto__:null,BUILTIN_TYPE:$i,CLUSTER_TYPE:af,Client:Zi,NODE_TYPE:of,PARENT_OF_RELATIONSHIP_TYPE:pf,RELATIONSHIP_DELETE_CHANNEL_NAME:Rf,RELATIONSHIP_SET_CHANNEL_NAME:jf,RESOURCE_DELETE_CHANNEL_NAME:If,RESOURCE_SET_CHANNEL_NAME:Cf,ROOT_ID:cf,idToString:Rt,idZ:U,idsEqual:uf,matchRelationship:yf,oppositeRelationshipDirection:hf,parseIDs:Fi,relationshipToString:ff,relationshipZ:df,resourceTypeZ:Cr,resourceZ:qi},Symbol.toStringTag,{value:"Module"})),Y=r=>s.z.union([s.z.union([s.z.null(),s.z.undefined()]).transform(()=>[]),r.array()]),Vt=s.z.uuid(),is=s.z.object({key:Vt,subjects:Y(U),objects:Y(U),actions:Y(Sn)}),Mf=s.z.object({key:Vt.optional(),subjects:U.array().or(U),objects:U.array().or(U),actions:Sn.array().or(Sn)}),Lf=s.z.object({keys:Vt.array().optional(),subjects:U.array().optional()}),Pf=s.z.object({key:Vt}).transform(({key:r})=>({keys:[r]})),Df=s.z.union([s.z.object({for:U}).transform(({for:r})=>({subjects:[r]})),s.z.object({for:U.array()}).transform(({for:r})=>({subjects:r})),Lf]),Bf=s.z.union([Pf,Df]),$f=s.z.object({policies:Y(is)}),Ff=s.z.object({policies:is.partial({key:!0}).array()}),qf=s.z.object({policies:is.array()}),Zf=s.z.object({keys:Vt.array()}),Yf=s.z.object({}),_f="/access/policy/retrieve",Vf="/access/policy/create",Hf="/access/policy/delete";let Wf=class{client;constructor(r){this.client=r}async create(r){const e=Array.isArray(r),t=Mf.array().parse(O.toArray(r)).map(a=>({objects:O.toArray(a.objects),actions:O.toArray(a.actions),subjects:O.toArray(a.subjects)})),n=await g(this.client,Vf,{policies:t},Ff,qf);return e?n.policies:n.policies[0]}async retrieve(r){const e="key"in r,t=await g(this.client,_f,r,Bf,$f);return e?t.policies[0]:t.policies}async delete(r){await g(this.client,Hf,{keys:O.toArray(r)},Zf,Yf)}},Gf=class{policy;constructor(r){this.policy=new Wf(r)}};const D=s.z.number(),pe=s.z.string(),Yi=_t.statusZ(),ft=s.z.object({name:pe,key:D,dataType:N.z,leaseholder:s.z.number(),index:D,isIndex:s.z.boolean(),internal:s.z.boolean(),virtual:s.z.boolean(),alias:s.z.string().optional(),expression:s.z.string().default(""),requires:Y(D),status:Yi.optional()}),_i=ft.extend({key:D.optional(),leaseholder:s.z.number().optional(),index:D.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(D).optional().default([])}),Fe=s.z.union([kt.toArray(D),kt.toArray(pe),kt.toArray(ft).transform(r=>r.map(e=>e.key))]),Kf=new Error("request for lock canceled");var Jf=function(r,e,t,n){function a(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function l(d){try{u(n.next(d))}catch(h){o(h)}}function c(d){try{u(n.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):a(d.value).then(l,c)}u((n=n.apply(r,e||[])).next())})};class Xf{constructor(e,t=Kf){this._value=e,this._cancelError=t,this._queue=[],this._weightedWaiters=[]}acquire(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return new Promise((n,a)=>{const i={resolve:n,reject:a,weight:e,priority:t},o=Vi(this._queue,l=>t<=l.priority);o===-1&&e<=this._value?this._dispatchItem(i):this._queue.splice(o+1,0,i)})}runExclusive(e){return Jf(this,arguments,void 0,function*(t,n=1,a=0){const[i,o]=yield this.acquire(n,a);try{return yield t(i)}finally{o()}})}waitForUnlock(e=1,t=0){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);return this._couldLockImmediately(e,t)?Promise.resolve():new Promise(n=>{this._weightedWaiters[e-1]||(this._weightedWaiters[e-1]=[]),Qf(this._weightedWaiters[e-1],{resolve:n,priority:t})})}isLocked(){return this._value<=0}getValue(){return this._value}setValue(e){this._value=e,this._dispatchQueue()}release(e=1){if(e<=0)throw new Error(`invalid weight ${e}: must be positive`);this._value+=e,this._dispatchQueue()}cancel(){this._queue.forEach(e=>e.reject(this._cancelError)),this._queue=[]}_dispatchQueue(){for(this._drainUnlockWaiters();this._queue.length>0&&this._queue[0].weight<=this._value;)this._dispatchItem(this._queue.shift()),this._drainUnlockWaiters()}_dispatchItem(e){const t=this._value;this._value-=e.weight,e.resolve([t,this._newReleaser(e.weight)])}_newReleaser(e){let t=!1;return()=>{t||(t=!0,this.release(e))}}_drainUnlockWaiters(){if(this._queue.length===0)for(let e=this._value;e>0;e--){const t=this._weightedWaiters[e-1];t&&(t.forEach(n=>n.resolve()),this._weightedWaiters[e-1]=[])}else{const e=this._queue[0].priority;for(let t=this._value;t>0;t--){const n=this._weightedWaiters[t-1];if(!n)continue;const a=n.findIndex(i=>i.priority<=e);(a===-1?n:n.splice(0,a)).forEach(i=>i.resolve())}}}_couldLockImmediately(e,t){return(this._queue.length===0||this._queue[0].priority<t)&&e<=this._value}}function Qf(r,e){const t=Vi(r,n=>e.priority<=n.priority);r.splice(t+1,0,e)}function Vi(r,e){for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1}var ep=function(r,e,t,n){function a(i){return i instanceof t?i:new t(function(o){o(i)})}return new(t||(t=Promise))(function(i,o){function l(d){try{u(n.next(d))}catch(h){o(h)}}function c(d){try{u(n.throw(d))}catch(h){o(h)}}function u(d){d.done?i(d.value):a(d.value).then(l,c)}u((n=n.apply(r,e||[])).next())})};class tp{constructor(e){this._semaphore=new Xf(1,e)}acquire(){return ep(this,arguments,void 0,function*(e=0){const[,t]=yield this._semaphore.acquire(1,e);return t})}runExclusive(e,t=0){return this._semaphore.runExclusive(()=>e(),1,t)}isLocked(){return this._semaphore.isLocked()}waitForUnlock(e=0){return this._semaphore.waitForUnlock(1,e)}release(){this._semaphore.isLocked()&&this._semaphore.release()}cancel(){return this._semaphore.cancel()}}const rp=(r,e,{convertNumericStrings:t=!0}={})=>{const n=!Array.isArray(r);let a=O.toArray(r);const i=a[0],o=typeof i;let l;return o==="string"&&t&&!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:r}},pt=(r,e,t,n)=>{if(n){if(t.length===0)throw new at(`${r} not found matching ${JSON.stringify(e)}`);if(t.length>1)throw new vr(`Expected one ${r} matching ${JSON.stringify(e)}, but found ${t.length}`)}},np=s.z.object({leaseholder:s.z.number().optional(),keys:D.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:N.z.array().optional(),notDataTypes:N.z.array().optional(),virtual:s.z.boolean().optional(),isIndex:s.z.boolean().optional(),internal:s.z.boolean().optional(),calculated:s.z.boolean().optional()}),sp=s.z.object({channels:Y(ft)}),ee=r=>(Array.isArray(r)&&r.length>0&&typeof r[0]=="object"?r=r.map(e=>e.key):typeof r=="object"&&"key"in r&&(r=[r.key]),rp(r,{number:"keys",string:"names"}));class Ht{static ENDPOINT="/channel/retrieve";client;constructor(e){this.client=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.execute(e);const n=ee(e),{variant:a}=n;let{normalized:i}=n;return a==="keys"&&i.indexOf(0)!==-1&&(i=i.filter(o=>o!==0)),i.length===0?[]:await this.execute({[a]:i,...t})}async execute(e){const[t,n]=await this.client.send(Ht.ENDPOINT,e,np,sp);if(n!=null)throw n;return t.channels}}class os{cache;namesToKeys;wrapped;constructor(e){this.cache=new Map,this.namesToKeys=new Map,this.wrapped=e}async retrieve(e,t){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:n}=ee(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,t);return this.set(o),a.concat(o)}delete(e){const{variant:t,normalized:n}=ee(e);t==="names"?n.forEach(a=>{const i=this.namesToKeys.get(a);i!=null&&(i.forEach(o=>this.cache.delete(o)),this.namesToKeys.delete(a))}):n.forEach(a=>{const i=this.cache.get(a);i!=null&&(this.cache.delete(a),this.namesToKeys.delete(i.name))})}rename(e,t){e.forEach((n,a)=>{const i=t[a],o=this.cache.get(n);if(o==null)return;this.cache.delete(n);const 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(t=>{this.cache.set(t.key,t);const n=this.namesToKeys.get(t.name);n==null?this.namesToKeys.set(t.name,new Set([t.key])):n.add(t.key)})}get(e){if(typeof e=="number"){const a=this.cache.get(e);return a==null?void 0:[a]}const t=this.namesToKeys.get(e);if(t==null)return;const n=[];if(t.forEach(a=>{const i=this.cache.get(a);i!=null&&n.push(i)}),n.length!==0)return n}}class Hi{mu=new tp;requests=new Map;wrapped;debouncedRun;constructor(e,t){this.wrapped=e,this.debouncedRun=Fh(()=>{this.run()},t)}async retrieve(e){if(!Array.isArray(e)&&typeof e=="object")return await this.wrapped.retrieve(e);const{normalized:t,variant:n}=ee(e);return n==="names"?await this.wrapped.retrieve(t):await new Promise((a,i)=>{this.mu.runExclusive(()=>{this.requests.set(t,{resolve:a,reject:i}),this.debouncedRun()})})}async run(){await this.mu.runExclusive(async()=>{const e=new Set;this.requests.forEach((t,n)=>n.forEach(a=>e.add(a)));try{const t=await this.wrapped.retrieve(Array.from(e));this.requests.forEach((n,a)=>n.resolve(t.filter(i=>a.includes(i.key))))}catch(t){this.requests.forEach(n=>n.reject(t))}finally{this.requests.clear()}})}}const Wi=async(r,e)=>{const{normalized:t}=ee(e),n=await r.retrieve(t),a=[];if(t.forEach(i=>{n.find(o=>o.name===i||o.key===i)==null&&a.push(i)}),a.length>0)throw new je(`Could not find channels: ${JSON.stringify(a)}`);return n},ap="sy_channel_set",ip="sy_channel_delete";class An{_frameClient;key;name;dataType;leaseholder;index;isIndex;internal;alias;virtual;expression;requires;status;constructor({dataType:e,name:t,leaseholder:n=0,key:a=0,isIndex:i=!1,index:o=0,internal:l=!1,virtual:c=!1,frameClient:u,alias:d,status:h,expression:b="",requires:S=[]}){this.key=a,this.name=t,this.dataType=new N(e),this.leaseholder=n,this.index=o,this.isIndex=i,this.internal=l,this.alias=d,this.virtual=c,this.expression=b,this.requires=S??[],h!=null&&(this.status=_t.create(h)),this._frameClient=u??null}get framer(){if(this._frameClient==null)throw new $("cannot read from a channel that has not been created");return this._frameClient}get payload(){return ft.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 Tr(this.payload)}get ontologyID(){return Ji(this.key)}async read(e){return await this.framer.read(e,this.key)}async write(e,t){return await this.framer.write(e,this.key,t)}}const op="sy_calculation_status",lp="/channel/retrieve-group",cp=s.z.object({}),up=s.z.object({group:Bi});let Gi=class{type="channel";frameClient;client;retriever;writer;constructor(r,e,t,n){this.frameClient=r,this.retriever=e,this.client=t,this.writer=n}async create(r,e={}){const{retrieveIfNameExists:t=!1}=e,n=!Array.isArray(r);let a=O.toArray(r),i=[];if(t){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(r,e){if(typeof r=="object"&&!Array.isArray(r))return this.sugar(await this.retriever.retrieve(r));const t=!Array.isArray(r),n=this.sugar(await this.retriever.retrieve(r,e));return pt("channel",r,n,t),t?n[0]:n}async delete(r){const{normalized:e,variant:t}=ee(r);return t==="keys"?await this.writer.delete({keys:e}):await this.writer.delete({names:e})}async rename(r,e){return await this.writer.rename(O.toArray(r),O.toArray(e))}createDebouncedBatchRetriever(r=10){return new os(new Hi(new Ht(this.client),r))}sugar(r){const{frameClient:e}=this;return Array.isArray(r)?r.map(t=>new An({...t,frameClient:e})):new An({...r,frameClient:e})}async retrieveGroup(){const r=await g(this.client,lp,{},cp,up);return new Di(r.group.name,r.group.key)}};const Tr=({virtual:r,expression:e})=>r&&e!=="",Ki=async(r,e)=>{if(!Tr(e))return e.index;for(const t of e.requires){const n=await r(t);if(n==null)return null;if(!n.virtual)return n.index}for(const t of e.requires){const n=await r(t);if(n==null)return null;if(Tr(n)){const a=await Ki(r,n);if(a!=null)return a}}return null},Ji=r=>({type:"channel",key:r.toString()}),hp=s.z.object({channels:_i.array()}),dp=s.z.object({channels:ft.array()}),fp=s.z.object({keys:D.array().optional(),names:pe.array().optional()}),pp=s.z.object({}),yp=s.z.object({keys:D.array(),names:pe.array()}),gp=s.z.object({}),mp="/channel/create",wp="/channel/delete",bp="/channel/rename";let Xi=class{client;cache;constructor(r,e){this.client=r,this.cache=e}async create(r){const{channels:e}=await g(this.client,mp,{channels:r.map(t=>({...t,dataType:t.dataType}))},hp,dp);return this.cache.set(e),e}async delete(r){await g(this.client,wp,r,fp,pp),r.keys!=null&&this.cache.delete(r.keys),r.names!=null&&this.cache.delete(r.names)}async rename(r,e){await g(this.client,bp,{keys:r,names:e},yp,gp),this.cache.rename(r,e)}};const vp=Object.freeze(Object.defineProperty({__proto__:null,CALCULATION_STATUS_CHANNEL_NAME:op,CacheRetriever:os,Channel:An,Client:Gi,ClusterRetriever:Ht,DELETE_CHANNEL_NAME:ip,DebouncedBatchRetriever:Hi,SET_CHANNEL_NAME:ap,Writer:Xi,analyzeParams:ee,isCalculated:Tr,keyZ:D,nameZ:pe,newZ:_i,ontologyID:Ji,paramsZ:Fe,payloadZ:ft,resolveCalculatedIndex:Ki,retrieveRequired:Wi,statusZ:Yi},Symbol.toStringTag,{value:"Module"})),qe=s.z.uuid(),Ir=s.z.object({key:qe,username:s.z.string().min(1),firstName:s.z.string().default(""),lastName:s.z.string().default(""),rootUser:s.z.boolean().default(!0)}),Tp=Ir.partial({key:!0,firstName:!0,lastName:!0}).omit({rootUser:!0}).extend({password:s.z.string().min(1)}),Op=s.z.object({keys:qe.array().optional(),usernames:s.z.string().array().optional()}),Sp=s.z.object({key:qe}).transform(({key:r})=>({keys:[r]})),zp=s.z.object({username:s.z.string()}).transform(({username:r})=>({usernames:[r]})),Ep=s.z.object({usernames:s.z.string().array()}).transform(({usernames:r})=>({usernames:r})),Np=s.z.union([Sp,zp,Ep,Op]),Ap=s.z.object({users:Y(Ir)}),kp=s.z.object({users:Tp.array()}),xp=s.z.object({users:Ir.array()}),Cp=s.z.object({key:qe,username:s.z.string().min(1)}),Ip=s.z.object({}),jp=s.z.object({key:qe,firstName:s.z.string().optional(),lastName:s.z.string().optional()}),Rp=s.z.object({}),Up=s.z.object({keys:qe.array()}),Mp=s.z.object({}),Lp="/user/retrieve",Pp="/user/create",Dp="/user/change-username",Bp="/user/rename",$p="/user/delete";let Fp=class{client;constructor(r){this.client=r}async create(r){const e=Array.isArray(r),t=await g(this.client,Pp,{users:O.toArray(r)},kp,xp);return e?t.users:t.users[0]}async changeUsername(r,e){await g(this.client,Dp,{key:r,username:e},Cp,Ip)}async retrieve(r){const e="key"in r||"username"in r,t=await g(this.client,Lp,r,Np,Ap);if(!e)return t.users;if(t.users.length===0){const n="key"in r?`key ${r.key}`:`username ${r.username}`;throw new at(`No user with ${n} found`)}if(t.users.length>1){const n="key"in r?`key ${r.key}`:`username ${r.username}`;throw new vr(`Multiple users found with ${n}`)}return t.users[0]}async rename(r,e,t){await g(this.client,Bp,{key:r,firstName:e,lastName:t},jp,Rp)}async delete(r){await g(this.client,$p,{keys:O.toArray(r)},Up,Mp)}};const qp=s.z.object({username:s.z.string(),password:s.z.string()}),Zp=s.z.object({token:s.z.string(),user:Ir}),ra="/auth/login",Yp=3,_p="/auth/change-password",Vp=s.z.object({username:s.z.string(),password:s.z.string(),newPassword:s.z.string().min(1)}),Hp=s.z.object({}),Wp=[zn,En];let Gp=class{token;client;credentials;authenticating;authenticated;user;retryCount;constructor(r,e){this.client=r,this.authenticated=!1,this.credentials=e,this.retryCount=0}async changePassword(r){if(!this.authenticated)throw new Error("Not authenticated");await g(this.client,_p,{username:this.credentials.username,password:this.credentials.password,newPassword:r},Vp,Hp),this.credentials.password=r}middleware(){const r=async(e,t)=>{if(!this.authenticated&&!e.target.endsWith(ra)){this.authenticating??=new Promise((o,l)=>{this.client.send(ra,this.credentials,qp,Zp).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 t(e);return Wp.some(i=>i.matches(a))&&this.retryCount<Yp?(this.authenticated=!1,this.authenticating=void 0,this.retryCount+=1,r(e,t)):(this.retryCount=0,[n,a])};return r}};const Kp=s.z.enum(["disconnected","connecting","connected","failed"]),Jp=s.z.object({status:Kp,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()}),Xp=s.z.object({clusterKey:s.z.string(),nodeVersion:s.z.string().optional()}),na={clusterKey:"",status:"disconnected",error:void 0,message:"Disconnected",clientServerCompatible:!1,clientVersion:"0.44.2"},sa=(r,e,t)=>{const n=t?"cluster":"client";return`Synnax cluster node version ${r!=null?`${r} `:""}is too ${t?"old":"new"} for client version ${e}.
|
|
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 Or{static ENDPOINT="/connectivity/check";static DEFAULT=na;_state;pollFrequency=z.seconds(30);client;name;interval;clientVersion;onChangeHandlers=[];static connectionStateZ=Jp;versionWarned=!1;constructor(e,t=z.seconds(30),n,a){this._state={...na},this.client=e,this.pollFrequency=t,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[t,n]=await this.client.send(Or.ENDPOINT,{},s.z.object({}),Xp);if(n!=null)throw n;const a=t.nodeVersion,i=this.clientVersion,o=this.versionWarned;a==null?(this._state.clientServerCompatible=!1,o||(console.warn(sa(null,i,!0)),this.versionWarned=!0)):Xs.versionsEqual(i,a,{checkMajor:!0,checkMinor:!0,checkPatch:!1})?this._state.clientServerCompatible=!0:(this._state.clientServerCompatible=!1,o||(console.warn(sa(a,i,Xs.semVerNewer(i,a))),this.versionWarned=!0)),this._state.status="connected",this._state.message=`Connected to ${this.name??"cluster"}`,this._state.clusterKey=t.clusterKey,this._state.nodeVersion=t.nodeVersion,this._state.clientVersion=this.clientVersion}catch(t){this._state.status="failed",this._state.error=t,this._state.message=this.state.error?.message}return this.onChangeHandlers.length>0&&e!==this._state.status&&this.onChangeHandlers.forEach(t=>t(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 Qp=s.z.object({keys:D.array().optional(),bounds:M.z,names:pe.array().optional()}),ey=s.z.object({}),ty="/frame/delete";class ry{client;constructor(e){this.client=e}async delete(e){await g(this.client,ty,e,Qp,ey)}}const aa=r=>{const e=O.toArray(r);return e.length===0?null:typeof e[0]=="number"||!isNaN(parseInt(e[0]))?"key":"name"},ia=(r,e)=>{const t=O.toArray(r);if(t.length===e.length)return;const n=aa(r);throw aa===null?new $("[Frame] - channel keys or names must be provided when constructing a frame."):new $(`[Frame] - ${n}s and series must be the same length.
|
|
24
|
-
Got ${t.length} ${n}s and ${e.length} series.`)};let K=class Je{columns=[];series=[];constructor(e=[],t=[]){if(e instanceof Je){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=>Qi(i));ia(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(t),a=O.toArray(e);ia(a,n),n.forEach((i,o)=>this.push(a[o],i));return}throw new $(`[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 $s.unique(this.keys)}get names(){if(this.colType==="key")throw new W("colType is not name");return this.columns??[]}get uniqueNames(){return $s.unique(this.names)}get uniqueColumns(){return this.colType==="key"?this.uniqueKeys:this.uniqueNames}toPayload(){return{series:this.series.map(e=>eo(e)),keys:[...this.keys]}}get isVertical(){return this.uniqueColumns.length===this.columns.length}get isHorizontal(){return this.uniqueColumns.length===1}get isSquare(){return this.isHorizontal&&this.isVertical}get isWeaklyAligned(){if(this.columns.length<=1)return!0;const e=this.timeRanges;return e.every(t=>t.equals(e[0]))}timeRange(e){if(e==null){if(this.columns.length===0)return M.ZERO;const n=E.min(...this.series.map(i=>i.timeRange.start)),a=E.max(...this.series.map(i=>i.timeRange.end));return new M(n,a)}const t=this.get(e);return t==null?M.ZERO:t.timeRange}latest(){return this.at(-1)}get timeRanges(){return this.uniqueColumns.map(e=>this.timeRange(e))}get(e){return Array.isArray(e)?this.filter(t=>e.includes(t)):new Bh(this.series.filter((t,n)=>this.columns[n]===e))}push(e,...t){if(e instanceof Je){if(this.colType!==null&&e.colType!==this.colType)throw new $("keyVariant must match");this.series.push(...e.series),this.columns.push(...e.columns)}else{if(this.series.push(...t),typeof e=="string"&&this.colType==="key")throw new $("keyVariant must match");if(typeof e!="string"&&this.colType==="name")throw new $("keyVariant must match");this.columns.push(...Array.from({length:t.length},()=>e))}}concat(e){return new Je([...this.columns,...e.columns],[...this.series,...e.series])}has(e){return typeof e=="string"&&this.colType==="key"||typeof e=="number"&&this.colType==="name"?!1:this.columns.includes(e)}map(e){const t=new Je;return this.forEach((n,a,i)=>t.push(...e(n,a,i))),t}forEach(e){this.columns.forEach((t,n)=>{const a=this.series[n];e(t,a,n)})}at(e,t=!1){const n={};return this.uniqueColumns.forEach(a=>{n[a]=this.get(a).at(e,t)}),n}filter(e){const t=new Je;return this.columns.forEach((n,a)=>{const i=this.series[a];e(n,i,a)&&t.push(n,i)}),t}get byteLength(){return new st(this.series.reduce((e,t)=>e.add(t.byteLength),st.ZERO))}get digest(){const e={};return this.keys.forEach((t,n)=>{const a=this.series[n].digest;t in e?e[t].push(a):e[t]=[a]}),e}get length(){return this.series.reduce((e,t)=>e+t.length,0)}toString(){let e=`Frame{
|
|
27
|
-
`;return this.uniqueColumns.forEach(t=>{e+=` ${t}: ${this.get(t).series.map(n=>n.toString()).join(",")}
|
|
28
|
-
`}),e+="}",e}};const jr=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(()=>[]),Ae.crudeZ.array().optional().default([])])}),Qi=r=>{const{dataType:e,data:t,timeRange:n,alignment:a}=r;return new Ae({data:t,dataType:e,timeRange:n,glBufferUsage:"static",alignment:a})},eo=r=>({timeRange:r.timeRange,dataType:r.dataType,data:new Uint8Array(r.data.buffer),alignment:r.alignment});var it=(r=>(r[r.Open=0]="Open",r[r.Write=1]="Write",r[r.Commit=2]="Commit",r[r.SetAuthority=3]="SetAuthority",r))(it||{}),Ut=(r=>(r[r.PersistStream=1]="PersistStream",r[r.Persist=2]="Persist",r[r.Stream=3]="Stream",r))(Ut||{});const ny=new z(-1);class kn extends le.sub("writer_closed"){constructor(){super("WriterClosed")}}const sy=s.z.enum(Ut).or(s.z.enum(["persist","stream","persistStream"]).transform(r=>{switch(r){case"persist":return 2;case"stream":return 3;case"persistStream":return 1}})),to=s.z.object({start:E.z.optional(),controlSubject:X.subjectZ.optional(),authorities:s.z.union([X.authorityZ.transform(r=>[r]),X.authorityZ.array()]).default([X.ABSOLUTE_AUTHORITY]),mode:sy.default(1),errOnUnauthorized:s.z.boolean().default(!1),enableAutoCommit:s.z.boolean().default(!1),autoIndexPersistInterval:z.z.default(z.SECOND),useExperimentalCodec:s.z.boolean().default(!1)}),ay=to.extend({keys:D.array().optional()}),oa=to.extend({channels:Fe}),ro=oa.or(Fe.transform(r=>oa.parse({channels:r,start:E.now()}))),iy=s.z.object({command:s.z.enum(it),config:ay.optional(),frame:jr.optional(),buffer:s.z.instanceof(Uint8Array).optional()}),oy=s.z.object({command:s.z.enum(it),end:E.z,err:ye.payloadZ.optional()}),ly=s.z.tuple([s.z.union([s.z.record(D.or(pe),X.authorityZ),D.or(pe),X.authorityZ]),X.authorityZ.optional()]).transform(([r,e])=>{if(X.authorityZ.safeParse(r).success)return{keys:[],authorities:[r]};if(D.or(pe).safeParse(r).success){if(e==null)throw new Error("authority is required when setting authority for a single channel");return{keys:[r],authorities:[e]}}const t=r;return{keys:Object.keys(t),authorities:Object.values(t)}});let no=class xn{static ENDPOINT="/frame/write";stream;adapter;closeErr=null;constructor(e,t){this.stream=e,this.adapter=t}static async _open(e,t,n){const a=ro.parse(n),i=await cs.open(e,a.channels);a.useExperimentalCodec&&(t=t.withCodec(new py(i.codec)));const o=await t.stream(xn.ENDPOINT,iy,oy),l=new xn(o,i);return await l.execute({command:0,config:{...a,keys:i.keys}}),l}async write(e,t){if(this.closeErr!=null)throw this.closeErr;if(this.stream.received())return await this.close();const n=await this.adapter.adapt(e,t);this.stream.send({command:1,frame:n.toPayload()})}async setAuthority(e,t){if(this.closeErr!=null)throw this.closeErr;const n=ly.parse([e,t]),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(kn.matches(this.closeErr))return null;throw this.closeErr}const[t,n]=await this.stream.receive();n!=null?this.closeErr=te.matches(n)?new kn:n:this.closeErr=ye.decode(t?.err)}}async execute(e){const t=this.stream.send(e);for(t!=null&&await this.closeInternal(t);;){const[n,a]=await this.stream.receive();a!=null&&await this.closeInternal(a);const i=ye.decode(n?.err);if(i!=null&&await this.closeInternal(i),n?.command==e.command)return n}}};const la=r=>r.data.byteLength/r.dataType.density.valueOf(),cy=r=>{const{keys:e,series:t}=r;e.forEach((n,a)=>{t[a].key=n}),t.sort((n,a)=>n.key-a.key),e.sort((n,a)=>n-a),t.forEach(n=>delete n.key)},ca=5,ua=4,ha=3,da=2,fa=1,pa=0,ne=N.TIMESTAMP.density.valueOf(),Te=8,Oe=4,Kr=4,Jr=4,uy=1;class so{contentType="application/sy-framer";states=new Map;currState;seqNum=0;constructor(e=[],t=[]){(e.length>0||t.length>0)&&this.update(e,t)}update(e,t){this.seqNum++;const n={keys:e,keyDataTypes:new Map,hasVariableDataTypes:!1};e.forEach((a,i)=>{const o=t[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 $(`
|
|
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,t=0){this.throwIfNotUpdated("encode");let n=e;e!=null&&typeof e=="object"&&"toPayload"in e&&(n=e.toPayload()),cy(n);let a=-1,i,o,l,c=t+uy+Jr,u=!this.currState?.hasVariableDataTypes,d=!0,h=!0,b=!0,S=!0,R=!0;n.keys.length!==this.currState?.keys.length&&(b=!1,c+=n.keys.length*Kr),n.series.forEach((L,re)=>{const Q=la(L),wt=n.keys[re],Ue=this.currState?.keyDataTypes.get(wt);if(Ue==null)throw new $(`Channel ${wt} was not provided in the list of channels when opening the writer`);if(!Ue.equals(L.dataType))throw new $(`Series data type of ${L.dataType.toString()} does not match the data type of ${Ue.toString()} for channel ${wt}`);if(c+=L.data.byteLength,a===-1){a=Q,i=L.timeRange?.start,o=L.timeRange?.end,l=BigInt(L.alignment??0n);return}a!==Q&&(u=!1),(i?.valueOf()!==L.timeRange?.start.valueOf()||o?.valueOf()!==L.timeRange?.end.valueOf())&&(d=!1),l!==BigInt(L.alignment??0)&&(S=!1)}),h=d&&i==null&&o==null,R=S&&(l===void 0||l===0n),u?c+=Oe:c+=n.keys.length*Oe,h||(d?c+=ne*2:c+=n.keys.length*ne*2),R||(S?c+=Te:c+=n.keys.length*Te);const A=new Uint8Array(c),B=new DataView(A.buffer);let x=t;return A[x]=Number(R)<<ca|Number(S)<<ua|Number(u)<<ha|Number(d)<<da|Number(h)<<fa|Number(b)<<pa,x++,B.setUint32(x,this.seqNum,!0),x+=Jr,u&&(B.setUint32(x,a,!0),x+=Oe),d&&!h&&(B.setBigUint64(x,i?.valueOf()??0n,!0),B.setBigUint64(x,o?.valueOf()??0n,!0),x+=ne*2),S&&!R&&(B.setBigUint64(x,l??0n,!0),x+=Te),n.series.forEach((L,re)=>{if(b||(B.setUint32(x,n.keys[re],!0),x+=Kr),!u){let Q=L.data.byteLength;L.dataType.isVariable||(Q=la(L)),B.setUint32(x,Q,!0),x+=Oe}A.set(new Uint8Array(L.data),x),x+=L.data.byteLength,!d&&!h&&(B.setBigUint64(x,L.timeRange?.start.valueOf()??0n,!0),B.setBigUint64(x,L.timeRange?.end.valueOf()??0n,!0),x+=ne*2),!S&&!R&&(B.setBigUint64(x,L.alignment??0n,!0),x+=Te)}),A}decode(e,t=0){this.throwIfNotUpdated("decode");const n=e instanceof Uint8Array?e:new Uint8Array(e),a={keys:[],series:[]};let i=t,o=0,l=0,c,u,d;const h=new DataView(n.buffer,n.byteOffset,n.byteLength),b=!!(n[i]>>ca&1),S=!!(n[i]>>ua&1),R=!!(n[i]>>ha&1),A=!!(n[i]>>da&1),B=!!(n[i]>>fa&1),x=!!(n[i]>>pa&1);i++;const L=h.getUint32(i,!0);i+=Jr;const re=this.states.get(L);if(re==null)return a;if(R){if(i+Oe>h.byteLength)return a;o=h.getUint32(i,!0),i+=Oe}if(A&&!B){if(i+ne>h.byteLength)return a;c=new E(h.getBigUint64(i,!0)),i+=ne,u=new E(h.getBigUint64(i,!0)),i+=ne}if(S&&!b){if(i+Te>h.byteLength)return a;d=h.getBigUint64(i,!0),i+=Te}return x&&(a.keys=[...re.keys]),re.keys.forEach((Q,wt)=>{if(!x){if(i>=h.byteLength||h.getUint32(i,!0)!==Q)return;i+=Kr,a.keys.push(Q)}const Ue=re.keyDataTypes.get(Q);if(l=0,R)l=o;else{if(i+Oe>h.byteLength)return;l=h.getUint32(i,!0),i+=Oe}let tr=l;if(Ue.isVariable||(tr*=Ue.density.valueOf()),i+tr>h.byteLength){a.keys.splice(wt,1);return}const Me={dataType:Ue,data:n.slice(i,i+tr).buffer};if(i+=tr,!A&&!B){if(i+ne*2>h.byteLength)return;const Ol=h.getBigUint64(i,!0);i+=ne;const Sl=h.getBigUint64(i,!0);i+=ne,Me.timeRange=new M({start:Ol,end:Sl})}else B?Me.timeRange=new M({start:0n,end:0n}):Me.timeRange=new M({start:c?.valueOf()??0n,end:u?.valueOf()??0n});if(!S&&!b){if(i+Te>h.byteLength)return;d=h.getBigUint64(i,!0),i+=Te,Me.alignment=d}else b?Me.alignment=0n:Me.alignment=d;a.series.push(Me)}),a}}const ls=254,hy=new Uint8Array([ls]),dy=255,fy=new Uint8Array([dy]),ao="application/sy-framer";class py{contentType=ao;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=$e.JSON_CODEC}encode(e){const t=e;if(t.type=="close"||t.payload?.command!=it.Write){const a=this.lowPerfCodec.encode(t),i=new Uint8Array({length:a.byteLength+1});return i.set(hy,0),i.set(new Uint8Array(a),1),i}const n=this.base.encode(t.payload?.frame,1);return n.set(fy,0),n}decode(e,t){if(new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ls)return this.lowPerfCodec.decode(e.slice(1),t);const n={type:"data"},a=this.base.decode(e,1);return n.payload={command:it.Write,frame:a},n}}class yy{contentType=ao;base;lowPerfCodec;constructor(e){this.base=e,this.lowPerfCodec=$e.JSON_CODEC}encode(e){return this.lowPerfCodec.encode(e)}decode(e,t){return new DataView(e instanceof Uint8Array?e.buffer:e).getUint8(0)===ls?this.lowPerfCodec.decode(e.slice(1),t):{type:"data",payload:{frame:this.base.decode(e,1)}}}}class Rr{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new so}static async open(e,t){const n=new Rr(e);return await n.update(t),n}async update(e){const{variant:t,normalized:n}=ee(e),a=await this.retriever.retrieve(n),i=a.map(l=>l.key);if(Fs.uniqueUnorderedPrimitiveArrays(this.keys,i)===Fs.EQUAL)return!1;if(this.codec.update(i,a.map(l=>l.dataType)),t==="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 t=this.adapter;return e.map((n,a)=>{if(typeof n=="number"){const i=t.get(n);if(i==null)throw new Error(`Channel ${n} not found`);return[i,a]}return[n,a]})}}class cs{adapter;retriever;keys;codec;constructor(e){this.retriever=e,this.adapter=null,this.keys=[],this.codec=new so}static async open(e,t){const n=new cs(e);return await n.update(t),n}async adaptParams(e){const t=Fe.parse(e);return await Promise.all(t.map(async n=>await this.adaptToKey(n)))}async update(e){const t=await Wi(this.retriever,e),n=t.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(t.map(c=>[c.name,c.key])),this.keys=n,this.codec.update(this.keys,t.map(c=>c.dataType)),!0):!1}async fetchChannel(e){const t=await this.retriever.retrieve(e);if(t.length===0)throw new Error(`Channel ${JSON.stringify(e)} not found`);return t[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,t){if(typeof e=="string"||typeof e=="number"){if(t==null)throw new $(`
|
|
32
|
-
Received a single channel name or key but no series.
|
|
33
|
-
`);if(Array.isArray(t)){if(t.some(c=>c instanceof Ae||Array.isArray(c)))throw new $(`
|
|
34
|
-
Received a single channel name or key but multiple series.
|
|
35
|
-
`);t=t}const o=await this.fetchChannel(e),l=new Ae({data:t,dataType:o.dataType});return new K(o.key,l)}if(Array.isArray(e)){if(t==null)throw new $(`
|
|
36
|
-
Received an array of channel names or keys but no series.
|
|
37
|
-
`);if(!Array.isArray(t))throw new $(`
|
|
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>=t.length)throw new $(`
|
|
40
|
-
Received an array of channel names or keys but not enough series.
|
|
41
|
-
`);const d=new Ae({data:t[c],dataType:u.dataType});o.push(u.key),l.push(d)}return new K(o,l)}if(e instanceof K||e instanceof Map){const o=new K(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 $(`
|
|
42
|
-
Channel ${c} was not provided in the list of channels when opening the writer
|
|
43
|
-
`);return u});return new K(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),d=new Ae({data:c,dataType:u.dataType});n.push(u.key),a.push(d)}return new K(n,a)}}class io{name;stream;constructor(e,t){this.stream=t,this.name=e}async receive(){const[e,t]=await this.stream.receive();if(t!=null)throw t;return e}received(){return this.stream.received()}async closeAndAck(){for(this.stream.closeSend();;){const[e,t]=await this.stream.receive();if(e!=null&&console.warn(`${this.name} received unexpected response on ${JSON.stringify(e)} closure.
|
|
44
|
-
Please report this error to the Synnax team.`),t!=null){if(te.matches(t))return;throw t}}}closeSend(){this.stream.closeSend()}send(e){const t=this.stream.send(e);if(t!=null)throw t}}const Sr=new z(-1);var us=(r=>(r[r.Open=0]="Open",r[r.Next=1]="Next",r[r.Prev=2]="Prev",r[r.SeekFirst=3]="SeekFirst",r[r.SeekLast=4]="SeekLast",r[r.SeekLE=5]="SeekLE",r[r.SeekGE=6]="SeekGE",r[r.Valid=7]="Valid",r[r.Error=8]="Error",r))(us||{}),oo=(r=>(r[r.None=0]="None",r[r.Ack=1]="Ack",r[r.Data=2]="Data",r))(oo||{});const gy=s.z.object({command:s.z.enum(us),span:z.z.optional(),bounds:M.z.optional(),stamp:E.z.optional(),keys:D.array().optional(),chunkSize:s.z.number().optional()}),my=s.z.object({variant:s.z.enum(oo),ack:s.z.boolean(),command:s.z.enum(us),error:ye.payloadZ.optional().nullable(),frame:jr.optional()});class Mt{static ENDPOINT="/frame/iterate";stream;adapter;value;constructor(e,t){this.stream=new io("Iterator",e),this.value=new K,this.adapter=t}static async _open(e,t,n,a,i={}){const o=await Rr.open(n,t),l=await a.stream(Mt.ENDPOINT,gy,my),c=new Mt(l,o);return await c.execute({command:0,keys:o.keys,bounds:new M(e),chunkSize:i.chunkSize??1e5}),c}async next(e=Sr){return await this.execute({command:1,span:new z(e)})}async prev(e=Sr){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 wy(this)}async execute(e){for(this.stream.send(e),this.value=new K;;){const t=await this.stream.receive();if(t.variant===1)return t.ack;this.value.push(this.adapter.adapt(new K(t.frame)))}}}class wy{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 by=s.z.object({keys:s.z.number().array(),downsampleFactor:s.z.number()}),vy=s.z.object({frame:jr}),Ty="/frame/stream",ya=s.z.object({channels:Fe,downsampleFactor:s.z.number().optional().default(1),useExperimentalCodec:s.z.boolean().optional().default(!1)}),hs=ya.or(Fe.transform(r=>ya.parse({channels:r}))),lo=(r,e)=>async t=>{const n=hs.parse(t),a=await Rr.open(r,n.channels);n.useExperimentalCodec&&(e=e.withCodec(new yy(a.codec)));const i=await e.stream(Ty,by,vy),o=new Oy(i,a);i.send({keys:a.keys,downsampleFactor:n.downsampleFactor??1});const[,l]=await i.receive();if(l!=null)throw l;return o},co=async(r,e,t)=>await lo(r,e)(t);class Oy{stream;adapter;downsampleFactor;constructor(e,t){this.stream=new io("Streamer",e),this.adapter=t,this.downsampleFactor=1}get keys(){return this.adapter.keys}async next(){try{return{done:!1,value:await this.read()}}catch(e){if(te.matches(e))return{done:!0,value:void 0};throw e}}async read(){return this.adapter.adapt(new K((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 Ur{wrapped_=null;breaker;opener;config;constructor(e,t,n={}){this.opener=e,this.config=hs.parse(t);const{maxRetries:a=5e3,baseInterval:i=z.seconds(1),scale:o=1}=n??{};this.breaker=new Oi.Breaker({maxRetries:a,baseInterval:i,scale:o})}static async open(e,t,n){const a=new Ur(e,t,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=Fe.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(te.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(te.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 uo extends Hh.Observer{streamer;closePromise;constructor(e,t){super(t),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 Sy=r=>({type:"framer",key:r.toString()});let ho=class{streamClient;retriever;deleter;constructor(r,e,t){this.streamClient=r,this.retriever=t,this.deleter=new ry(e)}async openIterator(r,e,t){return await Mt._open(r,e,this.retriever,this.streamClient,t)}async openWriter(r){return await no._open(this.retriever,this.streamClient,r)}async openStreamer(r){return await co(this.retriever,this.streamClient,r)}async write(r,e,t){if(t==null){const a=e,i=await this.openWriter({start:r,channels:Object.keys(a),mode:Ut.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});return await i.write(a),await i.close()}const n=await this.openWriter({start:r,channels:e,mode:Ut.Persist,errOnUnauthorized:!0,enableAutoCommit:!0,autoIndexPersistInterval:z.MAX});await n.write(e,t),await n.close()}async read(r,e){const{single:t}=ee(e),n=await this.readFrame(r,e);return t?n.get(e):n}async readFrame(r,e){const t=await this.openIterator(r,e),n=new K;try{for await(const a of t)n.push(a)}finally{await t.close()}return n}async readLatest(r,e=1){const{single:t}=ee(r),n=await this.readLatestNFrame(r,e);return t?n.get(r):n}async readLatestNFrame(r,e){const t=await this.openIterator(M.MAX,r,{chunkSize:e}),n=new K;if(e>0)try{await t.seekLast(),await t.prev(Sr),n.push(t.value)}finally{await t.close()}return n}async delete(r,e){const{normalized:t,variant:n}=ee(r);return n==="keys"?await this.deleter.delete({keys:t,bounds:e}):await this.deleter.delete({names:t,bounds:e})}};const zy=Object.freeze(Object.defineProperty({__proto__:null,ALWAYS_INDEX_PERSIST_ON_AUTO_COMMIT:ny,AUTO_SPAN:Sr,Client:ho,Frame:K,HardenedStreamer:Ur,Iterator:Mt,ObservableStreamer:uo,Writer:no,WriterClosedError:kn,WriterCommand:it,WriterMode:Ut,createStreamOpener:lo,frameZ:jr,ontologyID:Sy,openStreamer:co,seriesFromPayload:Qi,seriesToPayload:eo,streamerConfigZ:hs,writerConfigZ:ro},Symbol.toStringTag,{value:"Module"})),Ey=X.ABSOLUTE_AUTHORITY,Ny=X.ZERO_AUTHORITY,Ay=X.stateZ(s.z.number()),ky=r=>r.to==null?`${r.from?.resource} - ${r.from?.subject.name} -> released`:r.from==null?`${r.to.resource} - released -> ${r.to.subject.name} (${r.to.authority.toString()})`:`${r.to.resource} - ${r.from.subject.name} -> ${r.to.subject.name} (${r.to.authority.toString()})`,xy=s.z.object({transfers:s.z.array(X.transferZ(D))});class fo extends uo{states;codec;constructor(e){super(e,t=>{const n=this.codec.decode(t.series[0].buffer,xy);return this.merge(n),[n.transfers,!0]}),this.states=new Map,this.codec=new $e.JSONCodec}subjects(){const e=new Map;return this.states.forEach(t=>e.set(t.subject.key,t.subject)),Array.from(e.values())}merge(e){e.transfers.forEach(t=>{t.from==null&&t.to==null&&console.warn("Invalid transfer: ",t),t.to==null?this.states.delete(t.from.resource):this.states.set(t.to.resource,t.to)})}}const po="sy_node_1_control";let yo=class{framer;constructor(r){this.framer=r}async openStateTracker(){const r=await Ur.open(async e=>await this.framer.openStreamer(e),po);return new fo(r)}};const Cy=Object.freeze(Object.defineProperty({__proto__:null,ABSOLUTE_AUTHORITY:Ey,CONTROL_STATE_CHANNEL_NAME:po,Client:yo,StateTracker:fo,ZERO_AUTHORITY:Ny,stateZ:Ay,transferString:ky},Symbol.toStringTag,{value:"Module"}));let Iy=class{tasks;racks;devices;constructor(r,e,t){this.tasks=r,this.racks=e,this.devices=t}};const ce=s.z.uint32(),go=_t.statusZ(s.z.object({rack:ce})),Mr=s.z.object({key:ce,name:s.z.string(),status:kt.nullToUndefined(go)}),mo=Mr.partial({key:!0}),wo=r=>r?$e.JSON_CODEC.decodeString(r,ge.unknownZ):{},yt=s.z.string(),bo=_t.statusZ(s.z.object({rack:ce,device:yt})),Lr=s.z.object({key:yt,rack:ce,name:s.z.string(),make:s.z.string(),model:s.z.string(),location:s.z.string(),configured:s.z.boolean().optional(),properties:ge.unknownZ.or(s.z.string().transform(wo)),status:kt.nullToUndefined(bo)}),vo=Lr.extend({properties:s.z.unknown().transform(r=>$e.JSON_CODEC.encodeString(r))}),jy="sy_device_set",Ry="sy_device_delete",Uy="sy_device_status",My="/hardware/device/retrieve",Ly="/hardware/device/create",Py="/hardware/device/delete",Dy=s.z.object({devices:vo.array()}),By=s.z.object({devices:Lr.array()}),$y=s.z.object({keys:yt.array()}),Fy=s.z.object({}),qy=s.z.object({keys:yt.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:ce.array().optional(),searchTerm:s.z.string().optional(),limit:s.z.number().optional(),offset:s.z.number().optional(),includeStatus:s.z.boolean().optional()}),Zy=s.z.object({devices:Y(Lr)}),Yy=s.z.object({key:yt,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),_y=s.z.union([Yy,qy]);let To=class{type="device";client;constructor(r){this.client=r}async retrieve(r){const e=typeof r=="object"&&"key"in r,t=await g(this.client,My,r,_y,Zy);pt("Device",r,t.devices,e);const n=t.devices;return e?n[0]:n}async create(r){const e=!Array.isArray(r),t=(await g(this.client,Ly,{devices:O.toArray(r)},Dy,By)).devices;return e?t[0]:t}async delete(r){await g(this.client,Py,{keys:O.toArray(r)},$y,Fy)}};const Vy=r=>({type:"device",key:r}),Hy=Object.freeze(Object.defineProperty({__proto__:null,Client:To,DELETE_CHANNEL_NAME:Ry,SET_CHANNEL_NAME:jy,STATUS_CHANNEL_NAME:Uy,deviceZ:Lr,keyZ:yt,newZ:vo,ontologyID:Vy,statusZ:bo},Symbol.toStringTag,{value:"Module"})),Wy="/hardware/rack/retrieve",Gy="/hardware/rack/create",Ky="/hardware/rack/delete",Jy="sy_rack_status",Xy="sy_rack_set",Qy="sy_rack_delete",eg=s.z.object({keys:ce.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()}),tg=s.z.object({racks:Y(Mr)}),rg=s.z.union([s.z.object({key:ce,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),ng=eg,sg=s.z.union([rg,ng]),ag=s.z.object({racks:mo.array()}),ig=s.z.object({racks:Mr.array()}),og=s.z.object({keys:ce.array()}),lg=s.z.object({});let Oo=class{type="rack";client;tasks;constructor(r,e){this.client=r,this.tasks=e}async delete(r){await g(this.client,Ky,{keys:O.toArray(r)},og,lg)}async create(r){const e=!Array.isArray(r),t=await g(this.client,Gy,{racks:O.toArray(r)},ag,ig),n=this.sugar(t.racks);return e?n[0]:n}async retrieve(r){const e="key"in r||"name"in r,t=await g(this.client,Wy,r,sg,tg),n=this.sugar(t.racks);return pt("Rack",r,n,e),e?n[0]:n}sugar(r){const e=!Array.isArray(r),t=O.toArray(r).map(({key:n,name:a,status:i})=>new So(n,a,this.tasks,i));return e?t[0]:t}};class So{key;name;status;tasks;constructor(e,t,n,a){this.key=e,this.name=t,this.tasks=n,this.status=a}async listTasks(){return await this.tasks.retrieve({rack:this.key})}async createTask(e,t){return e.key=((BigInt(this.key)<<32n)+(BigInt(e.key??0)&0xffffffffn)).toString(),await this.tasks.create(e,t)}async deleteTask(e){await this.tasks.delete([e])}get payload(){return{key:this.key,name:this.name,status:this.status}}}const cg=r=>({type:"rack",key:r.toString()}),ug=Object.freeze(Object.defineProperty({__proto__:null,Client:Oo,DELETE_CHANNEL_NAME:Qy,Rack:So,SET_CHANNEL_NAME:Xy,STATUS_CHANNEL_NAME:Jy,keyZ:ce,newZ:mo,ontologyID:cg,rackZ:Mr,statusZ:go},Symbol.toStringTag,{value:"Module"})),me=r=>r?JSON.parse(r):{},we=s.z.union([s.z.string(),s.z.bigint().transform(r=>r.toString()),s.z.number().transform(r=>r.toString())]),zo=r=>s.z.object({task:we,running:s.z.boolean(),data:r}),ds=r=>_t.statusZ(zo(r)),Wt=(r={typeSchema:s.z.string(),configSchema:s.z.unknown(),statusDataSchema:s.z.unknown()})=>s.z.object({key:we,name:s.z.string(),type:r.typeSchema,internal:s.z.boolean().optional(),config:s.z.string().transform(wo).or(r.configSchema),status:ds(r.statusDataSchema).optional().nullable(),snapshot:s.z.boolean().optional()}),Eo=r=>Wt(r).omit({key:!0}).extend({key:we.transform(e=>e.toString()).optional(),config:s.z.unknown().transform(e=>$e.JSON_CODEC.encodeString(e))}),hg=s.z.object({task:we,type:s.z.string(),key:s.z.string(),args:ge.unknownZ.or(s.z.string().transform(me)).or(s.z.array(s.z.unknown())).or(s.z.null()).optional()}),dg=r=>Number(BigInt(r)>>32n),Cn="sy_task_status",In="sy_task_cmd",fg="sy_task_set",pg="sy_task_delete",Le=new Error("Task not created"),No=async(r,e)=>{const t=await e.retrieveParents(fs(r));return t.length===0?null:t[0]};class Ao{key;name;internal;type;snapshot;config;status;schemas;frameClient_;ontologyClient_;rangeClient_;get frameClient(){if(this.frameClient_==null)throw Le;return this.frameClient_}get ontologyClient(){if(this.ontologyClient_==null)throw Le;return this.ontologyClient_}get rangeClient(){if(this.rangeClient_==null)throw Le;return this.rangeClient_}constructor({key:e,type:t,name:n,config:a,internal:i=!1,snapshot:o=!1,status:l},c,u,d,h){this.key=e,this.name=n,this.type=t,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_=d,this.rangeClient_=h}get payload(){return{key:this.key,name:this.name,type:this.type,config:this.config,status:this.status,internal:this.internal}}get ontologyID(){return fs(this.key)}async executeCommand(e,t){return await ps(this.frameClient,this.key,e,t)}async executeCommandSync(e,t,n){return await xo(this.frameClient,this.key,e,t,this.name,this.schemas?.statusDataSchema,n)}async snapshottedTo(){if(this.ontologyClient==null||this.rangeClient==null)throw Le;return this.snapshot?await No(this.key,this.ontologyClient):null}}const yg=s.z.object({rack:ce.optional(),keys:we.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()}),gg=s.z.union([s.z.object({key:we,includeStatus:s.z.boolean().optional()}).transform(({key:r,includeStatus:e})=>({keys:[r],includeStatus:e})),s.z.object({name:s.z.string(),includeStatus:s.z.boolean().optional()}).transform(({name:r,includeStatus:e})=>({names:[r],includeStatus:e}))]),mg=yg,wg=s.z.union([gg,mg]),bg=r=>s.z.object({tasks:Y(Wt(r))}),vg="/hardware/task/retrieve",Tg="/hardware/task/create",Og="/hardware/task/delete",Sg="/hardware/task/copy",zg=r=>s.z.object({tasks:Eo(r).array()}),Eg=r=>s.z.object({tasks:Wt(r).array()}),Ng=s.z.object({keys:we.array()}),Ag=s.z.object({}),kg=s.z.object({key:we,name:s.z.string(),snapshot:s.z.boolean()}),xg=r=>s.z.object({task:Wt(r)});let ko=class{type="task";client;frameClient;ontologyClient;rangeClient;constructor(r,e,t,n){this.client=r,this.frameClient=e,this.ontologyClient=t,this.rangeClient=n}async create(r,e){const t=!Array.isArray(r),n=zg(e),a=Eg(e),i=await g(this.client,Tg,{tasks:O.toArray(r)},n,a),o=this.sugar(i.tasks,e);return t?o[0]:o}async delete(r){await g(this.client,Og,{keys:O.toArray(r)},Ng,Ag)}async retrieve({schemas:r,...e}){const t="key"in e||"name"in e,n=(await g(this.client,vg,e,wg,bg(r))).tasks,a=this.sugar(n,r);return pt("Task",e,a,t),t?a[0]:a}async copy(r,e,t){const n=xg(),a=await g(this.client,Sg,{key:r,name:e,snapshot:t},kg,n);return this.sugar(a.task)}async retrieveSnapshottedTo(r){if(this.ontologyClient==null)throw Le;return await No(r,this.ontologyClient)}sugar(r,e){const t=!Array.isArray(r),n=O.toArray(r).map(({key:a,name:i,type:o,config:l,status:c,internal:u,snapshot:d})=>new Ao({key:a,name:i,type:o,config:l,internal:u,snapshot:d,status:c},e,this.frameClient,this.ontologyClient,this.rangeClient));return t?n[0]:n}async executeCommand(r,e,t){return await ps(this.frameClient,r,e,t)}async executeCommandSync(r,e,t,n,a,i=s.z.unknown()){const o=async()=>(await this.retrieve({key:r})).name;return await xo(this.frameClient,r,e,t,a??o,i,n)}};const fs=r=>({type:"task",key:r}),ps=async(r,e,t,n)=>{if(r==null)throw Le;const a=zh.create(),i=await r.openWriter(In);return await i.write(In,[{args:n,key:a,task:e,type:t}]),await i.close(),a},xo=async(r,e,t,n,a,i,o)=>{if(r==null)throw Le;const l=await r.openStreamer(Cn),c=await ps(r,e,t,o),u=new z(n);let d;const h=new Promise((b,S)=>{d=setTimeout(()=>{(async()=>S(await Cg(t,a,u,e)))()},u.milliseconds)});try{for(;;){const b=await Promise.race([l.read(),h]),S=ds(i).parse(b.at(-1)[Cn]);if(S.key===c)return S}}finally{clearTimeout(d),l.close()}},Cg=async(r,e,t,n)=>{const a=Iu.capitalize(r),i=t.toString();try{const o=typeof e=="string"?e:await e();return new Error(`${a} command to ${o} 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 ${n} timed out after ${i}`)}},Ig=Object.freeze(Object.defineProperty({__proto__:null,COMMAND_CHANNEL_NAME:In,Client:ko,DELETE_CHANNEL_NAME:pg,SET_CHANNEL_NAME:fg,STATUS_CHANNEL_NAME:Cn,Task:Ao,commandZ:hg,keyZ:we,newZ:Eo,ontologyID:fs,rackKey:dg,statusDetailsZ:zo,statusZ:ds,taskZ:Wt},Symbol.toStringTag,{value:"Module"})),Re=s.z.uuid(),Gt=s.z.object({key:Re,name:s.z.string().min(1),color:s.z.string()}),jg="labeled_by",Rg="sy_label_set",Ug="sy_label_delete",Co=Gt.extend({key:Re.optional()}),Mg=s.object({labels:Co.array()}),Lg=s.object({labels:Gt.array()}),Pg=s.object({keys:Re.array()}),Io=s.object({id:U,labels:Re.array(),replace:s.boolean().optional()}),Dg=Io.omit({replace:!0}),Xr=s.object({}),Bg="/label/create",$g="/label/delete",Fg="/label/set",qg="/label/remove",Zg="/label/retrieve",Yg=s.object({keys:Re.array().optional(),for:U.optional(),searchTerm:s.string().optional(),offset:s.number().optional(),limit:s.number().optional()}),_g=s.object({key:Re}).transform(({key:r})=>({keys:[r]})),Vg=s.union([_g,Yg]),Hg=s.object({labels:Y(Gt)});let jo=class{type="label";client;constructor(r){this.client=r}async retrieve(r){const e="key"in r,t=await g(this.client,Zg,r,Vg,Hg);return pt("Label",r,t.labels,e),e?t.labels[0]:t.labels}async label(r,e,t={}){await g(this.client,Fg,{id:r,labels:e,replace:t.replace},Io,Xr)}async remove(r,e){await g(this.client,qg,{id:r,labels:e},Dg,Xr)}async create(r){const e=Array.isArray(r),t=await g(this.client,Bg,{labels:O.toArray(r)},Mg,Lg);return e?t.labels:t.labels[0]}async delete(r){await g(this.client,$g,{keys:O.toArray(r)},Pg,Xr)}};const Wg=r=>({type:"label",key:r}),Gg=Object.freeze(Object.defineProperty({__proto__:null,Client:jo,DELETE_CHANNEL_NAME:Ug,LABELED_BY_ONTOLOGY_RELATIONSHIP_TYPE:jg,SET_CHANNEL_NAME:Rg,keyZ:Re,labelZ:Gt,newZ:Co,ontologyID:Wg},Symbol.toStringTag,{value:"Module"})),_=s.z.uuid(),ys=s.z.string().min(1),Kt=s.z.object({key:_,name:ys,timeRange:M.z,color:s.z.string().optional(),labels:Gt.array().or(s.z.null().transform(()=>{})).optional(),get parent(){return Kt.optional().nullable().transform(r=>r===void 0?null:r)}}),Ro=Kt.omit({parent:!0,labels:!0}).partial({key:!0}),Kg="sy_range_alias_set",Jg="sy_range_alias_delete",Xg=s.z.object({range:_,aliases:s.z.string().array()}),Qg=s.z.object({aliases:s.z.record(s.z.string(),D)}),em=s.z.object({range:_,aliases:s.z.record(D.or(s.z.string()),s.z.string())}),tm=s.z.unknown(),rm=s.z.object({range:_,channels:D.array()}),nm=s.z.unknown(),sm=s.z.object({range:_}),am=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())}),im=s.z.object({range:_,channels:D.array()}),om=s.z.object({aliases:s.z.record(s.z.string(),s.z.string())});let Xe=class Qe{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,t,n){this.rangeKey=e,this.cache=new Map,this.client=n,this.frameClient=t}async resolve(e){const t=[],n=typeof e=="string",a={};if(n){const o=this.cache.get(e);if(o!=null)return o;t.push(e)}else e.forEach(o=>{const l=this.cache.get(o);l!=null?a[o]=l:t.push(o)});if(t.length===0)return a;const i=await g(this.client,Qe.RESOLVE_ENDPOINT,{range:this.rangeKey,aliases:t},Xg,Qg);return Object.entries(i.aliases).forEach(([o,l])=>this.cache.set(o,l)),n?i.aliases[t[0]]:{...a,...i.aliases}}async set(e){await g(this.client,Qe.SET_ENDPOINT,{range:this.rangeKey,aliases:e},em,tm)}async list(){return(await g(this.client,Qe.LIST_ENDPOINT,{range:this.rangeKey},sm,am)).aliases}async retrieve(e){const t=typeof e=="number",n=await g(this.client,Qe.RETRIEVE_ENDPOINT,{range:this.rangeKey,channels:O.toArray(e)},im,om);return t?n.aliases[e]:n.aliases}async delete(e){await g(this.client,Qe.DELETE_ENDPOINT,{range:this.rangeKey,channels:e},rm,nm)}};const lm=s.z.object({alias:s.z.string().optional(),channel:D,range:_}),Uo="---",cm=r=>`${r.range}${Uo}${r.channel}`,um=r=>{const[e,t]=r.split(Uo);return{range:e,channel:Number(t)}},hm="sy_range_kv_set",dm="sy_range_kv_delete",gs=s.z.object({range:_,key:s.z.string(),value:s.z.string()}),fm=({range:r,key:e})=>`${r}<--->${e}`,pm=s.z.object({range:_,keys:s.z.string().array()}),ym=s.z.object({pairs:Y(gs)}),gm=s.z.object({range:_,pairs:gs.array()}),mm=s.z.object({range:_,keys:s.z.string().array()});class Be{static GET_ENDPOINT="/range/kv/get";static SET_ENDPOINT="/range/kv/set";static DELETE_ENDPOINT="/range/kv/delete";rangeKey;client;constructor(e,t){this.rangeKey=e,this.client=t}async get(e){const t=await g(this.client,Be.GET_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},pm,ym);return typeof e=="string"?t.pairs[0].value:Object.fromEntries(t.pairs.map(n=>[n.key,n.value]))}async list(){return this.get([])}async set(e,t=""){let n;Ja(e)?n=Object.entries(e).map(([a,i])=>({range:this.rangeKey,key:a,value:i})):n=[{range:this.rangeKey,key:e,value:t}],await g(this.client,Be.SET_ENDPOINT,{range:this.rangeKey,pairs:n},gm,s.z.unknown())}async delete(e){await g(this.client,Be.DELETE_ENDPOINT,{range:this.rangeKey,keys:O.toArray(e)},mm,s.z.unknown())}}const wm="sy_range_set",bm="sy_range_delete";class Mo{key;name;kv;timeRange;color;parent;labels;channels;aliaser;frameClient;labelClient;ontologyClient;rangeClient;constructor({name:e,timeRange:t=M.ZERO,key:n,color:a,parent:i,labels:o},{frameClient:l,kv:c,aliaser:u,channels:d,labelClient:h,ontologyClient:b,rangeClient:S}){this.key=n,this.name=e,this.timeRange=t,this.parent=i,this.labels=o,this.frameClient=l,this.color=a,this.kv=c,this.aliaser=u,this.channels=d,this.labelClient=h,this.ontologyClient=b,this.rangeClient=S}get ontologyID(){return et(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,t){const n=await this.channels.retrieve(e);if(n.length===0)throw new je(`Channel ${e} does not exist`);await this.aliaser.set({[n[0].key]:t})}async deleteAlias(...e){await this.aliaser.delete(e)}async listAliases(){return await this.aliaser.list()}async resolveAlias(e){return await this.aliaser.resolve(e)}async retrieveParent(){return this.rangeClient.retrieveParent(this.key)}async retrieveChildren(){const e=(await this.ontologyClient.retrieveChildren(this.ontologyID,{excludeFieldData:!0,types:["range"]})).map(t=>t.id.key);return await this.rangeClient.retrieve(e)}async read(e){return await this.frameClient.read(this.timeRange,e)}async retrieveLabels(){return await this.labelClient.retrieve({for:et(this.key)})}async addLabel(...e){await this.labelClient.label(et(this.key),e)}async removeLabel(...e){await this.labelClient.remove(et(this.key),e)}static sort(e,t){return M.sort(e.timeRange,t.timeRange)}}const vm=s.z.object({keys:_.array().optional(),names:s.z.array(s.z.string()).optional(),searchTerm:s.z.string().optional(),overlapsWith:M.z.optional(),limit:s.z.number().int().optional(),offset:s.z.number().int().optional(),hasLabels:Re.array().optional(),includeLabels:s.z.boolean().optional(),includeParent:s.z.boolean().optional()}),Tm=vm.or(_.array().transform(r=>({keys:r}))).or(_.transform(r=>({keys:[r]}))).or(s.z.string().transform(r=>({names:[r]}))).or(s.z.string().array().transform(r=>({names:r}))).or(M.z.transform(r=>({overlapsWith:r}))),Om="/range/retrieve",Sm=s.z.object({ranges:Y(Kt)});let Lo=class{type="range";frameClient;writer;unaryClient;channels;labelClient;ontologyClient;constructor(r,e,t,n,a,i){this.frameClient=r,this.writer=e,this.unaryClient=t,this.channels=n,this.labelClient=a,this.ontologyClient=i}async create(r,e){const t=!Array.isArray(r),n=this.sugarMany(await this.writer.create(O.toArray(r),e));return t?n[0]:n}async rename(r,e){await this.writer.rename(r,e)}async delete(r){await this.writer.delete(O.toArray(r))}async retrieve(r){const e=typeof r=="string",{ranges:t}=await g(this.unaryClient,Om,r,Tm,Sm);return pt("Range",r,t,e),e?this.sugarMany(t)[0]:this.sugarMany(t)}getKV(r){return new Be(r,this.unaryClient)}async retrieveParent(r){const e=await this.ontologyClient.retrieveParents(et(r));if(e.length===0)return null;const t=e[0];return t.id.type!=="range"?null:await this.retrieve(t.id.key)}sugarOntologyResource(r){return this.sugarOne(Po(r))}async retrieveAlias(r,e){return await new Xe(r,this.frameClient,this.unaryClient).retrieve(e)}async retrieveAliases(r,e){return await new Xe(r,this.frameClient,this.unaryClient).retrieve(e)}async listAliases(r){return await new Xe(r,this.frameClient,this.unaryClient).list()}async setAlias(r,e,t){await new Xe(r,this.frameClient,this.unaryClient).set({[e]:t})}sugarOne(r){return new Mo(r,{frameClient:this.frameClient,kv:new Be(r.key,this.unaryClient),aliaser:new Xe(r.key,this.frameClient,this.unaryClient),channels:this.channels,labelClient:this.labelClient,ontologyClient:this.ontologyClient,rangeClient:this})}sugarMany(r){return r.map(e=>this.sugarOne(e))}resourceToRange(r){return this.sugarOne({key:r.id.key,name:r.data?.name,timeRange:new M(r.data?.timeRange),color:r.data?.color,labels:[],parent:null})}};const et=r=>({type:"range",key:r}),zm=r=>({type:"range-alias",key:r}),Po=({data:r,id:{key:e},name:t})=>{const n=M.z.parse(r?.timeRange);return{key:e,name:t,timeRange:n,color:typeof r?.color=="string"?r.color:void 0,labels:[],parent:null}},Em=s.z.object({ranges:Kt.array()}),Nm=s.z.object({parent:U.optional(),ranges:Ro.array()}),Am=s.z.object({keys:_.array()}),km=s.z.object({}),xm=s.z.object({key:_,name:ys}),Cm=s.z.object({}),Im="/range/create",jm="/range/delete",Rm="/range/rename";class Do{client;constructor(e){this.client=e}async rename(e,t){await g(this.client,Rm,{key:e,name:t},xm,Cm)}async create(e,t){return(await g(this.client,Im,{ranges:e,...t},Nm,Em)).ranges}async delete(e){await g(this.client,jm,{keys:e},Am,km)}}const Um=Object.freeze(Object.defineProperty({__proto__:null,Aliaser:Xe,Client:Lo,DELETE_ALIAS_CHANNEL_NAME:Jg,DELETE_CHANNEL_NAME:bm,KV:Be,KV_DELETE_CHANNEL:dm,KV_SET_CHANNEL:hm,Range:Mo,SET_ALIAS_CHANNEL_NAME:Kg,SET_CHANNEL_NAME:wm,Writer:Do,aliasKey:cm,aliasOntologyID:zm,aliasZ:lm,convertOntologyResourceToPayload:Po,decodeDeleteAliasChange:um,keyZ:_,kvPairKey:fm,kvPairZ:gs,nameZ:ys,newZ:Ro,ontologyID:et,payloadZ:Kt},Symbol.toStringTag,{value:"Module"})),Mm="/api/v1/";class Lm{url;unary;stream;secure;constructor(e,t={},n=!1){this.secure=n,this.url=e.child(Mm);const a=new $e.JSONCodec;this.unary=mu(new gu(this.url,a,this.secure),t),this.stream=new Ou(this.url,a,this.secure)}use(...e){this.unary.use(...e),this.stream.use(...e)}}const Jt=s.z.uuid(),ms=s.z.object({key:Jt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me))}),Pm=ms.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),ue=s.z.uuid(),Pr=s.z.object({key:ue,name:s.z.string(),layout:ge.unknownZ.or(s.z.string().transform(me))}),Bo=Pr.partial({key:!0}).transform(r=>({...r,layout:JSON.stringify(r.layout)})),$o=Pr.omit({layout:!0}).extend({layout:s.z.string().transform(me)}),Dm="/workspace/lineplot/retrieve",Bm="/workspace/lineplot/create",$m="/workspace/lineplot/rename",Fm="/workspace/lineplot/set-data",qm="/workspace/lineplot/delete",Zm=s.z.object({keys:Jt.array()}),Ym=s.z.object({workspace:ue,linePlots:Pm.array()}),_m=s.z.object({key:Jt,name:s.z.string()}),Vm=s.z.object({key:Jt,data:s.z.string()}),Hm=s.z.object({keys:Jt.array()}),Wm=s.z.object({linePlots:Y(ms)}),Gm=s.z.object({linePlots:ms.array()}),Qr=s.z.object({});let Km=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,Bm,{workspace:r,linePlots:O.toArray(e)},Ym,Gm);return t?n.linePlots:n.linePlots[0]}async rename(r,e){await g(this.client,$m,{key:r,name:e},_m,Qr)}async setData(r,e){await g(this.client,Fm,{key:r,data:JSON.stringify(e)},Vm,Qr)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,Dm,{keys:O.toArray(r)},Zm,Wm);return e?t.linePlots:t.linePlots[0]}async delete(r){await g(this.client,qm,{keys:O.toArray(r)},Hm,Qr)}};const Xt=s.z.uuid(),ws=s.z.object({key:Xt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me))}),Jm=ws.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Xm="/workspace/log/retrieve",Qm="/workspace/log/create",ew="/workspace/log/rename",tw="/workspace/log/set-data",rw="/workspace/log/delete",nw=s.z.object({keys:Xt.array()}),sw=s.z.object({workspace:ue,logs:Jm.array()}),aw=s.z.object({key:Xt,name:s.z.string()}),iw=s.z.object({key:Xt,data:s.z.string()}),ow=s.z.object({keys:Xt.array()}),lw=s.z.object({logs:ws.array()}),cw=s.z.object({logs:ws.array()}),en=s.z.object({});let uw=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,Qm,{workspace:r,logs:O.toArray(e)},sw,cw);return t?n.logs:n.logs[0]}async rename(r,e){await g(this.client,ew,{key:r,name:e},aw,en)}async setData(r,e){await g(this.client,tw,{key:r,data:JSON.stringify(e)},iw,en)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,Xm,{keys:O.toArray(r)},nw,lw);return e?t.logs:t.logs[0]}async delete(r){await g(this.client,rw,{keys:O.toArray(r)},ow,en)}};const gt=s.z.uuid(),bs=s.z.object({key:gt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me)),snapshot:s.z.boolean()}),hw=bs.partial({key:!0,snapshot:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Fo=bs.extend({data:s.z.string().transform(me)}),dw="/workspace/schematic/retrieve",fw="/workspace/schematic/create",pw="/workspace/schematic/rename",yw="/workspace/schematic/set-data",gw="/workspace/schematic/delete",mw="/workspace/schematic/copy",ww=s.z.object({keys:gt.array()}),bw=s.z.object({workspace:ue,schematics:hw.array()}),vw=s.z.object({key:gt,name:s.z.string()}),Tw=s.z.object({key:gt,data:s.z.string()}),Ow=s.z.object({keys:gt.array()}),Sw=s.z.object({key:gt,name:s.z.string(),snapshot:s.z.boolean()}),zw=s.z.object({schematics:Y(Fo)}),Ew=s.z.object({schematics:Fo.array()}),Nw=s.z.object({schematic:bs}),tn=s.z.object({});let Aw=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,fw,{workspace:r,schematics:O.toArray(e)},bw,Ew);return t?n.schematics:n.schematics[0]}async rename(r,e){await g(this.client,pw,{key:r,name:e},vw,tn)}async setData(r,e){await g(this.client,yw,{key:r,data:JSON.stringify(e)},Tw,tn)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,dw,{keys:O.toArray(r)},ww,zw);return e?t.schematics:t.schematics[0]}async delete(r){await g(this.client,gw,{keys:O.toArray(r)},Ow,tn)}async copy(r,e,t){return(await g(this.client,mw,{key:r,name:e,snapshot:t},Sw,Nw)).schematic}};const Qt=s.z.uuid(),qo=s.z.object({key:Qt,name:s.z.string(),data:ge.unknownZ.or(s.z.string().transform(me))}),kw=qo.partial({key:!0}).transform(r=>({...r,data:JSON.stringify(r.data)})),Zo=qo.extend({data:s.z.string().transform(me)}),xw="/workspace/table/retrieve",Cw="/workspace/table/create",Iw="/workspace/table/rename",jw="/workspace/table/set-data",Rw="/workspace/table/delete",Uw=s.z.object({keys:Qt.array()}),Mw=s.z.object({workspace:ue,tables:kw.array()}),Lw=s.z.object({key:Qt,name:s.z.string()}),Pw=s.z.object({key:Qt,data:s.z.string()}),Dw=s.z.object({keys:Qt.array()}),Bw=s.z.object({tables:Zo.array()}),$w=s.z.object({tables:Zo.array()}),rn=s.z.object({});let Fw=class{client;constructor(r){this.client=r}async create(r,e){const t=Array.isArray(e),n=await g(this.client,Cw,{workspace:r,tables:O.toArray(e)},Mw,$w);return t?n.tables:n.tables[0]}async rename(r,e){await g(this.client,Iw,{key:r,name:e},Lw,rn)}async setData(r,e){await g(this.client,jw,{key:r,data:JSON.stringify(e)},Pw,rn)}async retrieve(r){const e=Array.isArray(r),t=await g(this.client,xw,{keys:O.toArray(r)},Uw,Bw);return e?t.tables:t.tables[0]}async delete(r){await g(this.client,Rw,{keys:O.toArray(r)},Dw,rn)}};const ga="/workspace/retrieve",qw="/workspace/create",Zw="/workspace/rename",Yw="/workspace/set-layout",_w="/workspace/delete",ma=s.z.object({keys:ue.array().optional(),searchTerm:s.z.string().optional(),author:qe.optional(),offset:s.z.number().optional(),limit:s.z.number().optional()}),Vw=s.z.object({workspaces:Bo.array()}),Hw=s.z.object({key:ue,name:s.z.string()}),Ww=s.z.object({key:ue,layout:s.z.string()}),Gw=s.z.object({keys:ue.array()}),wa=s.z.object({workspaces:Y(Pr)}),Kw=s.z.object({workspaces:$o.array()}),nn=s.z.object({}),Jw="sy_workspace_set",Xw="sy_workspace_delete";class Yo{type="workspace";schematic;linePlot;log;table;client;constructor(e){this.client=e,this.schematic=new Aw(e),this.linePlot=new Km(e),this.log=new uw(e),this.table=new Fw(e)}async create(e){const t=Array.isArray(e),n=await g(this.client,qw,{workspaces:O.toArray(e)},Vw,Kw);return t?n.workspaces:n.workspaces[0]}async rename(e,t){await g(this.client,Zw,{key:e,name:t},Hw,nn)}async setLayout(e,t){await g(this.client,Yw,{key:e,layout:JSON.stringify(t)},Ww,nn)}async retrieve(e){let t;const n=typeof e!="string";typeof e=="string"||Array.isArray(e)?t={keys:O.toArray(e)}:t=e;const a=await g(this.client,ga,t,ma,wa);return n?a.workspaces:a.workspaces[0]}async retrieveByAuthor(e){return(await g(this.client,ga,{author:e},ma,wa)).workspaces}async delete(e){await g(this.client,_w,{keys:O.toArray(e)},Gw,nn)}}const Qw=r=>({type:"workspace",key:r}),eb=Object.freeze(Object.defineProperty({__proto__:null,Client:Yo,DELETE_CHANNEL_NAME:Xw,SET_CHANNEL_NAME:Jw,keyZ:ue,newZ:Bo,ontologyID:Qw,remoteZ:$o,workspaceZ:Pr},Symbol.toStringTag,{value:"Module"})),_o=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:Oi.breakerConfigZ.optional()});class tb extends ho{createdAt;props;ranges;channels;auth;user;access;connectivity;ontology;workspaces;labels;hardware;control;static connectivity=Or;transport;clientVersion="0.44.2";constructor(e){const t=_o.parse(e),{host:n,port:a,username:i,password:o,connectivityPollFrequency:l,secure:c,retry:u}=t,d=new Lm(new At({host:n,port:Number(a)}),u,c);d.use(nf);let h;i!=null&&o!=null&&(h=new Gp(d.unary,{username:i,password:o}),d.use(h.middleware()));const b=new os(new Ht(d.unary)),S=new Xi(d.unary,b);super(d.stream,d.unary,b),this.createdAt=E.now(),this.props=t,this.auth=h,this.transport=d,this.channels=new Gi(this,b,d.unary,S),this.connectivity=new Or(d.unary,l,this.clientVersion,t.name),this.control=new yo(this),this.ontology=new Zi(d.unary,this);const R=new Do(this.transport.unary);this.labels=new jo(this.transport.unary),this.ranges=new Lo(this,R,this.transport.unary,b,this.labels,this.ontology),this.access=new Gf(this.transport.unary),this.user=new Fp(this.transport.unary),this.workspaces=new Yo(this.transport.unary);const A=new To(this.transport.unary),B=new ko(this.transport.unary,this,this.ontology,this.ranges),x=new Oo(this.transport.unary,B);this.hardware=new Iy(B,x,A)}get key(){return this.createdAt.valueOf().toString()}close(){this.connectivity.stopChecking()}}const rb=r=>Array.isArray(r)?r:r==null?[]:[r],nb=Object.freeze(Object.defineProperty({__proto__:null,toArray:rb},Symbol.toStringTag,{value:"Module"})),sn=r=>r!=null&&typeof r=="object"&&!Array.isArray(r),sb=(r,e)=>{let t=null;return e===0?r:(...n)=>{t!==null&&(clearTimeout(t),t=null),t=setTimeout(()=>r(...n),e)}},ab=(r,e)=>{let t=null;return e===0?r:(...n)=>{t===null&&(t=setTimeout(()=>{r(...n),t=null},e))}},Vo=(r,e,t=".")=>{const n=r.split(t);return n.map((a,i)=>{const o=e(a,i,n);return o==null?null:typeof o=="string"?o:o.join(t)}).filter(a=>a!=null).join(t)},vs=(r,e)=>{if(!Array.isArray(r))return r[e];const t=r[e];if(t!=null||r.length==0)return t;const n=r[0];if(typeof n=="object"&&"key"in n)return r.find(a=>a.key===e)},ib=(r,e)=>{const t=r.split(".");return t.forEach((n,a)=>{e=vs(e,n),e!=null&&typeof e=="object"&&"key"in e&&(t[a]=e.key)}),t.join(".")},Ts=(r,e,t={optional:!1,separator:"."})=>{t.separator??=".";const{optional:n,getter:a=vs}=t,i=e.split(t.separator);if(i.length===1&&i[0]==="")return r;let o=r;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},ob=(r,e,t)=>{const n=e.split(".");let a=r;for(let i=0;i<n.length-1;i++){const o=n[i],l=vs(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]]=t;return}if(a.length===0)return;const i=parseInt(n[n.length-1]);if(isNaN(i)){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]=t;return}}return}a[i]=t}catch(i){throw console.error("failed to set value",t,"at path",e,"on object",r),i}},lb=(r,e)=>{const t=e.split(".");let n=r;for(let a=0;a<t.length-1;a++){const i=t[a];if(n[i]==null)return;n=n[i]}if(Array.isArray(n)){const a=parseInt(t[t.length-1]);if(isNaN(a))return;n.splice(a,1);return}delete n[t[t.length-1]]},cb=(r,e)=>{const t=r.split(".");return e<0?t[t.length+e]:t[e]},ub=(r,e)=>{try{return Ts(r,e),!0}catch{return!1}},hb=(r,e)=>{if(e.length===0)return!0;const t=r.split("."),n=e.split(".");if(n.length>t.length)return!1;for(let a=0;a<n.length;a++){const i=t[a],o=n[a];if(o!=="*"&&i!==o)return!1}return!0},db=r=>{try{return structuredClone(r)}catch{return console.warn("Failed to deep copy object, falling back to JSON.parse(JSON.stringify)",r),console.trace(),JSON.parse(JSON.stringify(r))}},fb=(r,...e)=>(e.forEach(t=>{let n=r;const a=t.split(".");a.forEach((i,o)=>{typeof n!="object"||n===null||(o===a.length-1?delete n[i]:i in n&&(n=n[i]))})}),r),pb=(r,e,t="")=>{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(r,e,t),n},jn=(r,e)=>{const t=Array.isArray(r),n=Array.isArray(e);if(t!==n)return!1;if(t&&n){const o=r,l=e;if(o.length!==l.length)return!1;for(let c=0;c<o.length;c++)if(!jn(o[c],l[c]))return!1;return!0}if(r==null||e==null||typeof r!="object"||typeof e!="object")return r===e;if("equals"in r)return r.equals(e);const a=Object.keys(r),i=Object.keys(e);if(a.length!==i.length)return!1;for(const o of a){const l=r[o],c=e[o];if(typeof l=="object"&&typeof c=="object"){if(!jn(l,c))return!1}else if(l!==c)return!1}return!0},Ho=(r,e)=>{if(typeof r!="object"||r==null)return r===e;const t=Object.keys(r),n=Object.keys(e);if(n.length>t.length)return!1;for(const a of n){const i=r[a],o=e[a];if(typeof i=="object"&&typeof o=="object"){if(!Ho(i,o))return!1}else if(i!==o)return!1}return!0},Rn=(r,...e)=>{if(e.length===0)return r;const t=e.shift();if(sn(r)&&sn(t))for(const n in t)try{sn(t[n])?(n in r||Object.assign(r,{[n]:{}}),Rn(r[n],t[n])):Object.assign(r,{[n]:t[n]})}catch(a){throw a instanceof TypeError?new TypeError(`.${n}: ${a.message}`):a}return Rn(r,...e)},yb=(r,e,t)=>{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 d=u[l].safeParse(c);if(d.success){a[l]=d.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({...r},e,t)},Wo=Object.freeze(Object.defineProperty({__proto__:null,copy:db,deleteD:fb,difference:pb,element:cb,equal:jn,get:Ts,has:ub,override:Rn,overrideValidItems:yb,partialEqual:Ho,pathsMatch:hb,remove:lb,resolvePath:ib,set:ob,transformPath:Vo},Symbol.toStringTag,{value:"Module"}));let gb=class{sender;handlers;constructor(e){this.sender=e,this.handlers=new Map}handle({data:e}){const t=this.handlers.get(e.type)?.handler;t==null?console.warn(`No handler for ${e.type}`):t(e.payload)}route(e){const t=mb(e,this.sender),n=new wb(t);return this.handlers.set(e,n),n}};const mb=(r,e)=>(t,n)=>e({type:r,payload:t},n);class wb{_send;handler;constructor(e){this._send=e,this.handler=null}send(e,t=[]){this._send(e,t)}handle(e){this.handler=e}}const Un=(r,e,t="")=>{try{return r.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(`${t} - ${a.join(`
|
|
45
|
-
`)}`)}else throw n}},Go=r=>typeof r=="function",Os=(r,e)=>Go(r)?r(e):r,er=r=>Ko(r)?r():r,Ko=r=>typeof r=="function",Jo=({initial:r,value:e,onChange:t})=>{const[n,a]=_n.useState(er(e??r));return e!=null&&t!=null?[e,t]:[n,a]},Xo=({initial:r,value:e,onChange:t})=>{const[n,a]=_n.useState(er(e??r));return e!=null&&t!=null?[e,t]:[n,a]},bb=(r,e)=>{const[t,n]=_n.useState(()=>{const a=localStorage.getItem(e);return a==null?er(r):JSON.parse(a)});return[t,a=>{n(a),localStorage.setItem(e,JSON.stringify(a))}]},vb=Object.freeze(Object.defineProperty({__proto__:null,executeInitialSetter:er,executeSetter:Os,isInitialSetter:Ko,isSetter:Go,usePassthrough:Jo,usePersisted:bb,usePurePassthrough:Xo},Symbol.toStringTag,{value:"Module"}));let ba=null;const Tb=()=>(ba??=document.createElement("canvas"),ba),Ob=(r,e,t)=>{if(f.S.RUNTIME==="node")return{width:0,height:0};t??=Tb().getContext("2d"),t.font=e;const n=t.measureText(r);return Dr(n)},Dr=r=>({width:Math.trunc(Math.abs(r.actualBoundingBoxLeft)+Math.abs(r.actualBoundingBoxRight)),height:Math.trunc(Math.abs(r.actualBoundingBoxAscent)+Math.abs(r.actualBoundingBoxDescent))}),xt=["h1","h2","h3","h4","h5","p","small"],Sb=s.z.enum(xt),zb=r=>{const e=xt.indexOf(r);return e===-1||e===xt.length-1?r:xt[e+1]},Eb=s.z.union([s.z.number(),s.z.enum(["normal","bold","bolder","lighter"])]),Ee=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()}),Nb={tiny:"small",small:"small",medium:"p",large:"h5",huge:"h2"},Ab={h1:"huge",h2:"huge",h3:"huge",h4:"large",h5:"small",p:"medium",small:"small"},kb=s.z.object({l0:f.ir.colorZ,l1:f.ir.colorZ,l2:f.ir.colorZ,l3:f.ir.colorZ,l4:f.ir.colorZ,l5:f.ir.colorZ,l6:f.ir.colorZ,l7:f.ir.colorZ,l8:f.ir.colorZ,l9:f.ir.colorZ,l10:f.ir.colorZ,l11:f.ir.colorZ}),J=(r,e)=>[r[0],r[1],e,r[3]],xb=s.z.object({m2:f.ir.colorZ,m1:f.ir.colorZ,z:f.ir.colorZ,p1:f.ir.colorZ,p2:f.ir.colorZ}),or=xb.or(f.ir.colorZ.transform(r=>{const e=f.ir.hsla(r);return{m2:f.ir.fromHSLA(J(e,40)),m1:f.ir.fromHSLA(J(e,45)),z:r,p1:f.ir.fromHSLA(J(e,55)),p2:f.ir.fromHSLA(J(e,65))}})),Qo=s.z.object({name:s.z.string(),key:s.z.string(),colors:s.z.object({border:f.ir.colorZ,primary:or,gray:kb,error:or,secondary:or,warning:or,palettes:s.z.record(s.z.string(),f.ir.paletteZ),visualization:s.z.object({palettes:s.z.record(s.z.string(),s.z.array(f.ir.colorZ))}).optional().default({palettes:{}}),white:f.ir.colorZ,black:f.ir.colorZ,text:f.ir.colorZ,textInverted:f.ir.colorZ,textOnPrimary:f.ir.colorZ.optional().default(f.ir.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:Ee,h2:Ee,h3:Ee,h4:Ee,h5:Ee,p:Ee,small:Ee})}).transform(r=>((r.colors.textOnPrimary==null||f.ir.isZero(r.colors.textOnPrimary))&&(r.colors.textOnPrimary=f.ir.pickByContrast(r.colors.primary.z,r.colors.text,r.colors.textInverted)),r)),Cb="'Inter Variable', sans-serif",Ib="'Geist Mono', monospace",jb=6,bt=[357,91,55,1],vt=[48,90,55,1],Rb=["#FEFEFE","#FAFAFA","#F2F2F2","#ECECEC","#E4E4E4","#D1D1D1","#BCBCBC","#ACACAC","#8F8F8F","#4F4F4F","#292929","#050505"],Tt=Object.fromEntries(Rb.map((r,e)=>[`l${e}`,r])),Ub=()=>typeof window>"u"?!1:window.devicePixelRatio>1,Mb=Ub(),Mn={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:Tt,border:Tt.l4,error:{m2:f.ir.fromHSLA(J(bt,30)),m1:f.ir.fromHSLA(J(bt,40)),z:f.ir.fromHSLA(bt),p1:f.ir.fromHSLA(J(bt,65)),p2:f.ir.fromHSLA(J(bt,77))},warning:{m2:f.ir.fromHSLA(J(vt,30)),m1:f.ir.fromHSLA(J(vt,40)),z:f.ir.fromHSLA(vt),p1:f.ir.fromHSLA(J(vt,65)),p2:f.ir.fromHSLA(J(vt,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:Tt.l11,textInverted:Tt.l0,textOnPrimary:Tt.l0},sizes:{base:jb,border:{radius:3,width:Mb?.5:1,thickWidth:1},schematic:{elementStrokeWidth:2}},typography:{family:Cb,codeFamily:Ib,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}}},el=Object.freeze({...Mn,key:"synnaxLight",name:"Synnax Light"}),Lb=["#020202","#080808","#151515","#242424","#2F2F2F","#3B3B3B","#4A4A4A","#5C5C5C","#767676","#959595","#dadada","#FAFAFA"],Ot=Object.fromEntries(Lb.map((r,e)=>[`l${e}`,r])),tl=Object.freeze({...Mn,key:"synnaxDark",name:"Synnax Dark",colors:{...Mn.colors,gray:Ot,logo:"var(--pluto-text-color)",border:Ot.l3,text:Ot.l11,textInverted:Ot.l0,textOnPrimary:Ot.l11}}),Pb={synnaxDark:tl,synnaxLight:el},rl=["tiny","small","medium","large","huge"],nl=s.z.enum(rl),Db=r=>nl.safeParse(r).success;class ot{_noop=!1;key;path;serviceName;constructor(e,t,n="",a=!1){this.key=e,this.path=t,this.serviceName=n,this._noop=a}child(e){return new ot(e,this.extendPath(e),this.serviceName,this.noop)}extendPath(e){return`${this.path}.${e}`}get noop(){return this._noop}static NOOP=new ot("","","")}const Ln=["debug","info","warn","error"],sl=r=>{const e=Ln.indexOf(r);return({level:t})=>Ln.indexOf(t)>=e},Bb=r=>{const{include:e,exclude:t}=r;return({path:n})=>!(e!=null&&!e.some(a=>n.startsWith(a))||t!=null&&t.some(a=>n.startsWith(a)))};class lt{meta=ot.NOOP;filters;constructor(e={}){const{filters:t=[]}=e;this.filters=t}filter(e){return!this.meta.noop&&this.filters.every(t=>t({key:this.meta.key,path:this.meta.path,level:e}))}child(e){const t=new lt({filters:this.filters});return t.meta=e,t}debug(e,t,n=!1){!this.filter("debug")&&!n||(t==null?console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e):console.log("%cDEBUG","color: #8c00f0;",this.meta.path,e,lr(t)))}info(e,t,n=!1){!this.filter("info")&&!n||(t==null?console.log("%cINFO","color: #005eff;",this.meta.path,e):console.log("%cINFO","color: #005eff;",this.meta.path,e,lr(t)))}warn(e,t,n=!1){!this.filter("warn")&&!n||(t==null?console.warn("WARN",this.meta.path,e):console.warn("WARN",this.meta.path,e,lr(t)))}error(e,t,n=!1){!this.filter("error")&&!n||(t==null?console.error("ERROR",this.meta.path,e):console.error("ERROR",this.meta.path,e,lr(t)))}static NOOP=new lt}const lr=r=>typeof r=="function"?r():r;var $b=typeof globalThis=="object"?globalThis:typeof self=="object"?self:typeof window=="object"?window:typeof global=="object"?global:{},Pe="1.9.0",va=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Fb(r){var e=new Set([r]),t=new Set,n=r.match(va);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===r};function i(l){return t.add(l),!1}function o(l){return e.add(l),!0}return function(l){if(e.has(l))return!0;if(t.has(l))return!1;var c=l.match(va);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 qb=Fb(Pe),Zb=Pe.split(".")[0],Lt=Symbol.for("opentelemetry.js.api."+Zb),Pt=$b;function Ss(r,e,t,n){var a;n===void 0&&(n=!1);var i=Pt[Lt]=(a=Pt[Lt])!==null&&a!==void 0?a:{version:Pe};if(!n&&i[r]){var o=new Error("@opentelemetry/api: Attempted duplicate registration of API: "+r);return t.error(o.stack||o.message),!1}if(i.version!==Pe){var o=new Error("@opentelemetry/api: Registration of version v"+i.version+" for "+r+" does not match previously registered API v"+Pe);return t.error(o.stack||o.message),!1}return i[r]=e,t.debug("@opentelemetry/api: Registered a global for "+r+" v"+Pe+"."),!0}function Dt(r){var e,t,n=(e=Pt[Lt])===null||e===void 0?void 0:e.version;if(!(!n||!qb(n)))return(t=Pt[Lt])===null||t===void 0?void 0:t[r]}function zs(r,e){e.debug("@opentelemetry/api: Unregistering a global for "+r+" v"+Pe+".");var t=Pt[Lt];t&&delete t[r]}var Yb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),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&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},_b=function(r,e,t){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 r.concat(i||Array.prototype.slice.call(e))},Vb=function(){function r(e){this._namespace=e.namespace||"DiagComponentLogger"}return r.prototype.debug=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return St("debug",this._namespace,e)},r.prototype.error=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return St("error",this._namespace,e)},r.prototype.info=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return St("info",this._namespace,e)},r.prototype.warn=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return St("warn",this._namespace,e)},r.prototype.verbose=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return St("verbose",this._namespace,e)},r}();function St(r,e,t){var n=Dt("diag");if(n)return t.unshift(e),n[r].apply(n,_b([],Yb(t),!1))}var G;(function(r){r[r.NONE=0]="NONE",r[r.ERROR=30]="ERROR",r[r.WARN=50]="WARN",r[r.INFO=60]="INFO",r[r.DEBUG=70]="DEBUG",r[r.VERBOSE=80]="VERBOSE",r[r.ALL=9999]="ALL"})(G||(G={}));function Hb(r,e){r<G.NONE?r=G.NONE:r>G.ALL&&(r=G.ALL),e=e||{};function t(n,a){var i=e[n];return typeof i=="function"&&r>=a?i.bind(e):function(){}}return{error:t("error",G.ERROR),warn:t("warn",G.WARN),info:t("info",G.INFO),debug:t("debug",G.DEBUG),verbose:t("verbose",G.VERBOSE)}}var Wb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),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&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},Gb=function(r,e,t){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 r.concat(i||Array.prototype.slice.call(e))},Kb="diag",Bt=function(){function r(){function e(a){return function(){for(var i=[],o=0;o<arguments.length;o++)i[o]=arguments[o];var l=Dt("diag");if(l)return l[a].apply(l,Gb([],Wb(i),!1))}}var t=this,n=function(a,i){var o,l,c;if(i===void 0&&(i={logLevel:G.INFO}),a===t){var u=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((o=u.stack)!==null&&o!==void 0?o:u.message),!1}typeof i=="number"&&(i={logLevel:i});var d=Dt("diag"),h=Hb((l=i.logLevel)!==null&&l!==void 0?l:G.INFO,a);if(d&&!i.suppressOverrideMessage){var b=(c=new Error().stack)!==null&&c!==void 0?c:"<failed to generate stacktrace>";d.warn("Current logger will be overwritten from "+b),h.warn("Current logger will overwrite one already registered from "+b)}return Ss("diag",h,t,!0)};t.setLogger=n,t.disable=function(){zs(Kb,t)},t.createComponentLogger=function(a){return new Vb(a)},t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}return r.instance=function(){return this._instance||(this._instance=new r),this._instance},r}(),Jb=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),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&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},Xb=function(r){var e=typeof Symbol=="function"&&Symbol.iterator,t=e&&r[e],n=0;if(t)return t.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")},Qb=function(){function r(e){this._entries=e?new Map(e):new Map}return r.prototype.getEntry=function(e){var t=this._entries.get(e);if(t)return Object.assign({},t)},r.prototype.getAllEntries=function(){return Array.from(this._entries.entries()).map(function(e){var t=Jb(e,2),n=t[0],a=t[1];return[n,a]})},r.prototype.setEntry=function(e,t){var n=new r(this._entries);return n._entries.set(e,t),n},r.prototype.removeEntry=function(e){var t=new r(this._entries);return t._entries.delete(e),t},r.prototype.removeEntries=function(){for(var e,t,n=[],a=0;a<arguments.length;a++)n[a]=arguments[a];var i=new r(this._entries);try{for(var o=Xb(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&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}return i},r.prototype.clear=function(){return new r},r}();Bt.instance();function ev(r){return r===void 0&&(r={}),new Qb(new Map(Object.entries(r)))}function tv(r){return Symbol.for(r)}var rv=function(){function r(e){var t=this;t._currentContext=e?new Map(e):new Map,t.getValue=function(n){return t._currentContext.get(n)},t.setValue=function(n,a){var i=new r(t._currentContext);return i._currentContext.set(n,a),i},t.deleteValue=function(n){var a=new r(t._currentContext);return a._currentContext.delete(n),a}}return r}(),nv=new rv,sv={get:function(r,e){if(r!=null)return r[e]},keys:function(r){return r==null?[]:Object.keys(r)}},av={set:function(r,e,t){r!=null&&(r[e]=t)}},iv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),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&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},ov=function(r,e,t){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 r.concat(i||Array.prototype.slice.call(e))},lv=function(){function r(){}return r.prototype.active=function(){return nv},r.prototype.with=function(e,t,n){for(var a=[],i=3;i<arguments.length;i++)a[i-3]=arguments[i];return t.call.apply(t,ov([n],iv(a),!1))},r.prototype.bind=function(e,t){return t},r.prototype.enable=function(){return this},r.prototype.disable=function(){return this},r}(),cv=function(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),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&&(t=n.return)&&t.call(n)}finally{if(o)throw o.error}}return i},uv=function(r,e,t){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 r.concat(i||Array.prototype.slice.call(e))},an="context",hv=new lv,al=function(){function r(){}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalContextManager=function(e){return Ss(an,e,Bt.instance())},r.prototype.active=function(){return this._getContextManager().active()},r.prototype.with=function(e,t,n){for(var a,i=[],o=3;o<arguments.length;o++)i[o-3]=arguments[o];return(a=this._getContextManager()).with.apply(a,uv([e,t,n],cv(i),!1))},r.prototype.bind=function(e,t){return this._getContextManager().bind(e,t)},r.prototype._getContextManager=function(){return Dt(an)||hv},r.prototype.disable=function(){this._getContextManager().disable(),zs(an,Bt.instance())},r}(),Pn;(function(r){r[r.UNSET=0]="UNSET",r[r.OK=1]="OK",r[r.ERROR=2]="ERROR"})(Pn||(Pn={}));var dv=al.getInstance(),fv=function(){function r(){}return r.prototype.inject=function(e,t){},r.prototype.extract=function(e,t){return e},r.prototype.fields=function(){return[]},r}(),Es=tv("OpenTelemetry Baggage Key");function il(r){return r.getValue(Es)||void 0}function pv(){return il(al.getInstance().active())}function yv(r,e){return r.setValue(Es,e)}function gv(r){return r.deleteValue(Es)}var on="propagation",mv=new fv,wv=function(){function r(){this.createBaggage=ev,this.getBaggage=il,this.getActiveBaggage=pv,this.setBaggage=yv,this.deleteBaggage=gv}return r.getInstance=function(){return this._instance||(this._instance=new r),this._instance},r.prototype.setGlobalPropagator=function(e){return Ss(on,e,Bt.instance())},r.prototype.inject=function(e,t,n){return n===void 0&&(n=av),this._getGlobalPropagator().inject(e,t,n)},r.prototype.extract=function(e,t,n){return n===void 0&&(n=sv),this._getGlobalPropagator().extract(e,t,n)},r.prototype.fields=function(){return this._getGlobalPropagator().fields()},r.prototype.disable=function(){zs(on,Bt.instance())},r.prototype._getGlobalPropagator=function(){return Dt(on)||mv},r}(),bv=wv.getInstance();const Ta=["bench","debug","prod"],vv=r=>e=>Ta.indexOf(e)>=Ta.indexOf(r);class $t{meta=ot.NOOP;otelTracer;filter;constructor(e,t=vv("debug")){this.otelTracer=e,this.filter=t}child(e){const t=new $t(this.otelTracer,this.filter);return t.meta=e,t}debug(e,t){return this.trace(e,"debug",t)}bench(e,t){return this.trace(e,"bench",t)}prod(e,t){return this.trace(e,"prod",t)}trace(e,t,n){const a=this.meta.noop||!this.filter(t)||this.otelTracer==null;if(n==null){if(a)return()=>{};const i=new Dn(e,this.otelTracer.startSpan(e));return i.start(),()=>i.end()}return a?n(new ol(e)):this.otelTracer.startActiveSpan(e,i=>{const o=new Dn(e,i);return n(o)})}propagate(e){if(this.meta.noop)return;const t=dv.active();bv.inject(t,e,{set:(n,a,i)=>{n[a]=i}})}static NOOP=new $t}class Dn{key;otel;constructor(e,t){this.key=e,this.otel=t}set(e,t){this.otel.setAttribute(e,t)}recordError(e){e!=null&&(this.otel.recordException(e),this.otel.setStatus({code:Pn.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 ol{key;constructor(e){this.key=e}set(){}recordError(e){}}class ct{meta;T;L;constructor({key:e="",serviceName:t="",logger:n=lt.NOOP,tracer:a=$t.NOOP,noop:i=!1,__meta:o}){this.meta=o??new ot(e,e,t,i),this.T=a.child(this.meta),this.L=n.child(this.meta)}child(e){const t=this.meta.child(e);return new ct({__meta:t,tracer:this.T,logger:this.L})}static NOOP=new ct({noop:!0})}const Tv=ct.NOOP,ke=Object.freeze(Object.defineProperty({__proto__:null,Instrumentation:ct,LOG_LEVELS:Ln,Logger:lt,NOOP:Tv,NoopSpan:ol,Tracer:$t,_Span:Dn,logLevelKeyFiler:Bb,logThresholdFilter:sl},Symbol.toStringTag,{value:"Module"})),ln=(r,e)=>r instanceof Error?(r.message=`[${e}] - ${r.message}`,r):new Error(e??"unknown error",{cause:r});class Br{type;key;sender;_internalState;_state;_prevState;_deleted=!1;parentCtxValues;childCtxValues;childCtxChangedKeys;instrumentation;schema=void 0;constructor({key:e,type:t,sender:n,instrumentation:a,parentCtxValues:i}){this.type=t,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 $(`[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 t=Os(e,this.state);this._prevState=f.br(this._state),this._state=Un(this._schema,t,`${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 t=this.parentCtxValues.get(e);if(t===void 0)throw new at(`Context value for ${e} not found on ${this.toString()}`);return t},getOptional:e=>this.parentCtxValues.get(e),has:e=>this.parentCtxValues.has(e),wasSetPreviously:e=>this.childCtxValues.has(e),set:(e,t,n=!0)=>{this.childCtxValues.set(e,t),n&&this.childCtxChangedKeys.add(e)}}}toString(){return`${this.type}(${this.key})`}_updateState({path:e,state:t}){if(!this.deleted)try{const n=this.instrumentation.T.debug(`${this.toString()}:updateState`);this.validatePath(e);const a=Un(this._schema,t,`${this.toString()}`);this._state!=null?this.instrumentation.L.debug("updating state",()=>({diff:Wo.difference(this.state,a)})):this.instrumentation.L.debug("setting initial state",{state:t,path:e}),this._prevState=this._state??a,this._state=a,this.afterUpdate(this.ctx),n()}catch(n){throw ln(n,`${this.toString()}.updateState`)}}_updateContext(e){try{const t=this.instrumentation.T.debug(`${this.toString()}:updateContext`);e.forEach((n,a)=>this.parentCtxValues.set(a,n)),this.afterUpdate(this.ctx),t()}catch(t){throw ln(t,`${this.type}.${this.key}.updateContext`)}}_delete(e){try{const t=this.instrumentation.T.debug(`${this.toString()}:delete`);this.validatePath(e),this._deleted=!0,this.afterDelete(this.ctx),t()}catch(t){throw ln(t,`[${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 t=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(t!==this.key)throw new W(`[Leaf.setState] - ${this.toString()} received a key ${t} but expected ${this.key}`)}}class mt extends Br{_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(t=>e.includes(t.type))}_updateState(e){const{path:t,type:n,create:a}=e;if(this.deleted)return;const i=this.parsePath(t);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 d=t.slice(0,t.indexOf(l)+1).join("."),h=t.join(".");throw new W(`Child of ${this.toString()} at path ${d} does not exist,
|
|
47
|
-
but an extended path ${h} 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(b=>`${b.type}:${b.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((t,n)=>e(t,n,this.childCtxValues)),this.parentCtxValues.forEach((t,n)=>{this.childCtxValues.has(n)||e(t,n,this.parentCtxValues)})}}}updateChildContexts(){const e=this.childCtx();this.children.forEach(t=>t._updateContext(e))}_delete(e){const t=this.parsePath(e);if(t.length===0){for(const a of this.children)a._delete([a.key]);this._children.clear(),super._delete([this.key])}const n=this.getChild(t[0]);if(n!=null){if(t.length>1)return n._delete(t);this._children.delete(n.key),n._delete(t)}}parsePath(e,t){const[n,...a]=e;if(n==null)throw new Error(`Composite ${this.toString()} received an empty path${t!=null?` for ${t}`:""}`);if(n!==this.key)throw new W(`[Composite.getRequiredKey] - ${this.toString()} received a key ${n} but expected ${this.key}`);return a}}const Ov=s.z.object({}),Sv=()=>{throw new Error("should not call create")};class xe extends mt{static TYPE="root";static KEY="root";comms;registry;schema=Ov;constructor({comms:e,instrumentation:t=ke.Instrumentation.NOOP,registry:n}){super({key:xe.KEY,type:xe.TYPE,sender:e,instrumentation:t,parentCtxValues:null}),this.comms=e,this.registry=n}static render(e){const t=new xe(e);return t._updateState({path:[xe.KEY],type:"",state:{},create:Sv}),t.comms.handle(n=>{try{t.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),t.comms.send({variant:"error",error:i})}}),t}handle(e){const{path:t,variant:n,type:a}=e;if(n==="delete"){this._delete(t);return}const{state:i}=e;this._updateState({path:t,type:a,state:i,create:o=>{const l=t[t.length-1];return this.create({key:l,type:a,parentCtxValues:o})}})}create({key:e,type:t,parentCtxValues:n}){const a=this.registry[t];if(a==null)throw new W(`[Root.create] - ${t} not found in registry`);return new a({key:e,type:t,sender:this.comms,instrumentation:this.instrumentation,parentCtxValues:n})}}const ll=xe.render.bind(xe),zv=Object.freeze(Object.defineProperty({__proto__:null,Composite:mt,Leaf:Br,Root:xe,render:ll},Symbol.toStringTag,{value:"Module"})),Ev=(r,e)=>Array.isArray(e)?e.some(t=>t.matches(r)):e?.matches(r)??!1,cl=(r,e,t)=>{const n=f._r.fromException(r,e);return console.error(n),Ev(r,t)?null:n},ul=(r,e,t,n)=>{if(typeof r=="function")return!0;const a=cl(r,t,n);return a!=null&&e(a),!1},hl=async(r,e,t,n)=>{try{const a=r();a!=null&&await a}catch(a){const i=cl(a,t,n);if(i!=null)return e(i)}},dl=r=>(e,t,n)=>{ul(e,r,t,n)&&hl(e,r,t,n)},fl=r=>async(e,t,n)=>{ul(e,r,t,n)&&await hl(e,r,t,n)},pl=s.z.object({statuses:f._r.statusZ().array()}),zr="status.aggregator";class Bn extends mt{static TYPE="status.Aggregator";schema=pl;afterUpdate(e){e.wasSetPreviously(zr)||e.set(zr,{add:this.add.bind(this),create:f._r.create})}add(e){this.setState(t=>({...t,statuses:[...t.statuses,f._r.create(e)]}))}}const $r=r=>r.get(zr).add,Nv=r=>{const e=r.getOptional(zr);return e!=null?e.add:()=>{}},Ns=r=>dl($r(r)),Av=r=>fl($r(r)),kv={[Bn.TYPE]:Bn},$n="pluto-theming-context",yl=s.z.object({name:s.z.string(),url:s.z.string()}),xv=s.z.object({theme:Qo,fontURLs:s.z.array(yl)});let Fn=class gl extends mt{static TYPE="theming.Provider";static z=xv;schema=gl.z;afterUpdate(e){if(e.getOptional($n)!=null&&this.state.theme.key===this.prevState.theme.key)return;e.set($n,this.state.theme),Ns(e)(async()=>{await this.loadFonts()},"failed to load theme fonts")}async loadFonts(){await Promise.all(this.state.fontURLs.map(async({name:e,url:t})=>{const n=new FontFace(e,`url(${t})`);try{await n.load(),self.fonts.add(n)}catch(a){console.error(a)}}))}};const Cv=r=>r.get($n),Iv={[Fn.TYPE]:Fn},ml=s.z.object({include:s.z.string().array().optional(),exclude:s.z.string().array().optional(),level:s.z.enum(ke.LOG_LEVELS).optional().default("info")}),qn="alamos-provider";class Zn extends mt{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(ke.logLevelKeyFiler({include:a,exclude:i})),o!=null&&n.push(ke.logThresholdFilter(o)),n.length===0&&n.push(()=>!1),this.internal.ins=new ke.Instrumentation({key:"aether",logger:new ke.Logger({filters:n})}),e.set(qn,this.internal.ins)}}const wl=(r,e)=>{const t=r.get(qn);if(t==null)throw new Error("No instrumentation provider");return e==null?t:t.child(e)},jv={[Zn.TYPE]:Zn},gr=(r,e)=>f.Ho.construct(f.Ho.left(r)-e.x,f.Ho.top(r)-e.y,f.Ho.width(r)+e.x*2,f.Ho.height(r)+e.y*2);class Er{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,t,n,a=f.C.XY.IDENTITY){this.wrapped=e,this.scale_=a,this.atlasRegistry=t,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 Er(this,this.atlasRegistry,this.dpr,e)}get canvas(){return this.wrapped.canvas}get miterLimit(){return this.cachedMiterLimit??this.wrapped.miterLimit}set miterLimit(e){const t=this.scale_.x.dim(e);t!==this.cachedMiterLimit&&(this.cachedMiterLimit=t,this.wrapped.miterLimit=t)}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,t,n,a,i,o,l,c,u){this.wrapped.drawImage(e,t,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,t){this.wrapped.clip(e,t)}fill(e,t){if(e==null)return this.wrapped.fill();this.wrapped.fill(e,t)}isPointInPath(e,t,n,a){return this.wrapped.isPointInPath(e,t,n,a)}isPointInStroke(e,t,n){return this.wrapped.isPointInStroke(e,t,n)}stroke(e){if(e==null)return this.wrapped.stroke();this.wrapped.stroke(e)}createConicGradient(e,t,n){return this.wrapped.createConicGradient(e,t,n)}createLinearGradient(e,t,n,a){return this.wrapped.createLinearGradient(e,t,n,a)}createPattern(e,t){return this.wrapped.createPattern(e,t)}createRadialGradient(e,t,n,a,i,o){return this.wrapped.createRadialGradient(e,t,n,a,i,o)}get filter(){return this.wrapped.filter}set filter(e){this.wrapped.filter=e}createImageData(e,t,n){return this.wrapped.createImageData(e,t,n)}getImageData(e,t,n,a,i){return this.wrapped.getImageData(e,t,n,a,i)}putImageData(e,t,n,a,i,o,l){this.wrapped.putImageData(e,t,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,t,n,a,i,o){this.wrapped.arc(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),a,i,o)}arcTo(e,t,n,a,i){this.wrapped.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,t,n,a,i,o){this.wrapped.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),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,t,n,a,i,o,l,c){this.wrapped.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,t){this.wrapped.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}moveTo(e,t){this.wrapped.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}quadraticCurveTo(e,t,n,a){this.wrapped.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,t,n,a){this.wrapped.rect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,t,n,a,i){this.wrapped.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(t),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 t=this.scale_.x.dim(e);t!==this.cachedLineWidth&&(this.cachedLineWidth=t,this.wrapped.lineWidth=t)}getLineDash(){return this.wrapped.getLineDash()}setLineDash(e){const t=Array.from(e).map(n=>this.scale_.x.dim(n));this.wrapped.setLineDash(t)}clearRect(e,t,n,a){this.wrapped.clearRect(e,t,n,a)}fillRect(e,t,n,a){this.wrapped.fillRect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a))}strokeRect(e,t,n,a){this.wrapped.strokeRect(this.scale_.x.pos(e),this.scale_.y.pos(t),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,t,n,a,i={}){const[o,l]=this.checkAtlasFillStyle(i.useAtlas);if(o){this.atlasRegistry.get({font:this.font,textColor:l}).fillText(this,e,t,n);return}this.wrapped.fillText(e,this.scale_.x.pos(t),this.scale_.y.pos(n),a!=null?this.scale_.x.dim(a):void 0)}measureText(e){return this.wrapped.measureText(e)}textDimensions(e,t={}){const[n,a]=this.checkAtlasFillStyle(t.useAtlas);return n?this.atlasRegistry.get({font:this.font,textColor:a}).measureText(e):Dr(this.measureText(e))}strokeText(e,t,n,a){this.wrapped.strokeText(e,this.scale_.x.pos(t),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,t){this.wrapped.scale(e,t),this.dpr=e}scissor(e,t=f.K.ZERO){const n=new Rv(this.scale_);return e=gr(e,t),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,t,n,a,i,o){this.wrapped.setTransform(e,t,n,a,i,o)}transform(e,t,n,a,i,o){this.wrapped.transform(e,t,n,a,i,o)}translate(e,t){this.wrapped.translate(e,t)}}class Rv{scale_;path;constructor(e=f.C.XY.IDENTITY,t){this.scale_=e,t instanceof Path2D||typeof t=="string"?this.path=new Path2D(t):this.path=new Path2D}addPath(e,t){this.path.addPath(e,t)}arc(e,t,n,a,i,o){this.path.arc(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),a,i,o)}arcTo(e,t,n,a,i){this.path.arcTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a),this.scale_.x.dim(i))}bezierCurveTo(e,t,n,a,i,o){this.path.bezierCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),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,t,n,a,i,o,l,c){this.path.ellipse(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a),i,o,l,c)}lineTo(e,t){this.path.lineTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}moveTo(e,t){this.path.moveTo(this.scale_.x.pos(e),this.scale_.y.pos(t))}quadraticCurveTo(e,t,n,a){this.path.quadraticCurveTo(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.pos(n),this.scale_.y.pos(a))}rect(e,t,n,a){this.path.rect(this.scale_.x.pos(e),this.scale_.y.pos(t),this.scale_.x.dim(n),this.scale_.y.dim(a))}roundRect(e,t,n,a,i){const o=this.scaleRadii(i);this.path.roundRect(this.scale_.x.pos(e),this.scale_.y.pos(t),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(t=>this.scaleRadius(t)):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 Uv=`precision mediump float;
|
|
54
|
-
|
|
55
|
-
void main(void) {
|
|
56
|
-
gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0);
|
|
57
|
-
}
|
|
58
|
-
`,Mv=`attribute vec4 a_position;
|
|
59
|
-
|
|
60
|
-
void main(void) {
|
|
61
|
-
gl_Position = a_position;
|
|
62
|
-
}
|
|
63
|
-
`,Oa=r=>new Error(`failed to compile webgl program: ${r}`),Lv=new Error("null shader encountered");let bl=class{renderCtx;prog;vertShader;fragShader;uniformLocCache=new Map;constructor(e,t,n){this.renderCtx=e;const a=e.gl.createProgram();if(a==null)throw Oa("failed to create program");this.prog=a,this.vertShader=t,this.fragShader=n,this.compile()}setAsActive(){return this.renderCtx.gl.useProgram(this.prog),()=>this.renderCtx.gl.useProgram(null)}uniformXY(e,t){this.renderCtx.gl.uniform2fv(this.getUniformLoc(e),f.K.couple(t))}uniformColor(e,t){this.renderCtx.gl.uniform4fv(this.getUniformLoc(e),f.ir.rgba1(t))}getUniformLoc(e){const t=this.uniformLocCache.get(e);if(t!=null)return t;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,t){const n=this.renderCtx.gl,a=n.createShader(t);if(a==null)throw Lv;if(n.shaderSource(a,e),n.compileShader(a),!n.getShaderParameter(a,n.COMPILE_STATUS)){const o=n.getShaderInfoLog(a);throw n.deleteShader(a),Oa(o??"unknown")}n.attachShader(this.prog,a)}};const Pv=new Float32Array([0,0,0,0,0,0]);class Dv extends bl{positionBuffer;constructor(e){super(e,Mv,Uv);const t=e.gl.createBuffer();if(t==null)throw new W("webgl: failed to create buffer");this.positionBuffer=t,e.gl.bindBuffer(e.gl.ARRAY_BUFFER,this.positionBuffer),e.gl.bufferData(e.gl.ARRAY_BUFFER,Pv,e.gl.STATIC_DRAW)}exec(){const{gl:e}=this.renderCtx,t=e.getAttribLocation(this.prog,"a_position");e.bindBuffer(e.ARRAY_BUFFER,this.positionBuffer);const n=e.createVertexArray();e.bindVertexArray(n),e.enableVertexAttribArray(t),e.vertexAttribPointer(t,2,e.FLOAT,!1,0,0),this.setAsActive(),e.drawArrays(e.TRIANGLES,0,3)}}const Sa={high:1,low:0};class vl{requests=new Map;cleanup=new Map;afterRender;instrumentation;handleError;constructor({afterRender:e,instrumentation:t=ke.Instrumentation.NOOP,handleError:n}){this.afterRender=e,this.instrumentation=t,this.handleError=n,this.start()}set(e){const t=this.requests.get(e.key);if(t==null)this.requests.set(e.key,e);else{const n=Sa[e.priority]>=Sa[t.priority],a=e.canvases.length>=t.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:t}=this;e.forEach((n,a)=>{const i=t.get(a);i!=null&&(n(i),e.delete(a))})}renderSync(){const{requests:e}=this;e.forEach(t=>{try{const n=t.render();n!=null&&this.cleanup.set(t.key,n)}catch(n){this.handleError(n,"render loop failed")}})}start(){const e=()=>{try{this.render()}catch(t){this.handleError(t,"render loop failed")}requestAnimationFrame(e)};requestAnimationFrame(e)}}const cr=2,he=2;class As{atlas;charDims;charMap;static DEFAULT_CHARS="0123456789.:-µmsNa∞ᴇ";constructor(e){const{font:t,characters:n=As.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=t;const c=l.measureText("0");this.charDims=Dr(c),this.charDims.width+=cr,this.charDims.height+=cr;const u=i.length,d=this.charDims.width,h=this.charDims.height,b=Math.ceil(Math.sqrt(u)),S=Math.ceil(u/b);this.atlas=new OffscreenCanvas(d*b*he,h*(S+1)*he);const R=this.atlas.getContext("2d");R.scale(he,he),R.font=t,R.textBaseline="alphabetic",R.textAlign="left",R.fillStyle=f.ir.hex(a),R.clearRect(0,0,this.atlas.width,this.atlas.height),i.forEach((A,B)=>{const x=B%b,L=Math.floor(B/b),re=x*d,Q=(L+1)*h;R.fillText(A,re,Q),this.charMap.set(A,B)})}fillText(e,t,n,a){const{width:i,height:o}=this.charDims,l=Math.ceil(Math.sqrt(this.charMap.size));for(let c=0;c<t.length;c++){const u=t[c],d=this.charMap.get(u);if(d===void 0)continue;const h=d%l,b=Math.floor(d/l);e.drawImage(this.atlas,h*i*he,b*o*he+cr,i*he,o*he,n+c*i,a-o-cr/he,i,o)}}measureText(e){return{width:e.length*this.charDims.width,height:this.charDims.height}}}class Bv{atlases;constructor(){this.atlases=new Map}get(e){const t=`${e.font}-${f.ir.hex(e.textColor)}-${e.characters}`;if(this.atlases.has(t))return this.atlases.get(t);const n=new As(e);return this.atlases.set(t,n),n}}const za=r=>(r.textRendering="optimizeSpeed",r.imageSmoothingEnabled=!1,r);class Ne{glCanvas;upper2dCanvas;lower2dCanvas;gl;lower2d;upper2d;region;dpr;loop;clearProgram;os;static CONTEXT_KEY=f.CSS.B("render-context");instrumentation;static create(e,t,n,a,i){const o=wl(e,"render_context"),l=new Ne(t,n,a,i,o,$r(e),Ns(e));return e.set(Ne.CONTEXT_KEY,l),l}constructor(e,t,n,a,i,o,l){this.upper2dCanvas=n,this.lower2dCanvas=t,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 Bv;this.lower2d=za(new Er(c,u,this.dpr));const d=this.upper2dCanvas.getContext("2d");if(d==null)throw new Error("Could not get 2D context");this.upper2d=za(new Er(d,u,this.dpr));const h={preserveDrawingBuffer:!0,powerPreference:"high-performance",stencil:!1,depth:!1},b=this.glCanvas.getContext("webgl2",h);if(b==null)throw new Error("Could not get WebGL context");b.disable(b.DEPTH_TEST),b.disable(b.STENCIL_TEST),b.disable(b.CULL_FACE),b.disable(b.DITHER),this.gl=b,this.glCanvas.oncontextlost=()=>o({variant:"error",message:"WebGL context lost"});const S=()=>{this.gl.flush(),this.gl.finish()};this.loop=new vl({afterRender:S,instrumentation:this.instrumentation,handleError:l}),this.region=f.Ho.ZERO,this.os==="Windows"&&(this.clearProgram=new Dv(this))}static useOptional(e){return e.getOptional(Ne.CONTEXT_KEY)}static use(e){return e.get(Ne.CONTEXT_KEY)}update(e){e.set(Ne.CONTEXT_KEY,this)}resize(e,t){f.Ho.equals(this.region,e)&&this.dpr===t||(this.region=e,this.dpr=t,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)*t,f.Ho.height(e)*t))}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,t=f.K.ZERO,n){const a=[];return n.includes("upper2d")&&a.push(this.upper2d.scissor(e,t)),n.includes("lower2d")&&a.push(this.lower2d.scissor(e,t)),n.includes("gl")&&a.push(this.scissorGL(e,t)),()=>a.forEach(i=>i())}scissorGL(e,t=f.K.ZERO){return this.gl.enable(this.gl.SCISSOR_TEST),e=gr(e,t),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,t=f.K.ZERO,...n){t=f.K.construct(t),n.length===0&&(n=["upper2d","lower2d","gl"]),n.includes("upper2d")&&this.eraseCanvas(this.upper2d,e,t),n.includes("lower2d")&&this.eraseCanvas(this.lower2d,e,t),n.includes("gl")&&this.eraseGL(e,t)}eraseGL(e,t=f.K.ZERO){const{gl:n}=this,a=this.scissorGL(gr(e,t));n.clearColor(...f.ir.rgba1(f.ir.ZERO)),n.clear(n.COLOR_BUFFER_BIT),this.os==="Windows"&&this.clearProgram?.exec(),a()}eraseCanvas(e,t,n=f.K.ZERO){const a=gr(t,n);e.clearRect(...f.K.couple(f.Ho.topLeft(a)),...f._.couple(f.Ho.dims(a)))}}const Tl=s.z.object({region:f.Ho.box,enabled:s.z.boolean().optional().default(!1)}),Ea=["gl","lower2d","upper2d"];class Yn extends Br{static TYPE="eraser";schema=Tl;afterUpdate(e){this.deleted||(this.internal.renderCtx=Ne.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:Ea})}render(){this.deleted||!this.state.enabled||this.internal.renderCtx.erase(this.state.region,f.K.construct(0),...Ea)}}const $v={[Yn.TYPE]:Yn};exports.$=N;exports.Aggregator=Bn;exports.COMPONENT_SIZE_LEVELS=Nb;exports.Ce=je;exports.Composite=mt;exports.Context=Ne;exports.Eraser=Yn;exports.Fm=zy;exports.GLProgram=bl;exports.Hm=Hy;exports.Km=ug;exports.LEVELS=xt;exports.LEVEL_COMPONENT_SIZES=Ab;exports.Leaf=Br;exports.Loop=vl;exports.Mm=vp;exports.N=Wo;exports.O=ct;exports.O$1=z;exports.Om=ef;exports.P=$;exports.Provider=Fn;exports.Provider$1=Zn;exports.REGISTRY=Iv;exports.REGISTRY$1=kv;exports.REGISTRY$2=$v;exports.REGISTRY$3=jv;exports.S=E;exports.SIZES=rl;exports.SYNNAX_DARK=tl;exports.SYNNAX_LIGHT=el;exports.SYNNAX_THEMES=Pb;exports.Xm=Ig;exports.Ym=Cy;exports.Yt=at;exports._=lt;exports.aether=zv;exports.aggregatorStateZ=pl;exports.be=sl;exports.createAsyncErrorHandler=fl;exports.createErrorHandler=dl;exports.d=gb;exports.dimensions=Ob;exports.dimensionsFromMetrics=Dr;exports.downLevel=zb;exports.eraserStateZ=Tl;exports.ew=Gg;exports.executeInitialSetter=er;exports.executeSetter=Os;exports.f=Vo;exports.fontSpecZ=yl;exports.g=ke;exports.hw=eb;exports.isSize=Db;exports.km=Uf;exports.levelZ=Sb;exports.lt=W;exports.nm=_o;exports.o=sb;exports.prettyParse=Un;exports.providerStateZ=ml;exports.r=ab;exports.render=ll;exports.rw=Um;exports.size=nl;exports.sm=tb;exports.specZ=Ee;exports.state=vb;exports.t=nb;exports.themeZ=Qo;exports.u=Ts;exports.use=Cv;exports.useAdder=$r;exports.useAsyncErrorHandler=Av;exports.useErrorHandler=Ns;exports.useInstrumentation=wl;exports.useOptionalAdder=Nv;exports.usePassthrough=Jo;exports.usePurePassthrough=Xo;exports.weightZ=Eb;
|